diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fa69f9a..28c78b1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,6 +55,13 @@ jobs: set -o pipefail cargo test -p mx --test conformance -- --test-threads=1 2>&1 | tee validation.log ! grep -q "mX Vulkan validation error" validation.log + - name: openOMSI's shaders on lavapipe under the validation layer + env: + VK_INSTANCE_LAYERS: VK_LAYER_KHRONOS_validation + run: | + set -o pipefail + cargo test -p mx --test openomsi_shaders -- --nocapture 2>&1 | tee shaders.log + ! grep -q "mX Vulkan validation error" shaders.log - name: wgpu-mx through wgpu's API, and as a wgpu backend run: cargo test -p wgpu-mx --features custom - name: Android (Vulkan) compiles @@ -101,5 +108,13 @@ jobs: run: cargo test -p mx-types -p mx-shader --all-features - name: Conformance tests on WARP run: cargo test -p mx --test conformance -- --test-threads=1 + # (openOMSI's shaders through DXC, as the game ships it: the Windows SDK's dxcompiler.dll + # and dxil.dll on the path, or mX falls back to FXC) + - name: openOMSI's shaders through DXC on WARP + shell: pwsh + run: | + $dxc = Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin\*\x64\dxcompiler.dll" | Sort-Object FullName -Descending | Select-Object -First 1 + if ($dxc) { $env:PATH = "$($dxc.DirectoryName);$env:PATH"; Write-Host "DXC: $($dxc.FullName)" } else { Write-Host "no dxcompiler.dll in the Windows SDK: FXC" } + cargo test -p mx --test openomsi_shaders -- --nocapture - name: wgpu-mx through wgpu's API, and as a wgpu backend run: cargo test -p wgpu-mx --features custom -- --test-threads=1 diff --git a/crates/mx-dx12/src/command.rs b/crates/mx-dx12/src/command.rs index 27eebe4..dc63a25 100644 --- a/crates/mx-dx12/src/command.rs +++ b/crates/mx-dx12/src/command.rs @@ -318,7 +318,10 @@ impl CommandEncoder { ); assert_eq!(texture.dimension(), t::TextureDimension::D2, "generate_mipmaps: 2D textures only on Direct3D 12"); let format = texture.format(); - let device = Device { shared: self.rec.shared.clone() }; + let device = Device { + shared: self.rec.shared.clone(), + owner: None, + }; let (pipeline, sampler) = device.mip_tools(format); for layer in 0..texture.layers() { for level in 1..texture.mip_level_count() { @@ -641,7 +644,10 @@ impl CommandEncoder { "GPU-driven draw arguments need STORAGE | INDIRECT usage" ); assert!(count.usage().contains(t::BufferUsages::INDIRECT), "a GPU-driven draw count needs INDIRECT usage"); - let device = Device { shared: self.rec.shared.clone() }; + let device = Device { + shared: self.rec.shared.clone(), + owner: None, + }; let tool = device.indirect_tool(); let n = if draws.0.indexed { 20 } else { 16 }; let bg = device.create_bind_group(&crate::BindGroupDescriptor { diff --git a/crates/mx-dx12/src/device.rs b/crates/mx-dx12/src/device.rs index 39d42ab..794085a 100644 --- a/crates/mx-dx12/src/device.rs +++ b/crates/mx-dx12/src/device.rs @@ -497,7 +497,14 @@ impl Adapter { mips: Mutex::new(crate::command::MipTools::default()), indirect: Mutex::new(None), }); - Ok((Device { shared: shared.clone() }, Queue { shared })) + let owner = Some(Arc::new(Owner(shared.clone()))); + Ok(( + Device { + shared: shared.clone(), + owner: owner.clone(), + }, + Queue { shared, owner }, + )) } } @@ -961,10 +968,26 @@ impl Drop for Shared { } } +/// The program's hold on a device: every `Device` and `Queue` it was given (and their clones) +/// share one. When the last goes, the queue is waited for, which submits the pending queue +/// writes and reclaims what finished submissions and released views keep. Those keep textures +/// and buffers, and so the device's shared state: after the program's last submission nothing +/// reclaimed them, and the device was never released (#4). +pub(crate) struct Owner(pub(crate) Arc); + +impl Drop for Owner { + fn drop(&mut self) { + let _ = self.0.wait_idle(); + } +} + /// The GPU. Cheap to clone; every clone is the same device. #[derive(Clone)] pub struct Device { pub(crate) shared: Arc, + /// (held for its drop; none for the device handles mX makes for itself while recording) + #[allow(dead_code)] + pub(crate) owner: Option>, } impl Device { @@ -1030,6 +1053,9 @@ impl Device { #[derive(Clone)] pub struct Queue { pub(crate) shared: Arc, + /// (held for its drop, as the device's) + #[allow(dead_code)] + pub(crate) owner: Option>, } impl Queue { diff --git a/crates/mx-dx12/src/heap.rs b/crates/mx-dx12/src/heap.rs index 19f70e6..191a469 100644 --- a/crates/mx-dx12/src/heap.rs +++ b/crates/mx-dx12/src/heap.rs @@ -231,10 +231,13 @@ pub(crate) struct Heap { textures: Slots, samplers: Slots, buffers: Slots, - /// Textures whose heap view was released but which a submission may still read. - retired: Vec<(u64, Texture)>, + /// The resources of textures whose heap view was released but which a submission may + /// still read. The resource alone, not the `Texture`: a texture holds the device's shared + /// state, which holds this list - after the last submission nothing reclaimed it, and the + /// device and every texture retired late were never released (#4). + retired: Vec<(u64, ID3D12Resource)>, /// Buffers likewise. - retired_buffers: Vec<(u64, Buffer)>, + retired_buffers: Vec<(u64, ID3D12Resource)>, /// The buffers with views in the heap (by resource), with how many views and how many /// writable ones: a command list keeps them in the state shaders reach them in (see /// `Heap::buffer_states`). @@ -270,7 +273,7 @@ impl Heap { /// Release a buffer slot (reused after submission `after` is done) and keep the buffer /// alive until then. - pub fn release_buffer(&mut self, slot: u32, after: u64, buffer: Buffer, writable: bool) { + pub fn release_buffer(&mut self, slot: u32, after: u64, buffer: &Buffer, writable: bool) { self.buffers.release(slot, after); if let Some(e) = self.heap_buffers.get_mut(&buffer.key()) { e.1 -= 1; @@ -280,7 +283,7 @@ impl Heap { } } self.buffer_generation += 1; - self.retired_buffers.push((after, buffer)); + self.retired_buffers.push((after, buffer.0.raw.clone())); } /// The state each buffer with heap views is in while shaders may reach it through the @@ -306,9 +309,9 @@ impl Heap { /// Release a texture slot (reused after submission `after` is done) and keep the texture /// alive until then. - pub fn release_texture(&mut self, slot: u32, after: u64, texture: Texture) { + pub fn release_texture(&mut self, slot: u32, after: u64, texture: &Texture) { self.textures.release(slot, after); - self.retired.push((after, texture)); + self.retired.push((after, texture.0.raw.clone())); } pub fn alloc_sampler(&mut self) -> Result { @@ -329,16 +332,16 @@ impl Heap { } /// Everything released before submission `completed` finished is free again. Returns the - /// textures to drop outside the lock (buffers are dropped here: dropping one takes no lock) - /// and the texture and buffer slots freed, whose descriptors still point at what they held. - pub fn reclaim(&mut self, completed: u64) -> (Vec, Vec, Vec) { + /// textures' resources to release outside the lock and the texture and buffer slots freed, + /// whose descriptors still point at what they held. + pub fn reclaim(&mut self, completed: u64) -> (Vec, Vec, Vec) { let (mut tex_slots, mut buf_slots, mut sampler_slots) = (Vec::new(), Vec::new(), Vec::new()); self.textures.reclaim(completed, &mut tex_slots); self.samplers.reclaim(completed, &mut sampler_slots); self.buffers.reclaim(completed, &mut buf_slots); self.retired_buffers.retain(|(after, _)| *after > completed); let mut done = Vec::new(); - self.retired.retain_mut(|(after, t)| { + self.retired.retain(|(after, t)| { if *after <= completed { done.push(t.clone()); false diff --git a/crates/mx-dx12/src/resource.rs b/crates/mx-dx12/src/resource.rs index 445d656..5ed83a3 100644 --- a/crates/mx-dx12/src/resource.rs +++ b/crates/mx-dx12/src/resource.rs @@ -282,7 +282,7 @@ pub(crate) struct BufferViewInner { impl Drop for BufferViewInner { fn drop(&mut self) { let shared = &self.buffer.0.shared; - shared.heap.lock().release_buffer(self.slot, shared.release_after(), self.buffer.clone(), self.writable); + shared.heap.lock().release_buffer(self.slot, shared.release_after(), &self.buffer, self.writable); } } @@ -819,7 +819,7 @@ impl Drop for ViewInner { fn drop(&mut self) { let shared = &self.texture.0.shared; if let Some(slot) = self.slot { - shared.heap.lock().release_texture(slot, shared.release_after(), self.texture.clone()); + shared.heap.lock().release_texture(slot, shared.release_after(), &self.texture); } let mut cpu = shared.cpu.lock(); for d in [self.srv, self.uav].into_iter().flatten() { @@ -1027,7 +1027,11 @@ impl Device { if desc.usage.contains(t::BufferUsages::MAP_WRITE) { buffer.map_write(0..buffer.size(), |b| b.copy_from_slice(desc.contents))?; } else { - Queue { shared: self.shared.clone() }.write_buffer(&buffer, 0, desc.contents)?; + Queue { + shared: self.shared.clone(), + owner: None, + } + .write_buffer(&buffer, 0, desc.contents)?; } Ok(buffer) } diff --git a/crates/mx-gl/src/caps.rs b/crates/mx-gl/src/caps.rs index 884951a..b5f2120 100644 --- a/crates/mx-gl/src/caps.rs +++ b/crates/mx-gl/src/caps.rs @@ -40,6 +40,9 @@ pub(crate) struct Caps { pub combined_texture_units: u32, /// `GL_MAX_SAMPLES`. pub max_samples: u32, + /// Multisampled textures, `glTexStorage2DMultisample` (GL 3.2, ES 3.1). Without them a + /// multisampled render target is a renderbuffer (ES 3.0), which shaders cannot sample. + pub multisample_textures: bool, pub limits: t::Limits, } @@ -115,11 +118,14 @@ impl Caps { copy_image: at_least((4, 3), (3, 2)) || has("GL_EXT_copy_image"), indirect: at_least((4, 0), (3, 1)), texture_shadow_lod: has("GL_EXT_texture_shadow_lod"), - timestamps: (!es && version >= (3, 3)) || has("GL_EXT_disjoint_timer_query"), + // (an ES driver may have the extension for elapsed time alone: ANGLE's counter + // for timestamps has no bits, every timestamp read 0) + timestamps: ((!es && version >= (3, 3)) || has("GL_EXT_disjoint_timer_query")) && timestamps_count(gl), bc: has("GL_EXT_texture_compression_s3tc") && (has("GL_EXT_texture_compression_bptc") || has("GL_ARB_texture_compression_bptc") || at_least((4, 2), (9, 9))), explicit_bindings: at_least((4, 2), (3, 1)), invalidate: at_least((4, 3), (3, 0)), max_samples: get(glow::MAX_SAMPLES), + multisample_textures: at_least((3, 2), (3, 1)), vertex_texture_units: get(glow::MAX_VERTEX_TEXTURE_IMAGE_UNITS), fragment_texture_units: get(glow::MAX_TEXTURE_IMAGE_UNITS), combined_texture_units: get(glow::MAX_COMBINED_TEXTURE_IMAGE_UNITS), @@ -128,3 +134,22 @@ impl Caps { } } } + +/// Whether a timestamp query gives a time on this context: one is written and read back. +/// +/// # Safety +/// The context is current. +unsafe fn timestamps_count(gl: &glow::Context) -> bool { + // SAFETY: the caller's; a query made, used once and deleted here. + unsafe { + let Ok(q) = gl.create_query() else { return false }; + while gl.get_error() != glow::NO_ERROR {} + gl.query_counter(q, glow::TIMESTAMP); + gl.finish(); + let mut v = [0u8; 8]; + gl.get_query_parameter_u64_with_offset(q, glow::QUERY_RESULT, v.as_mut_ptr() as usize); + let ok = gl.get_error() == glow::NO_ERROR && u64::from_le_bytes(v) > 0; + gl.delete_query(q); + ok + } +} diff --git a/crates/mx-gl/src/command.rs b/crates/mx-gl/src/command.rs index 1ebdd60..8efdc4d 100644 --- a/crates/mx-gl/src/command.rs +++ b/crates/mx-gl/src/command.rs @@ -629,16 +629,58 @@ fn run(gl: &glow::Context, shared: &Shared, st: &mut State, cmd: Cmd) { Cmd::DrawIndirect(args, offset, indexed) => { let Pipeline::Render(p) = &st.pipeline else { panic!("draw without a pipeline") }; let p = p.clone(); - assert!(shared.caps.indirect, "indirect draws need OpenGL 4.0 / OpenGL ES 3.1"); - prepare_draw(gl, shared, st, &p, 0); - gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(args.0.raw)); - if indexed { - let (_, _, f) = st.index.clone().expect("draw_indexed_indirect without an index buffer"); - gl.draw_elements_indirect_offset(p.0.topology, conv::index_type(f).0, offset as i32); + if !shared.caps.indirect { + 'emulated: { + // OpenGL ES 3.0 (ANGLE over older chips) has no indirect draws: the + // arguments are read back and drawn directly (the GPU's earlier work on + // them waits; the draw is the same) + let len = if indexed { 20 } else { 16 }; + let mut a = [0u32; 5]; + gl.bind_buffer(glow::COPY_READ_BUFFER, Some(args.0.raw)); + let ptr = gl.map_buffer_range(glow::COPY_READ_BUFFER, offset as i32, len, glow::MAP_READ_BIT); + if !ptr.is_null() { + std::ptr::copy_nonoverlapping(ptr, a.as_mut_ptr() as *mut u8, len as usize); + gl.unmap_buffer(glow::COPY_READ_BUFFER); + } + gl.bind_buffer(glow::COPY_READ_BUFFER, None); + if indexed { + let (count, instances, first, base, first_instance) = (a[0], a[1], a[2], a[3] as i32, a[4]); + let (_, ioffset, f) = st.index.clone().expect("draw_indexed_indirect without an index buffer"); + let (ty, size) = conv::index_type(f); + if count == 0 || instances == 0 { + break 'emulated; + } + if base != 0 && !shared.caps.base_vertex { + log::warn!("mX: an indirect draw with a base vertex left out (OpenGL ES 3.0 has none)"); + break 'emulated; + } + prepare_draw(gl, shared, st, &p, first_instance); + let at = (ioffset + first as u64 * size) as i32; + if base != 0 { + gl.draw_elements_instanced_base_vertex(p.0.topology, count as i32, ty, at, instances as i32, base); + } else { + gl.draw_elements_instanced(p.0.topology, count as i32, ty, at, instances as i32); + } + } else { + let (count, instances, first, first_instance) = (a[0], a[1], a[2], a[3]); + if count == 0 || instances == 0 { + break 'emulated; + } + prepare_draw(gl, shared, st, &p, first_instance); + gl.draw_arrays_instanced(p.0.topology, first as i32, count as i32, instances as i32); + } + } } else { - gl.draw_arrays_indirect_offset(p.0.topology, offset as i32); + prepare_draw(gl, shared, st, &p, 0); + gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(args.0.raw)); + if indexed { + let (_, _, f) = st.index.clone().expect("draw_indexed_indirect without an index buffer"); + gl.draw_elements_indirect_offset(p.0.topology, conv::index_type(f).0, offset as i32); + } else { + gl.draw_arrays_indirect_offset(p.0.topology, offset as i32); + } + gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, None); } - gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, None); } Cmd::Dispatch(x, y, z) => { let Pipeline::Compute(p) = &st.pipeline else { panic!("dispatch without a pipeline") }; @@ -960,6 +1002,10 @@ unsafe fn attach(gl: &glow::Context, target: u32, attachment: u32, v: &TextureVi let tex = v.texture(); // SAFETY: the caller's. unsafe { + if let Some(rb) = tex.0.rb { + gl.framebuffer_renderbuffer(target, attachment, glow::RENDERBUFFER, Some(rb)); + return; + } match tex.0.target { glow::TEXTURE_2D | glow::TEXTURE_2D_MULTISAMPLE => gl.framebuffer_texture_2d(target, attachment, tex.0.target, Some(tex.0.raw), v.0.base_mip_level as i32), glow::TEXTURE_CUBE_MAP => gl.framebuffer_texture_2d(target, attachment, glow::TEXTURE_CUBE_MAP_POSITIVE_X + v.0.base_array_layer, Some(tex.0.raw), v.0.base_mip_level as i32), @@ -1357,6 +1403,7 @@ fn zero_range(gl: &glow::Context, shared: &Shared, tex: &Texture, mips: Range gl.framebuffer_renderbuffer(glow::DRAW_FRAMEBUFFER, attachment, glow::RENDERBUFFER, tex.0.rb), glow::TEXTURE_2D | glow::TEXTURE_2D_MULTISAMPLE => gl.framebuffer_texture_2d(glow::DRAW_FRAMEBUFFER, attachment, tex.0.target, Some(tex.0.raw), mip as i32), glow::TEXTURE_CUBE_MAP => gl.framebuffer_texture_2d(glow::DRAW_FRAMEBUFFER, attachment, image_target(tex, layer), Some(tex.0.raw), mip as i32), _ => gl.framebuffer_texture_layer(glow::DRAW_FRAMEBUFFER, attachment, Some(tex.0.raw), mip as i32, layer as i32), diff --git a/crates/mx-gl/src/device.rs b/crates/mx-gl/src/device.rs index 6f4f822..c297fd9 100644 --- a/crates/mx-gl/src/device.rs +++ b/crates/mx-gl/src/device.rs @@ -225,6 +225,7 @@ pub struct SubmissionIndex(pub u64); pub(crate) enum Garbage { Buffer(glow::Buffer), Texture(glow::Texture), + Renderbuffer(glow::Renderbuffer), Sampler(glow::Sampler), Program(glow::Program), Query(glow::Query), @@ -313,6 +314,7 @@ impl Shared { match g { Garbage::Buffer(b) => gl.delete_buffer(b), Garbage::Texture(t) => gl.delete_texture(t), + Garbage::Renderbuffer(r) => gl.delete_renderbuffer(r), Garbage::Sampler(s) => gl.delete_sampler(s), Garbage::Program(p) => gl.delete_program(p), Garbage::Query(q) => gl.delete_query(q), diff --git a/crates/mx-gl/src/pipeline.rs b/crates/mx-gl/src/pipeline.rs index 3a8c64c..54dbdc1 100644 --- a/crates/mx-gl/src/pipeline.rs +++ b/crates/mx-gl/src/pipeline.rs @@ -122,10 +122,40 @@ impl Device { /// Lower the heap of every entry point now (GLSL is compiled with the pipeline, which /// numbers the bindings of its stages together). + /// Each entry point lowered to the bound tier, written as this context's GLSL and compiled + /// by the driver, on its own (a pipeline's stages are linked when it is made). Before, only + /// the lowering was tried: a module the driver's GLSL compiler refused passed. pub fn precompile(&self, module: &ShaderModule) -> Result<()> { + let options = self.options(); for ep in &module.0.module.module.entry_points { - if matches!(ep.stage, ShaderStage::Vertex | ShaderStage::Fragment | ShaderStage::Compute) { - glsl::stage(&module.0.module, ep.stage, Some(&ep.name), &[])?; + let kind = match ep.stage { + ShaderStage::Vertex => glow::VERTEX_SHADER, + ShaderStage::Fragment => glow::FRAGMENT_SHADER, + ShaderStage::Compute if self.shared.caps.compute => glow::COMPUTE_SHADER, + _ => continue, + }; + let stage = glsl::stage(&module.0.module, ep.stage, Some(&ep.name), &[])?; + let layout = glsl::Layout::for_pipeline(&[&stage]).map_err(|message| Error::Compile { + label: module.0.module.label.clone(), + message, + })?; + let out = glsl::write(&module.0.module, &stage, 0, &layout, &options)?; + let gl = self.shared.ctx.lock(); + // SAFETY: a shader made, compiled and deleted here, on the current context. + unsafe { + let sh = gl.create_shader(kind).map_err(|e| crate::gl_err("shader", e))?; + gl.shader_source(sh, &out.source); + gl.compile_shader(sh); + let ok = gl.get_shader_compile_status(sh); + let log = if ok { String::new() } else { gl.get_shader_info_log(sh) }; + gl.delete_shader(sh); + if !ok { + log::debug!("{}: GLSL that failed:\n{}", ep.name, out.source); + return Err(Error::Compile { + label: module.0.module.label.clone(), + message: format!("{}: {}", ep.name, if log.trim().is_empty() { "the driver gave no log" } else { &log }), + }); + } } } Ok(()) diff --git a/crates/mx-gl/src/resource.rs b/crates/mx-gl/src/resource.rs index 14ee2e0..d510cd7 100644 --- a/crates/mx-gl/src/resource.rs +++ b/crates/mx-gl/src/resource.rs @@ -206,6 +206,9 @@ impl BufferView { pub(crate) struct TextureInner { pub raw: glow::Texture, pub target: u32, + /// A multisampled render target on a context without multisampled textures (ES 3.0): its + /// samples live here, and `raw` is a name without storage. + pub rb: Option, pub size: t::Extent3d, pub format: t::TextureFormat, pub dimension: t::TextureDimension, @@ -221,6 +224,9 @@ impl Drop for TextureInner { fn drop(&mut self) { if !self.external { self.shared.retire(Garbage::Texture(self.raw)); + if let Some(rb) = self.rb { + self.shared.retire(Garbage::Renderbuffer(rb)); + } } } } @@ -509,8 +515,19 @@ impl Device { // from its views; mX decides at creation) let cube = desc.view_formats.is_empty() && layers == 6 && desc.size.width == desc.size.height && desc.usage.contains(t::TextureUsages::TEXTURE_BINDING); let target = conv::texture_target(desc.dimension, layers, desc.sample_count, cube); + // (ES 3.0 has multisampled renderbuffers only: enough for a render target that is + // resolved, as MSAA is; ES 3.0 drivers - ANGLE on older chips - drew it black before) + let as_renderbuffer = target == glow::TEXTURE_2D_MULTISAMPLE && !shared.caps.multisample_textures; + if as_renderbuffer + && desc + .usage + .intersects(t::TextureUsages::TEXTURE_BINDING | t::TextureUsages::STORAGE_BINDING | t::TextureUsages::COPY_SRC | t::TextureUsages::COPY_DST) + { + return Err(Error::Unsupported("multisampled textures that are sampled or copied (GL 3.2 / OpenGL ES 3.1)".into())); + } let f = conv::format(desc.format); let gl = shared.ctx.lock(); + let mut rb = None; let (w, h) = (desc.size.width as i32, desc.size.height as i32); // SAFETY: plain creation and allocation of the texture's storage. let raw = unsafe { @@ -518,6 +535,13 @@ impl Device { gl.bind_texture(target, Some(raw)); let levels = desc.mip_level_count as i32; match target { + glow::TEXTURE_2D_MULTISAMPLE if as_renderbuffer => { + let r = gl.create_renderbuffer().map_err(|e| gl_err("renderbuffer", e))?; + gl.bind_renderbuffer(glow::RENDERBUFFER, Some(r)); + gl.renderbuffer_storage_multisample(glow::RENDERBUFFER, desc.sample_count as i32, f.internal, w, h); + gl.bind_renderbuffer(glow::RENDERBUFFER, None); + rb = Some(r); + } glow::TEXTURE_2D_MULTISAMPLE => gl.tex_storage_2d_multisample(target, desc.sample_count as i32, f.internal, w, h, true), glow::TEXTURE_2D | glow::TEXTURE_CUBE_MAP => gl.tex_storage_2d(target, levels, f.internal, w, h), glow::TEXTURE_2D_ARRAY => gl.tex_storage_3d(target, levels, f.internal, w, h, layers as i32), @@ -541,6 +565,7 @@ impl Device { let tex = Texture(Arc::new(TextureInner { raw, target, + rb, size: desc.size, format: desc.format, dimension: desc.dimension, @@ -563,6 +588,7 @@ impl Device { Texture(Arc::new(TextureInner { raw, target: conv::texture_target(desc.dimension, layers, desc.sample_count, false), + rb: None, size: desc.size, format: desc.format, dimension: desc.dimension, diff --git a/crates/mx/tests/conformance.rs b/crates/mx/tests/conformance.rs index d7d25a8..46a2d05 100644 --- a/crates/mx/tests/conformance.rs +++ b/crates/mx/tests/conformance.rs @@ -17,6 +17,17 @@ struct Gpu { /// once (the test threads), the M4 sometimes returns timestamps of 0. A game has one device. static GPU: std::sync::Mutex<()> = std::sync::Mutex::new(()); +/// Whether the GPU lacks compute shaders or the buffer heap (OpenGL ES 3.0, OpenGL below 4.3: +/// ANGLE over older chips); the tests of them say so and pass. +fn lacks_compute() -> bool { + let a = Instance::new().default_adapter().expect("a GPU mX can use"); + let lacks = !a.supports_compute() || a.limits().max_bindless_buffers == 0; + if lacks { + eprintln!("skipped: no compute shaders or storage buffers on this GPU"); + } + lacks +} + fn gpu() -> Gpu { let guard = GPU.lock().unwrap_or_else(|e| e.into_inner()); let adapter = Instance::new().default_adapter().expect("a GPU mX can use"); @@ -398,6 +409,9 @@ fn pipeline_constants_reach_overrides() { #[test] fn compute_with_runtime_sized_storage() { + if lacks_compute() { + return; + } let g = gpu(); let m = g.shader( "@group(0) @binding(0) var src: array; @@ -658,6 +672,9 @@ fn render_bundles_replay_without_leaking_state() { #[test] fn indirect_dispatch_and_clear_buffer() { + if lacks_compute() { + return; + } let g = gpu(); let m = g.shader( "@group(0) @binding(0) var out: array; @@ -1430,6 +1447,9 @@ fn clear_texture_zeroes_its_range() { /// set for each dispatch): a reduction through it, two arrays of different sizes. #[test] fn workgroup_memory_is_shared() { + if lacks_compute() { + return; + } let g = gpu(); let m = g.shader( "@group(0) @binding(0) var out: array; @@ -1783,6 +1803,9 @@ fn heap_buffer(g: &Gpu, data: &[u8], usage: BufferUsages) -> Buffer { #[test] fn buffers_in_the_heap_need_no_bind_groups() { + if lacks_compute() { + return; + } let g = gpu(); // a typed read-only view at an offset, the words of a writable view, chosen by immediates let m = g.shader( @@ -1855,6 +1878,9 @@ var draw: Draw; #[test] fn fragments_read_heap_buffers_chosen_by_immediates() { + if lacks_compute() { + return; + } let g = gpu(); let red = heap_buffer(&g, bytemuck::cast_slice(&[1.0f32, 0.0, 0.0, 1.0]), BufferUsages::empty()); let green = heap_buffer(&g, bytemuck::cast_slice(&[0.0f32, 1.0, 0.0, 1.0]), BufferUsages::empty()); @@ -1886,6 +1912,9 @@ var draw: Draw; #[test] fn heap_buffers_see_writes_of_earlier_passes_and_copies() { + if lacks_compute() { + return; + } let g = gpu(); // pass 1 writes through the heap, a copy overwrites part of it, pass 2 reads both let fill = g.shader( @@ -1964,6 +1993,9 @@ var draw: Draw; #[test] fn buffer_heap_slots_are_reused_only_after_the_gpu_is_done() { + if lacks_compute() { + return; + } let g = gpu(); let b = heap_buffer(&g, &[0; 16], BufferUsages::empty()); let first = b.create_view(&Default::default()).unwrap(); diff --git a/crates/mx/tests/openomsi/README.md b/crates/mx/tests/openomsi/README.md new file mode 100644 index 0000000..8d22150 --- /dev/null +++ b/crates/mx/tests/openomsi/README.md @@ -0,0 +1,13 @@ +# openOMSI's WGSL modules + +The 23 shader modules of openOMSI's mX renderer (`omsi-render-mx`) as it assembles them for the +GPU, taken from openOMSI `940ab2f97` (2026-11-23): the list in `omsi-render-mx`'s +`shaders_validate_and_match_the_uniforms` test, each module written out as the test builds it. +The sky module holds the screen-space clouds, the scene module the glass and its mips, the +`*_basic` ones the phones' reduced precipitation. + +`cargo test -p mx --test openomsi_shaders` compiles every entry point of every module for the +platform's GPU: DXC (or FXC) and Direct3D 12 on Windows - in CI on WARP, the first time the +game's HLSL meets DXC - Vulkan SPIR-V (under the Khronos layer in CI, lavapipe) and Metal. +`MX_OPENOMSI_SHADERS=` takes another set (`tools/openomsi_shaders.py` writes an older +one from an openOMSI checkout). diff --git a/crates/mx/tests/openomsi/corona.wgsl b/crates/mx/tests/openomsi/corona.wgsl new file mode 100644 index 0000000..3e35970 --- /dev/null +++ b/crates/mx/tests/openomsi/corona.wgsl @@ -0,0 +1,951 @@ +// Light coronas ([light_enh]): camera-facing additive sprites. +struct Camera { + view_proj: mat4x4, + cam_pos: vec4, + // This remains part of the shared camera layout even though coronas only use + // `view_proj` and `cam_pos` today. Keeping the prefix aligned prevents later + // corona effects from reading every lighting field one vec4 too early. + world_origin: vec4, + sun_dir: vec4, + ambient: vec4, + fog: vec4, + sun_color: vec4, + sky_color: vec4, + light_grid: vec4, + sky: vec4, + cam_right: vec4, + cam_up: vec4, +}; +@group(0) @binding(0) var camera: Camera; +@group(1) @binding(0) var t_corona: texture_2d; +@group(1) @binding(1) var s_corona: sampler; + +struct CoronaIn { + @location(0) pos: vec3, // relative to the render origin + @location(1) size: f32, // world radius + @location(2) color: vec4, // rgb, alpha = brightness (0..2) + @location(3) dir: vec4, // xyz facing direction (0 = omni), w cos of the outer cone + @location(4) up: vec4, // xyz up / rotation axis, w rotating mode (0 flat, 1 about up, 2 billboard) + @location(5) extra: vec4, // x cos of the inner cone, y z offset (<0 default), z parameter bits + @builtin(vertex_index) vid: u32, +}; +struct CoronaOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + @location(1) color: vec4, + // 1 for what is drawn at the scene's level (a precipitation streak, lit fog: a cone or + // a halo), 0 for a light's glare + @location(2) kind: f32, + // 1 when the light is drawn with a star (`[light_enh_2]` parameter bit 1) + @location(3) star: f32, + // 1 for a light's cone in the fog (OMSI's fan, see below) + @location(4) beam: f32, + // the cone's inner and outer half angles (radians) + @location(5) cone: vec2, + // a smoke puff's: how high this point is over the ground it fades into (m), and how + // high the fade reaches (0: not faded) + @location(6) ground: vec2, + // precipitation (Enhanced, see `precip_light`): the particle's place, w 1 for rain, 2 + // for snow, 0 for anything else + @location(7) wpos: vec4, +}; + +// How many times wider than the light's own sprite the Enhanced picture draws a lamp's quad, for +// the faint glare round it (`fs_enhanced`) - with *Glow of lights* on: 64 times the pixels. +const GLARE_K: f32 = 8.0; +// the glare's strength at the sprite's rim, against the lamp's core +const GLARE_TAIL: f32 = 0.4; + +// How many times its sprite a lamp's quad is drawn: `GLARE_K` with *Glow of lights* on (enh.led.z), +// and in mist, fog and rain (which have a halo of their own, in the bitmap) only the sprite. +fn glare_scale() -> f32 { + let wet = clamp(enh.fog.x * 400.0 + enh.weather.z * 0.7, 0.0, 1.0); + return select(1.0, GLARE_K, enh.led.z > 0.5 && wet < 1.0); +} + +@vertex +fn vs_main(in: CoronaIn) -> CoronaOut { + return corona_vertex(in, 1.0); +} + +@vertex +fn vs_enhanced(in: CoronaIn) -> CoronaOut { + return corona_vertex(in, glare_scale()); +} + +fn corona_vertex(in: CoronaIn, glare: f32) -> CoronaOut { + var out: CoronaOut; + let corners = array, 6>(vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, 1.0)); + let c = corners[in.vid % 6u]; + if (in.extra.w > 2.5) { + // a [smoke] puff (`smoke_sprite`): rauch.tga facing the viewer as Omsi.exe lays it + // out (0x5a2b5c), turned about the line of sight by its own angle (dir: its cosine + // and sine) and moved up.z towards the eye in depth only - its size on the screen + // stays (Omsi.exe's 0.1 m: the view depth less 0.1 put through the projection's + // depth terms) + let to_cam = camera.cam_pos.xyz - in.pos; + let dist = length(to_cam); + let view_dir = to_cam / max(dist, 0.001); + var side = cross(vec3(0.0, 0.0, 1.0), view_dir); + if (length(side) < 0.0001) { + // (seen from straight above or below) + side = camera.cam_right.xyz; + } + let right0 = normalize(side); + let up0 = cross(view_dir, right0); + let right = right0 * in.dir.x + up0 * in.dir.y; + let up = up0 * in.dir.x - right0 * in.dir.y; + let size = max(in.size, dist * 0.002) * 0.9; + let wp = in.pos + (right * c.x + up * c.y) * size; + var sout: CoronaOut; + sout.clip = camera.view_proj * vec4(wp, 1.0); + if (in.up.z > 0.0) { + let nearer = camera.view_proj * vec4(wp + view_dir * min(in.up.z, dist * 0.9), 1.0); + sout.clip.z = nearer.z / nearer.w * sout.clip.w; + } + sout.uv = c * 0.5 + 0.5; + let a = min(in.color.a, 1.0); + sout.color = vec4(in.color.rgb, a); + // Omsi.exe lets a puff sink on into the road, which cuts it off in a straight line + // (under a wheel's spray: bright bands across the road); here it fades out over + // its lowest part into the ground it was thrown up from (up.x, when up.y is 1), + // from up.w above it (`smoke_ground_fade`) down to nothing + if (in.up.y > 0.5) { + sout.ground = vec2(wp.z - in.up.x, in.up.w); + } + if (!(a > 0.001) || (bitcast(a) & 0x7f800000u) == 0x7f800000u) { + sout.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return sout; + } + if (in.extra.w > 1.5) { + // the halo round a light in fog: licht.bmp turned to the + // viewer, pulled towards them by its size, seen from in front of the light (for a + // directional one the more, the further out of its cone's side the viewer stands) + let to_cam = camera.cam_pos.xyz - in.pos; + let dist = length(to_cam); + let vdir = to_cam / max(dist, 0.001); + var k = in.color.a; + if (length(in.dir.xyz) > 0.5) { + let axis = normalize(in.dir.xyz); + let inner = in.extra.x; + let outer = in.dir.w; + let ang = acos(clamp(dot(axis, vdir), -1.0, 1.0)); + var from_side = select(0.0, 1.0, ang > inner); + if (outer > inner + 0.0001) { + from_side = clamp((ang - inner) / (outer - inner), 0.0, 1.0); + } + let side = min(from_side, clamp(3.0 - ang, 0.0, 1.0)); + let front = (1.0 - side) * clamp(1.0 - (ang - 2.0) * 0.5, 0.5, 1.0); + k = k * front * front * select(0.0, 1.0, ang < 1.5705); + } + let fwd = normalize(cross(camera.cam_up.xyz, camera.cam_right.xyz)); + let on_screen = 2.0 * dot(fwd, -vdir) - 1.0; + let far = clamp(1.0 - dist / max(in.extra.y, 1.0), 0.0, 1.0); + k = k * max(on_screen, 0.0) * far; + let right = normalize(cross(vec3(0.0, 0.0, 1.0), vdir)); + let up = cross(vdir, right); + var hout: CoronaOut; + let centre = in.pos + vdir * min(in.size, dist * 0.9); + hout.clip = camera.view_proj * vec4(centre + (right * c.x + up * c.y) * in.size, 1.0); + hout.uv = c * 0.5 + 0.5; + hout.color = vec4(in.color.rgb, k); + hout.kind = 1.0; + hout.star = 0.0; + hout.beam = 0.0; + hout.cone = vec2(0.0, 0.0); + if (k <= 0.001 || on_screen <= 0.01) { + hout.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return hout; + } + if (in.extra.w > 0.5) { + // OMSI's cone in the fog: a flat + // fan from the lamp, `size` in radius, spreading to the outer half angle either side + // of the light's axis and turned about that axis to face the eye. + // It is drawn here as a square in that plane; the fragment cuts the fan out of it + // and maps light_cone.bmp onto it as the fan's vertices do. + let axis = normalize(in.dir.xyz); + let inner = in.extra.x; + let outer = in.dir.w; + let to_cam = camera.cam_pos.xyz - in.pos; + let dist = length(to_cam); + let vdir = to_cam / max(dist, 0.001); + var side = cross(vdir, axis); + if (length(side) < 0.001) { + side = cross(vec3(0.0, 0.0, 1.0), axis); + } + side = normalize(side); + // seen from the side it shows, from within its inner cone the glow does instead, + // and from behind (2..3 rad off its axis) it fades out + let ang = acos(clamp(dot(axis, vdir), -1.0, 1.0)); + var from_side = select(0.0, 1.0, ang > inner); + if (outer > inner + 0.0001) { + from_side = clamp((ang - inner) / (outer - inner), 0.0, 1.0); + } + let behind = clamp(3.0 - ang, 0.0, 1.0); + // towards the edge of the view it fades (2 cos - 1 of the angle off the view's axis) + let fwd = normalize(cross(camera.cam_up.xyz, camera.cam_right.xyz)); + let on_screen = 2.0 * dot(fwd, -vdir) - 1.0; + // and it goes with the lamp's distance through the fog + let far = clamp(1.0 - dist / max(in.extra.y, 1.0), 0.0, 1.0); + let k = in.color.a * min(from_side, behind) * max(on_screen, 0.0) * far; + var bout: CoronaOut; + bout.clip = camera.view_proj * vec4(in.pos + (axis * c.x + side * c.y) * in.size, 1.0); + bout.uv = c; + bout.color = vec4(in.color.rgb, k); + bout.kind = 1.0; + bout.star = 0.0; + bout.beam = 1.0; + bout.cone = vec2(inner, outer); + if (k <= 0.001 || on_screen <= 0.01) { + bout.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return bout; + } + let to_cam = camera.cam_pos.xyz - in.pos; + let dist = length(to_cam); + let view_dir = to_cam / max(dist, 0.001); + // (a cone of -2 marks a raindrop, of -3 a snowflake: rain.rs) + let streak = in.dir.w < -1.5 && in.dir.w > -2.5; + let flake = in.dir.w <= -2.5; + let directed = length(in.dir.xyz) > 0.5 && !streak; + var brightness = in.color.a; + if (directed) { + // a directional light is seen inside its outer cone, in full inside the inner one, + // linearly in the angle between them + let ang = acos(clamp(dot(normalize(in.dir.xyz), view_dir), -1.0, 1.0)); + let outer = acos(clamp(in.dir.w, -1.0, 1.0)); + let inner = select(0.0, acos(clamp(in.extra.x, -1.0, 1.0)), in.extra.x >= -1.0); + brightness = brightness * clamp((outer - ang) / max(outer - inner, 0.0001), 0.0, 1.0); + } + // the light that reaches the eye through the fog: Beer-Lambert's exp(-density x + // distance), the same law the scene's own fog follows (`shader.wgsl`). Left out, the + // street lamps and signals shone at full strength to the end of the view in a fog that + // had hidden their poles 50 m away, a fan of dots at the horizon (#1212). + if (!streak) { + brightness = brightness * exp(-dist * max(camera.fog.w, 0.0)); + } + // a star grows with the light's strength; every sprite's strength stops at 1 + let star_sprite = (u32(in.extra.z + 0.5) & 8u) != 0u && !streak; + let grow = select(1.0, brightness, star_sprite); + if (!streak) { + brightness = min(brightness, 1.0); + } + // the sprite's axes: flat and facing its direction (rotating 0), turned to the viewer + // about its up axis (1), or turned to the viewer entirely (2) + let mode = u32(in.up.w + 0.5); + var right = normalize(cross(vec3(0.0, 0.0, 1.0), view_dir)); + var up = cross(view_dir, right); + let axis = select(vec3(0.0, 0.0, 1.0), normalize(in.up.xyz), length(in.up.xyz) > 0.5); + if (!streak && mode == 0u && directed) { + let n = normalize(in.dir.xyz); + var u = axis - n * dot(axis, n); + if (length(u) < 0.01) { + u = vec3(0.0, 0.0, 1.0) - n * n.z; + } + up = normalize(u); + right = cross(up, n); + } else if (!streak && mode == 1u) { + let r = cross(axis, view_dir); + if (length(r) > 0.01) { + right = normalize(r); + up = axis; + } + } + // coronas keep a minimum on-screen size in the distance like the original; + // precipitation particles (cone < -1.5) follow their motion relative to the eye. + // A sprite's radius, from the light's size (its diameter) and that distance floor. The + // 0.9 is measured against Omsi.exe: at the size the game files ask for, every glow reads + // a shade too wide beside the original, which draws the sprite a little inside the + // diameter its `size` names. (Streaks keep their size: they are rain, not a light.) + let size = select(max(in.size * grow, dist * 0.002) * 0.9 * select(glare, 1.0, flake), in.size, streak); + let stretch = select(vec2(1.0, 1.0), vec2(0.06, 4.0), streak); + var upv = up; + if (streak) { + upv = vec3(0.0, 0.0, 1.0); + if (length(in.dir.xyz) > 0.5) { upv = normalize(in.dir.xyz); } + let across = cross(upv, view_dir); + if (length(across) > 0.001) { right = normalize(across); } + } + // the spot moved towards the viewer by its z offset, so that a lamp inside its housing + // shows (without one: half its size, at most half a metre) + let pull = select(min(size * 0.5, 0.5), in.extra.y, in.extra.y >= 0.0); + let wp = in.pos + (right * c.x * stretch.x + upv * c.y * stretch.y) * size + select(view_dir * min(pull, dist * 0.9), vec3(0.0), streak); + out.clip = camera.view_proj * vec4(wp, 1.0); + // A lamp's glare quad (Enhanced, *Glow of lights*) is `GLARE_K` times its sprite and flat, + // facing the eye. Left at the lamp's own depth it cuts into whatever stands within its + // reach - the bumper, the road in front of the bus, the lens itself - along a straight + // line, and fights with the lens's own depth: a bright plane standing in the air, seen + // the plainer the lower the camera. A glare is the eye's and the lens's, not a thing in + // the world: it is moved towards the eye in depth only (as a smoke puff is, above; its + // size on the screen stays) by the quad's own radius, so that only what truly stands + // between the eye and the lamp, further out than that, covers it. + if (!streak && !flake && glare > 1.0) { + let push = min(size, dist * 0.9); + let nearer = camera.view_proj * vec4(wp + view_dir * push, 1.0); + out.clip.z = nearer.z / nearer.w * out.clip.w; + } + out.uv = c * 0.5 + 0.5; + out.color = vec4(in.color.rgb, brightness); + out.kind = select(0.0, 1.0, streak); + out.wpos = vec4(in.pos, select(select(0.0, 2.0, flake), 1.0, streak)); + out.star = 0.0; + out.beam = 0.0; + out.cone = vec2(0.0, 0.0); + // (not `<= 0.001`: a NaN brightness is not smaller, and Direct3D drew it as a black + // square where Metal's fast maths had dropped it) + if (!(brightness > 0.001) || (bitcast(brightness) & 0x7f800000u) == 0x7f800000u) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +// The sprite's picture at `uv`, interpolated between its texels with a quintic ease instead +// of linearly. The pictures are small (light_cone.bmp is 64 x 64) and a lamp's sprite or a +// fog cone spans hundreds of pixels: a linear blend between texels has a kink at every texel +// line, and a steep gradient - the cone's bright axis, a glow's rim - shows them as a stair +// of squares along its edge, in the light of a lamp or a headlight's beam. The eased blend +// is smooth to the second order and costs the same single fetch. +fn soft_picture(uv: vec2) -> vec4 { + let dims = vec2(textureDimensions(t_corona)); + let p = uv * dims - vec2(0.5); + let i = floor(p); + let f = p - i; + let e = f * f * f * (f * (f * 6.0 - vec2(15.0)) + vec2(10.0)); + // (the level of detail from the true coordinates: the eased ones run slower and faster) + return textureSampleGrad(t_corona, s_corona, (i + e + vec2(0.5)) / dims, dpdx(uv), dpdy(uv)); +} + +// The sprite's light: the round texture (in its own colours), and for a star light four thin rays across it. +fn corona_shape(in: CoronaOut) -> vec3 { + // (the sprite keeps the bitmap's own colours, modulated by the light's colour) + // Read the right way up. `in.uv` is built the way the HUD's is (overlay.wgsl), where + // v = 0 is the picture's *first*, topmost row; but a sprite's corners are placed by its + // own `up`, which runs up the screen, so v = 1 comes to rest at its top. Taken as it + // stands the picture is drawn upside down - invisible on a round glow or a star, plain + // on an asymmetric effect, such as the light streak some buses' `[light_enh_2]` + // `lights_abbl`/`lights_stand` bitmaps draw. The fan below keeps the unflipped `in.uv`: + // it maps light_cone.bmp from its own `fan_uv` and only takes `r` and `phi` from here, + // which its geometry needs as they stand. + let t = soft_picture(vec2(in.uv.x, 1.0 - in.uv.y)).rgb; + // the cone's fan: its apex has uv (0, 1) and a rim vertex (sin a, 1 - cos a) + // (u = sin a, v = 1 - cos a), a being 0.05 inside + // the inner cone and rising to 0.9 pi/2 + 0.05 at the outer edge: light_cone.bmp's + // bright left column runs down the light's axis and fades towards the fan's edges. + // (With sin and cos the other way round the streaks ran along both edges, a "V" of + // light reaching out sideways and up from every lamp.) + let r = length(in.uv); + let phi = abs(atan2(in.uv.y, in.uv.x)); + let span = max(in.cone.y - in.cone.x, 0.0001); + let a = 0.05 + 0.9 * 1.5708 * clamp((phi - in.cone.x) / span, 0.0, 1.0); + let fan_uv = clamp(vec2(0.0, 1.0) + min(r, 1.0) * vec2(sin(a), -cos(a)), vec2(0.0), vec2(1.0)); + let tb = soft_picture(fan_uv).r; + if (in.beam > 0.5) { + let inside = select(0.0, 1.0, r <= 1.0 && phi <= in.cone.y); + return vec3(tb * inside); + } + return t; +} + +@fragment +fn fs_main(in: CoronaOut) -> @location(0) vec4 { + var shape = corona_shape(in); + if (in.kind < 0.5 && in.beam < 0.5) { + // A lamp's glare ends softly at its sprite's edge whatever its bitmap does there: a + // glow picture whose border is not quite black (a model's own, some a few levels + // off) showed the whole square of the sprite round a bright lamp - the classic + // picture adds the sprite as it is, and a brightness of 2 doubles the border too. + // (the Enhanced picture rounds the sprite off, see `fs_enhanced`) + let edge = max(abs(in.uv.x - 0.5), abs(in.uv.y - 0.5)) * 2.0; + shape = shape * (1.0 - smoothstep(0.88, 1.0, edge)); + } + return vec4(in.color.rgb * shape * in.color.a, 1.0); +} + +// Enhanced graphics: the corona in the pre-exposed high-range picture - the glare of a +// lamp is drawn relative to what the eye is adapted to, brighter than white so that the +// glow filter picks it up; precipitation streaks keep the vanilla level. +@fragment +fn fs_enhanced(in: CoronaOut) -> @location(0) vec4 { + if (in.wpos.w > 0.5) { + let to_eye = normalize(camera.cam_pos.xyz - in.wpos.xyz); + let l = precip_light(in.wpos.xyz, to_eye, in.wpos.w > 1.5); + return vec4(in.color.rgb * corona_shape(in) * in.color.a * l * enh.exposure.x, 1.0); + } + // (a fog cone is lit fog, not glare: it keeps the scene's level too) + let scale = select(enh.exposure.w, enh.exposure.y, in.kind > 0.5); + // (a lamp's quad is `GLARE_K` times its sprite: the sprite's own coordinates are these + // stretched out from the middle, and the rest of the quad holds the glare) + let lamp = in.kind < 0.5 && in.beam < 0.5; + var qin = in; + if (lamp) { + qin.uv = (in.uv - vec2(0.5)) * glare_scale() + vec2(0.5); + } + var shape = corona_shape(qin); + // (taken here, in uniform control flow: how much of the sprite one pixel spans) + let r = length(qin.uv - vec2(0.5)) * 2.0; + let px = fwidth(r); + var tail = 0.0; + // (only with the glow on: off, a lamp is drawn exactly as it was before the option) + if (lamp && glare_scale() > 1.0) { + // The glare of a lens (and of an eye) round a bright source: a long tail falling as the + // cube of the distance (the near term of the CIE's glare function, 10 / theta^3), from + // the sprite's rim out to the quad's edge, where it is let go. Mist, fog and rain + // have their own halo, which the bitmap carries; in clear air this is what is left. + let wet0 = clamp(enh.fog.x * 400.0 + enh.weather.z * 0.7, 0.0, 1.0); + let k = 0.8; + tail = GLARE_TAIL * k * k * k / (r * r * r + k * k * k) * (1.0 - smoothstep(GLARE_K * 0.6, GLARE_K, r)) * (1.0 - wet0); + } + if (lamp) { + // A lamp seen through clear air is a small, very bright core with a faint ring of + // glare round it, not a lit disc as wide as its sprite (OMSI's glow bitmaps are + // flat discs with soft rims): a narrow core bright enough for the glow pass to + // spread it the way a lens does, a short falloff of glare, and a dim trace of the + // bitmap (which keeps a star's rays and a streak's shape). Mist, fog and rain + // scatter the light round the lamp, and there the full halo comes back. + let wet = clamp(enh.fog.x * 400.0 + enh.weather.z * 0.7, 0.0, 1.0); + // (the core never narrower than a pixel and a half: a far lamp stays a point of + // light, as the sprite's distance floor keeps it on the screen) + let lit = textureSampleLevel(t_corona, s_corona, vec2(0.5, 0.5), 0.0).rgb; + let w = max(0.1, px * 1.5); + let core = exp(-r * r / (w * w)) * 3.0 + exp(-r * 9.0) * 0.35; + shape = mix(core * max(lit, shape) + shape * 0.22, shape, wet); + // (round, inside the circle the sprite holds: a far lamp's sprite is a few pixels, + // the core spans it, and brighter than white even in its corners it showed the + // whole quad - a square blot of light for every distant headlamp) + shape = shape * (1.0 - smoothstep(1.0 - px, 1.0, r)); + // (the tail is added after the core is scaled, and soft-limited just under white: + // pre-exposed at night it clipped to a flat white disc as wide as the sprite - a + // plane of light - where it should fall off smoothly into the dark; the glow filter + // takes the core's HDR peak for the halo) + let halo = vec3(tail) * max(lit, vec3(0.25)) * in.color.a * scale; + let soft = vec3(0.9) * (vec3(1.0) - exp(-halo / vec3(0.9))); + return vec4(in.color.rgb * (shape * in.color.a * scale + soft), 1.0); + } + return vec4(in.color.rgb * shape * in.color.a * scale, 1.0); +} + +// Smoke ([smoke] particles): the smoke texture tinted with the particle's colour, lit by the +// scene's ambient and sun light, blended with its alpha (the particle's times the texture's), +// faded out into the ground under it (see `vs_main`). +fn smoke_color(in: CoronaOut) -> vec4 { + // upside up, as the sprite's own picture above + let t = textureSample(t_corona, s_corona, vec2(in.uv.x, 1.0 - in.uv.y)); + let light = min(camera.ambient.rgb + camera.sun_color.rgb * 0.6, vec3(1.2)); + let over_ground = select(1.0, smoothstep(0.0, in.ground.y, in.ground.x), in.ground.y > 0.0); + return vec4(in.color.rgb * t.rgb * light, clamp(t.a * in.color.a * over_ground, 0.0, 1.0)); +} + +@fragment +fn fs_smoke(in: CoronaOut) -> @location(0) vec4 { + return smoke_color(in); +} + +@fragment +fn fs_smoke_enhanced(in: CoronaOut) -> @location(0) vec4 { + let c = smoke_color(in); + return vec4(c.rgb * enh.exposure.y, c.a); +} + +// Enhanced graphics: what the enhanced main pass, the sky and the coronas share - the +// light of the physically based sky (see atmosphere.rs), in its units (1 = 10 000 lux), +// and the air between the camera and what it sees. The scene is drawn pre-exposed: +// radiance times `enh.exposure.x`, so that the half-float target keeps its precision by +// night as well as by day. +struct Enhanced { + // x pre-exposure, y the level unlit things are drawn at, z a lit window's radiance + // (pre-exposed), w how bright a light's corona is drawn + exposure: vec4, + // rgb irradiance of the sun after the clouds, w its angular radius (rad) + sun: vec4, + // irradiance from the sky and the ground: order-2 spherical harmonics, rgb + sh: array, 9>, + // rgb radiance of the ground, w the sky table's scale + ground: vec4, + // x weather fog extinction (1/m) at its base, y its height falloff (1/m), z the base + // height (render-origin relative), w clear-air extinction (1/m) at the ground + fog: vec4, + // rgb fog radiance from the light around it (the sun's part is added by angle), + // w the table scale the reflection probe was drawn with + fog_color: vec4, + // x wet roads, y snow cover, z rain, w cloud cover in front of the sun + weather: vec4, + // x mip levels of the probe, y illuminance of a light's core (maplight colour 1), + // z cabin light illuminance, w how much of the sun the clouds let through + lights: vec4, + // rgb the sun disc's irradiance before the clouds, w frame time (s) + sun_disc: vec4, + // x which term the main pass shows alone (OMSI_DEBUG_ENHANCED, 0 = the picture), + // y the puddles' F0, z the envmap photo's strength, w the tone curve's contrast + debug: vec4, + // xyz where the sky cube is drawn from, relative to the camera + eye: vec4, + // x how bright an LED panel's dots burn (0 = off), y whether the LED panels' `\S:n` + // masks keep their mip chain (0: at full resolution, the dots stay visible when small), z 1 + // when lights glare and glow in the night air (the settings' `light_glow`) + led: vec4, + // xyz towards the moon, w its angular radius (rad) + moon: vec4, + // rgb the moon disc's irradiance before the clouds, w how much of the starry sky shows + moon_disc: vec4, + // rgb the sun's irradiance at 1400, 2100 and 2800 m (the cumulus layer) and 7000 m + // (the high thin layer), through the atmosphere from up there + cloud_sun: array, 4>, + // rgb the moonlight on a surface facing the moon (after the clouds), w 1 while the + // shadow maps are the moon's + moon_light: vec4, + // the condensation on the player's bus's panes (optical depths): windscreen, sides, + // rear, and how far the defroster has cleared the windscreen (0..1; omsi-app + // condensation.rs) + condensation: vec4, + // x the cumulus layer's base, y its top (m over the ground), z the altocumulus cover, + // w the storm's activity + layers: vec4, + // the lightning of this frame: x the light it throws on a surface facing it (1 = 10 000 + // lux), yz towards it (horizontal unit vector), w its elevation (rad) + flash: vec4, + // xyz towards the flash (unit vector), w how bright its channel is + flash2: vec4, + // x a number the channel's shape is drawn from + flash3: vec4, + // the clouds' shadow field (cloud_field.rs): xy its middle in cloud space, z one over its + // width, w 1 when there is one + cloud_f1: vec4, + // xy what takes a world point to cloud space, z the height of the plane it is taken on, + // w the share of the sun the main pass has taken off already for the clouds over the camera + cloud_f2: vec4, + // the player's bus's pitch and roll: sin, cos of each (its panes' condensation sits on + // the glass on a slope, `pane_local`) + pane_tilt: vec4, + // Slots of the weather overhaul, one owner each (zero until it fills them): + // the volumetric clouds, the volumetric fog, the precipitation, the bus's panes, the + // surfaces' PBR and the ray tracing, and two spare. + clouds_ext: vec4, + clouds_ext2: vec4, + vol_fog: vec4, + vol_fog2: vec4, + precip_ext: vec4, + glass_ext: vec4, + // (pbr_ext: x the share of the sun's light that still comes as a beam - the rest the + // clouds scatter, `sun_scattered` - y 1 when x is set) + pbr_ext: vec4, + rt_ext: vec4, +}; +@group(0) @binding(11) var enh: Enhanced; +@group(0) @binding(13) var s_lin: sampler; +@group(0) @binding(14) var t_sky_lut: texture_2d; + +const PI: f32 = 3.14159265; + +// Irradiance from the sky and the ground on a surface facing n. +fn sh_irradiance(n: vec3) -> vec3 { + let c = enh.sh; + let e = c[0].rgb * 0.282095 + + c[1].rgb * (0.488603 * n.y) + c[2].rgb * (0.488603 * n.z) + c[3].rgb * (0.488603 * n.x) + + c[4].rgb * (1.092548 * n.x * n.y) + c[5].rgb * (1.092548 * n.y * n.z) + + c[6].rgb * (0.315392 * (3.0 * n.z * n.z - 1.0)) + c[7].rgb * (1.092548 * n.x * n.z) + + c[8].rgb * (0.546274 * (n.x * n.x - n.y * n.y)); + return max(e, vec3(0.0)); +} + +// The lightning's light on a surface facing n: half of it from the cloud overhead and +// round it (a hemisphere), half along the way to the flash itself. +fn flash_irradiance(n: vec3) -> vec3 { + if (enh.flash.x <= 0.0) { + return vec3(0.0); + } + return vec3(0.80, 0.90, 1.0) * enh.flash.x * (0.5 * (0.5 + 0.5 * n.z) + 0.5 * max(dot(n, enh.flash2.xyz), 0.0)); +} + +// Sky radiance towards d (unscaled: times enh.ground.w is the radiance). The table runs +// over the azimuth from the sun (0..π) and the elevation (denser at the horizon). +// The sky table's texture: the table (32 x 48) in its corner and the clouds' shadow field +// (192 x 192) beside it, one texel clear (cloud_field.rs `SKY_TEX_W`, `FIELD_X0`). +const SKY_TEX: vec2 = vec2(225.0, 192.0); +const SKY_TABLE: vec2 = vec2(32.0, 48.0); +const FIELD_ORIGIN: f32 = 33.0; +const FIELD_N: f32 = 192.0; + +fn sky_table_raw(d: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let ls = length(s.xy); + let ld = length(d.xy); + var az = 0.0; + if (ls > 1e-4 && ld > 1e-4) { + az = acos(clamp(dot(s.xy / ls, d.xy / ld), -1.0, 1.0)); + } + let el = asin(clamp(d.z, -1.0, 1.0)); + let v = 0.5 + 0.5 * sign(el) * sqrt(min(abs(el) / 1.5707963, 1.0)); + // (kept a half texel inside the table: its neighbours in the texture are not the sky) + let tx = clamp(vec2(az / PI, v) * SKY_TABLE, vec2(0.5), SKY_TABLE - vec2(0.5)); + return textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).rgb; +} + +// The share of the sun that reaches the point p through the clouds, as against what the main +// pass's sun (`enh.sun`) already has for the camera's own place: the cumulus layer's shadow +// field read where the sun's way through p meets the layer's middle. 1 where there is no +// field, beyond its edge and where the sun is low (the camera's own factor stands there). +fn cloud_shadow_ratio(p: vec3) -> f32 { + let s = camera.sun_dir.xyz; + if (enh.cloud_f1.w < 0.5 || s.z < 0.06) { + return 1.0; + } + let cs = p.xy + s.xy / s.z * (enh.cloud_f2.z - p.z) + enh.cloud_f2.xy; + let uv = (cs - enh.cloud_f1.xy) * enh.cloud_f1.z + vec2(0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + let w = 1.0 - smoothstep(0.36, 0.48, edge); + if (w <= 0.0) { + return 1.0; + } + let tx = vec2(FIELD_ORIGIN, 0.0) + clamp(uv * FIELD_N, vec2(0.5), vec2(FIELD_N - 0.5)); + let f = textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).r; + let ratio = min(f / max(enh.cloud_f2.w, 0.02), 6.0); + return mix(1.0, ratio, w); +} + +fn sky_table(d: vec3) -> vec3 { + return sky_table_raw(d) * enh.ground.w; +} + +// Henyey-Greenstein phase function. +fn hg_phase(c: f32, g: f32) -> f32 { + let g2 = g * g; + return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * c, 1e-4), 1.5)); +} + +// Optical depth of an exponentially thinning layer (extinction sigma at height 0, falling +// off with k per metre) along a straight path of length dist from height h0 to h1. +fn layer_depth(sigma: f32, k: f32, h0: f32, h1: f32, dist: f32) -> f32 { + if (sigma <= 0.0) { + return 0.0; + } + let a = max(h0, 0.0); + let b = max(h1, 0.0); + let dh = b - a; + if (abs(k * dh) < 1e-3) { + return sigma * dist * exp(-k * 0.5 * (a + b)); + } + return sigma * dist * (exp(-k * a) - exp(-k * b)) / (k * dh); +} + +// The air between the camera and a point dist metres away in direction dir (from the +// camera), at heights h0 (camera) and h1 (point) above the fog's base: rgb the light it +// scatters towards the camera (radiance), a what it lets through of the point. +fn air(dir: vec3, dist: f32, h0: f32, h1: f32) -> vec4 { + return air_of(dir, dist, h0, h1, 1.0); +} + +// The same with the clear air's share scaled (0 for the sky, whose table holds it already). +fn air_of(dir: vec3, dist: f32, h0: f32, h1: f32, clear: f32) -> vec4 { + let tau_fog = layer_depth(enh.fog.x, enh.fog.y, h0, h1, dist); + let tau_air = layer_depth(enh.fog.w * clear, 1.0 / 1500.0, h0, h1, dist); + let tau = tau_fog + tau_air; + let t = exp(-tau); + if (tau < 1e-5) { + return vec4(0.0, 0.0, 0.0, 1.0); + } + // clear air takes on the sky's own colour at the horizon in this direction (which + // already holds the glow round the sun); a weather fog glows with the light around it + // and brighter towards the sun + let horizon = sky_table(normalize(vec3(dir.x, dir.y, max(dir.z, 0.0) * 0.3 + 0.03))); + let fog_in = enh.fog_color.rgb + enh.sun.rgb * hg_phase(dot(dir, camera.sun_dir.xyz), 0.55) * 0.9; + let inscatter = mix(horizon, fog_in, tau_fog / tau); + return vec4(inscatter * (1.0 - t), t); +} + +struct PointLight { + pos: vec4, + color: vec4, + dir: vec4, + extra: vec4, +}; +@group(0) @binding(3) var lights: array; +@group(0) @binding(4) var grid: array; +const CELL_CAP: u32 = 32u; + +// `beam_shadow.wgsl` for the shaders without the lamp shadow tiles: nothing stands in a beam. +fn beam_tile(li: u32, l: PointLight) -> u32 { + return 0xffffffffu; +} + +fn beam_reaches(k: u32, x: vec3) -> f32 { + return 1.0; +} + +// Enhanced graphics: the lamps as the scene and the sky share them - a headlamp's beam +// and the light the weather's fog scatters from the lamps towards the camera (needs the +// point lights, their grid and `camera.light_grid`). + +// A headlamp's intensity towards `t` (from the lamp) by the angles of a road lamp, not +// around its axis: wide across, brightest just under the lamp's horizon where it reaches +// far down the road, weak straight down, and with a low beam a sharp cut-off above it. +// `dir` is the lamp's axis in its vehicle's floor: its rise tilts the horizon with the +// vehicle, up a ramp and down (#1897). +fn headlamp(t: vec3, dir: vec3, low: bool) -> f32 { + let fwd = normalize(dir.xy + vec2(1e-6, 0.0)); + let ahead = dot(t.xy, fwd); + if (ahead <= 0.0) { + return 0.0; + } + let across = abs(t.x * fwd.y - t.y * fwd.x) / ahead; + let wide = 0.12 * smoothstep(1.0, 0.45, across) + 0.88 * exp(-across * across / 0.06); + let rise = t.z / max(length(t.xy), 1e-3); + let tilt = dir.z / max(length(dir.xy), 1e-3); + // (the tangent of the angle under that horizon) + let drop = (tilt - rise) / max(1.0 + rise * tilt, 1e-3); + // full out to where the road is 0.06 under the lamp's horizon, then less as the cube of + // the drop and a little more: the road is lit evenly from the bumper on, a little + // brighter as far as the beam reaches, and not as one hot pool where its axis lands + var up = min(1.0, pow(0.06 / max(abs(drop), 1e-4), 3.4)); + if (low) { + up = up * smoothstep(-0.012, 0.025, drop); + return wide * up; + } + // a full beam reaches far: a narrow, bright core along the lamp's horizon + let hot = exp(-across * across / 0.012 - drop * drop / 0.0004); + return wide * up + 6.0 * hot; +} + +// The lamps' light the weather's fog scatters towards the camera (radiance, not +// pre-exposed): single scattering along the view ray from `start` to `len` metres in +// direction `d` - the glow round a street lamp in the mist, its cone under it, a bus's +// beams reaching ahead into the fog or the falling snow. The droplets scatter strongly +// forward (fog and cloud droplets of some ten micrometres: g about 0.8), so the glow is +// brightest looking towards a lamp and a cone shows faintly from the side. +// +// Each lamp is taken once, over the whole stretch of the ray within its reach, in the grid +// cell the ray's point nearest to it lies in (the ray's cells are walked through; every +// cell lists the lamps reaching into it). Along a straight ray past a point source, with +// t - t0 = h tan(phi) (h the ray's distance from the lamp, t0 where it passes nearest), +// the inverse square cancels against the path element: dt / r^2 = dphi / h, and what is +// left is the phase function over the angle, cos(theta) = -sin(phi) - a smooth integral +// taken with five Gauss-Legendre nodes, at each of which a spot's or a headlamp's beam is +// asked how much it sends that way. The fog's extinction dims the light on its way from +// the lamp and to the camera (taken at the nearest point). A beam's light, which reaches +// only part of the way, is summed along the ray instead, its steps staggered by `jitter`. +// The droplets' phase function: a strong forward peak and the back-scattered light a +// fog's lidar ratio of some 18 sr asks for (0.055 per steradian straight back) - a single +// Henyey-Greenstein lobe of g 0.8 gave a tenth of it, and a bus's own headlights lit no +// wall of fog in front of the driver. Two lobes, 0.9 of g 0.85 and 0.1 of g -0.5. +fn fog_phase(c: f32) -> f32 { + return 0.9 * hg_phase(c, 0.85) + 0.1 * hg_phase(c, -0.5); +} +const AIRLIGHT_CELLS: u32 = 16u; + +// The clear night air's own haze, which lights a lamp's halo and a headlamp's beam as the fog's +// droplets do, only fainter: the lowest hundred metres of a city's air hold its dust, exhaust +// and humidity at several times the column's average aerosol extinction (`enh.fog.w`), 1-3e-4 +// per metre (a visibility of 15-40 km). A lamp then has a soft glow round it and a low beam +// a faint cone, as in any night photograph, instead of a lit disc on a black ground. +const GROUND_HAZE_GAIN: f32 = 8.0; + +// `droplets`: how much of the weather's extinction scatters like fog (see `FogLampUniform`). +fn lamp_airlight(c: vec3, d: vec3, start: f32, len: f32, jitter: f32, droplets: f32) -> vec3 { + var sum = vec3(0.0); + let sigma0 = enh.fog.x * droplets + enh.fog.w * GROUND_HAZE_GAIN * enh.led.z; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (sigma0 < 4e-5 || cell <= 0.0 || side == 0u || len <= start) { + return sum; + } + // (past a few optical depths nothing comes back) + let end = min(len, start + 4.0 / sigma0); + let gx = array(-0.9061798, -0.5384693, 0.0, 0.5384693, 0.9061798); + let gw = array(0.2369269, 0.4786287, 0.5688889, 0.4786287, 0.2369269); + // the walk through the grid's cells along the ray's plan + let o = (c.xy - camera.light_grid.xy) / cell; + let dd = d.xy / cell; + var ix = i32(floor(o.x + dd.x * start)); + var iy = i32(floor(o.y + dd.y * start)); + let sx = select(-1, 1, dd.x >= 0.0); + let sy = select(-1, 1, dd.y >= 0.0); + let inv_x = select(1e9, 1.0 / abs(dd.x), abs(dd.x) > 1e-7); + let inv_y = select(1e9, 1.0 / abs(dd.y), abs(dd.y) > 1e-7); + var tx = select((f32(ix) - o.x) / dd.x, (f32(ix + 1) - o.x) / dd.x, dd.x >= 0.0); + var ty = select((f32(iy) - o.y) / dd.y, (f32(iy + 1) - o.y) / dd.y, dd.y >= 0.0); + if (abs(dd.x) <= 1e-7) { tx = 1e9; } + if (abs(dd.y) <= 1e-7) { ty = 1e9; } + var t = start; + for (var k = 0u; k < AIRLIGHT_CELLS; k = k + 1u) { + if (t >= end) { + break; + } + let t_out = min(min(tx, ty), end); + if (ix >= 0 && iy >= 0 && ix < i32(side) && iy < i32(side)) { + let base = (u32(iy) * side + u32(ix)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let to_l = l.pos.xyz - c; + let t0 = dot(to_l, d); + // the ray's point nearest to the lamp: taken in this cell only + let tc = clamp(t0, start, end); + if (tc < t || tc > t_out) { + continue; + } + let range = l.extra.w; + let h = length(to_l - d * t0); + if (h >= range) { + continue; + } + // A beam (a headlamp, a spot) is lit in the weather's fog only: its cone is a sliver of + // sixteen jittered steps at half size, which the fog's density hides and the clear + // air's haze shows as shimmer and soap. The lamps' halo alone has the ground haze. + let beam_lamp = l.extra.z != 0.0 || l.dir.w > -1.5; + let fog_sigma = enh.fog.x * droplets; + if (beam_lamp && enh.fog.x < 2e-4) { + continue; + } + let s0 = select(sigma0, fog_sigma, beam_lamp); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + // (inside its core a lamp is as bright as at the core's edge) + let hh = max(h, select(core * 0.7, 0.4, l.extra.z != 0.0)); + let w = sqrt(range * range - h * h); + let ta = max(start, t0 - w); + let tb = min(end, t0 + w); + if (tb <= ta) { + continue; + } + var acc = 0.0; + var half = 0.0; + if (l.extra.z != 0.0 || l.dir.w > -1.5) { + // a beam (a headlamp, a spot): lit only where its cone or cut-off lets + // it - a sliver of the angles the lamp is seen under, which the five + // nodes missed. Sixteen even steps over that angle instead (dphi = + // h dt / r^2: the inverse square is in the step). (Sixteen even steps + // along the way put the few next to the lamp, where nearly all of its + // light is, a metre or more apart: the pixels' staggered steps came + // out as a coarse checker in the fog round every headlamp.) + let pa = atan((ta - t0) / hh); + let dphi = (atan((tb - t0) / hh) - pa) / 16.0; + let tile_k = beam_tile(li, l); + for (var q = 0u; q < 16u; q = q + 1u) { + let tq = t0 + hh * tan(pa + (f32(q) + jitter) * dphi); + let to = l.pos.xyz - (c + d * tq); + let ld = to * inverseSqrt(max(dot(to, to), 1e-6)); + var beam = 0.0; + if (l.extra.z != 0.0) { + beam = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0); + } else { + beam = smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } + // (the map is looked at only where the beam shines at all, and only for + // the few lamps that have a tile: no shadows, no tile, no tap) + var reach = 1.0; + if (beam > 0.002 && tile_k < 44u) { + reach = beam_reaches(tile_k, c + d * tq); + } + acc = acc + beam * reach * fog_phase(dot(ld, d)) * dphi; + } + half = 1.0; + } else { + let pa = atan((ta - t0) / hh); + let pb = atan((tb - t0) / hh); + half = 0.5 * (pb - pa); + let mid = 0.5 * (pa + pb); + let tile_p = beam_tile(li, l); + for (var q = 0u; q < 5u; q = q + 1u) { + let phi = mid + half * gx[q]; + let tq = t0 + hh * tan(phi); + let ld = normalize(l.pos.xyz - (c + d * tq)); + var beam = 1.0; + if (l.dir.z < -0.5) { + // (a lamp in a housing: see `lamp_light`) + beam = 0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z); + } + // (a lamp with a shadow map: what stands between it and the air + // keeps its light out of that air, as the headlamps' beams) + var reach = 1.0; + if (beam > 0.002 && tile_p < 44u) { + reach = beam_reaches(tile_p, c + d * tq); + } + acc = acc + gw[q] * beam * reach * fog_phase(-sin(phi)); + } + } + // a lamp's irradiance is core^2 / r^2 of its colour's (a headlamp's 1 / r^2) + let strength = select(core * core, 1.0, l.extra.z != 0.0); + let xc = c + d * tc; + let sigma = s0 * exp(-enh.fog.y * max(xc.z - enh.fog.z, 0.0)); + let dl = distance(xc, l.pos.xyz); + let atten = exp(-layer_depth(s0, enh.fog.y, c.z - enh.fog.z, xc.z - enh.fog.z, tc - start) - sigma * dl); + sum = sum + l.color.rgb * (l.color.w * strength * acc * half / hh * sigma * atten); + } + } + t = t_out; + if (tx < ty) { + tx = tx + inv_x; + ix = ix + sx; + } else { + ty = ty + inv_y; + iy = iy + sy; + } + } + return sum * enh.lights.y; +} + +// Enhanced: the light a raindrop or a snowflake sends towards the eye - what it scatters of +// the sky's light, the sun's and the lamps' round it, the drop's strongly forward (a +// streak flashes against a lamp seen through the rain, and is next to invisible in the +// dark between the lamps), the flake's nearly every way. (Drawn at the display's level +// whatever the light, the flakes of a snowfall at night shone white in the dark, far from +// any lamp.) +fn precip_light(x: vec3, to_eye: vec3, snow: bool) -> vec3 { + // the sky's and the ground's light round it, and the sun's on a small sphere + var e = enh.fog_color.rgb * (PI / 0.9) + enh.sun.rgb * 0.25; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell > 0.0 && side > 0u) { + let f = (x.xy - camera.light_grid.xy) / cell; + let gx = i32(floor(f.x)); + let gy = i32(floor(f.y)); + if (gx >= 0 && gy >= 0 && gx < i32(side) && gy < i32(side)) { + let base = (u32(gy) * side + u32(gx)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let dl = l.pos.xyz - x; + let dist2 = dot(dl, dl); + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let ld = dl * inverseSqrt(max(dist2, 1e-6)); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var k = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + if (l.extra.z != 0.0) { + k = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + k = k * smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } else if (l.dir.z < -0.5) { + k = k * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + // (the scattering towards the eye relative to an even one: a drop's light + // goes on forwards, a flake's every way. The angle is the one between the + // light's way from the lamp, -ld, and on to the eye: taken against -to_eye + // it put the forward peak behind the drop, and the drops in a bus's own + // beams, seen from behind the lamps, shone a hundred times too bright as + // white streaks down the road ahead) + let c = dot(-ld, to_eye); + let lobe = select(fog_phase(c), 0.7 * hg_phase(c, 0.3) + 0.3 / (4.0 * PI), snow) * 4.0 * PI; + e = e + l.color.rgb * l.color.w * enh.lights.y * k * lobe; + } + } + } + return e / PI; +} + diff --git a/crates/mx/tests/openomsi/fog_lamps.wgsl b/crates/mx/tests/openomsi/fog_lamps.wgsl new file mode 100644 index 0000000..1b3c90a --- /dev/null +++ b/crates/mx/tests/openomsi/fog_lamps.wgsl @@ -0,0 +1,907 @@ +// Enhanced graphics: the light the air scatters towards the camera that the main pass +// leaves out - the lamps' in the weather's fog, rain or falling snow (`lamp_airlight` in +// lamp_air.wgsl) and the sun's shafts between the shadows (`sun_shafts`) - added onto the +// drawn picture before its glow and its metering. Once per pixel over the depth prepass: worked out in +// the main pass it was paid again for every layer drawn over a pixel (painted ground, +// decals), several milliseconds a frame in a foggy night. +struct Camera { + view_proj: mat4x4, + cam_pos: vec4, + // (kept in lockstep with `CameraUniform` in lib.rs, as sky.wgsl's) + world_origin: vec4, + sun_dir: vec4, + ambient: vec4, + fog: vec4, + sun_color: vec4, + sky_color: vec4, + light_grid: vec4, + sky: vec4, + cam_right: vec4, + cam_up: vec4, + clouds: vec4, + light_view_proj: mat4x4, + light_view_proj_far: mat4x4, + shadow: vec4, + post: vec4, + inside_a: vec4, + inside_b: vec4, + inside_c: vec4, + flags: vec4, + light_view_proj_close: mat4x4, + wind: vec4, + lamp_view_proj: array, 56>, + lamp_atlas: vec4, + tree_wind: vec4, + inside2_a: vec4, + inside2_b: vec4, + inside2_c: vec4, + cookies: array, 8>, + cabin_lamps: array, 4>, + // x: the textures' mip bias (FSR 1: negative, see `CameraUniform::lod`) + lod: vec4, + // (the classic picture's headlight, `CameraUniform::spot`: unread here) + spot: array, 4>, +}; +@group(0) @binding(0) var camera: Camera; + +struct FogLampParams { + // clip space (reversed Z) back to the render-origin relative world + inv_view_proj: mat4x4, + // xy the picture's size in pixels, z 1: the sun's glare is added (2: it is all that is + // added, the half-size result holds only the sun's row), w the share of the weather's + // extinction that is mist and fog (not rain) + size: vec4, +}; +@group(1) @binding(0) var fp: FogLampParams; +@group(1) @binding(1) var t_depth: texture_depth_2d; +// the half-size result (rgb pre-exposed light, a the distance it was worked out to) +@group(1) @binding(2) var t_fog: texture_2d; + +struct FogVsOut { + @builtin(position) clip: vec4, +}; + +@vertex +fn vs_fog_lamps(@builtin(vertex_index) i: u32) -> FogVsOut { + let x = f32(i32(i & 1u) * 4 - 1); + let y = f32(i32(i >> 1u) * 4 - 1); + var out: FogVsOut; + out.clip = vec4(x, y, 0.0, 1.0); + return out; +} + +// The camera, the direction through a full-size pixel position and the distance to what +// the prepass holds there (3 km for the sky). +fn pixel_ray(at: vec2) -> vec4 { + let dims = vec2(textureDimensions(t_depth)); + let px = clamp(vec2(at), vec2(0), dims - vec2(1)); + let d = textureLoad(t_depth, px, 0); + let ndc = vec2(at.x / fp.size.x * 2.0 - 1.0, 1.0 - at.y / fp.size.y * 2.0); + let c = camera.cam_pos.xyz; + let mid = fp.inv_view_proj * vec4(ndc, 0.5, 1.0); + let dir = normalize(mid.xyz / mid.w - c); + var len = 3000.0; + if (d > 0.0) { + let h = fp.inv_view_proj * vec4(ndc, d, 1.0); + len = distance(h.xyz / h.w, c); + } + return vec4(dir, len); +} + +// The sun's shadow maps (shader.wgsl's bindings and constants). +@group(0) @binding(5) var t_shadow: texture_depth_2d; +@group(0) @binding(6) var s_shadow: sampler_comparison; +@group(0) @binding(7) var t_shadow_far: texture_depth_2d; +const SHAFT_DEPTH_RANGE: f32 = 2199.0; +const SHAFT_STEPS: u32 = 16u; +// how far the shafts are followed in the dense steps (the near cascade's reach, a little less) +const SHAFT_NEAR: f32 = 180.0; +// and, past it, in a few sparse ones to the far map's reach (the beams of a misty avenue, or +// a low sun between the blocks, reach farther than the first hundred metres) +const SHAFT_FAR_STEPS: u32 = 4u; +const SHAFT_REACH: f32 = 420.0; +// how far the sky's gaps are followed (the haze beyond that is the table's, lit as a whole) and in +// how many steps growing by a fixed ratio +const SKY_SHAFT_REACH: f32 = 7000.0; +const SKY_SHAFT_STEPS: u32 = 8u; + +// Whether the sun reaches a point in the air (1) or a house or a crown stands between (0). +fn sun_reaches(x: vec3) -> f32 { + let lp = camera.light_view_proj * vec4(x, 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (max(abs(uv.x - 0.5), abs(uv.y - 0.5)) < 0.48 && lp.z >= 0.0 && lp.z <= 1.0) { + return textureSampleCompareLevel(t_shadow, s_shadow, vec2(uv.x * 0.5, uv.y), lp.z - 0.15 / SHAFT_DEPTH_RANGE); + } + let fp2 = camera.light_view_proj_far * vec4(x, 1.0); + let fuv = vec2(fp2.x * 0.5 + 0.5, 0.5 - fp2.y * 0.5); + if (fuv.x < 0.0 || fuv.x > 1.0 || fuv.y < 0.0 || fuv.y > 1.0 || fp2.z < 0.0 || fp2.z > 1.0) { + return 1.0; + } + // (the far map takes the top of its texture, see shader.wgsl `shadow_pcf_far`) + return textureSampleCompareLevel(t_shadow_far, s_shadow, vec2(fuv.x, fuv.y * (1.0 / (camera.shadow.y * camera.lamp_atlas.z))), fp2.z - 0.6 / SHAFT_DEPTH_RANGE); +} + +fn sun_reaches_close(x: vec3) -> f32 { + let lp = camera.light_view_proj_close * vec4(x, 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (camera.flags.w <= 0.0 || max(abs(uv.x - 0.5), abs(uv.y - 0.5)) >= 0.48 || lp.z < 0.0 || lp.z > 1.0) { + return sun_reaches(x); + } + let s = select(1.0, camera.post.w, camera.post.w > 0.0); + return textureSampleCompareLevel(t_shadow, s_shadow, vec2(0.5 + uv.x * s * 0.5, uv.y * s), lp.z - 0.05 / SHAFT_DEPTH_RANGE); +} + +// Shafts of sunlight - crepuscular rays: the air between the camera and what it sees +// scatters the sun towards the eye wherever the sun reaches it, and not in the shadow of a +// house or a tree. The picture's air (`air` in enhanced_common.wgsl) holds that light as +// if the sun reached the air everywhere; along the first stretch of the ray, which the +// shadow maps cover, what lies in shadow is taken out again here (a negative radiance): +// lit and dark shafts through a hazy evening, a misty morning wood, a dusty street. The +// air scatters the way `air` has it - the weather's fog with g 0.55, the clear air's haze +// and dust forward with g 0.7 (its Rayleigh part is small near the ground). +fn sun_shafts(c: vec3, d: vec3, len: f32, jitter: f32) -> vec3 { + let s = camera.sun_dir.xyz; + let e_sun = enh.sun.rgb; + // (the clouds' shadow field: the shafts through a broken sky, followed to kilometres) + let sky_gaps = enh.cloud_f1.w > 0.5 && s.z >= 0.06; + let shadows = camera.shadow.x > 0.5; + // (with the volumetric fog on, its march has the shadows in the air already: + // volumetric_fog.wgsl, enh.vol_fog.x) + if (enh.vol_fog.x > 0.5 || (!shadows && !sky_gaps) || s.z <= 0.0 || max(e_sun.r, e_sun.g) < 1e-4) { + return vec3(0.0); + } + let end = min(len, SHAFT_NEAR); + let dt = end / f32(SHAFT_STEPS); + let far_len = max(min(len, SHAFT_REACH) - SHAFT_NEAR, 0.0); + let dt_far = far_len / f32(SHAFT_FAR_STEPS); + let cos_t = dot(s, d); + let p_fog = hg_phase(cos_t, 0.55) * 0.9; + let p_air = hg_phase(cos_t, 0.7); + let h0 = c.z - enh.fog.z; + // the clouds' part reaches on, out to the haze's own horizon: from the sparse steps' + // end, in steps growing by a fixed ratio + let sky_end = select(SHAFT_REACH, min(len, SKY_SHAFT_REACH), sky_gaps); + // (the most the shadows could take out along the way, on the screen: where that is + // too little to see - most of the picture, looking away from the sun - nothing is done) + let most = (enh.fog.x * p_fog + enh.fog.w * p_air) * max(e_sun.r, e_sun.g) * max(end, select(0.0, sky_end, sky_gaps)) * enh.exposure.x; + if (most < 0.004) { + return vec3(0.0); + } + var shade = vec3(0.0); + for (var i = 0u; i < SHAFT_STEPS + SHAFT_FAR_STEPS; i = i + 1u) { + let far = i >= SHAFT_STEPS; + if (far && far_len <= 0.0) { + break; + } + let t = select((f32(i) + jitter) * dt, SHAFT_NEAR + (f32(i - SHAFT_STEPS) + jitter) * dt_far, far); + let w = select(dt, dt_far, far); + let x = c + d * t; + var lit = 1.0; + if (shadows) { + lit = sun_reaches(x); + } + if (sky_gaps) { + lit = lit * cloud_shadow_ratio(x); + } + // (a point the cloud lets more sun through than the camera's own place gets adds light) + if (lit >= 0.999 && lit <= 1.001) { + continue; + } + let h = max(x.z - enh.fog.z, 0.0); + let s_fog = enh.fog.x * exp(-enh.fog.y * h); + let s_air = enh.fog.w * exp(-h / 1500.0); + let tau = layer_depth(enh.fog.x, enh.fog.y, h0, h, t) + layer_depth(enh.fog.w, 1.0 / 1500.0, h0, h, t); + shade = shade + vec3((1.0 - lit) * (s_fog * p_fog + s_air * p_air) * exp(-tau) * w); + } + // the part beyond the shadow maps: only the clouds' shadow is known there + if (sky_gaps && sky_end > SHAFT_REACH) { + let r = pow(sky_end / SHAFT_REACH, 1.0 / f32(SKY_SHAFT_STEPS)); + var t0 = SHAFT_REACH; + for (var i = 0u; i < SKY_SHAFT_STEPS; i = i + 1u) { + let t1 = t0 * r; + let t = t0 + (t1 - t0) * jitter; + let x = c + d * t; + let lit = cloud_shadow_ratio(x); + if (lit < 0.999 || lit > 1.001) { + let h = max(x.z - enh.fog.z, 0.0); + let s_fog = enh.fog.x * exp(-enh.fog.y * h); + let s_air = enh.fog.w * exp(-h / 1500.0); + let tau = layer_depth(enh.fog.x, enh.fog.y, h0, h, t) + layer_depth(enh.fog.w, 1.0 / 1500.0, h0, h, t); + shade = shade + vec3((1.0 - lit) * (s_fog * p_fog + s_air * p_air) * exp(-tau) * (t1 - t0)); + } + t0 = t1; + } + } + return -shade * e_sun; +} + +// at half size: one ray per four pixels +@fragment +fn fs_fog_lamps(in: FogVsOut) -> @location(0) vec4 { + // (the texture's last row: how much of the sun is seen, worked out once for the frame + // in its first texel) + // (t_fog is not this pass's target: the row is the one under the half picture) + if (i32(in.clip.y) >= i32(ceil(fp.size.y * 0.5))) { + var seen = 0.0; + if (i32(in.clip.x) == 0 && fp.size.z > 0.5 && camera.sun_dir.z > -0.02) { + seen = sun_seen(camera.cam_pos.xyz, camera.sun_dir.xyz); + } + return vec4(seen, 0.0, 0.0, 0.0); + } + let r = pixel_ray(floor(in.clip.xy) * 2.0 + vec2(0.5)); + let q = vec2(in.clip.xy) & vec2(1); + let ign = (f32(q.x * 2 + (q.x ^ q.y)) + 0.5) * 0.25; + // (the lamps' halo and cones only from the mist's and fog's droplets: fp.size.w) + let l = (lamp_airlight(camera.cam_pos.xyz, r.xyz, 0.0, r.w, ign, fp.size.w) + sun_shafts(camera.cam_pos.xyz, r.xyz, r.w, ign)) * enh.exposure.x; + return vec4(clamp(l, vec3(-4000.0), vec3(4000.0)), r.w); +} + +// How much of the sun's disc is seen (0..1): houses, trees and the bus in front of it +// are in the depth prepass (the clouds and the fog are in `enh.sun` already). +fn sun_seen(c: vec3, s: vec3) -> f32 { + let r = enh.sun.w; + let up0 = select(vec3(0.0, 0.0, 1.0), vec3(1.0, 0.0, 0.0), abs(s.z) > 0.9); + let a = normalize(cross(s, up0)); + let b = cross(s, a); + var seen = 0.0; + var n = 0.0; + for (var k = 0; k < 13; k = k + 1) { + var o = vec2(0.0); + if (k > 0) { + let ang = f32(k) * 2.3999632; + o = vec2(cos(ang), sin(ang)) * sqrt(f32(k) / 12.0) * 0.9; + } + let dir = normalize(s + (a * o.x + b * o.y) * r); + let clip = camera.view_proj * vec4(c + dir * 1000.0, 1.0); + let ndc = clip.xy / max(clip.w, 1e-6); + n = n + 1.0; + if (clip.w <= 0.0 || abs(ndc.x) > 1.0 || abs(ndc.y) > 1.0) { + // Beyond the picture's edge the prepass knows nothing: whether the eye stands in + // the shadow of anything the sun's shadow maps hold (without shadows: seen). + // What stood at the edge was taken before - a house or a pole reaching the edge + // as the camera turned put out the whole veil at once, and sky put it back, a + // sheet of light over the picture switched off and on. + if (camera.shadow.x > 0.5) { + seen = seen + sun_reaches_close(c + dir * 0.3); + } else { + seen = seen + 1.0; + } + continue; + } + let px = vec2((ndc.x * 0.5 + 0.5) * fp.size.x, (0.5 - ndc.y * 0.5) * fp.size.y); + let dims = vec2(textureDimensions(t_depth)); + let q = clamp(vec2(px), vec2(0), dims - vec2(1)); + seen = seen + select(0.0, 1.0, textureLoad(t_depth, q, 0) <= 0.0); + } + return seen / n; +} + +// Glare: the light a lens scatters round a bright source - the sun seen directly washes out +// what is right beside it. The picture is a camera's, and the player compares it with +// photographs: a good lens' stray light falls off as the near term of the CIE's glare +// function, 10/theta^3 per unit of the source's illuminance (theta in degrees, CIE +// 146:2002), a glow of a few degrees. The eye's own share - the wide veil of 5/theta^2 and +// more that the vitreous and the eye's wall add, its ciliary streaks and its lenticular +// halo - was drawn as well and made a white blot ten degrees round the sun of a clear day, +// "the sun is too large" (#2400): a photograph shows none of it. +fn sun_glare(dir: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + if (max(enh.sun.r, enh.sun.g) < 1e-5 || s.z < -0.02) { + return vec3(0.0); + } + let cos_t = clamp(dot(dir, s), -1.0, 1.0); + // (cos 100 degrees: past it there is no veil, and the arc cosine is not needed) + if (cos_t < -0.17364818) { + return vec3(0.0); + } + let theta = max(degrees(acos(cos_t)), 0.25); + let seen = textureLoad(t_fog, vec2(0, i32(textureDimensions(t_fog).y) - 1), 0).r; + if (seen <= 0.0) { + return vec3(0.0); + } + return enh.sun.rgb * seen * (10.0 / (theta * theta * theta)); +} + +// at full size, added onto the picture: the four nearest half-size rays, each as far as +// it was worked out to a distance like this pixel's (the light in front of a near pole +// is not the light in front of the houses behind it) +@fragment +fn fs_fog_composite(in: FogVsOut) -> @location(0) vec4 { + let ray = pixel_ray(in.clip.xy); + var air_light = vec3(0.0); + if (fp.size.z < 1.5) { + air_light = gathered_air_light(in.clip.xy, ray.w); + } + // the eye's glare from the sun, on top of everything (fp.size.z: on) + var glare = vec3(0.0); + if (fp.size.z > 0.5) { + glare = sun_glare(ray.xyz) * enh.exposure.x; + } + return vec4(air_light + min(glare, vec3(4000.0)), 0.0); +} + +fn gathered_air_light(at: vec2, len: f32) -> vec3 { + let hp = at * 0.5 - vec2(0.5); + let base = vec2(floor(hp)); + let f = hp - floor(hp); + // (the last row is the sun's, see `fs_fog_lamps`) + let hd = vec2(textureDimensions(t_fog)) - vec2(1, 2); + // (not one of the sixteen half-size rays holds any light: no lamp's cone and no shaft + // here - most of a picture in clear air - and the weighted sum below would only add up + // zeros, so it is not worked out. All sixteen, the whole footprint of the tent: a lit + // ray at its edge still lights the pixel) + var lit = false; + for (var k = 0; k < 16; k = k + 1) { + let o = vec2(k & 3, k >> 2) - vec2(1); + lit = lit || any(textureLoad(t_fog, clamp(base + o, vec2(0), hd), 0).rgb != vec3(0.0)); + } + if (!lit) { + return vec3(0.0); + } + var sum = vec3(0.0); + var wsum = 0.0; + // (a twig or a wire none of the four rays met: the one nearest in distance) + var best = vec3(0.0); + var best_d = 1e9; + // (a tent over the 4 x 4 nearest: the edge of a headlight's beam in the haze, worked + // out at half size, showed its 2 x 2 blocks under a plain bilinear one) + for (var k = 0; k < 16; k = k + 1) { + let o = vec2(k & 3, k >> 2) - vec2(1); + let s = textureLoad(t_fog, clamp(base + o, vec2(0), hd), 0); + let dx = abs(f32(o.x) - f.x); + let dy = abs(f32(o.y) - f.y); + let bil = max(1.0 - dx * 0.5, 0.0) * max(1.0 - dy * 0.5, 0.0); + let dd = abs(s.a - len); + // (a Gaussian of the distance difference, not an exponential: a road's rows differ by + // a few per cent of its length from one half-size row to the next, and an exponential + // weighted every row differently - the offsets of the staggered steps, which cancel + // over the tent exactly when its weights are even, then came out as a stripe along + // every other row of a bright beam. A step in depth, a pole against what is behind it, + // still keeps the taps of the far side out.) + let tol = (dd / (0.05 * len + 0.5)) * 1.2; + let w = (bil + 1e-3) * exp(-tol * tol); + sum = sum + s.rgb * w; + wsum = wsum + w; + if (dd < best_d) { + best_d = dd; + best = s.rgb * min(len / max(s.a, 0.1), 1.0); + } + } + if (wsum < 1e-4) { + return best; + } + return sum / max(wsum, 1e-6); +} + + +// Enhanced graphics: what the enhanced main pass, the sky and the coronas share - the +// light of the physically based sky (see atmosphere.rs), in its units (1 = 10 000 lux), +// and the air between the camera and what it sees. The scene is drawn pre-exposed: +// radiance times `enh.exposure.x`, so that the half-float target keeps its precision by +// night as well as by day. +struct Enhanced { + // x pre-exposure, y the level unlit things are drawn at, z a lit window's radiance + // (pre-exposed), w how bright a light's corona is drawn + exposure: vec4, + // rgb irradiance of the sun after the clouds, w its angular radius (rad) + sun: vec4, + // irradiance from the sky and the ground: order-2 spherical harmonics, rgb + sh: array, 9>, + // rgb radiance of the ground, w the sky table's scale + ground: vec4, + // x weather fog extinction (1/m) at its base, y its height falloff (1/m), z the base + // height (render-origin relative), w clear-air extinction (1/m) at the ground + fog: vec4, + // rgb fog radiance from the light around it (the sun's part is added by angle), + // w the table scale the reflection probe was drawn with + fog_color: vec4, + // x wet roads, y snow cover, z rain, w cloud cover in front of the sun + weather: vec4, + // x mip levels of the probe, y illuminance of a light's core (maplight colour 1), + // z cabin light illuminance, w how much of the sun the clouds let through + lights: vec4, + // rgb the sun disc's irradiance before the clouds, w frame time (s) + sun_disc: vec4, + // x which term the main pass shows alone (OMSI_DEBUG_ENHANCED, 0 = the picture), + // y the puddles' F0, z the envmap photo's strength, w the tone curve's contrast + debug: vec4, + // xyz where the sky cube is drawn from, relative to the camera + eye: vec4, + // x how bright an LED panel's dots burn (0 = off), y whether the LED panels' `\S:n` + // masks keep their mip chain (0: at full resolution, the dots stay visible when small), z 1 + // when lights glare and glow in the night air (the settings' `light_glow`) + led: vec4, + // xyz towards the moon, w its angular radius (rad) + moon: vec4, + // rgb the moon disc's irradiance before the clouds, w how much of the starry sky shows + moon_disc: vec4, + // rgb the sun's irradiance at 1400, 2100 and 2800 m (the cumulus layer) and 7000 m + // (the high thin layer), through the atmosphere from up there + cloud_sun: array, 4>, + // rgb the moonlight on a surface facing the moon (after the clouds), w 1 while the + // shadow maps are the moon's + moon_light: vec4, + // the condensation on the player's bus's panes (optical depths): windscreen, sides, + // rear, and how far the defroster has cleared the windscreen (0..1; omsi-app + // condensation.rs) + condensation: vec4, + // x the cumulus layer's base, y its top (m over the ground), z the altocumulus cover, + // w the storm's activity + layers: vec4, + // the lightning of this frame: x the light it throws on a surface facing it (1 = 10 000 + // lux), yz towards it (horizontal unit vector), w its elevation (rad) + flash: vec4, + // xyz towards the flash (unit vector), w how bright its channel is + flash2: vec4, + // x a number the channel's shape is drawn from + flash3: vec4, + // the clouds' shadow field (cloud_field.rs): xy its middle in cloud space, z one over its + // width, w 1 when there is one + cloud_f1: vec4, + // xy what takes a world point to cloud space, z the height of the plane it is taken on, + // w the share of the sun the main pass has taken off already for the clouds over the camera + cloud_f2: vec4, + // the player's bus's pitch and roll: sin, cos of each (its panes' condensation sits on + // the glass on a slope, `pane_local`) + pane_tilt: vec4, + // Slots of the weather overhaul, one owner each (zero until it fills them): + // the volumetric clouds, the volumetric fog, the precipitation, the bus's panes, the + // surfaces' PBR and the ray tracing, and two spare. + clouds_ext: vec4, + clouds_ext2: vec4, + vol_fog: vec4, + vol_fog2: vec4, + precip_ext: vec4, + glass_ext: vec4, + // (pbr_ext: x the share of the sun's light that still comes as a beam - the rest the + // clouds scatter, `sun_scattered` - y 1 when x is set) + pbr_ext: vec4, + rt_ext: vec4, +}; +@group(0) @binding(11) var enh: Enhanced; +@group(0) @binding(13) var s_lin: sampler; +@group(0) @binding(14) var t_sky_lut: texture_2d; + +const PI: f32 = 3.14159265; + +// Irradiance from the sky and the ground on a surface facing n. +fn sh_irradiance(n: vec3) -> vec3 { + let c = enh.sh; + let e = c[0].rgb * 0.282095 + + c[1].rgb * (0.488603 * n.y) + c[2].rgb * (0.488603 * n.z) + c[3].rgb * (0.488603 * n.x) + + c[4].rgb * (1.092548 * n.x * n.y) + c[5].rgb * (1.092548 * n.y * n.z) + + c[6].rgb * (0.315392 * (3.0 * n.z * n.z - 1.0)) + c[7].rgb * (1.092548 * n.x * n.z) + + c[8].rgb * (0.546274 * (n.x * n.x - n.y * n.y)); + return max(e, vec3(0.0)); +} + +// The lightning's light on a surface facing n: half of it from the cloud overhead and +// round it (a hemisphere), half along the way to the flash itself. +fn flash_irradiance(n: vec3) -> vec3 { + if (enh.flash.x <= 0.0) { + return vec3(0.0); + } + return vec3(0.80, 0.90, 1.0) * enh.flash.x * (0.5 * (0.5 + 0.5 * n.z) + 0.5 * max(dot(n, enh.flash2.xyz), 0.0)); +} + +// Sky radiance towards d (unscaled: times enh.ground.w is the radiance). The table runs +// over the azimuth from the sun (0..π) and the elevation (denser at the horizon). +// The sky table's texture: the table (32 x 48) in its corner and the clouds' shadow field +// (192 x 192) beside it, one texel clear (cloud_field.rs `SKY_TEX_W`, `FIELD_X0`). +const SKY_TEX: vec2 = vec2(225.0, 192.0); +const SKY_TABLE: vec2 = vec2(32.0, 48.0); +const FIELD_ORIGIN: f32 = 33.0; +const FIELD_N: f32 = 192.0; + +fn sky_table_raw(d: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let ls = length(s.xy); + let ld = length(d.xy); + var az = 0.0; + if (ls > 1e-4 && ld > 1e-4) { + az = acos(clamp(dot(s.xy / ls, d.xy / ld), -1.0, 1.0)); + } + let el = asin(clamp(d.z, -1.0, 1.0)); + let v = 0.5 + 0.5 * sign(el) * sqrt(min(abs(el) / 1.5707963, 1.0)); + // (kept a half texel inside the table: its neighbours in the texture are not the sky) + let tx = clamp(vec2(az / PI, v) * SKY_TABLE, vec2(0.5), SKY_TABLE - vec2(0.5)); + return textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).rgb; +} + +// The share of the sun that reaches the point p through the clouds, as against what the main +// pass's sun (`enh.sun`) already has for the camera's own place: the cumulus layer's shadow +// field read where the sun's way through p meets the layer's middle. 1 where there is no +// field, beyond its edge and where the sun is low (the camera's own factor stands there). +fn cloud_shadow_ratio(p: vec3) -> f32 { + let s = camera.sun_dir.xyz; + if (enh.cloud_f1.w < 0.5 || s.z < 0.06) { + return 1.0; + } + let cs = p.xy + s.xy / s.z * (enh.cloud_f2.z - p.z) + enh.cloud_f2.xy; + let uv = (cs - enh.cloud_f1.xy) * enh.cloud_f1.z + vec2(0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + let w = 1.0 - smoothstep(0.36, 0.48, edge); + if (w <= 0.0) { + return 1.0; + } + let tx = vec2(FIELD_ORIGIN, 0.0) + clamp(uv * FIELD_N, vec2(0.5), vec2(FIELD_N - 0.5)); + let f = textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).r; + let ratio = min(f / max(enh.cloud_f2.w, 0.02), 6.0); + return mix(1.0, ratio, w); +} + +fn sky_table(d: vec3) -> vec3 { + return sky_table_raw(d) * enh.ground.w; +} + +// Henyey-Greenstein phase function. +fn hg_phase(c: f32, g: f32) -> f32 { + let g2 = g * g; + return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * c, 1e-4), 1.5)); +} + +// Optical depth of an exponentially thinning layer (extinction sigma at height 0, falling +// off with k per metre) along a straight path of length dist from height h0 to h1. +fn layer_depth(sigma: f32, k: f32, h0: f32, h1: f32, dist: f32) -> f32 { + if (sigma <= 0.0) { + return 0.0; + } + let a = max(h0, 0.0); + let b = max(h1, 0.0); + let dh = b - a; + if (abs(k * dh) < 1e-3) { + return sigma * dist * exp(-k * 0.5 * (a + b)); + } + return sigma * dist * (exp(-k * a) - exp(-k * b)) / (k * dh); +} + +// The air between the camera and a point dist metres away in direction dir (from the +// camera), at heights h0 (camera) and h1 (point) above the fog's base: rgb the light it +// scatters towards the camera (radiance), a what it lets through of the point. +fn air(dir: vec3, dist: f32, h0: f32, h1: f32) -> vec4 { + return air_of(dir, dist, h0, h1, 1.0); +} + +// The same with the clear air's share scaled (0 for the sky, whose table holds it already). +fn air_of(dir: vec3, dist: f32, h0: f32, h1: f32, clear: f32) -> vec4 { + let tau_fog = layer_depth(enh.fog.x, enh.fog.y, h0, h1, dist); + let tau_air = layer_depth(enh.fog.w * clear, 1.0 / 1500.0, h0, h1, dist); + let tau = tau_fog + tau_air; + let t = exp(-tau); + if (tau < 1e-5) { + return vec4(0.0, 0.0, 0.0, 1.0); + } + // clear air takes on the sky's own colour at the horizon in this direction (which + // already holds the glow round the sun); a weather fog glows with the light around it + // and brighter towards the sun + let horizon = sky_table(normalize(vec3(dir.x, dir.y, max(dir.z, 0.0) * 0.3 + 0.03))); + let fog_in = enh.fog_color.rgb + enh.sun.rgb * hg_phase(dot(dir, camera.sun_dir.xyz), 0.55) * 0.9; + let inscatter = mix(horizon, fog_in, tau_fog / tau); + return vec4(inscatter * (1.0 - t), t); +} + +struct PointLight { + pos: vec4, + color: vec4, + dir: vec4, + extra: vec4, +}; +@group(0) @binding(3) var lights: array; +@group(0) @binding(4) var grid: array; +const CELL_CAP: u32 = 32u; + +// The shadows in a lamp's beam (the fog pass: its camera uniform has the lamp shadow tiles and +// the far shadow map's texture, see `fog_lamps.wgsl`). The other shaders that share +// `lamp_air.wgsl` take `beam_shadow_none.wgsl`'s: no map to look up, the beam goes on. + +// Which of the lamp shadow tiles (under the far shadow map, see `lamp_shadow_at` in the +// scene's lamps) belongs to lamp `li`: its record names it in `pos.w` (a multiple of 32 of the +// marks below zero, `light_marks`), or 0xffffffff for a lamp with none. +fn beam_tile(li: u32, l: PointLight) -> u32 { + let tile = floor(max(-l.pos.w, 0.0) / 32.0); + return select(0xffffffffu, u32(tile - 0.5), tile > 0.5); +} + +// How much of a beam reaches a point of the air, in tile `k` of its lamp's map: 0 where a +// pole, a car or a wall stands between the lamp and the point, so that the fog shows the +// shadow in its beam as it shows the sun's in a shaft. A tap of the hardware's filtered +// compare; off the tile, or without a map, the beam goes on. +fn beam_reaches(k: u32, x: vec3) -> f32 { + if (k >= 44u) { + return 1.0; + } + let q = camera.lamp_view_proj[k] * vec4(x, 1.0); + if (q.w <= 0.0) { + return 1.0; + } + let ndc = q.xyz / q.w; + if (abs(ndc.x) >= 1.0 || abs(ndc.y) >= 1.0 || ndc.z >= 1.0 || ndc.z <= 0.0) { + return 1.0; + } + let dims = vec2(1.0 / camera.shadow.y, camera.lamp_atlas.z); + let tile = camera.lamp_atlas.x; + let cols = u32(camera.lamp_atlas.y); + let tuv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + let tx = clamp(tuv * tile, vec2(1.5), vec2(tile - 1.5)); + let at = (vec2(f32(k % cols) * tile, dims.x + f32(k / cols) * tile) + tx) / dims; + // (a little more off the occluder than a surface takes: the air has no surface to + // acne, and the lamp's own housing must not shade its beam) + return textureSampleCompareLevel(t_shadow_far, s_shadow, at, ndc.z - 0.0002); +} + +// Enhanced graphics: the lamps as the scene and the sky share them - a headlamp's beam +// and the light the weather's fog scatters from the lamps towards the camera (needs the +// point lights, their grid and `camera.light_grid`). + +// A headlamp's intensity towards `t` (from the lamp) by the angles of a road lamp, not +// around its axis: wide across, brightest just under the lamp's horizon where it reaches +// far down the road, weak straight down, and with a low beam a sharp cut-off above it. +// `dir` is the lamp's axis in its vehicle's floor: its rise tilts the horizon with the +// vehicle, up a ramp and down (#1897). +fn headlamp(t: vec3, dir: vec3, low: bool) -> f32 { + let fwd = normalize(dir.xy + vec2(1e-6, 0.0)); + let ahead = dot(t.xy, fwd); + if (ahead <= 0.0) { + return 0.0; + } + let across = abs(t.x * fwd.y - t.y * fwd.x) / ahead; + let wide = 0.12 * smoothstep(1.0, 0.45, across) + 0.88 * exp(-across * across / 0.06); + let rise = t.z / max(length(t.xy), 1e-3); + let tilt = dir.z / max(length(dir.xy), 1e-3); + // (the tangent of the angle under that horizon) + let drop = (tilt - rise) / max(1.0 + rise * tilt, 1e-3); + // full out to where the road is 0.06 under the lamp's horizon, then less as the cube of + // the drop and a little more: the road is lit evenly from the bumper on, a little + // brighter as far as the beam reaches, and not as one hot pool where its axis lands + var up = min(1.0, pow(0.06 / max(abs(drop), 1e-4), 3.4)); + if (low) { + up = up * smoothstep(-0.012, 0.025, drop); + return wide * up; + } + // a full beam reaches far: a narrow, bright core along the lamp's horizon + let hot = exp(-across * across / 0.012 - drop * drop / 0.0004); + return wide * up + 6.0 * hot; +} + +// The lamps' light the weather's fog scatters towards the camera (radiance, not +// pre-exposed): single scattering along the view ray from `start` to `len` metres in +// direction `d` - the glow round a street lamp in the mist, its cone under it, a bus's +// beams reaching ahead into the fog or the falling snow. The droplets scatter strongly +// forward (fog and cloud droplets of some ten micrometres: g about 0.8), so the glow is +// brightest looking towards a lamp and a cone shows faintly from the side. +// +// Each lamp is taken once, over the whole stretch of the ray within its reach, in the grid +// cell the ray's point nearest to it lies in (the ray's cells are walked through; every +// cell lists the lamps reaching into it). Along a straight ray past a point source, with +// t - t0 = h tan(phi) (h the ray's distance from the lamp, t0 where it passes nearest), +// the inverse square cancels against the path element: dt / r^2 = dphi / h, and what is +// left is the phase function over the angle, cos(theta) = -sin(phi) - a smooth integral +// taken with five Gauss-Legendre nodes, at each of which a spot's or a headlamp's beam is +// asked how much it sends that way. The fog's extinction dims the light on its way from +// the lamp and to the camera (taken at the nearest point). A beam's light, which reaches +// only part of the way, is summed along the ray instead, its steps staggered by `jitter`. +// The droplets' phase function: a strong forward peak and the back-scattered light a +// fog's lidar ratio of some 18 sr asks for (0.055 per steradian straight back) - a single +// Henyey-Greenstein lobe of g 0.8 gave a tenth of it, and a bus's own headlights lit no +// wall of fog in front of the driver. Two lobes, 0.9 of g 0.85 and 0.1 of g -0.5. +fn fog_phase(c: f32) -> f32 { + return 0.9 * hg_phase(c, 0.85) + 0.1 * hg_phase(c, -0.5); +} +const AIRLIGHT_CELLS: u32 = 16u; + +// The clear night air's own haze, which lights a lamp's halo and a headlamp's beam as the fog's +// droplets do, only fainter: the lowest hundred metres of a city's air hold its dust, exhaust +// and humidity at several times the column's average aerosol extinction (`enh.fog.w`), 1-3e-4 +// per metre (a visibility of 15-40 km). A lamp then has a soft glow round it and a low beam +// a faint cone, as in any night photograph, instead of a lit disc on a black ground. +const GROUND_HAZE_GAIN: f32 = 8.0; + +// `droplets`: how much of the weather's extinction scatters like fog (see `FogLampUniform`). +fn lamp_airlight(c: vec3, d: vec3, start: f32, len: f32, jitter: f32, droplets: f32) -> vec3 { + var sum = vec3(0.0); + let sigma0 = enh.fog.x * droplets + enh.fog.w * GROUND_HAZE_GAIN * enh.led.z; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (sigma0 < 4e-5 || cell <= 0.0 || side == 0u || len <= start) { + return sum; + } + // (past a few optical depths nothing comes back) + let end = min(len, start + 4.0 / sigma0); + let gx = array(-0.9061798, -0.5384693, 0.0, 0.5384693, 0.9061798); + let gw = array(0.2369269, 0.4786287, 0.5688889, 0.4786287, 0.2369269); + // the walk through the grid's cells along the ray's plan + let o = (c.xy - camera.light_grid.xy) / cell; + let dd = d.xy / cell; + var ix = i32(floor(o.x + dd.x * start)); + var iy = i32(floor(o.y + dd.y * start)); + let sx = select(-1, 1, dd.x >= 0.0); + let sy = select(-1, 1, dd.y >= 0.0); + let inv_x = select(1e9, 1.0 / abs(dd.x), abs(dd.x) > 1e-7); + let inv_y = select(1e9, 1.0 / abs(dd.y), abs(dd.y) > 1e-7); + var tx = select((f32(ix) - o.x) / dd.x, (f32(ix + 1) - o.x) / dd.x, dd.x >= 0.0); + var ty = select((f32(iy) - o.y) / dd.y, (f32(iy + 1) - o.y) / dd.y, dd.y >= 0.0); + if (abs(dd.x) <= 1e-7) { tx = 1e9; } + if (abs(dd.y) <= 1e-7) { ty = 1e9; } + var t = start; + for (var k = 0u; k < AIRLIGHT_CELLS; k = k + 1u) { + if (t >= end) { + break; + } + let t_out = min(min(tx, ty), end); + if (ix >= 0 && iy >= 0 && ix < i32(side) && iy < i32(side)) { + let base = (u32(iy) * side + u32(ix)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let to_l = l.pos.xyz - c; + let t0 = dot(to_l, d); + // the ray's point nearest to the lamp: taken in this cell only + let tc = clamp(t0, start, end); + if (tc < t || tc > t_out) { + continue; + } + let range = l.extra.w; + let h = length(to_l - d * t0); + if (h >= range) { + continue; + } + // A beam (a headlamp, a spot) is lit in the weather's fog only: its cone is a sliver of + // sixteen jittered steps at half size, which the fog's density hides and the clear + // air's haze shows as shimmer and soap. The lamps' halo alone has the ground haze. + let beam_lamp = l.extra.z != 0.0 || l.dir.w > -1.5; + let fog_sigma = enh.fog.x * droplets; + if (beam_lamp && enh.fog.x < 2e-4) { + continue; + } + let s0 = select(sigma0, fog_sigma, beam_lamp); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + // (inside its core a lamp is as bright as at the core's edge) + let hh = max(h, select(core * 0.7, 0.4, l.extra.z != 0.0)); + let w = sqrt(range * range - h * h); + let ta = max(start, t0 - w); + let tb = min(end, t0 + w); + if (tb <= ta) { + continue; + } + var acc = 0.0; + var half = 0.0; + if (l.extra.z != 0.0 || l.dir.w > -1.5) { + // a beam (a headlamp, a spot): lit only where its cone or cut-off lets + // it - a sliver of the angles the lamp is seen under, which the five + // nodes missed. Sixteen even steps over that angle instead (dphi = + // h dt / r^2: the inverse square is in the step). (Sixteen even steps + // along the way put the few next to the lamp, where nearly all of its + // light is, a metre or more apart: the pixels' staggered steps came + // out as a coarse checker in the fog round every headlamp.) + let pa = atan((ta - t0) / hh); + let dphi = (atan((tb - t0) / hh) - pa) / 16.0; + let tile_k = beam_tile(li, l); + for (var q = 0u; q < 16u; q = q + 1u) { + let tq = t0 + hh * tan(pa + (f32(q) + jitter) * dphi); + let to = l.pos.xyz - (c + d * tq); + let ld = to * inverseSqrt(max(dot(to, to), 1e-6)); + var beam = 0.0; + if (l.extra.z != 0.0) { + beam = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0); + } else { + beam = smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } + // (the map is looked at only where the beam shines at all, and only for + // the few lamps that have a tile: no shadows, no tile, no tap) + var reach = 1.0; + if (beam > 0.002 && tile_k < 44u) { + reach = beam_reaches(tile_k, c + d * tq); + } + acc = acc + beam * reach * fog_phase(dot(ld, d)) * dphi; + } + half = 1.0; + } else { + let pa = atan((ta - t0) / hh); + let pb = atan((tb - t0) / hh); + half = 0.5 * (pb - pa); + let mid = 0.5 * (pa + pb); + let tile_p = beam_tile(li, l); + for (var q = 0u; q < 5u; q = q + 1u) { + let phi = mid + half * gx[q]; + let tq = t0 + hh * tan(phi); + let ld = normalize(l.pos.xyz - (c + d * tq)); + var beam = 1.0; + if (l.dir.z < -0.5) { + // (a lamp in a housing: see `lamp_light`) + beam = 0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z); + } + // (a lamp with a shadow map: what stands between it and the air + // keeps its light out of that air, as the headlamps' beams) + var reach = 1.0; + if (beam > 0.002 && tile_p < 44u) { + reach = beam_reaches(tile_p, c + d * tq); + } + acc = acc + gw[q] * beam * reach * fog_phase(-sin(phi)); + } + } + // a lamp's irradiance is core^2 / r^2 of its colour's (a headlamp's 1 / r^2) + let strength = select(core * core, 1.0, l.extra.z != 0.0); + let xc = c + d * tc; + let sigma = s0 * exp(-enh.fog.y * max(xc.z - enh.fog.z, 0.0)); + let dl = distance(xc, l.pos.xyz); + let atten = exp(-layer_depth(s0, enh.fog.y, c.z - enh.fog.z, xc.z - enh.fog.z, tc - start) - sigma * dl); + sum = sum + l.color.rgb * (l.color.w * strength * acc * half / hh * sigma * atten); + } + } + t = t_out; + if (tx < ty) { + tx = tx + inv_x; + ix = ix + sx; + } else { + ty = ty + inv_y; + iy = iy + sy; + } + } + return sum * enh.lights.y; +} + +// Enhanced: the light a raindrop or a snowflake sends towards the eye - what it scatters of +// the sky's light, the sun's and the lamps' round it, the drop's strongly forward (a +// streak flashes against a lamp seen through the rain, and is next to invisible in the +// dark between the lamps), the flake's nearly every way. (Drawn at the display's level +// whatever the light, the flakes of a snowfall at night shone white in the dark, far from +// any lamp.) +fn precip_light(x: vec3, to_eye: vec3, snow: bool) -> vec3 { + // the sky's and the ground's light round it, and the sun's on a small sphere + var e = enh.fog_color.rgb * (PI / 0.9) + enh.sun.rgb * 0.25; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell > 0.0 && side > 0u) { + let f = (x.xy - camera.light_grid.xy) / cell; + let gx = i32(floor(f.x)); + let gy = i32(floor(f.y)); + if (gx >= 0 && gy >= 0 && gx < i32(side) && gy < i32(side)) { + let base = (u32(gy) * side + u32(gx)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let dl = l.pos.xyz - x; + let dist2 = dot(dl, dl); + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let ld = dl * inverseSqrt(max(dist2, 1e-6)); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var k = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + if (l.extra.z != 0.0) { + k = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + k = k * smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } else if (l.dir.z < -0.5) { + k = k * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + // (the scattering towards the eye relative to an even one: a drop's light + // goes on forwards, a flake's every way. The angle is the one between the + // light's way from the lamp, -ld, and on to the eye: taken against -to_eye + // it put the forward peak behind the drop, and the drops in a bus's own + // beams, seen from behind the lamps, shone a hundred times too bright as + // white streaks down the road ahead) + let c = dot(-ld, to_eye); + let lobe = select(fog_phase(c), 0.7 * hg_phase(c, 0.3) + 0.3 / (4.0 * PI), snow) * 4.0 * PI; + e = e + l.color.rgb * l.color.w * enh.lights.y * k * lobe; + } + } + } + return e / PI; +} + diff --git a/crates/mx/tests/openomsi/lamp_sight.wgsl b/crates/mx/tests/openomsi/lamp_sight.wgsl new file mode 100644 index 0000000..70af375 --- /dev/null +++ b/crates/mx/tests/openomsi/lamp_sight.wgsl @@ -0,0 +1,49 @@ +struct Sight { + view_proj: mat4x4, + inv_view_proj: mat4x4, + eye: vec4, + lamps: array, 256>, +} + +@group(0) @binding(0) var u: Sight; +@group(0) @binding(1) var t_depth: texture_depth_2d; + +@vertex +fn vs_main(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { + let p = vec2(f32((i << 1u) & 2u), f32(i & 2u)); + return vec4(p * 2.0 - 1.0, 0.0, 1.0); +} + +fn covered(px: vec2, size: vec2, lamp_dist: f32) -> f32 { + let q = clamp(px, vec2(0), size - vec2(1)); + let d = textureLoad(t_depth, q, 0); + if (d <= 0.0) { + return 0.0; + } + let uv = (vec2(q) + 0.5) / vec2(size); + let w = u.inv_view_proj * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, d, 1.0); + let dist = length(w.xyz / w.w - u.eye.xyz); + return select(0.0, 1.0, dist < lamp_dist - (0.75 + 0.03 * lamp_dist)); +} + +@fragment +fn fs_sight(@builtin(position) pos: vec4) -> @location(0) vec4 { + let lamp = u.lamps[min(u32(pos.x), 255u)]; + let clip = u.view_proj * vec4(lamp.xyz, 1.0); + if (lamp.w < 0.5 || clip.w <= 0.0) { + return vec4(1.0); + } + let ndc = clip.xy / clip.w; + if (abs(ndc.x) > 1.0 || abs(ndc.y) > 1.0) { + return vec4(1.0); + } + let size = vec2(textureDimensions(t_depth)); + let px = vec2(vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * vec2(size)); + let lamp_dist = length(lamp.xyz - u.eye.xyz); + var taps = array, 5>(vec2(0, 0), vec2(3, 0), vec2(-3, 0), vec2(0, 3), vec2(0, -3)); + var hidden = 0.0; + for (var k = 0; k < 5; k++) { + hidden += covered(px + taps[k], size, lamp_dist); + } + return vec4(1.0 - hidden / 5.0, 0.0, 0.0, 1.0); +} diff --git a/crates/mx/tests/openomsi/mip.wgsl b/crates/mx/tests/openomsi/mip.wgsl new file mode 100644 index 0000000..299017b --- /dev/null +++ b/crates/mx/tests/openomsi/mip.wgsl @@ -0,0 +1,79 @@ +// Mipmap generation: each texel of the smaller level is the average of exactly the area of +// the bigger level it covers. For even sizes that is a 2x2 block; for odd ones (15 texels -> +// 7) it is a bit more than two texels a side, the outer ones with partial weights - a plain +// 2x2 block there shifts the picture and drops its last row, and display digits grew bolder +// each level and lost their bottom row. +// +// `fs_main` alpha-weights RGB so bright RGB stored in transparent texels does not bleed into +// tree/fence silhouettes when the texture switches to a smaller mip. Where all alpha is 0 +// the plain average is kept: on opaque materials the alpha channel is often only the envmap +// mask, and 0 there (lamps, wheels) must not turn the colour black. +// +// `fs_text` averages colour and alpha each on its own, as OMSI does for text and script +// textures (the cab displays, `[CTC]` pictures): alpha-weighted, the white of a digit kept +// full brightness out to the edge of its fading alpha, and digits grew bold and ran together +// from a few metres off. +@group(0) @binding(0) var t_src: texture_2d; +@group(0) @binding(1) var s_src: sampler; +struct VsOut { @builtin(position) clip: vec4, @location(0) uv: vec2 }; +@vertex +fn vs_main(@builtin(vertex_index) i: u32) -> VsOut { + let x = f32(i32(i & 1u) * 4 - 1); + let y = f32(i32(i >> 1u) * 4 - 1); + var out: VsOut; + out.clip = vec4(x, y, 0.0, 1.0); + out.uv = vec2((x + 1.0) * 0.5, (1.0 - y) * 0.5); + return out; +} + +// How much of destination texel `i` source texel `j` covers along one axis (source size +// `s`, destination size `d`). In units of 1/d of a source texel the destination texel runs +// from i*s to (i+1)*s and source texel j from j*d to (j+1)*d: whole numbers, so the shares +// are exact and add up to 1. +fn share(i: u32, j: u32, s: u32, d: u32) -> f32 { + let start = max(i * s, j * d); + let end = min((i + 1u) * s, (j + 1u) * d); + if (end <= start) { + return 0.0; + } + return f32(end - start) / f32(s); +} + +// The texels of the bigger level under one texel of the smaller, summed by their shares: +// colour times alpha, colour alone, and alpha. They are at most four a side (s <= 2d + 1). +struct Mix { by_alpha: vec3, colour: vec3, cover: f32 }; + +fn mix_under(pos: vec2) -> Mix { + let s = textureDimensions(t_src); + let d = max(s / 2u, vec2(1u)); + let at = min(vec2(pos), d - vec2(1u)); + let first = at * s / d; + let last = min(((at + vec2(1u)) * s - vec2(1u)) / d, s - vec2(1u)); + var m = Mix(vec3(0.0), vec3(0.0), 0.0); + for (var y = first.y; y <= last.y; y = y + 1u) { + let wy = share(at.y, y, s.y, d.y); + for (var x = first.x; x <= last.x; x = x + 1u) { + let w = wy * share(at.x, x, s.x, d.x); + let q = textureLoad(t_src, vec2(i32(x), i32(y)), 0); + m.by_alpha = m.by_alpha + q.rgb * (q.a * w); + m.colour = m.colour + q.rgb * w; + m.cover = m.cover + q.a * w; + } + } + return m; +} + +@fragment +fn fs_main(in: VsOut) -> @location(0) vec4 { + let m = mix_under(in.clip.xy); + if (m.cover > 2.5e-6) { + return vec4(m.by_alpha / m.cover, m.cover); + } + return vec4(m.colour, m.cover); +} + +@fragment +fn fs_text(in: VsOut) -> @location(0) vec4 { + let m = mix_under(in.clip.xy); + return vec4(m.colour, m.cover); +} diff --git a/crates/mx/tests/openomsi/post.wgsl b/crates/mx/tests/openomsi/post.wgsl new file mode 100644 index 0000000..50b6521 --- /dev/null +++ b/crates/mx/tests/openomsi/post.wgsl @@ -0,0 +1,497 @@ +// Enhanced graphics: what happens to the pre-exposed high-range picture before it reaches +// the screen - nothing that paints over it. A glow that only real highlights produce +// (a wide blur of the picture mixed in at a few per cent: a lamp a hundred times brighter +// than white spreads, a white wall does not), automatic exposure that meters the picture +// and follows it slowly within a narrow range, a photographic tone curve (a camera's +// contrast in the middle tones, a soft shoulder), dithering against banding, FXAA. +// The vanilla path never runs this. +struct PostParams { + // x glow strength, y how far the metering may darken (EV), z brighten (EV), + // w adaptation this frame (0..1; 1 = at once) + a: vec4, + // x how fast the exposure follows a darker picture, y a brighter one (fractions of the + // way per frame), z the metering target (log2 of the mean luminance), w exposure bias (EV) + b: vec4, + // x how much of the metered difference is corrected (the light model's own exposure is + // an incident meter: snow stays white and a night dark; the metering only helps where + // it cannot know, a dark cab or an underpass), y night vision strength, z the scene's + // pre-exposure (for absolute luminance), w how much an LED panel's dots count for in + // the glow's source (0 = not at all, `Led glow`) + c: vec4, + // x Enhanced+'s grade (0/1), y the vignette's strength, z sharpening, w the tone + // curve's contrast about mid grey (1 = none; a camera's by day, less at night) + d: vec4, + // x how much of a metered shortfall (the picture darker than the light model expects: a + // tunnel, a dark cab) the eye makes up. Nothing anchors it as white anchors a surplus (a + // snow field stays white), so it follows far more of it than of a surplus. + e: vec4, +}; +@group(0) @binding(0) var p: PostParams; +@group(0) @binding(1) var t_src: texture_2d; +@group(0) @binding(2) var s_lin: sampler; +@group(0) @binding(3) var t_base: texture_2d; +@group(0) @binding(4) var t_adapt: texture_2d; +// (the tone mapping's: the screen mask, whose r under 0.5 is MIST_MASK x the share of the +// light the player's bus's misted glass scatters there - enhanced.wgsl `pane_condensation`) +@group(0) @binding(5) var t_mask: texture_2d; + +struct VsOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +}; + +@vertex +fn vs_main(@builtin(vertex_index) i: u32) -> VsOut { + let x = f32(i32(i & 1u) * 4 - 1); + let y = f32(i32(i >> 1u) * 4 - 1); + var out: VsOut; + out.clip = vec4(x, y, 0.0, 1.0); + out.uv = vec2((x + 1.0) * 0.5, (1.0 - y) * 0.5); + return out; +} + +fn luma(c: vec3) -> f32 { + return dot(c, vec3(0.2126, 0.7152, 0.0722)); +} + +// A pixel that is not a finite number (a NaN or an infinity from the scene) as black - +// tested on the bits, which fast maths cannot drop. Unguarded, the glow's down- and +// up-sampling spread one such pixel over the picture as half and fully black squares +// (Vulkan and Direct3D keep NaNs, Metal's fast maths happened to hide them). +fn clean(c: vec3) -> vec3 { + let e = bitcast>(c) & vec3(0x7f800000u); + let ok = all(e != vec3(0x7f800000u)); + return select(vec3(0.0), clamp(c, vec3(0.0), vec3(65000.0)), ok); +} + +fn src(uv: vec2, texel: vec2, x: f32, y: f32) -> vec3 { + return clean(textureSampleLevel(t_src, s_lin, uv + vec2(x, y) * texel, 0.0).rgb); +} + +// The picture without the bus's own screens (the screen mask is the first glow level's +// t_base): a lit display glows no halo over its own letters. An LED panel's dots are the +// panel's own light, though - they stay in the source (the mask's g) and count for several +// times their colour there (`p.c.w`), so that the faint mix the glow is blooms a halo +// around the panel without the dots themselves having to burn. +// +// What glows is only the light above the display's white (`GLARE_WHITE`, in the picture's +// pre-exposed terms): the viewer's own eye scatters the light of everything the screen can +// show, as it does in a street - only what lies beyond the screen's range has to have its +// scattered light drawn (Spencer et al., "Physically-based glare effects for digital +// images", 1995). The alpha carries the picture's whole luminance down the chain for the +// metering. +const GLARE_WHITE: f32 = 1.0; +fn is_screen_mask(m: vec4) -> bool { + // Clear panes attenuate both screen channels together. Condensation adds only to + // r; water also has b. Recover the screen code before interpreting a low r as mist. + let code = m.g / max(m.r, 1e-3); + return m.r >= 0.5 || (m.r > 0.004 && m.b < 0.004 && + ((code > 0.2 && code < 0.3) || (code > 0.9 && code < 1.1))); +} + +fn src_unmasked(uv: vec2, texel: vec2, x: f32, y: f32) -> vec4 { + let at = uv + vec2(x, y) * texel; + let m = textureSampleLevel(t_base, s_lin, at, 0.0); + let c = clean(textureSampleLevel(t_src, s_lin, at, 0.0).rgb); + let screen = select(0.0, 1.0, is_screen_mask(m)); + let led = step(0.5, m.g); + let picture = c * (1.0 - screen); + let over = min(max(picture - vec3(GLARE_WHITE), vec3(0.0)), vec3(64.0)) + c * (led * p.c.w) * screen; + return vec4(over, luma(picture + c * (led * p.c.w) * screen)); +} + +fn src4(uv: vec2, texel: vec2, x: f32, y: f32) -> vec4 { + let t = textureSampleLevel(t_src, s_lin, uv + vec2(x, y) * texel, 0.0); + return vec4(clean(t.rgb), clamp(select(0.0, t.a, t.a == t.a), 0.0, 65000.0)); +} + +// --- the glow: 13-tap downsampling (the first level with Karis' average, so that a single +// bright pixel does not flicker), tent upsampling + +@fragment +fn fs_down_first(in: VsOut) -> @location(0) vec4 { + let texel = 1.0 / vec2(textureDimensions(t_src)); + let uv = in.uv; + let a = src_unmasked(uv, texel, -2.0, -2.0); + let b = src_unmasked(uv, texel, 0.0, -2.0); + let c = src_unmasked(uv, texel, 2.0, -2.0); + let d = src_unmasked(uv, texel, -2.0, 0.0); + let e = src_unmasked(uv, texel, 0.0, 0.0); + let f = src_unmasked(uv, texel, 2.0, 0.0); + let g = src_unmasked(uv, texel, -2.0, 2.0); + let h = src_unmasked(uv, texel, 0.0, 2.0); + let i = src_unmasked(uv, texel, 2.0, 2.0); + let j = src_unmasked(uv, texel, -1.0, -1.0); + let k = src_unmasked(uv, texel, 1.0, -1.0); + let l = src_unmasked(uv, texel, -1.0, 1.0); + let m = src_unmasked(uv, texel, 1.0, 1.0); + let g0 = (j + k + l + m) * 0.25; + let g1 = (a + b + d + e) * 0.25; + let g2 = (b + c + e + f) * 0.25; + let g3 = (d + e + g + h) * 0.25; + let g4 = (e + f + h + i) * 0.25; + // (Karis' average: no single bright pixel flickers through. A small, very bright source - + // a lamp, a headlight - gets its halo from the eye's glare drawn round it instead + // (fog_lamps.wgsl `point_glare`); the glow is the halo of what is wide and bright) + let w0 = 0.5 / (1.0 + luma(g0.rgb)); + let w1 = 0.125 / (1.0 + luma(g1.rgb)); + let w2 = 0.125 / (1.0 + luma(g2.rgb)); + let w3 = 0.125 / (1.0 + luma(g3.rgb)); + let w4 = 0.125 / (1.0 + luma(g4.rgb)); + let sum = g0.rgb * w0 + g1.rgb * w1 + g2.rgb * w2 + g3.rgb * w3 + g4.rgb * w4; + // (the luminance for the metering: the plain average) + let lum = (g0.a * 0.5 + (g1.a + g2.a + g3.a + g4.a) * 0.125); + return vec4(sum / (w0 + w1 + w2 + w3 + w4), lum); +} + +@fragment +fn fs_down(in: VsOut) -> @location(0) vec4 { + let texel = 1.0 / vec2(textureDimensions(t_src)); + let uv = in.uv; + let outer = src4(uv, texel, -2.0, -2.0) + src4(uv, texel, 2.0, -2.0) + src4(uv, texel, -2.0, 2.0) + src4(uv, texel, 2.0, 2.0); + let arms = src4(uv, texel, 0.0, -2.0) + src4(uv, texel, -2.0, 0.0) + src4(uv, texel, 2.0, 0.0) + src4(uv, texel, 0.0, 2.0); + let inner = src4(uv, texel, -1.0, -1.0) + src4(uv, texel, 1.0, -1.0) + src4(uv, texel, -1.0, 1.0) + src4(uv, texel, 1.0, 1.0); + return src4(uv, texel, 0.0, 0.0) * 0.125 + outer * 0.03125 + arms * 0.0625 + inner * 0.125; +} + +@fragment +fn fs_up(in: VsOut) -> @location(0) vec4 { + let texel = 1.0 / vec2(textureDimensions(t_src)); + let uv = in.uv; + // (a round kernel: the centre and two rings of eight, 1 and 2 texels out - the outer + // turned by half a step - weighted as a Gaussian of about a texel. A 3x3 tent, however + // wide, is a square: a far headlamp, a pixel or two that the coarse levels hold in one + // texel, came back as a square halo, the squarer the further the lamp) + var ring1 = vec3(0.0); + var ring2 = vec3(0.0); + for (var k = 0; k < 8; k = k + 1) { + let a = f32(k) * 0.78539816; + ring1 = ring1 + src(uv, texel, cos(a), sin(a)); + ring2 = ring2 + src(uv, texel, 2.0 * cos(a + 0.39269908), 2.0 * sin(a + 0.39269908)); + } + let tent = (src(uv, texel, 0.0, 0.0) + ring1 * 0.60653066 + ring2 * 0.13533528) / (1.0 + 8.0 * 0.60653066 + 8.0 * 0.13533528); + let base = clean(textureSampleLevel(t_base, s_lin, uv, 0.0).rgb); + // (each level keeps a quarter of its own and passes three quarters of the wider ones + // on: the levels' shares follow the eye's scattering - about 5.7 % of the light lands + // 0.3-1 degree from where it should, 2.4 % at 1-3 degrees, 1.7 % at 3-10 and some 3.6 % + // further out, CIE 146:2002's glare function integrated over those rings) + return vec4(mix(base, tent, 0.75), 1.0); +} + +// The picture as absolute radiance (1 = 10 000 cd/m²) at half size, kept for the next +// frame's ambient occlusion: the light the surfaces of the street send to each other (the +// bounce) is what they looked like a frame ago. Four taps at the corners of the 2x2 block. +@fragment +fn fs_history(in: VsOut) -> @location(0) vec4 { + let texel = 1.0 / vec2(textureDimensions(t_src)); + var c = (src(in.uv, texel, -0.5, -0.5) + src(in.uv, texel, 0.5, -0.5) + src(in.uv, texel, -0.5, 0.5) + src(in.uv, texel, 0.5, 0.5)) * 0.25; + // A small bright thing - a lamp, a spot of glare, a sign's edge - is one texel among a + // hundred its neighbours: of the AO's samples it takes one, and the blur turned it into a + // square of the blur's size. What is far brighter than what lies round it (four taps + // eight pixels out) is cut down to a little more than that: a wall, a sign or a window + // is as bright as its neighbours. + let ring = (src(in.uv, texel, 8.0, 0.0) + src(in.uv, texel, -8.0, 0.0) + src(in.uv, texel, 0.0, 8.0) + src(in.uv, texel, 0.0, -8.0)) * 0.25; + c = min(c, ring * 1.5 + vec3(0.02) * max(p.c.z, 1e-6)); + return vec4(c / max(p.c.z, 1e-6), 1.0); +} + +// --- automatic exposure: the mean log luminance of the smallest glow level, weighted to +// the middle of the picture, and its slow follower + +@fragment +fn fs_meter(in: VsOut) -> @location(0) vec4 { + let dims = vec2(textureDimensions(t_src)); + var sum = 0.0; + var wsum = 0.0; + for (var y = 0; y < dims.y; y = y + 1) { + for (var x = 0; x < dims.x; x = x + 1) { + let c = textureLoad(t_src, vec2(x, y), 0).a; + let q = (vec2(f32(x), f32(y)) + 0.5) / vec2(dims) * 2.0 - 1.0; + // the middle and the lower half count most: the sky is not what one looks at + let w = exp(-dot(q, q) * 1.5) * (0.6 + 0.4 * clamp(q.y + 0.5, 0.0, 1.0)); + sum = sum + log2(clamp(select(1e-4, c, c == c), 1e-4, 64.0)) * w; + wsum = wsum + w; + } + } + return vec4(sum / max(wsum, 1e-6), 0.0, 0.0, 1.0); +} + +@fragment +fn fs_adapt(in: VsOut) -> @location(0) vec4 { + let now = textureLoad(t_src, vec2(0, 0), 0).r; + let before_raw = textureLoad(t_base, vec2(0, 0), 0).r; + // (a NaN once in the adaptation would stay there and turn the whole picture black) + let before = select(now, before_raw, (bitcast(before_raw) & 0x7f800000u) != 0x7f800000u); + // the eye takes to the light quickly and to the dark slowly + var k = select(p.b.y, p.b.x, now < before); + k = max(k, p.a.w); + return vec4(mix(before, now, k), 0.0, 0.0, 1.0); +} + +// --- the picture + +// Night vision: where the scene is darker than a lit street (about a candela per square +// metre) the eye's rods take over from its cones: colours fade and what is left of them +// shifts towards blue-green (the Purkinje shift). A lamp's pool keeps its colour, the +// street beyond it turns to a bluish grey. `pre` is the pre-exposure, which gives the +// absolute luminance (1 = 10 000 cd/m²). +fn night_vision(c: vec3, strength: f32, pre: f32) -> vec3 { + let lum = luma(c); + let cd = lum / max(pre, 1e-6) * 10000.0; + // fully scotopic below 0.01 cd/m², photopic above 3 + let rods = 1.0 - smoothstep(-2.0, 0.5, log(max(cd, 1e-6)) / log(10.0)); + // the rods' sensitivity peaks at 507 nm: blue and green count, red hardly + let scot = dot(c, vec3(0.05, 0.62, 0.45)); + let tint = vec3(0.86, 0.95, 1.12); + let night = tint * scot * (lum / max(dot(tint * scot, vec3(0.2126, 0.7152, 0.0722)), 1e-8)); + return mix(c, night, rods * strength); +} + +fn to_srgb(c: vec3) -> vec3 { + let lo = c * 12.92; + let hi = 1.055 * pow(max(c, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return select(hi, lo, c <= vec3(0.0031308)); +} + +fn from_srgb(c: vec3) -> vec3 { + let lo = c / 12.92; + let hi = pow(max((c + 0.055) / 1.055, vec3(0.0)), vec3(2.4)); + return select(hi, lo, c <= vec3(0.04045)); +} + +// The shoulder of `natural_tone` for one value: identity up to the knee, then an +// exponential approach to white with the slope kept at the knee. +const KNEE: f32 = 0.66; +fn soft_shoulder(x: vec3) -> vec3 { + let d = 1.0 - KNEE; + let over = vec3(KNEE) + d * (vec3(1.0) - exp(-(x - vec3(KNEE)) / d)); + return select(x, over, x > vec3(KNEE)); +} + +// The tone curve of a photograph rather than of a renderer: a camera's curve gives the +// middle tones some contrast (about mid grey, per channel in log space - colours gain a +// little with it, as they do on film and on a phone's picture) where a plain linear +// mapping leaves a sunny street grey and flat, with lifted shadows and no white in it; +// above the knee the highlights roll off softly, partly per channel (a low sun's sky +// near the disc runs to a warm white, as on film) and partly by the brightest channel +// (a lit yellow bus stays yellow), and what lies far above white bleaches out. +fn natural_tone(color: vec3, contrast: f32) -> vec3 { + let x = max(color, vec3(0.0)); + let y = 0.18 * pow(x / 0.18 + vec3(1e-7), vec3(contrast)); + let peak = max(y.r, max(y.g, y.b)); + if (peak <= KNEE) { + return y; + } + let np = soft_shoulder(vec3(peak)).x; + let by_peak = y * (np / peak); + let o = mix(by_peak, soft_shoulder(y), 0.4); + let g = 1.0 - 1.0 / (0.3 * (peak - np) + 1.0); + return mix(o, vec3(np), g); +} + +// Enhanced+'s grade: the natural curve, the light a shade warmer. +fn filmic_grade(c: vec3) -> vec3 { + return natural_tone(c * vec3(1.015, 1.0, 0.985), max(p.d.w, 1.0)); +} + +// What a misted pane shows of what lies behind it: half the light its film scatters is +// diffracted forward by the droplets, within some 2 degrees for droplets of 10 um (0.61 +// lambda / radius) - about a fortieth of the picture's height at the usual field of view - +// so the street goes soft and every light behind the glass spreads into a glowing patch: +// that share of the picture averaged over the lobe, from the same misted glass only (the +// frame and the dashboard beside it keep their edges). +const MIST_MASK: f32 = 0.24; +fn misted(uv: vec2, c: vec3) -> vec3 { + let dims = vec2(textureDimensions(t_src)); + let px = vec2(uv * dims); + let mask = textureLoad(t_mask, clamp(px, vec2(0), vec2(dims) - vec2(1)), 0); + let m = mask.r; + if (m < 0.004 || is_screen_mask(mask)) { + return c; + } + let fog = clamp(m / MIST_MASK, 0.0, 1.0); + let radius = dims.y * 0.025; + var sum = c; + var w = 1.0; + for (var k = 1; k < 24; k = k + 1) { + let a = f32(k) * 2.3999632; + let r = sqrt(f32(k) / 23.0) * radius; + let q = uv + vec2(cos(a), sin(a)) * r / dims; + let qm = textureLoad(t_mask, clamp(vec2(q * dims), vec2(0), vec2(dims) - vec2(1)), 0); + if (qm.r > 0.004 && !is_screen_mask(qm)) { + sum = sum + clean(textureSampleLevel(t_src, s_lin, q, 0.0).rgb); + w = w + 1.0; + } + } + return mix(c, sum / w, 0.5 * fog); +} + +// The tone-mapped picture, encoded for the display (gamma), dithered. +fn graded(in: VsOut) -> vec3 { + let hdr = misted(in.uv, clean(textureSampleLevel(t_src, s_lin, in.uv, 0.0).rgb)); + let glow = clean(textureSampleLevel(t_base, s_lin, in.uv, 0.0).rgb); + // the eye's scattered light of what is brighter than the screen, added + var c = hdr + glow * p.a.x; + let metered = textureLoad(t_adapt, vec2(0, 0), 0).r; + let gap = p.b.z - metered; + let ev = clamp(gap * select(p.c.x, p.e.x, gap > 0.0), -p.a.y, p.a.z) + p.b.w; + c = max(c, vec3(0.0)); + if (p.c.y > 0.0) { + c = night_vision(c, p.c.y, p.c.z); + } + if (p.d.x > 0.5) { + c = filmic_grade(c * pow(2.0, ev)); + // the lens: the corners a little darker + let q = in.uv * 2.0 - vec2(1.0); + c = c * (1.0 - p.d.y * pow(clamp(dot(q, q) * 0.5, 0.0, 1.0), 1.6)); + } else { + c = natural_tone(c * pow(2.0, ev), max(p.d.w, 1.0)); + } + var e = to_srgb(clamp(c, vec3(0.0), vec3(1.0))); + // triangular dither of one code value: no bands in the sky's gradient + let px = in.clip.xy; + let n1 = fract(52.9829189 * fract(dot(px, vec2(0.06711056, 0.00583715)))); + let n2 = fract(52.9829189 * fract(dot(px + vec2(17.0, 31.0), vec2(0.06711056, 0.00583715)))); + e = e + vec3((n1 + n2 - 1.0) / 255.0); + return e; +} + +// straight to the (sRGB) target +@fragment +fn fs_tonemap(in: VsOut) -> @location(0) vec4 { + return vec4(from_srgb(clamp(graded(in), vec3(0.0), vec3(1.0))), 1.0); +} + +// into the gamma-encoded target FXAA reads, with its luma in alpha +@fragment +fn fs_tonemap_encoded(in: VsOut) -> @location(0) vec4 { + let e = clamp(graded(in), vec3(0.0), vec3(1.0)); + return vec4(e, dot(e, vec3(0.299, 0.587, 0.114))); +} + +// Enhanced+: contrast-adaptive sharpening of the anti-aliased picture (in its gamma +// encoding): a pixel is pushed away from its four neighbours' mean by as much as their +// spread leaves room for, so that flat areas stay calm and fine detail comes out. +fn sharpened(uv: vec2, c: vec3) -> vec3 { + if (p.d.z <= 0.0) { + return c; + } + let texel = 1.0 / vec2(textureDimensions(t_src)); + let n = textureSampleLevel(t_src, s_lin, uv + vec2(0.0, -texel.y), 0.0).rgb; + let s = textureSampleLevel(t_src, s_lin, uv + vec2(0.0, texel.y), 0.0).rgb; + let e = textureSampleLevel(t_src, s_lin, uv + vec2(texel.x, 0.0), 0.0).rgb; + let w = textureSampleLevel(t_src, s_lin, uv + vec2(-texel.x, 0.0), 0.0).rgb; + let lo = min(c, min(min(n, s), min(e, w))); + let hi = max(c, max(max(n, s), max(e, w))); + let room = clamp(min(lo, vec3(1.0) - hi) / max(hi, vec3(1e-4)), vec3(0.0), vec3(1.0)); + let k = sqrt(room) * p.d.z * 0.25; + return clamp(c + (c * 4.0 - (n + s + e + w)) * k, vec3(0.0), vec3(1.0)); +} + +// --- FXAA 3.11 (quality, 12 search steps) over the tone-mapped picture + +fn lum_at(uv: vec2) -> f32 { + return textureSampleLevel(t_src, s_lin, uv, 0.0).a; +} + +@fragment +fn fs_fxaa(in: VsOut) -> @location(0) vec4 { + let texel = 1.0 / vec2(textureDimensions(t_src)); + let uv = in.uv; + let rgbm = textureSampleLevel(t_src, s_lin, uv, 0.0); + // the bus's own screens as they are: FXAA took half the contrast out of their + // letters (the screen mask is this pass's t_base) + if (is_screen_mask(textureSampleLevel(t_base, s_lin, uv, 0.0))) { + return vec4(from_srgb(rgbm.rgb), 1.0); + } + let m = rgbm.a; + let n = lum_at(uv + vec2(0.0, -1.0) * texel); + let s = lum_at(uv + vec2(0.0, 1.0) * texel); + let e = lum_at(uv + vec2(1.0, 0.0) * texel); + let w = lum_at(uv + vec2(-1.0, 0.0) * texel); + let hi = max(m, max(max(n, s), max(e, w))); + let lo = min(m, min(min(n, s), min(e, w))); + let range = hi - lo; + if (range < max(0.0312, hi * 0.125)) { + return vec4(from_srgb(sharpened(uv, rgbm.rgb)), 1.0); + } + let nw = lum_at(uv + vec2(-1.0, -1.0) * texel); + let ne = lum_at(uv + vec2(1.0, -1.0) * texel); + let sw = lum_at(uv + vec2(-1.0, 1.0) * texel); + let se = lum_at(uv + vec2(1.0, 1.0) * texel); + // sub-pixel aliasing + let avg = (2.0 * (n + s + e + w) + nw + ne + sw + se) / 12.0; + let sub = clamp(abs(avg - m) / range, 0.0, 1.0); + let sub2 = smoothstep(0.0, 1.0, sub); + let blend_sub = sub2 * sub2 * 0.75; + // edge direction + let horz = abs(nw + sw - 2.0 * w) + abs(n + s - 2.0 * m) * 2.0 + abs(ne + se - 2.0 * e); + let vert = abs(nw + ne - 2.0 * n) + abs(w + e - 2.0 * m) * 2.0 + abs(sw + se - 2.0 * s); + let is_h = horz >= vert; + var stp = select(texel.x, texel.y, is_h); + let l1 = select(w, n, is_h); + let l2 = select(e, s, is_h); + let g1 = abs(l1 - m); + let g2 = abs(l2 - m); + let neg = g1 >= g2; + let grad = max(g1, g2) * 0.25; + let edge_l = 0.5 * (m + select(l2, l1, neg)); + if (neg) { + stp = -stp; + } + var cuv = uv; + if (is_h) { + cuv.y = cuv.y + stp * 0.5; + } else { + cuv.x = cuv.x + stp * 0.5; + } + let dir = select(vec2(0.0, texel.y), vec2(texel.x, 0.0), is_h); + // walk along the edge both ways + let steps = array(1.0, 1.0, 1.0, 1.0, 1.0, 1.5, 2.0, 2.0, 2.0, 2.0, 4.0, 8.0); + var p_uv = cuv + dir; + var n_uv = cuv - dir; + var p_end = lum_at(p_uv) - edge_l; + var n_end = lum_at(n_uv) - edge_l; + var p_done = abs(p_end) >= grad; + var n_done = abs(n_end) >= grad; + for (var i = 1; i < 12; i = i + 1) { + if (p_done && n_done) { + break; + } + if (!p_done) { + p_uv = p_uv + dir * steps[i]; + p_end = lum_at(p_uv) - edge_l; + p_done = abs(p_end) >= grad; + } + if (!n_done) { + n_uv = n_uv - dir * steps[i]; + n_end = lum_at(n_uv) - edge_l; + n_done = abs(n_end) >= grad; + } + } + var dp: f32; + var dn: f32; + if (is_h) { + dp = p_uv.x - uv.x; + dn = uv.x - n_uv.x; + } else { + dp = p_uv.y - uv.y; + dn = uv.y - n_uv.y; + } + let near_neg = dn <= dp; + let end_l = select(p_end, n_end, near_neg); + let span = dp + dn; + var blend_edge = 0.0; + // only when the end of the edge is on the other side of the middle + if ((m - edge_l < 0.0) != (end_l < 0.0)) { + blend_edge = 0.5 - min(dp, dn) / span; + } + let blend = max(blend_edge, blend_sub); + var fuv = uv; + if (is_h) { + fuv.y = fuv.y + blend * stp; + } else { + fuv.x = fuv.x + blend * stp; + } + return vec4(from_srgb(textureSampleLevel(t_src, s_lin, fuv, 0.0).rgb), 1.0); +} diff --git a/crates/mx/tests/openomsi/puddles.wgsl b/crates/mx/tests/openomsi/puddles.wgsl new file mode 100644 index 0000000..b90914d --- /dev/null +++ b/crates/mx/tests/openomsi/puddles.wgsl @@ -0,0 +1,439 @@ +fn srgb_encode(c: vec3) -> vec3 { + let x = max(c, vec3(0.0)); + return select(1.055 * pow(x, vec3(1.0 / 2.4)) - 0.055, x * 12.92, x <= vec3(0.0031308)); +} +fn srgb_decode(c: vec3) -> vec3 { + let x = max(c, vec3(0.0)); + return select(pow((x + 0.055) / 1.055, vec3(2.4)), x / 12.92, x <= vec3(0.04045)); +} + +// The water normal shared by shading and scene reflections. The integer hash and the +// 1000 m period match shader.wgsl, keeping the rings fixed through floating-origin moves. +fn puddle_hash(c: vec2) -> f32 { + let cells = 8000.0; + let w = c - cells * floor(c / cells); + var v = vec2(w) * 1664525u + vec2(1013904223u); + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + return f32(v.x >> 8u) / 16777215.0; +} + +// The rings the rain makes on standing water (Enhanced): xy the water's slope (a horizontal +// offset to its normal), z how much it is stirred (0..1, for its roughness as well). +// +// A falling drop sends out a short train of capillary waves: two or three rings close +// together, running out at a few decimetres a second and dying away within a hand's +// breadth. Three lattices of cells of 18 to 27 cm, turned against each other so that no grid +// shows, each take a drop now and then - the harder it rains the more often, and in more +// of them - every drop at a new place in its cell. A ring is a wave packet on its circle +// (a cosine under a Gaussian), its slope worked out exactly, and it stays inside its cell +// (no ring is cut off at a cell's edge). +fn puddle_ripple(pattern_xy: vec2, time: f32, rain: f32, coverage: f32) -> vec3 { + if (rain <= 0.001 || coverage <= 0.0) { + return vec3(0.0); + } + var slope = vec2(0.0); + var stir = 0.0; + let rate = 0.7 + 1.6 * rain; + let amp = min(1.0, 0.45 + rain) * coverage; + for (var i = 0; i < 3; i = i + 1) { + let fi = f32(i); + let size = 0.18 + 0.045 * fi; + let cs = vec2(cos(fi * 1.93), sin(fi * 1.93)); + let turned = vec2(pattern_xy.x * cs.x - pattern_xy.y * cs.y, pattern_xy.x * cs.y + pattern_xy.y * cs.x); + let q = turned / size + vec2(fi * 17.0, fi * 5.0); + let cell = floor(q); + let seed = puddle_hash(cell + vec2(fi * 311.0, 0.0)); + let tt = time * rate * (0.8 + 0.4 * seed) + seed * 7.0; + let n = floor(tt); + let age = tt - n; + let h = puddle_hash(cell + vec2(n - 97.0 * floor(n / 97.0) + 401.0, fi * 13.0 + 7.0)); + let hit = step(fract(h * 31.7), 0.3 + 0.65 * rain); + let centre = vec2(0.3) + 0.4 * vec2(h, fract(h * 13.7)); + let local = fract(q) - centre; + let r = length(local); + let radius = 0.05 + 0.24 * sqrt(age); + let d = r - radius; + let w = 0.045; + let k = 6.2831853 / 0.07; + let env = exp(-(d * d) / (w * w)); + let a = (1.0 - age) * (1.0 - age) * hit; + // the height is a * env * cos(k d): its slope along the radius + let dh = a * env * (-2.0 * d / (w * w) * cos(k * d) - k * sin(k * d)); + slope = slope - local / max(r, 1e-4) * dh / k; + stir = stir + a * env; + } + return vec3(slope * 0.03 * amp, clamp(stir * amp, 0.0, 1.0)); +} + +// The rings as a picture whose pixel covers `fp` metres of the water sees them: their +// slopes are a few centimetres long, and a pixel (or a puddle ray standing for several) +// wider than half of that lands on a ring's crest one frame and its trough the next - the +// water's picture trembled and broke into blocks. Faded out there, the rings leave their +// stir (the roughness) and the reflection keeps still. +fn puddle_ripple_seen(pattern_xy: vec2, time: f32, rain: f32, coverage: f32, fp: f32) -> vec3 { + let fade = 1.0 - smoothstep(0.012, 0.035, fp); + let r = puddle_ripple(pattern_xy, time, rain, coverage); + return vec3(r.xy * fade, r.z); +} + +// The classic rings (Vanilla+'s puddle reflections): one lattice of 12.5 cm cells. +fn puddle_ripple_classic(pattern_xy: vec2, time: f32, rain: f32, coverage: f32) -> vec3 { + let cell = floor(pattern_xy * 8.0); + let seed = puddle_hash(cell); + let phase = fract(time * (0.8 + seed * 0.9) + seed * 13.0); + let local = fract(pattern_xy * 8.0) - vec2(0.5); + let ring = abs(length(local) - phase * 0.4); + let hit = step(1.0 - clamp(0.25 + 0.6 * rain, 0.0, 0.9), fract(seed * 31.7)); + let strength = (1.0 - smoothstep(0.0, 0.06, ring)) * (1.0 - phase) * rain * coverage * hit; + // Shallow rain rings disturb the image gently; steep normals break neighbouring + // reflection rays apart and make otherwise still puddles look like rough waves. + let bump = normalize(local + vec2(1e-5, 0.0)) * strength * 0.018; + return vec3(bump, strength); +} + +// Current-frame puddle reflections. Rays are capped at quality.y screen-space steps and +// quality.x m (48 and 100 m high, 24 and 40 m low); +// only wet pixels run them. Misses leave the main shader's sky reflection untouched. +struct PuddleVehicleBox { a: vec4, b: vec4, c: vec4 }; +struct PuddleParams { + view_proj: mat4x4, + inv_view_proj: mat4x4, + eye_time: vec4, + // xy: floating origin modulo 1000 m, z: rain without snow, w: probe mip count + origin_rain: vec4, + // rgb: the main shader's horizon surround, w: probe scale (both pre-exposed) + sky: vec4, + // xy: projection z coefficients, z: diagnostic view (0 normally), w: hit thickness + projection_trace: vec4, + vehicle_plane: vec4, + // xyz: capture count and scene size; w: -1 Vanilla+, 0 Vanilla, 1 Enhanced + vehicle_info: vec4, + vehicle_parts: array, + // x: the farthest wet pixel traced (m), y: the most steps a ray takes, z: the picture + // pixels one ray stands for, each way + quality: vec4, +}; +@group(0) @binding(0) var p: PuddleParams; +@group(0) @binding(1) var t_scene: texture_2d; +@group(0) @binding(2) var t_mask: texture_2d; +@group(0) @binding(3) var t_depth: texture_depth_2d; +@group(0) @binding(4) var t_trace: texture_2d; +@group(0) @binding(5) var s_linear: sampler; +@group(0) @binding(6) var t_probe: texture_cube; +// Opaque scene depth plus reflective windows; receiver reconstruction uses t_depth. +@group(0) @binding(7) var t_hit_depth: texture_depth_2d; +@group(0) @binding(8) var t_vehicle: texture_2d; + +struct PuddleVertex { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +}; +@vertex +fn vs_main(@builtin(vertex_index) i: u32) -> PuddleVertex { + let x = f32(i32(i & 1u) * 4 - 1); + let y = f32(i32(i >> 1u) * 4 - 1); + return PuddleVertex(vec4(x, y, 0.0, 1.0), vec2((x + 1.0) * 0.5, (1.0 - y) * 0.5)); +} + +fn scene_pixel(uv: vec2) -> vec2 { + let size = vec2(textureDimensions(t_scene)); + return clamp(vec2(uv * vec2(size)), vec2(0), size - vec2(1)); +} +fn world_pos(uv: vec2, depth: f32) -> vec3 { + let h = p.inv_view_proj * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0); + return h.xyz / h.w; +} +fn linear_depth(depth: f32) -> f32 { + return p.projection_trace.y / max(depth + p.projection_trace.x, 1e-7); +} +fn clip_uv(c: vec4) -> vec2 { + return vec2(c.x / c.w * 0.5 + 0.5, 0.5 - c.y / c.w * 0.5); +} +fn finite_colour(c: vec3) -> vec3 { + let exponent = bitcast>(c) & vec3(0x7f800000u); + return select(vec3(0.0), clamp(c, vec3(0.0), vec3(65000.0)), all(exponent != vec3(0x7f800000u))); +} +fn reflection_colour(c: vec3) -> vec3 { + return select(c, srgb_encode(c), abs(p.vehicle_info.w) < 0.5); +} +fn scene_colour(c: vec3) -> vec3 { + return select(c, srgb_decode(c), abs(p.vehicle_info.w) < 0.5); +} +fn trace_miss(depth: f32) -> vec4 { + return vec4(select(vec3(0.0), vec3(1.0, 0.0, 0.0), p.projection_trace.z == 2.0), depth); +} +fn fallback_light(direction: vec3, px: vec2) -> vec3 { + if (p.vehicle_info.w < 0.5) { return p.sky.rgb; } + let lod = 0.03 * (p.origin_rain.w - 1.0); + let sky = finite_colour(textureSampleLevel(t_probe, s_linear, direction.xzy, lod).rgb * p.sky.w); + let open = smoothstep(-0.05, 0.35, direction.z); + let fallback = mix(p.sky.rgb, sky, mix(open, 1.0, 0.25)); + let mask = textureLoad(t_mask, px, 0); + // Sky ambient occlusion removes sky light; a local scene hit already contains its + // own lighting and must not be suppressed by the receiver's ambient occlusion. + return fallback * clamp(mask.g / max(mask.b * 0.49, 1e-6), 0.0, 1.0); +} +fn player_surface(world: vec3) -> bool { + for (var i = 0u; i < u32(p.vehicle_info.x); i++) { + let box = p.vehicle_parts[i]; + let d = world - box.a.xyz; + let local = vec3(d.x * box.b.x - d.y * box.a.w, + d.x * box.a.w + d.y * box.b.x, d.z) - box.c.xyz; + if (all(abs(local) < box.b.yzw + vec3(0.35))) { return true; } + } + return false; +} + +fn local_vehicle_plane(world: vec3) -> bool { + return p.vehicle_info.x > 0.5 && abs(dot(p.vehicle_plane.xyz, world) - p.vehicle_plane.w) < 0.04; +} + +// Reconstruct the receiver's geometric normal for roads on other grades. Use the +// nearer neighbor on each axis so a foreground bus or kerb does not tilt the water. +fn receiver_normal(px: vec2, uv: vec2, world: vec3, depth: f32) -> vec3 { + let size = vec2(textureDimensions(t_depth)); + var axes: array, 2>; + for (var i = 0; i < 2; i++) { + let axis = select(vec2(1, 0), vec2(0, 1), i == 1); + let plus = clamp(px + axis, vec2(0), size - vec2(1)); + let minus = clamp(px - axis, vec2(0), size - vec2(1)); + let dp = textureLoad(t_depth, plus, 0); + let dm = textureLoad(t_depth, minus, 0); + let forward = dp > 0.0 && (dm <= 0.0 || abs(dp - depth) < abs(dm - depth)); + let q = select(minus, plus, forward); + let d = select(dm, dp, forward); + axes[i] = (world_pos((vec2(q) + vec2(0.5)) / vec2(size), d) - world) + * select(-1.0, 1.0, forward); + } + let n = cross(axes[0], axes[1]); + if (dot(n, n) < 1e-12) { return vec3(0.0, 0.0, 1.0); } + return normalize(n * select(-1.0, 1.0, n.z > 0.0)); +} + +// How far from `world` the view ray through `uv` meets the water's plane there (normal +// `n`): a ray's footprint on it, one way (m). +fn ray_footprint(uv: vec2, world: vec3, n: vec3) -> f32 { + let r = normalize(world_pos(uv, 0.5) - p.eye_time.xyz); + let den = dot(r, n); + if (abs(den) < 1e-3) { return 1.0; } + let t = dot(world - p.eye_time.xyz, n) / den; + if (t <= 0.0) { return 1.0; } + return min(length(p.eye_time.xyz + r * t - world), 1.0); +} + +// Whether the trace's texel at `q` (its depth `d`) holds water of the same surface as the +// point `world` (Enhanced): the water lies flat, so a texel of it is at nearly the same +// height - a kerb, a bus's side or a wall behind is not. Compared by depth, the texels of a +// road seen at a slant differ more from row to row than the bilateral filters allowed, and +// the low quality's rays (4x4 pixels each) were kept apart into blocks. +fn same_water(q: vec2, d: f32, world: vec3) -> f32 { + let size = vec2(textureDimensions(t_trace)); + let w = world_pos((vec2(q) + vec2(0.5)) / size, d); + let tol = 0.05 + 0.004 * length(world - p.eye_time.xyz); + return 1.0 - smoothstep(tol, 2.0 * tol, abs(w.z - world.z)); +} + +@fragment +fn fs_trace(in: PuddleVertex) -> @location(0) vec4 { + let size = vec2(textureDimensions(t_scene)); + let centre = vec2(in.uv * vec2(size)); + // Pick a wet sample among the pixels this ray stands for (2x2 at half size, 4x4 on Low or + // past the ray budget), so a small pool off its centre still gets a ray: at most 3x3 + // looks, spread over them (2x2, the same pixels, at half size) - the looks per ray do not + // grow with the picture. The full-size resolve reapplies the exact mask. + var px = clamp(centre, vec2(0), size - vec2(1)); + var weight = 0.0; + let span = clamp(i32(p.quality.z), 1, 8); + let half = span / 2; + let taps = min(span, 3); + for (var y = 0; y < taps; y++) { + for (var x = 0; x < taps; x++) { + let at = (vec2(2 * x + 1, 2 * y + 1) * span) / (2 * taps) - vec2(half); + let q = clamp(centre + at, vec2(0), size - vec2(1)); + let w = textureLoad(t_mask, q, 0).b; + if (w > weight) { weight = w; px = q; } + } + } + if (weight < 0.004) { return vec4(0.0); } + let depth = textureLoad(t_depth, px, 0); + if (depth <= 0.0) { return vec4(0.0); } + let uv = (vec2(px) + vec2(0.5)) / vec2(size); + let world = world_pos(uv, depth); + let distance = length(world - p.eye_time.xyz); + if (distance > p.quality.x) { return vec4(0.0); } + var surface_normal = p.vehicle_plane.xyz; + if (!local_vehicle_plane(world)) { surface_normal = receiver_normal(px, uv, world, depth); } + // (Enhanced's rain rings, as fine as the ray's footprint on the water lets it see them; + // Vanilla+'s own) + var ripple = vec3(0.0); + if (p.vehicle_info.w > 0.5) { + let span = f32(clamp(i32(p.quality.z), 1, 8)); + let fp = max(ray_footprint(uv + vec2(span / f32(size.x), 0.0), world, surface_normal), + ray_footprint(uv + vec2(0.0, span / f32(size.y)), world, surface_normal)); + ripple = puddle_ripple_seen(world.xy + p.origin_rain.xy, p.eye_time.w, p.origin_rain.z, 1.0, fp); + } else { + ripple = puddle_ripple_classic(world.xy + p.origin_rain.xy, p.eye_time.w, p.origin_rain.z, 1.0); + } + let normal = normalize(surface_normal + vec3(ripple.xy, 0.0)); + let direction = reflect(normalize(world - p.eye_time.xyz), normal); + if (local_vehicle_plane(world)) { + let vehicle = textureSampleLevel(t_vehicle, s_linear, uv + ripple.xy * 0.006, 0.0); + if (vehicle.a > 0.01) { + if (p.projection_trace.z == 2.0) { return vec4(0.0, 1.0, 0.0, depth); } + if (p.projection_trace.z == 3.0) { return vec4(finite_colour(vehicle.rgb), depth); } + return vec4((reflection_colour(finite_colour(vehicle.rgb / max(vehicle.a, 1e-5))) - fallback_light(direction, px)) * vehicle.a, depth); + } + } + let start = world + normal * 0.025 + direction * 0.08; + let c0 = p.view_proj * vec4(start, 1.0); + let cd = p.view_proj * vec4(direction, 0.0); + var ray_length = 80.0; + // A steep downward camera reflects towards the near plane. Clip before projecting; + // projecting an endpoint behind the eye would turn the ray inside out. + if (cd.w < 0.0) { ray_length = min(ray_length, max(0.0, (c0.w - 0.1) / -cd.w)); } + if (ray_length < 0.1 || c0.w <= 0.0) { return trace_miss(depth); } + let c1 = c0 + cd * ray_length; + let uv0 = clip_uv(c0); + let uv1 = clip_uv(c1); + let duv = uv1 - uv0; + var end = 1.0; + // Trim to the screen rather than spending the rest of the budget outside it. + for (var axis = 0; axis < 2; axis++) { + if (abs(duv[axis]) > 1e-6) { + let edge = select(0.002, 0.998, duv[axis] > 0.0); + end = min(end, max(0.0, (edge - uv0[axis]) / duv[axis])); + } + } + let pixels = length(duv * end * vec2(size)); + if (pixels < 2.0) { return trace_miss(depth); } + let steps = i32(clamp(ceil(pixels / 8.0), 8.0, p.quality.y)); + let z0 = c0.z / c0.w; + let z1 = c1.z / c1.w; + var previous = 0.0; + var previous_delta = -1.0; + for (var i = 1; i <= steps; i++) { + let t = end * f32(i) / f32(steps); + let at = uv0 + duv * t; + let seen = textureLoad(t_hit_depth, scene_pixel(at), 0); + let delta = linear_depth(mix(z0, z1, t)) - linear_depth(seen); + if (seen > 0.0 && delta >= 0.0) { + var lo = previous; + var hi = t; + // Refine a crossing; checking thickness afterwards rejects silhouettes with + // empty space behind them instead of stretching the object's edge into water. + for (var j = 0; j < 5 && previous_delta < 0.0; j++) { + let mid = (lo + hi) * 0.5; + let md = textureLoad(t_hit_depth, scene_pixel(uv0 + duv * mid), 0); + if (md > 0.0 && linear_depth(mix(z0, z1, mid)) >= linear_depth(md)) { hi = mid; } + else { lo = mid; } + } + let hit_uv = uv0 + duv * hi; + let hit_depth = textureLoad(t_hit_depth, scene_pixel(hit_uv), 0); + let hit_linear = linear_depth(hit_depth); + let gap = linear_depth(mix(z0, z1, hi)) - hit_linear; + let hit_world = world_pos(hit_uv, hit_depth); + // The player vehicle has one consistent planar projection. A screen-space + // hit outside that silhouette would create a second, offset bumper/window. + if (player_surface(hit_world) && local_vehicle_plane(world)) { return trace_miss(depth); } + if (hit_depth > 0.0 && gap >= 0.0 && gap < p.projection_trace.w + hit_linear * 0.015 + && dot(hit_world - world, normal) > 0.05) { + let border = min(min(hit_uv.x, hit_uv.y), min(1.0 - hit_uv.x, 1.0 - hit_uv.y)); + let confidence = smoothstep(0.0, 0.04, border) * (1.0 - smoothstep(p.quality.x * 0.35, p.quality.x, distance)); + let colour = finite_colour(textureSampleLevel(t_scene, s_linear, hit_uv, 0.0).rgb); + if (p.projection_trace.z == 2.0) { return vec4(0.0, 1.0, 0.0, depth); } + if (p.projection_trace.z == 3.0) { return vec4(colour, depth); } + // Replace the reflected sky light rather than adding a second reflection. + return vec4((reflection_colour(colour) - fallback_light(direction, px)) * confidence, depth); + } + } + previous = t; + previous_delta = select(-1.0, delta, seen > 0.0); + } + return trace_miss(depth); +} + +// Separable five-tap binomial filter at the bounded trace resolution. Filter the +// signed lighting change, including misses, to soften silhouettes and isolated gaps. +// Receiver depth prevents mixing water on opposite sides of a kerb or foreground mesh. +fn filter_reflection(px: vec2, axis: vec2) -> vec4 { + let size = vec2(textureDimensions(t_trace)); + let centre = textureLoad(t_trace, px, 0); + if (centre.a <= 0.0) { return vec4(0.0); } + let kernel = array(1.0, 4.0, 6.0, 4.0, 1.0); + var sum = vec3(0.0); + var total = 0.0; + // (Enhanced blurs wider: a puddle on asphalt is no mirror, its picture is soft) + let step = select(1, 3, p.vehicle_info.w > 0.5); + let enhanced = p.vehicle_info.w > 0.5; + var here = vec3(0.0); + if (enhanced) { + here = world_pos((vec2(px) + vec2(0.5)) / vec2(size), centre.a); + } + for (var i = -2; i <= 2; i++) { + let q = clamp(px + axis * i * step, vec2(0), size - vec2(1)); + let r = textureLoad(t_trace, q, 0); + let difference = abs(r.a - centre.a) / max(centre.a, 1e-6); + var same = 1.0 - smoothstep(0.015, 0.06, difference); + if (enhanced && r.a > 0.0) { same = same_water(q, r.a, here); } + let w = kernel[u32(i + 2)] * same + * select(0.0, 1.0, r.a > 0.0); + sum += r.rgb * w; + total += w; + } + return vec4(sum / max(total, 1e-5), centre.a); +} +@fragment +fn fs_blur_x(in: PuddleVertex) -> @location(0) vec4 { + return filter_reflection(vec2(in.clip.xy), vec2(1, 0)); +} +@fragment +fn fs_blur_y(in: PuddleVertex) -> @location(0) vec4 { + return filter_reflection(vec2(in.clip.xy), vec2(0, 1)); +} + +@fragment +fn fs_resolve(in: PuddleVertex) -> @location(0) vec4 { + let px = vec2(in.clip.xy); + let base = textureLoad(t_scene, px, 0); + let weight = textureLoad(t_mask, px, 0).b; + if (p.projection_trace.z == 1.0) { return vec4(vec3(weight * 4.0), 1.0); } + if (weight < 0.004) { return base; } + let depth = textureLoad(t_depth, px, 0); + let size = vec2(textureDimensions(t_trace)); + if (p.projection_trace.z == 4.0) { + let world = world_pos(in.uv, depth); + return vec4(vec3(0.5 + (dot(p.vehicle_plane.xyz, world) - p.vehicle_plane.w) * 2.0), 1.0); + } + let q = in.uv * vec2(size) - vec2(0.5); + let origin = vec2(floor(q)); + let fraction = fract(q); + var sum = vec3(0.0); + var total = 0.0; + let enhanced = p.vehicle_info.w > 0.5; + var here = vec3(0.0); + if (enhanced) { + here = world_pos(in.uv, depth); + } + for (var y = 0; y < 2; y++) { + for (var x = 0; x < 2; x++) { + let c = clamp(origin + vec2(x, y), vec2(0), size - vec2(1)); + let r = textureLoad(t_trace, c, 0); + let f = select(vec2(1.0) - fraction, fraction, vec2(x == 1, y == 1)); + // Bilateral upsampling keeps a half-size ray on its receiver. The full-size + // material mask keeps reflections off kerbs, bus bodies and dry patches. + let difference = abs(r.a - depth) / max(depth, 1e-6); + var same = 1.0 - smoothstep(0.01, 0.04, difference); + if (enhanced && r.a > 0.0) { same = same_water(c, r.a, here); } + let w = f.x * f.y * same * select(0.0, 1.0, r.a > 0.0); + sum += r.rgb * w; + total += w; + } + } + if (p.projection_trace.z > 1.0) { return vec4(max(sum / max(total, 1e-5), vec3(0.0)), 1.0); } + return vec4(scene_colour(max(reflection_colour(base.rgb) + sum / max(total, 1e-5) * weight, vec3(0.0))), base.a); +} diff --git a/crates/mx/tests/openomsi/rain.wgsl b/crates/mx/tests/openomsi/rain.wgsl new file mode 100644 index 0000000..50b2afe --- /dev/null +++ b/crates/mx/tests/openomsi/rain.wgsl @@ -0,0 +1,1218 @@ +// What the snowfall (snow.wgsl) and the rainfall (rain.wgsl) share: the camera, a hash of +// a particle's number, and the player's vehicle the weather is kept out of. +struct Camera { + view_proj: mat4x4, + cam_pos: vec4, + // (kept in lockstep with `CameraUniform` in lib.rs, as sky.wgsl's) + world_origin: vec4, + sun_dir: vec4, + ambient: vec4, + fog: vec4, + sun_color: vec4, + sky_color: vec4, + light_grid: vec4, + sky: vec4, + cam_right: vec4, + cam_up: vec4, + clouds: vec4, + light_view_proj: mat4x4, + light_view_proj_far: mat4x4, + shadow: vec4, + post: vec4, + inside_a: vec4, + inside_b: vec4, + inside_c: vec4, + flags: vec4, + light_view_proj_close: mat4x4, + wind: vec4, + lamp_view_proj: array, 56>, + lamp_atlas: vec4, + tree_wind: vec4, + inside2_a: vec4, + inside2_b: vec4, + inside2_c: vec4, + cookies: array, 8>, + cabin_lamps: array, 4>, + // x: the textures' mip bias (FSR 1: negative, see `CameraUniform::lod`) + lod: vec4, + // (the classic picture's headlight, `CameraUniform::spot`: unread here) + spot: array, 4>, +}; +@group(0) @binding(0) var camera: Camera; + +fn hash4(n: u32) -> vec4 { + var x = vec4(n, n * 747796405u + 2891336453u, n ^ 0x9e3779b9u, n * 1664525u + 1013904223u); + x = x * 1664525u + 1013904223u; + x.x = x.x + x.y * x.w; + x.y = x.y + x.z * x.x; + x.z = x.z + x.x * x.y; + x.w = x.w + x.y * x.z; + x = x ^ (x >> vec4(16u)); + x.x = x.x + x.y * x.w; + x.y = x.y + x.z * x.x; + x.z = x.z + x.x * x.y; + return vec4(x & vec4(0xffffffu)) / 16777216.0; +} + +// The precipitation's roof map (passes/precip_map.rs): what stands over the ground round +// the camera, its depth seen from straight above. +@group(1) @binding(1) var roof_map: texture_depth_2d; +fn roof_depth(t: vec2) -> f32 { return textureLoad(roof_map, t, 0); } + +// Whether something solid stands over `p` (the map's matrix `m`; `on` 0 without a map): a +// bus's or a car's roof, a shelter, a bridge, a house - no drop or flake falls there. +fn under_roof(p: vec3, m: mat4x4, on: f32) -> bool { + let c = m * vec4(p, 1.0); + let uv = vec2(c.x * 0.5 + 0.5, 0.5 - c.y * 0.5); + let side = f32(textureDimensions(roof_map).x); + let t = vec2(clamp(uv, vec2(0.0), vec2(0.9999)) * side); + let top = roof_depth(t); + // (5 cm under it: the map's depth reaches 300 m) + return on > 0.5 && all(abs(c.xy) < vec2(1.0)) && c.z > top + 0.00017; +} + +// 1 inside the player's own vehicle (its box, a little wider): no snow falls in the cab +fn in_own_vehicle(p: vec3) -> bool { + // (the front and, of an articulated bus, the rear section: it snowed in the back, #1967; + // without branches - two boxes tested with early returns and short-circuits brought + // Apple's M4 shader compiler service down, XPC_ERROR_CONNECTION_INTERRUPTED, and the + // game fell back to no snowfall) + return any(vec2(in_box(p, camera.inside_a, camera.inside_b, camera.inside_c), in_box(p, camera.inside2_a, camera.inside2_b, camera.inside2_c))); +} + +fn in_box(p: vec3, a: vec4, b: vec4, c: vec4) -> bool { + let d = p - a.xyz; + let sh = a.w; + let ch = b.x; + let q = vec3(d.x * ch - d.y * sh - c.x, d.x * sh + d.y * ch - c.y, d.z - c.z); + let h = b.yzw + vec3(0.3); + return select(false, all(abs(q) < h), c.w >= 0.5); +} + +// Enhanced: the sun's far shadow map (the scene's camera group), which keeps every caster - +// a drop or a flake in the shade of a house or under the trees does not catch the sun. +@group(0) @binding(6) var s_shadow: sampler_comparison; +@group(0) @binding(7) var t_shadow_far: texture_depth_2d; + +// Enhanced: the procedural flake atlas (precip.rs `FlakeAtlas`): eight cells of snow +// crystals and flakes, R how much of a texel they cover, G how bright it is. +@group(1) @binding(2) var t_flakes: texture_2d; +@group(1) @binding(3) var s_flakes: sampler; + +// How far `p` is over whatever stands uppermost there by the roof map (m): below 0 under a +// roof, and far over everything where there is no map. +fn roof_clearance(p: vec3, m: mat4x4, on: f32) -> f32 { + let c = m * vec4(p, 1.0); + let uv = vec2(c.x * 0.5 + 0.5, 0.5 - c.y * 0.5); + let side = f32(textureDimensions(roof_map).x); + let top = roof_depth(vec2(clamp(uv, vec2(0.0), vec2(0.9999)) * side)); + // (the map looks straight down: its depth goes against the height, m[2].z < 0) + let h = (c.z - top) / m[2].z; + return select(1e4, h, on > 0.5 && all(abs(c.xy) < vec2(1.0)) && top < 0.9999); +} + +// The wind's gusts: it swells and slackens over some seconds, each swell running downwind +// over the ground as a wave some 70 m long, so that neighbouring drops and flakes are blown +// together and a gust is seen to sweep through the rain. x: the time's worth of the mean +// wind the gusts have added to a particle's way by `t` (the swell's integral, s), y: the +// swell now (a share of the mean wind). +fn precip_gust(x: vec2, t: f32, wind: vec2, strength: f32) -> vec2 { + let speed = length(wind); + let along = dot(x, wind / max(speed, 1e-3)) * (6.2831853 / 70.0); + let across = dot(x, vec2(-wind.y, wind.x) / max(speed, 1e-3)) * (6.2831853 / 160.0); + let w1 = 0.42; + let w2 = 1.17; + let a1 = 0.38 * strength; + let a2 = 0.17 * strength; + let p1 = w1 * t - along + 0.6 * sin(across); + let p2 = w2 * t - 2.3 * along + 1.7 + across; + return vec2(-a1 * cos(p1) / w1 - a2 * cos(p2) / w2, a1 * sin(p1) + a2 * sin(p2)); +} + +// How much of the sun reaches `p` (Enhanced): one compare in the far cascade, lit beyond it +// and without shadow maps. +fn precip_sun(p: vec3) -> f32 { + if (camera.shadow.x < 0.5 || enh.sun.r + enh.sun.g < 1e-4) { + return 1.0; + } + let lp = camera.light_view_proj_far * vec4(p, 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (any(uv < vec2(0.0)) || any(uv > vec2(1.0)) || lp.z < 0.0 || lp.z > 1.0) { + return 1.0; + } + return textureSampleCompareLevel(t_shadow_far, s_shadow, uv, lp.z - 0.0004); +} + +// A hash of a cell of the plane (0..1 each), its integer coordinates taken modulo 4096 so +// that the world's large figures stay exact. +fn cell_hash(c: vec2) -> vec4 { + let w = c - 4096.0 * floor(c / 4096.0); + let i = vec2(w); + return hash4(i.x * 4099u + i.y * 7919u + 17u); +} + +// The panels of a far veil of rain or snow (Enhanced): rings of upright panels round the +// camera, twelve a ring, each a strip of four vertices. Beyond the particles' layers the +// drops or flakes are too many and too small to draw one by one, and a heavy fall is seen +// there as what it is, a grey sheet streaked or speckled by them, sweeping by with the +// wind. `c`: the corner (0..1 each way); returns the corner's place (render frame) in xyz +// and its ring's radius in w. +fn veil_corner(panel: u32, c: vec2) -> vec4 { + var radii = array(30.0, 48.0, 78.0); + let ring = min(panel / 12u, 2u); + let r = radii[ring]; + // (each panel a little wider than its twelfth, so that the chords close the ring; the + // rings turned against each other, so their joins do not line up) + let a = (f32(panel % 12u) + c.x * 1.04 - 0.02 + 0.37 * f32(ring)) * (6.2831853 / 12.0); + let z = camera.cam_pos.z + mix(-6.0, 26.0 + 0.4 * r, c.y); + return vec4(camera.cam_pos.xy + vec2(cos(a), sin(a)) * r, z, r); +} + +// The rainfall, every mode: a field of drops that lives on the GPU alone, as the snowfall +// does (snow.wgsl) - each drop's place is worked out here from its number, the time, the +// wind and the camera, so that a downpour is a quarter of a million drops for one draw. +// The field is the world's, repeating round the camera in three layers, dense close by, +// thinner further out; beyond them the rain's extinction takes the view (the fog). +// +// A drop is seen as the streak it draws in the eye's time (`ep.eye.w`): its way against +// the eye in that time, short and upright standing, long and slanting at a moving bus's +// windscreen. It is as wide as the drop is - a raindrop of two millimetres is less than a +// pixel wide a few metres off - so a streak is drawn a pixel wide at least, as transparent +// as the drop covers less of it: a downpour is a veil of many fine, faint lines, not a few +// thick ones. The drops are drawn as rain shows them, weighted by the light they catch +// (their cross-section) from Marshall and Palmer's sizes (a gamma of order 3 over the +// exponential), each falling at its own speed (Atlas, Srivastava and Sekhon 1973). + +struct RainParams { + // xyz the wind the drops drift with (m/s), w the time (s) + wind: vec4, + // xyz the eye's velocity (m/s, world), w the time the eye sees a drop as one streak (s) + eye: vec4, + // x how hard it rains (0..1), y the median volume diameter of its drops (m), zw how + // many drops the first two layers hold (the rest are the third's) + fall: vec4, + // xy the picture's size (px), z how opaque a drop's streak is, w how many of the + // instances are drops (the rest are their splashes) + view: vec4, + // the precipitation's roof map: its matrix, and x 1 when there is one + roof: mat4x4, + roof_on: vec4, + // Enhanced: x the instance the veil's panels begin at (the drops' and the splashes' end), + // y how many panels there are, z how strong the wind's gusts are (0..1), w the rain's + // quality (0 low .. 2 high) + ext: vec4, +}; +@group(1) @binding(0) var rp: RainParams; + +struct RainOut { + @builtin(position) clip: vec4, + // across the streak and along it from its tail (px) + @location(0) uv: vec2, + // x the streak's half width, y its length (px), z its cover (alpha) + @location(1) @interpolate(flat) shape: vec3, + @location(2) pos: vec3, +}; + +// The layers round the camera: half width, bottom and top (m). +const RAIN_LAYERS = array, 3>(vec3(5.0, -2.5, 6.0), vec3(14.0, -3.0, 12.0), vec3(32.0, -3.0, 22.0)); + +// Where a drop lands: a crown of water a centimetre or two high that is gone in a tenth of +// a second - on whatever is uppermost there, the ground, a kerb, a bus's roof, as the +// precipitation's roof map has it (none without the map). Each splash takes a new place +// round the camera every time it comes round again; the most of them close by. +fn splash(vid: u32, s: u32) -> RainOut { + // (a strip of four vertices) + let c = vec2(f32(i32(vid & 1u) * 2 - 1), f32(i32(vid >> 1u) * 2 - 1)); + var out: RainOut; + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + out.uv = vec2(0.0); + out.shape = vec3(0.0); + out.pos = vec3(0.0); + let life = 0.1; + let h0 = hash4(s * 3u + 11u); + let cycle = rp.wind.w / life + h0.w; + let age = fract(cycle); + let h = hash4(s * 7919u + u32(floor(cycle)) * 2654435761u); + // its place in the world: a field 28 m square laid over the world (in the world's own + // figures), the copy of it round the camera - a splash stays where it landed however + // the camera moves or turns, and only those the camera leaves behind come round again + // ahead of it + let size = 28.0; + let world_cam = camera.cam_pos.xy + camera.world_origin.xy; + let lo = world_cam - vec2(0.5 * size); + let wxy = lo + (((h.xy * size - lo) % size) + size) % size; + let xy = wxy - camera.world_origin.xy; + // (fewer further off, faded in and out by the distance alone) + let fade_far = 1.0 - smoothstep(6.0, 14.0, length(xy - camera.cam_pos.xy)); + let m = rp.roof; + let mc = m * vec4(xy, 0.0, 1.0); + let uv = vec2(mc.x * 0.5 + 0.5, 0.5 - mc.y * 0.5); + let side = f32(textureDimensions(roof_map).x); + let top = roof_depth(vec2(clamp(uv, vec2(0.0), vec2(0.9999)) * side)); + // (the map's depth back to a height: it looks straight down) + let z = (top - mc.z) / m[2].z; + let p = vec3(xy, z + 0.008 + 0.012 * age); + let ch = camera.view_proj * vec4(p, 1.0); + let cu = camera.view_proj * vec4(p + camera.cam_up.xyz, 1.0); + if (rp.roof_on.x < 0.5 || top >= 0.9999 || ch.w < 0.3 || in_own_vehicle(p)) { + return out; + } + let half_px = 0.5 * rp.view.xy; + let px_per_m = length(cu.xy / cu.w * half_px - ch.xy / ch.w * half_px); + // the crown widens as it rises and falls back, and fades + let w = (0.006 + 0.02 * age) * px_per_m; + let hw = max(0.5 * w, 0.5); + let pad = hw + 1.0; + let cover = min(w, 1.0) * (1.0 - age) * (1.0 - age) * 0.8 * rp.view.z * fade_far; + out.clip = vec4(ch.xy + c * pad / half_px * ch.w, ch.zw); + out.uv = c * pad; + // (a round speck: no length, see `streak_alpha`) + out.shape = vec3(hw, -1.0, cover); + out.pos = p; + return out; +} + +@vertex +fn vs_rain(@builtin(vertex_index) vid: u32, @builtin(instance_index) k: u32) -> RainOut { + if (k >= u32(rp.view.w)) { + return splash(vid, k - u32(rp.view.w)); + } + // across (-1, 1) and along (0 the tail, 1 the head) + let c = vec2(f32(i32(vid & 1u) * 2 - 1), f32(vid >> 1u)); + var out: RainOut; + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + out.uv = vec2(0.0); + out.shape = vec3(0.0); + out.pos = vec3(0.0); + let n0 = u32(rp.fall.z); + let n1 = u32(rp.fall.w); + let layer = select(select(2u, 1u, k < n0 + n1), 0u, k < n0); + let lh = RAIN_LAYERS[layer]; + let size = vec3(2.0 * lh.x, 2.0 * lh.x, lh.z - lh.y); + let h1 = hash4(k * 2u + 3u); + let h2 = hash4(k * 2u + 6007u); + // the drop: its diameter (m), drawn by its cross-section from the rain's sizes, and + // the speed it falls at + let lambda = 3.67 / max(rp.fall.y, 1e-4); + let d = clamp(-log(max(h2.x * h2.y * h2.z, 1e-12)) / lambda, 0.0003, 0.006); + let fall = max(9.65 - 10.3 * exp(-600.0 * d), 0.5); + // its place in the world: where it started, carried by the wind, falling; then the + // copy of the field nearest the camera (in the world's own figures, so that it stays + // put while the render origin moves) + let t = rp.wind.w; + let world_cam = camera.cam_pos.xyz + vec3(camera.world_origin.xy, 0.0); + let vel = vec3(rp.wind.xy, -fall); + let lo = world_cam + vec3(-lh.x, -lh.x, lh.y); + // (the field repeats every `size`: the place wrapped into one copy of it) + let wrapped = (h1.xyz * size + vel * t - lo) / size; + let q = lo + (wrapped - floor(wrapped)) * size; + let p = q - vec3(camera.world_origin.xy, 0.0); + // a denser layer thins out with the distance from the eye, over the whole of its reach, + // into the thinner one round it: faded only at its edges, it stood round the camera as a + // box of dense rain that went wherever the camera went + let rel = q - lo; + let e = min(rel, size - rel) / (lh.x * 0.3); + let edge = clamp(min(min(e.x, e.y), e.z), 0.0, 1.0); + let reach = 1.0 - smoothstep(0.25 * lh.x, lh.x, length((q - world_cam).xy)); + let fade = select(1.0, edge * reach, layer < 2u); + // a drop right at the eye is a blur too wide and faint to see, not a streak + let near = smoothstep(0.6, 1.6, length(p - camera.cam_pos.xyz)); + // the streak: from where the drop was against the eye a streak's time ago to where it is + let ch = camera.view_proj * vec4(p, 1.0); + // (the field reaches all round the camera, most of it out of the picture: a drop well + // beyond its edge - a streak is a few per cent of the picture long - is let go before + // the rest of its work, and so is one too faint to see) + if (fade * near < 0.01 || ch.w < 0.1 || abs(ch.x) > 1.5 * ch.w || abs(ch.y) > 1.5 * ch.w) { + return out; + } + let tail = p - (vel - rp.eye.xyz) * rp.eye.w; + let ct = camera.view_proj * vec4(tail, 1.0); + if (ct.w < 0.1 || in_own_vehicle(p) || under_roof(p, rp.roof, rp.roof_on.x)) { + return out; + } + let cu = camera.view_proj * vec4(p + camera.cam_up.xyz, 1.0); + let half_px = 0.5 * rp.view.xy; + let sh = ch.xy / ch.w * half_px; + let st = ct.xy / ct.w * half_px; + let along = sh - st; + let len = length(along); + let dir = select(vec2(0.0, 1.0), along / max(len, 1e-4), len > 1e-3); + let across = vec2(-dir.y, dir.x); + // as wide as the drop (out of focus close by: its blur as wide as the pupil, some + // 2.5 mm), a pixel at least - and as much fainter as it is narrower than that + let px_per_m = length(cu.xy / cu.w * half_px - sh); + let blur = sqrt(d * d + 0.0025 * 0.0025); + let w = blur * px_per_m; + // and spread along its way: the drop lies on each pixel of its streak for the share of + // the eye's time it takes to cross it - a long streak is a faint one (the drop's lens + // gathers the sky's light, brighter than what is behind it: some six times its width) + let spread = clamp(6.0 * max(w, 1.0) / max(len, 1.0), 0.2, 1.0); + let cover = min(w, 1.0) * (d / blur) * spread * fade * near * rp.view.z * clamp(sqrt(d / 0.002), 0.5, 1.4); + // (a hair under a pixel at the least: a picture drawn smaller and scaled up widened the + // full-pixel lines into the thick white bars of the old sprites) + let hw = max(0.5 * w, 0.4); + let pad = hw + 1.0; + // the quad round the streak (the head's and the tail's clip positions mixed, so that it + // keeps the depth along it) widened in the picture's pixels + let clip = mix(ct, ch, c.y); + let off = across * c.x * pad + dir * (c.y * 2.0 - 1.0) * pad; + out.clip = vec4(clip.xy + off / half_px * clip.w, clip.zw); + out.uv = vec2(c.x * pad, c.y * (len + 2.0 * pad) - pad); + out.shape = vec3(hw, len, cover); + out.pos = p; + return out; +} + +fn streak_alpha(in: RainOut) -> f32 { + let hw = in.shape.x; + let len = in.shape.y; + // a pixel's edge across and at both ends, and a little fainter towards the tail + let a_across = clamp(hw + 0.5 - abs(in.uv.x), 0.0, 1.0); + let a_along = clamp(0.5 + min(in.uv.y, len - in.uv.y), 0.0, 1.0); + let tail = mix(0.55, 1.0, clamp(in.uv.y / max(len, 1.0), 0.0, 1.0)); + // (a splash's round speck) + let speck = clamp(hw + 0.5 - length(in.uv), 0.0, 1.0); + return clamp(in.shape.z * select(a_across * a_along * tail, speck, len < 0.0), 0.0, 1.0); +} + +// the classic picture: water lit as the scene is (envir.cfg's ambient and sun light) +@fragment +fn fs_rain(in: RainOut) -> @location(0) vec4 { + let a = streak_alpha(in); + let light = min(camera.ambient.rgb + camera.sky_color.rgb * 0.5 + camera.sun_color.rgb * 0.3, vec3(1.0)) * vec3(0.68, 0.7, 0.75); + return vec4(light * a, a); +} + + +// ---- The enhanced rainfall +// +// The same field of drops, drawn as rain photographs: each drop the streak it leaves in the +// eye's time, its length and slant its way against the eye (the bus's own motion, the wind +// and its gusts), a soft line as wide as the drop with rounded ends, beaded along a long +// streak where the oscillating drop flickers. A drop is a small ball lens: it carries the +// light of what lies round it turned over - the sky in its lower half, the street in its +// upper - so that by day it is a silvery line, faint against the bright sky and clear +// against a dark street, glows when the sun shines through it from behind, colours the +// rainbow's ring round the antisolar point, and flashes in the lamps and headlights at +// night (`precip_light`). Where the drops land, crowns of water rise and throw droplets; +// beyond the drops' layers the rain is a veil of streaks (`veil_corner`). + +struct RainOutE { + @builtin(position) clip: vec4, + // a drop: across its streak and along it from the tail (px); a splash: across it and up + // it (-1..1, 0..1 and over); the veil: the panel's corner (0..1) + @location(0) uv: vec2, + // a drop: x the streak's half width, y its length (px); a splash: x one pixel in its + // own measure, y its age (0..1); z the cover, w which it is (0 a drop, 1 a splash, 2 the + // veil) + @location(1) @interpolate(flat) shape: vec4, + @location(2) pos: vec3, + // x a number of the particle's own (0..1), y the veil's radius (m), z its ring + @location(3) @interpolate(flat) seed: vec4, +}; + +fn rain_none() -> RainOutE { + var out: RainOutE; + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + out.uv = vec2(0.0); + out.shape = vec4(0.0); + out.pos = vec3(0.0); + out.seed = vec4(0.0); + return out; +} + +@vertex +fn vs_rain_enhanced(@builtin(vertex_index) vid: u32, @builtin(instance_index) k: u32) -> RainOutE { + if (k >= u32(rp.ext.x)) { + return rain_veil(vid, k - u32(rp.ext.x)); + } + if (k >= u32(rp.view.w)) { + return rain_crown(vid, k - u32(rp.view.w)); + } + return rain_drop(vid, k); +} + +fn rain_drop(vid: u32, k: u32) -> RainOutE { + // across (-1, 1) and along (0 the tail, 1 the head) + let c = vec2(f32(i32(vid & 1u) * 2 - 1), f32(vid >> 1u)); + var out = rain_none(); + let n0 = u32(rp.fall.z); + let n1 = u32(rp.fall.w); + let layer = select(select(2u, 1u, k < n0 + n1), 0u, k < n0); + let lh = RAIN_LAYERS[layer]; + let size = vec3(2.0 * lh.x, 2.0 * lh.x, lh.z - lh.y); + let h1 = hash4(k * 2u + 3u); + let h2 = hash4(k * 2u + 6007u); + // the drop's diameter and speed, as `vs_rain` draws them + let lambda = 3.67 / max(rp.fall.y, 1e-4); + let d = clamp(-log(max(h2.x * h2.y * h2.z, 1e-12)) / lambda, 0.0003, 0.006); + let fall = max(9.65 - 10.3 * exp(-600.0 * d), 0.5); + let t = rp.wind.w; + let world_cam = camera.cam_pos.xyz + vec3(camera.world_origin.xy, 0.0); + let lo = world_cam + vec3(-lh.x, -lh.x, lh.y); + let wrapped = (h1.xyz * size + vec3(rp.wind.xy, -fall) * t - lo) / size; + let q0 = lo + (wrapped - floor(wrapped)) * size; + // the gusts carry it on from its place in the field, and slant it as they blow + let g = precip_gust(q0.xy, t, rp.wind.xy, rp.ext.z); + let q = q0 + vec3(rp.wind.xy * g.x, 0.0); + let vel = vec3(rp.wind.xy * (1.0 + g.y), -fall); + let p = q - vec3(camera.world_origin.xy, 0.0); + // every layer fades out at its edges (where its drops come round again, the gusts' + // way at the far side of the field differs from the near side's), the denser ones + // over their whole reach into the thinner round them + let rel = q0 - lo; + let e = min(rel, size - rel) / (lh.x * 0.3); + let edge = clamp(min(min(e.x, e.y), e.z), 0.0, 1.0); + let reach = 1.0 - smoothstep(0.25 * lh.x, lh.x, length((q - world_cam).xy)); + let fade = edge * select(1.0, reach, layer < 2u); + let near = smoothstep(0.5, 1.4, length(p - camera.cam_pos.xyz)); + let ch = camera.view_proj * vec4(p, 1.0); + if (fade * near < 0.01 || ch.w < 0.1 || abs(ch.x) > 1.5 * ch.w || abs(ch.y) > 1.5 * ch.w) { + return out; + } + let tail = p - (vel - rp.eye.xyz) * rp.eye.w; + let ct = camera.view_proj * vec4(tail, 1.0); + if (ct.w < 0.1 || in_own_vehicle(p) || under_roof(p, rp.roof, rp.roof_on.x)) { + return out; + } + let cu = camera.view_proj * vec4(p + camera.cam_up.xyz, 1.0); + let half_px = 0.5 * rp.view.xy; + let sh = ch.xy / ch.w * half_px; + let st = ct.xy / ct.w * half_px; + let along = sh - st; + let len = length(along); + let dir = select(vec2(0.0, 1.0), along / max(len, 1e-3), len > 1e-3); + let across = vec2(-dir.y, dir.x); + // as wide as the drop, a millimetre's blur at the least (crisp close by: the eye is + // focused on the street, a few metres off, and a drop there is sharp), and spread over + // its way as `vs_rain` spreads it + let px_per_m = length(cu.xy / cu.w * half_px - sh); + // (a millimetre and a half at the least: at one millimetre the near drops drew as opaque + // grey lines) + let blur = sqrt(d * d + 0.0015 * 0.0015); + let w = blur * px_per_m; + let spread = clamp(6.0 * max(w, 1.0) / max(len, 1.0), 0.1, 1.0); + let cover = min(w, 1.0) * (d / blur) * spread * fade * near * rp.view.z * clamp(sqrt(d / 0.002), 0.5, 1.4); + let hw = max(0.5 * w, 0.4); + let pad = hw + 1.5; + let clip = mix(ct, ch, c.y); + let off = across * c.x * pad + dir * (c.y * 2.0 - 1.0) * pad; + out.clip = vec4(clip.xy + off / half_px * clip.w, clip.zw); + out.uv = vec2(c.x * pad, c.y * (len + 2.0 * pad) - pad); + out.shape = vec4(hw, len, cover, 0.0); + out.pos = p; + out.seed = vec4(h2.w, 0.0, 0.0, 0.0); + return out; +} + +// Where a drop lands (`splash`'s places): a crown of water rises round the impact for a +// few hundredths of a second, its rim breaks into points, and the points fling droplets +// out on short arcs that fall back - on the street, a kerb, a bus's roof. Upright, it is +// drawn facing the eye. +fn rain_crown(vid: u32, s: u32) -> RainOutE { + // across (-1, 1) and up (0, 1) + let c = vec2(f32(i32(vid & 1u) * 2 - 1), f32(vid >> 1u)); + var out = rain_none(); + let life = 0.24; + let h0 = hash4(s * 3u + 11u); + let cycle = rp.wind.w / life + h0.w; + let age = fract(cycle); + let h = hash4(s * 7919u + u32(floor(cycle)) * 2654435761u); + let size = 28.0; + let world_cam = camera.cam_pos.xy + camera.world_origin.xy; + let lo = world_cam - vec2(0.5 * size); + let wxy = lo + (((h.xy * size - lo) % size) + size) % size; + let xy = wxy - camera.world_origin.xy; + let fade_far = 1.0 - smoothstep(7.0, 16.0, length(xy - camera.cam_pos.xy)); + let m = rp.roof; + let mc = m * vec4(xy, 0.0, 1.0); + let uv = vec2(mc.x * 0.5 + 0.5, 0.5 - mc.y * 0.5); + let side = f32(textureDimensions(roof_map).x); + let top = roof_depth(vec2(clamp(uv, vec2(0.0), vec2(0.9999)) * side)); + let p = vec3(xy, (top - mc.z) / m[2].z + 0.002); + let ch = camera.view_proj * vec4(p, 1.0); + if (rp.roof_on.x < 0.5 || top >= 0.9999 || fade_far <= 0.0 || ch.w < 0.3 || in_own_vehicle(p)) { + return out; + } + let cu = camera.view_proj * vec4(p + camera.cam_up.xyz, 1.0); + let half_px = 0.5 * rp.view.xy; + let px_per_m = length(cu.xy / cu.w * half_px - ch.xy / ch.w * half_px); + // a few centimetres across, the bigger the drops the bigger, and at least a few pixels + // (the crown drawn smaller inside it, its parts no thinner than a pixel) + let scale = clamp(rp.fall.y / 0.0018, 0.6, 1.6) * (0.7 + 0.6 * h.z); + let half_w = 0.045 * scale; + let grow = max(1.0, 2.0 / max(half_w * px_per_m, 1e-3)); + let to_cam = camera.cam_pos.xyz - p; + let flat_side = vec3(-to_cam.y, to_cam.x, 0.0); + let ax = select(vec3(1.0, 0.0, 0.0), normalize(flat_side), length(flat_side) > 1e-4); + let corner = p + ax * (c.x * half_w * grow) + vec3(0.0, 0.0, (c.y * 1.2 * grow - 0.05) * half_w); + out.clip = camera.view_proj * vec4(corner, 1.0); + out.uv = vec2(c.x * grow, (c.y * 1.2 * grow - 0.05)); + out.shape = vec4(1.0 / max(half_w * px_per_m, 1e-3), age, 0.9 * rp.view.z * fade_far, 1.0); + out.pos = p; + out.seed = vec4(h.w, 0.0, 0.0, 0.0); + return out; +} + +fn rain_veil(vid: u32, panel: u32) -> RainOutE { + let c = vec2(f32(vid & 1u), f32(vid >> 1u)); + var out = rain_none(); + let v = veil_corner(panel, c); + let ring = f32(panel / 12u); + // (none in a light rain, whose drops are not seen that far) + if (rp.fall.x < 0.15) { + return out; + } + out.clip = camera.view_proj * vec4(v.xyz, 1.0); + out.uv = c; + // (the rain's streaks are seen beyond the drops only in a fair rain, and as a veil in a + // heavy one; the further rings stand for more rain behind them) + out.shape = vec4(0.0, 0.0, pow(rp.fall.x, 1.5) * 0.085 * (0.8 + 0.2 * ring), 2.0); + out.pos = v.xyz; + out.seed = vec4(0.0, v.w, ring, 0.0); + return out; +} + +fn drop_alpha(in: RainOutE) -> f32 { + let hw = in.shape.x; + let len = in.shape.y; + // across: a soft line, as a lens draws a thin one - at least a pixel's blur + let s = max(hw * 0.85, 0.6); + let across = exp(-0.5 * in.uv.x * in.uv.x / (s * s)); + // along: the drop's way, its ends rounded as wide as the drop + let e = hw + 0.7; + let along = smoothstep(-e, e, in.uv.y) * smoothstep(-e, e, len - in.uv.y); + // a little brighter at the head (where the drop is now), and a long streak beaded: a + // falling drop oscillates a few hundred times a second, its glint flickering on its way + let f = clamp(in.uv.y / max(len, 1.0), 0.0, 1.0); + let beads = 1.0 + 0.22 * sin(in.uv.y * (0.35 + 0.3 * in.seed.x) + in.seed.x * 40.0) * smoothstep(12.0, 40.0, len); + return clamp(in.shape.z * across * along * mix(0.75, 1.0, f) * beads, 0.0, 1.0); +} + +fn crown_alpha(in: RainOutE) -> f32 { + let px = in.shape.x; + let age = in.shape.y; + let seed = in.seed.x; + let uv = in.uv; + // the crown: a thin sheet rising round the impact, a cylinder seen from the side - most + // of it at its outline, where the eye looks along the sheet - its rim pulled into points + let rise = smoothstep(0.0, 0.18, age) * (1.0 - smoothstep(0.3, 0.6, age)); + let r = 0.35 + 0.5 * sqrt(age); + let x = uv.x / r; + let points = 7.0 + floor(seed * 5.0); + let ang = asin(clamp(x, -1.0, 1.0)); + let tips = pow(abs(cos(ang * points * 0.5 + seed * 6.2831853)), 6.0); + let top = rise * (0.5 + 0.35 * tips) * (0.8 + 0.4 * fract(seed * 7.3)); + let outline = 0.3 + 0.7 * smoothstep(0.5, 1.0, abs(x)); + let side = 1.0 - smoothstep(1.0 - px / r, 1.0 + px / r, abs(x)); + let below = 1.0 - smoothstep(top - px, top + px, uv.y); + // (a sheet thinner than a pixel is as faint as it is thin) + let crown = side * below * outline * step(0.0, uv.y) * 0.75 * min(1.0, 0.04 / px); + // the droplets the points fling off, on arcs out and up and back down + var drops = 0.0; + let fly = max(age - 0.14, 0.0); + let rad = max(0.07, px); + for (var i = 0u; i < 5u; i = i + 1u) { + let hi = hash4(u32(seed * 16777216.0) + i * 977u); + let vx = (hi.x * 2.0 - 1.0) * 2.4; + let vy = 2.2 + 2.2 * hi.y; + let q = vec2(sign(vx) * r * 0.9 + vx * fly, 0.5 * rise + vy * fly - 14.0 * fly * fly); + let a = (1.0 - smoothstep(rad - px, rad + px, length(uv - q))) * step(0.0, q.y) * step(0.05, fly); + drops = max(drops, a * (0.07 / rad) * (0.07 / rad) * step(hi.z, 0.8)); + } + return clamp(in.shape.z * max(crown, drops) * (1.0 - age * age), 0.0, 1.0); +} + +fn veil_rain_alpha(in: RainOutE) -> f32 { + let r = in.seed.y; + let ring = in.seed.z; + let d = in.pos - camera.cam_pos.xyz; + let theta = atan2(d.y, d.x); + let t = rp.wind.w; + let tang = vec2(-sin(theta), cos(theta)); + let fall = 7.0; + // (the wind slants the streaks: so many metres sideways for each metre of fall) + let slant = dot(rp.wind.xy, tang) / fall; + // Columns of streaks, a fixed angle apart (a few pixels) and a whole number of them to + // the ring, so that its seam does not show; each column's drops fall at their own + // speed, a streak a stretch of it. + var streaks = 0.0; + for (var j = 0u; j < 2u; j = j + 1u) { + let fj = f32(j); + let cols = round((1400.0 + 216.0 * ring) * (1.0 + 0.37 * fj)); + let cw = 6.2831853 * r / cols; + let x = theta / 6.2831853 * cols - slant * in.pos.z / cw + 0.5 * fj; + let ci = floor(x); + let h = cell_hash(vec2(ci, 97.0 * fj + 13.0 * ring)); + let fx = fract(x) - 0.5 - (h.x - 0.5) * 0.4; + let speed = fall * (0.85 + 0.3 * h.y); + let period = r * (0.07 + 0.05 * h.z); + let v = fract((in.pos.z + speed * t) / period + h.w); + let len = 0.25 + 0.35 * h.x; + let along = smoothstep(0.0, 0.1, v) * (1.0 - smoothstep(len - 0.1, len, v)); + let across = 1.0 - smoothstep(0.06, 0.16, abs(fx)); + streaks = max(streaks, along * across * (0.4 + 0.6 * h.y)); + } + // the gusts sweep through it as a little denser sheets (at the full swing of 0.3 to 1.9 they + // stood in the sky as broad pale bands, sliding across it) + let g = precip_gust(in.pos.xy + camera.world_origin.xy, t, rp.wind.xy, rp.ext.z); + let sweep = clamp(1.0 + 0.6 * g.y, 0.7, 1.3); + // (thinned out towards the ground, where the panel meets it in a line, and above the + // horizon: the veil is the far rain seen edgewise along the ground - looked up at, its + // panels and their tops stood round the eye as a ring of grey sheets in the sky; what the + // rain takes from the view up there is its extinction, the fog's) + let up = in.pos.z - camera.cam_pos.z; + let height = smoothstep(-3.0, 3.0, up) * (1.0 - smoothstep(0.08, 0.3, up / r)); + // (the streaks themselves: a flat grey under them read as a sheet of frosted glass) + return clamp(in.shape.z * (0.12 + 0.88 * streaks) * sweep * height, 0.0, 1.0); +} + +// The light a drop sends to the eye besides the lamps': the sky's and the street's through +// it, and the sun's - refracted forwards (a shower lit from behind shines) and, at 42 and +// 51 degrees round the antisolar point, split into the rainbow's colours. +fn rain_surround(to_eye: vec3, sun: f32) -> vec3 { + let up = sh_irradiance(vec3(0.0, 0.0, 1.0)) / PI; + let down = sh_irradiance(vec3(0.0, 0.0, -1.0)) / PI; + // (a ball lens gathers the light of half the sky into the eye: a drop's streak is a + // little brighter than the overcast behind it - a silvery line - and much brighter + // than the street, the trees and the walls) + let l = mix(down, up, 0.8) * 1.0; + let c = dot(-camera.sun_dir.xyz, to_eye); + let forward = 0.85 * hg_phase(c, 0.82) + 0.15 / (4.0 * PI); + let a = degrees(acos(clamp(-c, -1.0, 1.0))); + let b1 = (a - vec3(42.3, 41.5, 40.7)) / 0.75; + let b2 = (a - vec3(50.3, 51.2, 52.4)) / 1.0; + let bow = exp(-b1 * b1) * 0.12 + exp(-b2 * b2) * 0.045; + return l + enh.sun.rgb * sun * (forward + bow); +} + +@fragment +fn fs_rain_enhanced(in: RainOutE) -> @location(0) vec4 { + let kind = in.shape.w; + var a = 0.0; + if (kind < 0.5) { + a = drop_alpha(in); + } else if (kind < 1.5) { + a = crown_alpha(in); + } else { + a = veil_rain_alpha(in); + } + if (a < 0.002) { + discard; + } + let to_eye = normalize(camera.cam_pos.xyz - in.pos); + var l = rain_surround(to_eye, precip_sun(in.pos)); + // (the lamps for the drops and the crowns alone: the veil's panels cover much of the + // picture, and the lamps' light in the air is the fog's). A drop sends a lamp's light + // every way - the glint of its surface, a small mirror ball, besides what it refracts on + // forwards - so the streaks shine in a street lamp's light however the eye looks at + // them, as rain is seen at night (`precip_light`'s flake lobe, less the light round it, + // which `rain_surround` gives already) + if (kind < 1.5) { + let round = enh.fog_color.rgb / 0.9 + enh.sun.rgb * (0.25 / PI); + l = max(precip_light(in.pos, to_eye, true) - round, vec3(0.0)) * 1.5 + l; + } + return vec4(min(l * enh.exposure.x, vec3(60.0)) * a, a); +} + +// Enhanced graphics: what the enhanced main pass, the sky and the coronas share - the +// light of the physically based sky (see atmosphere.rs), in its units (1 = 10 000 lux), +// and the air between the camera and what it sees. The scene is drawn pre-exposed: +// radiance times `enh.exposure.x`, so that the half-float target keeps its precision by +// night as well as by day. +struct Enhanced { + // x pre-exposure, y the level unlit things are drawn at, z a lit window's radiance + // (pre-exposed), w how bright a light's corona is drawn + exposure: vec4, + // rgb irradiance of the sun after the clouds, w its angular radius (rad) + sun: vec4, + // irradiance from the sky and the ground: order-2 spherical harmonics, rgb + sh: array, 9>, + // rgb radiance of the ground, w the sky table's scale + ground: vec4, + // x weather fog extinction (1/m) at its base, y its height falloff (1/m), z the base + // height (render-origin relative), w clear-air extinction (1/m) at the ground + fog: vec4, + // rgb fog radiance from the light around it (the sun's part is added by angle), + // w the table scale the reflection probe was drawn with + fog_color: vec4, + // x wet roads, y snow cover, z rain, w cloud cover in front of the sun + weather: vec4, + // x mip levels of the probe, y illuminance of a light's core (maplight colour 1), + // z cabin light illuminance, w how much of the sun the clouds let through + lights: vec4, + // rgb the sun disc's irradiance before the clouds, w frame time (s) + sun_disc: vec4, + // x which term the main pass shows alone (OMSI_DEBUG_ENHANCED, 0 = the picture), + // y the puddles' F0, z the envmap photo's strength, w the tone curve's contrast + debug: vec4, + // xyz where the sky cube is drawn from, relative to the camera + eye: vec4, + // x how bright an LED panel's dots burn (0 = off), y whether the LED panels' `\S:n` + // masks keep their mip chain (0: at full resolution, the dots stay visible when small), z 1 + // when lights glare and glow in the night air (the settings' `light_glow`) + led: vec4, + // xyz towards the moon, w its angular radius (rad) + moon: vec4, + // rgb the moon disc's irradiance before the clouds, w how much of the starry sky shows + moon_disc: vec4, + // rgb the sun's irradiance at 1400, 2100 and 2800 m (the cumulus layer) and 7000 m + // (the high thin layer), through the atmosphere from up there + cloud_sun: array, 4>, + // rgb the moonlight on a surface facing the moon (after the clouds), w 1 while the + // shadow maps are the moon's + moon_light: vec4, + // the condensation on the player's bus's panes (optical depths): windscreen, sides, + // rear, and how far the defroster has cleared the windscreen (0..1; omsi-app + // condensation.rs) + condensation: vec4, + // x the cumulus layer's base, y its top (m over the ground), z the altocumulus cover, + // w the storm's activity + layers: vec4, + // the lightning of this frame: x the light it throws on a surface facing it (1 = 10 000 + // lux), yz towards it (horizontal unit vector), w its elevation (rad) + flash: vec4, + // xyz towards the flash (unit vector), w how bright its channel is + flash2: vec4, + // x a number the channel's shape is drawn from + flash3: vec4, + // the clouds' shadow field (cloud_field.rs): xy its middle in cloud space, z one over its + // width, w 1 when there is one + cloud_f1: vec4, + // xy what takes a world point to cloud space, z the height of the plane it is taken on, + // w the share of the sun the main pass has taken off already for the clouds over the camera + cloud_f2: vec4, + // the player's bus's pitch and roll: sin, cos of each (its panes' condensation sits on + // the glass on a slope, `pane_local`) + pane_tilt: vec4, + // Slots of the weather overhaul, one owner each (zero until it fills them): + // the volumetric clouds, the volumetric fog, the precipitation, the bus's panes, the + // surfaces' PBR and the ray tracing, and two spare. + clouds_ext: vec4, + clouds_ext2: vec4, + vol_fog: vec4, + vol_fog2: vec4, + precip_ext: vec4, + glass_ext: vec4, + // (pbr_ext: x the share of the sun's light that still comes as a beam - the rest the + // clouds scatter, `sun_scattered` - y 1 when x is set) + pbr_ext: vec4, + rt_ext: vec4, +}; +@group(0) @binding(11) var enh: Enhanced; +@group(0) @binding(13) var s_lin: sampler; +@group(0) @binding(14) var t_sky_lut: texture_2d; + +const PI: f32 = 3.14159265; + +// Irradiance from the sky and the ground on a surface facing n. +fn sh_irradiance(n: vec3) -> vec3 { + let c = enh.sh; + let e = c[0].rgb * 0.282095 + + c[1].rgb * (0.488603 * n.y) + c[2].rgb * (0.488603 * n.z) + c[3].rgb * (0.488603 * n.x) + + c[4].rgb * (1.092548 * n.x * n.y) + c[5].rgb * (1.092548 * n.y * n.z) + + c[6].rgb * (0.315392 * (3.0 * n.z * n.z - 1.0)) + c[7].rgb * (1.092548 * n.x * n.z) + + c[8].rgb * (0.546274 * (n.x * n.x - n.y * n.y)); + return max(e, vec3(0.0)); +} + +// The lightning's light on a surface facing n: half of it from the cloud overhead and +// round it (a hemisphere), half along the way to the flash itself. +fn flash_irradiance(n: vec3) -> vec3 { + if (enh.flash.x <= 0.0) { + return vec3(0.0); + } + return vec3(0.80, 0.90, 1.0) * enh.flash.x * (0.5 * (0.5 + 0.5 * n.z) + 0.5 * max(dot(n, enh.flash2.xyz), 0.0)); +} + +// Sky radiance towards d (unscaled: times enh.ground.w is the radiance). The table runs +// over the azimuth from the sun (0..π) and the elevation (denser at the horizon). +// The sky table's texture: the table (32 x 48) in its corner and the clouds' shadow field +// (192 x 192) beside it, one texel clear (cloud_field.rs `SKY_TEX_W`, `FIELD_X0`). +const SKY_TEX: vec2 = vec2(225.0, 192.0); +const SKY_TABLE: vec2 = vec2(32.0, 48.0); +const FIELD_ORIGIN: f32 = 33.0; +const FIELD_N: f32 = 192.0; + +fn sky_table_raw(d: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let ls = length(s.xy); + let ld = length(d.xy); + var az = 0.0; + if (ls > 1e-4 && ld > 1e-4) { + az = acos(clamp(dot(s.xy / ls, d.xy / ld), -1.0, 1.0)); + } + let el = asin(clamp(d.z, -1.0, 1.0)); + let v = 0.5 + 0.5 * sign(el) * sqrt(min(abs(el) / 1.5707963, 1.0)); + // (kept a half texel inside the table: its neighbours in the texture are not the sky) + let tx = clamp(vec2(az / PI, v) * SKY_TABLE, vec2(0.5), SKY_TABLE - vec2(0.5)); + return textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).rgb; +} + +// The share of the sun that reaches the point p through the clouds, as against what the main +// pass's sun (`enh.sun`) already has for the camera's own place: the cumulus layer's shadow +// field read where the sun's way through p meets the layer's middle. 1 where there is no +// field, beyond its edge and where the sun is low (the camera's own factor stands there). +fn cloud_shadow_ratio(p: vec3) -> f32 { + let s = camera.sun_dir.xyz; + if (enh.cloud_f1.w < 0.5 || s.z < 0.06) { + return 1.0; + } + let cs = p.xy + s.xy / s.z * (enh.cloud_f2.z - p.z) + enh.cloud_f2.xy; + let uv = (cs - enh.cloud_f1.xy) * enh.cloud_f1.z + vec2(0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + let w = 1.0 - smoothstep(0.36, 0.48, edge); + if (w <= 0.0) { + return 1.0; + } + let tx = vec2(FIELD_ORIGIN, 0.0) + clamp(uv * FIELD_N, vec2(0.5), vec2(FIELD_N - 0.5)); + let f = textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).r; + let ratio = min(f / max(enh.cloud_f2.w, 0.02), 6.0); + return mix(1.0, ratio, w); +} + +fn sky_table(d: vec3) -> vec3 { + return sky_table_raw(d) * enh.ground.w; +} + +// Henyey-Greenstein phase function. +fn hg_phase(c: f32, g: f32) -> f32 { + let g2 = g * g; + return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * c, 1e-4), 1.5)); +} + +// Optical depth of an exponentially thinning layer (extinction sigma at height 0, falling +// off with k per metre) along a straight path of length dist from height h0 to h1. +fn layer_depth(sigma: f32, k: f32, h0: f32, h1: f32, dist: f32) -> f32 { + if (sigma <= 0.0) { + return 0.0; + } + let a = max(h0, 0.0); + let b = max(h1, 0.0); + let dh = b - a; + if (abs(k * dh) < 1e-3) { + return sigma * dist * exp(-k * 0.5 * (a + b)); + } + return sigma * dist * (exp(-k * a) - exp(-k * b)) / (k * dh); +} + +// The air between the camera and a point dist metres away in direction dir (from the +// camera), at heights h0 (camera) and h1 (point) above the fog's base: rgb the light it +// scatters towards the camera (radiance), a what it lets through of the point. +fn air(dir: vec3, dist: f32, h0: f32, h1: f32) -> vec4 { + return air_of(dir, dist, h0, h1, 1.0); +} + +// The same with the clear air's share scaled (0 for the sky, whose table holds it already). +fn air_of(dir: vec3, dist: f32, h0: f32, h1: f32, clear: f32) -> vec4 { + let tau_fog = layer_depth(enh.fog.x, enh.fog.y, h0, h1, dist); + let tau_air = layer_depth(enh.fog.w * clear, 1.0 / 1500.0, h0, h1, dist); + let tau = tau_fog + tau_air; + let t = exp(-tau); + if (tau < 1e-5) { + return vec4(0.0, 0.0, 0.0, 1.0); + } + // clear air takes on the sky's own colour at the horizon in this direction (which + // already holds the glow round the sun); a weather fog glows with the light around it + // and brighter towards the sun + let horizon = sky_table(normalize(vec3(dir.x, dir.y, max(dir.z, 0.0) * 0.3 + 0.03))); + let fog_in = enh.fog_color.rgb + enh.sun.rgb * hg_phase(dot(dir, camera.sun_dir.xyz), 0.55) * 0.9; + let inscatter = mix(horizon, fog_in, tau_fog / tau); + return vec4(inscatter * (1.0 - t), t); +} + +struct PointLight { + pos: vec4, + color: vec4, + dir: vec4, + extra: vec4, +}; +@group(0) @binding(3) var lights: array; +@group(0) @binding(4) var grid: array; +const CELL_CAP: u32 = 32u; + +// `beam_shadow.wgsl` for the shaders without the lamp shadow tiles: nothing stands in a beam. +fn beam_tile(li: u32, l: PointLight) -> u32 { + return 0xffffffffu; +} + +fn beam_reaches(k: u32, x: vec3) -> f32 { + return 1.0; +} + +// Enhanced graphics: the lamps as the scene and the sky share them - a headlamp's beam +// and the light the weather's fog scatters from the lamps towards the camera (needs the +// point lights, their grid and `camera.light_grid`). + +// A headlamp's intensity towards `t` (from the lamp) by the angles of a road lamp, not +// around its axis: wide across, brightest just under the lamp's horizon where it reaches +// far down the road, weak straight down, and with a low beam a sharp cut-off above it. +// `dir` is the lamp's axis in its vehicle's floor: its rise tilts the horizon with the +// vehicle, up a ramp and down (#1897). +fn headlamp(t: vec3, dir: vec3, low: bool) -> f32 { + let fwd = normalize(dir.xy + vec2(1e-6, 0.0)); + let ahead = dot(t.xy, fwd); + if (ahead <= 0.0) { + return 0.0; + } + let across = abs(t.x * fwd.y - t.y * fwd.x) / ahead; + let wide = 0.12 * smoothstep(1.0, 0.45, across) + 0.88 * exp(-across * across / 0.06); + let rise = t.z / max(length(t.xy), 1e-3); + let tilt = dir.z / max(length(dir.xy), 1e-3); + // (the tangent of the angle under that horizon) + let drop = (tilt - rise) / max(1.0 + rise * tilt, 1e-3); + // full out to where the road is 0.06 under the lamp's horizon, then less as the cube of + // the drop and a little more: the road is lit evenly from the bumper on, a little + // brighter as far as the beam reaches, and not as one hot pool where its axis lands + var up = min(1.0, pow(0.06 / max(abs(drop), 1e-4), 3.4)); + if (low) { + up = up * smoothstep(-0.012, 0.025, drop); + return wide * up; + } + // a full beam reaches far: a narrow, bright core along the lamp's horizon + let hot = exp(-across * across / 0.012 - drop * drop / 0.0004); + return wide * up + 6.0 * hot; +} + +// The lamps' light the weather's fog scatters towards the camera (radiance, not +// pre-exposed): single scattering along the view ray from `start` to `len` metres in +// direction `d` - the glow round a street lamp in the mist, its cone under it, a bus's +// beams reaching ahead into the fog or the falling snow. The droplets scatter strongly +// forward (fog and cloud droplets of some ten micrometres: g about 0.8), so the glow is +// brightest looking towards a lamp and a cone shows faintly from the side. +// +// Each lamp is taken once, over the whole stretch of the ray within its reach, in the grid +// cell the ray's point nearest to it lies in (the ray's cells are walked through; every +// cell lists the lamps reaching into it). Along a straight ray past a point source, with +// t - t0 = h tan(phi) (h the ray's distance from the lamp, t0 where it passes nearest), +// the inverse square cancels against the path element: dt / r^2 = dphi / h, and what is +// left is the phase function over the angle, cos(theta) = -sin(phi) - a smooth integral +// taken with five Gauss-Legendre nodes, at each of which a spot's or a headlamp's beam is +// asked how much it sends that way. The fog's extinction dims the light on its way from +// the lamp and to the camera (taken at the nearest point). A beam's light, which reaches +// only part of the way, is summed along the ray instead, its steps staggered by `jitter`. +// The droplets' phase function: a strong forward peak and the back-scattered light a +// fog's lidar ratio of some 18 sr asks for (0.055 per steradian straight back) - a single +// Henyey-Greenstein lobe of g 0.8 gave a tenth of it, and a bus's own headlights lit no +// wall of fog in front of the driver. Two lobes, 0.9 of g 0.85 and 0.1 of g -0.5. +fn fog_phase(c: f32) -> f32 { + return 0.9 * hg_phase(c, 0.85) + 0.1 * hg_phase(c, -0.5); +} +const AIRLIGHT_CELLS: u32 = 16u; + +// The clear night air's own haze, which lights a lamp's halo and a headlamp's beam as the fog's +// droplets do, only fainter: the lowest hundred metres of a city's air hold its dust, exhaust +// and humidity at several times the column's average aerosol extinction (`enh.fog.w`), 1-3e-4 +// per metre (a visibility of 15-40 km). A lamp then has a soft glow round it and a low beam +// a faint cone, as in any night photograph, instead of a lit disc on a black ground. +const GROUND_HAZE_GAIN: f32 = 8.0; + +// `droplets`: how much of the weather's extinction scatters like fog (see `FogLampUniform`). +fn lamp_airlight(c: vec3, d: vec3, start: f32, len: f32, jitter: f32, droplets: f32) -> vec3 { + var sum = vec3(0.0); + let sigma0 = enh.fog.x * droplets + enh.fog.w * GROUND_HAZE_GAIN * enh.led.z; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (sigma0 < 4e-5 || cell <= 0.0 || side == 0u || len <= start) { + return sum; + } + // (past a few optical depths nothing comes back) + let end = min(len, start + 4.0 / sigma0); + let gx = array(-0.9061798, -0.5384693, 0.0, 0.5384693, 0.9061798); + let gw = array(0.2369269, 0.4786287, 0.5688889, 0.4786287, 0.2369269); + // the walk through the grid's cells along the ray's plan + let o = (c.xy - camera.light_grid.xy) / cell; + let dd = d.xy / cell; + var ix = i32(floor(o.x + dd.x * start)); + var iy = i32(floor(o.y + dd.y * start)); + let sx = select(-1, 1, dd.x >= 0.0); + let sy = select(-1, 1, dd.y >= 0.0); + let inv_x = select(1e9, 1.0 / abs(dd.x), abs(dd.x) > 1e-7); + let inv_y = select(1e9, 1.0 / abs(dd.y), abs(dd.y) > 1e-7); + var tx = select((f32(ix) - o.x) / dd.x, (f32(ix + 1) - o.x) / dd.x, dd.x >= 0.0); + var ty = select((f32(iy) - o.y) / dd.y, (f32(iy + 1) - o.y) / dd.y, dd.y >= 0.0); + if (abs(dd.x) <= 1e-7) { tx = 1e9; } + if (abs(dd.y) <= 1e-7) { ty = 1e9; } + var t = start; + for (var k = 0u; k < AIRLIGHT_CELLS; k = k + 1u) { + if (t >= end) { + break; + } + let t_out = min(min(tx, ty), end); + if (ix >= 0 && iy >= 0 && ix < i32(side) && iy < i32(side)) { + let base = (u32(iy) * side + u32(ix)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let to_l = l.pos.xyz - c; + let t0 = dot(to_l, d); + // the ray's point nearest to the lamp: taken in this cell only + let tc = clamp(t0, start, end); + if (tc < t || tc > t_out) { + continue; + } + let range = l.extra.w; + let h = length(to_l - d * t0); + if (h >= range) { + continue; + } + // A beam (a headlamp, a spot) is lit in the weather's fog only: its cone is a sliver of + // sixteen jittered steps at half size, which the fog's density hides and the clear + // air's haze shows as shimmer and soap. The lamps' halo alone has the ground haze. + let beam_lamp = l.extra.z != 0.0 || l.dir.w > -1.5; + let fog_sigma = enh.fog.x * droplets; + if (beam_lamp && enh.fog.x < 2e-4) { + continue; + } + let s0 = select(sigma0, fog_sigma, beam_lamp); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + // (inside its core a lamp is as bright as at the core's edge) + let hh = max(h, select(core * 0.7, 0.4, l.extra.z != 0.0)); + let w = sqrt(range * range - h * h); + let ta = max(start, t0 - w); + let tb = min(end, t0 + w); + if (tb <= ta) { + continue; + } + var acc = 0.0; + var half = 0.0; + if (l.extra.z != 0.0 || l.dir.w > -1.5) { + // a beam (a headlamp, a spot): lit only where its cone or cut-off lets + // it - a sliver of the angles the lamp is seen under, which the five + // nodes missed. Sixteen even steps over that angle instead (dphi = + // h dt / r^2: the inverse square is in the step). (Sixteen even steps + // along the way put the few next to the lamp, where nearly all of its + // light is, a metre or more apart: the pixels' staggered steps came + // out as a coarse checker in the fog round every headlamp.) + let pa = atan((ta - t0) / hh); + let dphi = (atan((tb - t0) / hh) - pa) / 16.0; + let tile_k = beam_tile(li, l); + for (var q = 0u; q < 16u; q = q + 1u) { + let tq = t0 + hh * tan(pa + (f32(q) + jitter) * dphi); + let to = l.pos.xyz - (c + d * tq); + let ld = to * inverseSqrt(max(dot(to, to), 1e-6)); + var beam = 0.0; + if (l.extra.z != 0.0) { + beam = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0); + } else { + beam = smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } + // (the map is looked at only where the beam shines at all, and only for + // the few lamps that have a tile: no shadows, no tile, no tap) + var reach = 1.0; + if (beam > 0.002 && tile_k < 44u) { + reach = beam_reaches(tile_k, c + d * tq); + } + acc = acc + beam * reach * fog_phase(dot(ld, d)) * dphi; + } + half = 1.0; + } else { + let pa = atan((ta - t0) / hh); + let pb = atan((tb - t0) / hh); + half = 0.5 * (pb - pa); + let mid = 0.5 * (pa + pb); + let tile_p = beam_tile(li, l); + for (var q = 0u; q < 5u; q = q + 1u) { + let phi = mid + half * gx[q]; + let tq = t0 + hh * tan(phi); + let ld = normalize(l.pos.xyz - (c + d * tq)); + var beam = 1.0; + if (l.dir.z < -0.5) { + // (a lamp in a housing: see `lamp_light`) + beam = 0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z); + } + // (a lamp with a shadow map: what stands between it and the air + // keeps its light out of that air, as the headlamps' beams) + var reach = 1.0; + if (beam > 0.002 && tile_p < 44u) { + reach = beam_reaches(tile_p, c + d * tq); + } + acc = acc + gw[q] * beam * reach * fog_phase(-sin(phi)); + } + } + // a lamp's irradiance is core^2 / r^2 of its colour's (a headlamp's 1 / r^2) + let strength = select(core * core, 1.0, l.extra.z != 0.0); + let xc = c + d * tc; + let sigma = s0 * exp(-enh.fog.y * max(xc.z - enh.fog.z, 0.0)); + let dl = distance(xc, l.pos.xyz); + let atten = exp(-layer_depth(s0, enh.fog.y, c.z - enh.fog.z, xc.z - enh.fog.z, tc - start) - sigma * dl); + sum = sum + l.color.rgb * (l.color.w * strength * acc * half / hh * sigma * atten); + } + } + t = t_out; + if (tx < ty) { + tx = tx + inv_x; + ix = ix + sx; + } else { + ty = ty + inv_y; + iy = iy + sy; + } + } + return sum * enh.lights.y; +} + +// Enhanced: the light a raindrop or a snowflake sends towards the eye - what it scatters of +// the sky's light, the sun's and the lamps' round it, the drop's strongly forward (a +// streak flashes against a lamp seen through the rain, and is next to invisible in the +// dark between the lamps), the flake's nearly every way. (Drawn at the display's level +// whatever the light, the flakes of a snowfall at night shone white in the dark, far from +// any lamp.) +fn precip_light(x: vec3, to_eye: vec3, snow: bool) -> vec3 { + // the sky's and the ground's light round it, and the sun's on a small sphere + var e = enh.fog_color.rgb * (PI / 0.9) + enh.sun.rgb * 0.25; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell > 0.0 && side > 0u) { + let f = (x.xy - camera.light_grid.xy) / cell; + let gx = i32(floor(f.x)); + let gy = i32(floor(f.y)); + if (gx >= 0 && gy >= 0 && gx < i32(side) && gy < i32(side)) { + let base = (u32(gy) * side + u32(gx)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let dl = l.pos.xyz - x; + let dist2 = dot(dl, dl); + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let ld = dl * inverseSqrt(max(dist2, 1e-6)); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var k = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + if (l.extra.z != 0.0) { + k = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + k = k * smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } else if (l.dir.z < -0.5) { + k = k * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + // (the scattering towards the eye relative to an even one: a drop's light + // goes on forwards, a flake's every way. The angle is the one between the + // light's way from the lamp, -ld, and on to the eye: taken against -to_eye + // it put the forward peak behind the drop, and the drops in a bus's own + // beams, seen from behind the lamps, shone a hundred times too bright as + // white streaks down the road ahead) + let c = dot(-ld, to_eye); + let lobe = select(fog_phase(c), 0.7 * hg_phase(c, 0.3) + 0.3 / (4.0 * PI), snow) * 4.0 * PI; + e = e + l.color.rgb * l.color.w * enh.lights.y * k * lobe; + } + } + } + return e / PI; +} + diff --git a/crates/mx/tests/openomsi/rain_basic.wgsl b/crates/mx/tests/openomsi/rain_basic.wgsl new file mode 100644 index 0000000..03ada56 --- /dev/null +++ b/crates/mx/tests/openomsi/rain_basic.wgsl @@ -0,0 +1,1218 @@ +// What the snowfall (snow.wgsl) and the rainfall (rain.wgsl) share: the camera, a hash of +// a particle's number, and the player's vehicle the weather is kept out of. +struct Camera { + view_proj: mat4x4, + cam_pos: vec4, + // (kept in lockstep with `CameraUniform` in lib.rs, as sky.wgsl's) + world_origin: vec4, + sun_dir: vec4, + ambient: vec4, + fog: vec4, + sun_color: vec4, + sky_color: vec4, + light_grid: vec4, + sky: vec4, + cam_right: vec4, + cam_up: vec4, + clouds: vec4, + light_view_proj: mat4x4, + light_view_proj_far: mat4x4, + shadow: vec4, + post: vec4, + inside_a: vec4, + inside_b: vec4, + inside_c: vec4, + flags: vec4, + light_view_proj_close: mat4x4, + wind: vec4, + lamp_view_proj: array, 56>, + lamp_atlas: vec4, + tree_wind: vec4, + inside2_a: vec4, + inside2_b: vec4, + inside2_c: vec4, + cookies: array, 8>, + cabin_lamps: array, 4>, + // x: the textures' mip bias (FSR 1: negative, see `CameraUniform::lod`) + lod: vec4, + // (the classic picture's headlight, `CameraUniform::spot`: unread here) + spot: array, 4>, +}; +@group(0) @binding(0) var camera: Camera; + +fn hash4(n: u32) -> vec4 { + var x = vec4(n, n * 747796405u + 2891336453u, n ^ 0x9e3779b9u, n * 1664525u + 1013904223u); + x = x * 1664525u + 1013904223u; + x.x = x.x + x.y * x.w; + x.y = x.y + x.z * x.x; + x.z = x.z + x.x * x.y; + x.w = x.w + x.y * x.z; + x = x ^ (x >> vec4(16u)); + x.x = x.x + x.y * x.w; + x.y = x.y + x.z * x.x; + x.z = x.z + x.x * x.y; + return vec4(x & vec4(0xffffffu)) / 16777216.0; +} + +// The precipitation's roof map (passes/precip_map.rs): what stands over the ground round +// the camera, its depth seen from straight above. +@group(1) @binding(1) var roof_map: texture_depth_2d; +fn roof_depth(t: vec2) -> f32 { return textureLoad(roof_map, t, 0); } + +// Whether something solid stands over `p` (the map's matrix `m`; `on` 0 without a map): a +// bus's or a car's roof, a shelter, a bridge, a house - no drop or flake falls there. +fn under_roof(p: vec3, m: mat4x4, on: f32) -> bool { + let c = m * vec4(p, 1.0); + let uv = vec2(c.x * 0.5 + 0.5, 0.5 - c.y * 0.5); + let side = f32(textureDimensions(roof_map).x); + let t = vec2(clamp(uv, vec2(0.0), vec2(0.9999)) * side); + let top = roof_depth(t); + // (5 cm under it: the map's depth reaches 300 m) + return on > 0.5 && all(abs(c.xy) < vec2(1.0)) && c.z > top + 0.00017; +} + +// 1 inside the player's own vehicle (its box, a little wider): no snow falls in the cab +fn in_own_vehicle(p: vec3) -> bool { + // (the front and, of an articulated bus, the rear section: it snowed in the back, #1967; + // without branches - two boxes tested with early returns and short-circuits brought + // Apple's M4 shader compiler service down, XPC_ERROR_CONNECTION_INTERRUPTED, and the + // game fell back to no snowfall) + return any(vec2(in_box(p, camera.inside_a, camera.inside_b, camera.inside_c), in_box(p, camera.inside2_a, camera.inside2_b, camera.inside2_c))); +} + +fn in_box(p: vec3, a: vec4, b: vec4, c: vec4) -> bool { + let d = p - a.xyz; + let sh = a.w; + let ch = b.x; + let q = vec3(d.x * ch - d.y * sh - c.x, d.x * sh + d.y * ch - c.y, d.z - c.z); + let h = b.yzw + vec3(0.3); + return select(false, all(abs(q) < h), c.w >= 0.5); +} + +// Enhanced: the sun's far shadow map (the scene's camera group), which keeps every caster - +// a drop or a flake in the shade of a house or under the trees does not catch the sun. +@group(0) @binding(6) var s_shadow: sampler_comparison; +@group(0) @binding(7) var t_shadow_far: texture_depth_2d; + +// Enhanced: the procedural flake atlas (precip.rs `FlakeAtlas`): eight cells of snow +// crystals and flakes, R how much of a texel they cover, G how bright it is. +@group(1) @binding(2) var t_flakes: texture_2d; +@group(1) @binding(3) var s_flakes: sampler; + +// How far `p` is over whatever stands uppermost there by the roof map (m): below 0 under a +// roof, and far over everything where there is no map. +fn roof_clearance(p: vec3, m: mat4x4, on: f32) -> f32 { + let c = m * vec4(p, 1.0); + let uv = vec2(c.x * 0.5 + 0.5, 0.5 - c.y * 0.5); + let side = f32(textureDimensions(roof_map).x); + let top = roof_depth(vec2(clamp(uv, vec2(0.0), vec2(0.9999)) * side)); + // (the map looks straight down: its depth goes against the height, m[2].z < 0) + let h = (c.z - top) / m[2].z; + return select(1e4, h, on > 0.5 && all(abs(c.xy) < vec2(1.0)) && top < 0.9999); +} + +// The wind's gusts: it swells and slackens over some seconds, each swell running downwind +// over the ground as a wave some 70 m long, so that neighbouring drops and flakes are blown +// together and a gust is seen to sweep through the rain. x: the time's worth of the mean +// wind the gusts have added to a particle's way by `t` (the swell's integral, s), y: the +// swell now (a share of the mean wind). +fn precip_gust(x: vec2, t: f32, wind: vec2, strength: f32) -> vec2 { + let speed = length(wind); + let along = dot(x, wind / max(speed, 1e-3)) * (6.2831853 / 70.0); + let across = dot(x, vec2(-wind.y, wind.x) / max(speed, 1e-3)) * (6.2831853 / 160.0); + let w1 = 0.42; + let w2 = 1.17; + let a1 = 0.38 * strength; + let a2 = 0.17 * strength; + let p1 = w1 * t - along + 0.6 * sin(across); + let p2 = w2 * t - 2.3 * along + 1.7 + across; + return vec2(-a1 * cos(p1) / w1 - a2 * cos(p2) / w2, a1 * sin(p1) + a2 * sin(p2)); +} + +// How much of the sun reaches `p` (Enhanced): one compare in the far cascade, lit beyond it +// and without shadow maps. +fn precip_sun(p: vec3) -> f32 { + if (camera.shadow.x < 0.5 || enh.sun.r + enh.sun.g < 1e-4) { + return 1.0; + } + let lp = camera.light_view_proj_far * vec4(p, 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (any(uv < vec2(0.0)) || any(uv > vec2(1.0)) || lp.z < 0.0 || lp.z > 1.0) { + return 1.0; + } + return textureSampleCompareLevel(t_shadow_far, s_shadow, uv, lp.z - 0.0004); +} + +// A hash of a cell of the plane (0..1 each), its integer coordinates taken modulo 4096 so +// that the world's large figures stay exact. +fn cell_hash(c: vec2) -> vec4 { + let w = c - 4096.0 * floor(c / 4096.0); + let i = vec2(w); + return hash4(i.x * 4099u + i.y * 7919u + 17u); +} + +// The panels of a far veil of rain or snow (Enhanced): rings of upright panels round the +// camera, twelve a ring, each a strip of four vertices. Beyond the particles' layers the +// drops or flakes are too many and too small to draw one by one, and a heavy fall is seen +// there as what it is, a grey sheet streaked or speckled by them, sweeping by with the +// wind. `c`: the corner (0..1 each way); returns the corner's place (render frame) in xyz +// and its ring's radius in w. +fn veil_corner(panel: u32, c: vec2) -> vec4 { + var radii = array(30.0, 48.0, 78.0); + let ring = min(panel / 12u, 2u); + let r = radii[ring]; + // (each panel a little wider than its twelfth, so that the chords close the ring; the + // rings turned against each other, so their joins do not line up) + let a = (f32(panel % 12u) + c.x * 1.04 - 0.02 + 0.37 * f32(ring)) * (6.2831853 / 12.0); + let z = camera.cam_pos.z + mix(-6.0, 26.0 + 0.4 * r, c.y); + return vec4(camera.cam_pos.xy + vec2(cos(a), sin(a)) * r, z, r); +} + +// The rainfall, every mode: a field of drops that lives on the GPU alone, as the snowfall +// does (snow.wgsl) - each drop's place is worked out here from its number, the time, the +// wind and the camera, so that a downpour is a quarter of a million drops for one draw. +// The field is the world's, repeating round the camera in three layers, dense close by, +// thinner further out; beyond them the rain's extinction takes the view (the fog). +// +// A drop is seen as the streak it draws in the eye's time (`ep.eye.w`): its way against +// the eye in that time, short and upright standing, long and slanting at a moving bus's +// windscreen. It is as wide as the drop is - a raindrop of two millimetres is less than a +// pixel wide a few metres off - so a streak is drawn a pixel wide at least, as transparent +// as the drop covers less of it: a downpour is a veil of many fine, faint lines, not a few +// thick ones. The drops are drawn as rain shows them, weighted by the light they catch +// (their cross-section) from Marshall and Palmer's sizes (a gamma of order 3 over the +// exponential), each falling at its own speed (Atlas, Srivastava and Sekhon 1973). + +struct RainParams { + // xyz the wind the drops drift with (m/s), w the time (s) + wind: vec4, + // xyz the eye's velocity (m/s, world), w the time the eye sees a drop as one streak (s) + eye: vec4, + // x how hard it rains (0..1), y the median volume diameter of its drops (m), zw how + // many drops the first two layers hold (the rest are the third's) + fall: vec4, + // xy the picture's size (px), z how opaque a drop's streak is, w how many of the + // instances are drops (the rest are their splashes) + view: vec4, + // the precipitation's roof map: its matrix, and x 1 when there is one + roof: mat4x4, + roof_on: vec4, + // Enhanced: x the instance the veil's panels begin at (the drops' and the splashes' end), + // y how many panels there are, z how strong the wind's gusts are (0..1), w the rain's + // quality (0 low .. 2 high) + ext: vec4, +}; +@group(1) @binding(0) var rp: RainParams; + +struct RainOut { + @builtin(position) clip: vec4, + // across the streak and along it from its tail (px) + @location(0) uv: vec2, + // x the streak's half width, y its length (px), z its cover (alpha) + @location(1) @interpolate(flat) shape: vec3, + @location(2) pos: vec3, +}; + +// The layers round the camera: half width, bottom and top (m). +const RAIN_LAYERS = array, 3>(vec3(5.0, -2.5, 6.0), vec3(14.0, -3.0, 12.0), vec3(32.0, -3.0, 22.0)); + +// Where a drop lands: a crown of water a centimetre or two high that is gone in a tenth of +// a second - on whatever is uppermost there, the ground, a kerb, a bus's roof, as the +// precipitation's roof map has it (none without the map). Each splash takes a new place +// round the camera every time it comes round again; the most of them close by. +fn splash(vid: u32, s: u32) -> RainOut { + // (a strip of four vertices) + let c = vec2(f32(i32(vid & 1u) * 2 - 1), f32(i32(vid >> 1u) * 2 - 1)); + var out: RainOut; + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + out.uv = vec2(0.0); + out.shape = vec3(0.0); + out.pos = vec3(0.0); + let life = 0.1; + let h0 = hash4(s * 3u + 11u); + let cycle = rp.wind.w / life + h0.w; + let age = fract(cycle); + let h = hash4(s * 7919u + u32(floor(cycle)) * 2654435761u); + // its place in the world: a field 28 m square laid over the world (in the world's own + // figures), the copy of it round the camera - a splash stays where it landed however + // the camera moves or turns, and only those the camera leaves behind come round again + // ahead of it + let size = 28.0; + let world_cam = camera.cam_pos.xy + camera.world_origin.xy; + let lo = world_cam - vec2(0.5 * size); + let wxy = lo + (((h.xy * size - lo) % size) + size) % size; + let xy = wxy - camera.world_origin.xy; + // (fewer further off, faded in and out by the distance alone) + let fade_far = 1.0 - smoothstep(6.0, 14.0, length(xy - camera.cam_pos.xy)); + let m = rp.roof; + let mc = m * vec4(xy, 0.0, 1.0); + let uv = vec2(mc.x * 0.5 + 0.5, 0.5 - mc.y * 0.5); + let side = f32(textureDimensions(roof_map).x); + let top = roof_depth(vec2(clamp(uv, vec2(0.0), vec2(0.9999)) * side)); + // (the map's depth back to a height: it looks straight down) + let z = (top - mc.z) / m[2].z; + let p = vec3(xy, z + 0.008 + 0.012 * age); + let ch = camera.view_proj * vec4(p, 1.0); + let cu = camera.view_proj * vec4(p + camera.cam_up.xyz, 1.0); + if (rp.roof_on.x < 0.5 || top >= 0.9999 || ch.w < 0.3 || in_own_vehicle(p)) { + return out; + } + let half_px = 0.5 * rp.view.xy; + let px_per_m = length(cu.xy / cu.w * half_px - ch.xy / ch.w * half_px); + // the crown widens as it rises and falls back, and fades + let w = (0.006 + 0.02 * age) * px_per_m; + let hw = max(0.5 * w, 0.5); + let pad = hw + 1.0; + let cover = min(w, 1.0) * (1.0 - age) * (1.0 - age) * 0.8 * rp.view.z * fade_far; + out.clip = vec4(ch.xy + c * pad / half_px * ch.w, ch.zw); + out.uv = c * pad; + // (a round speck: no length, see `streak_alpha`) + out.shape = vec3(hw, -1.0, cover); + out.pos = p; + return out; +} + +@vertex +fn vs_rain(@builtin(vertex_index) vid: u32, @builtin(instance_index) k: u32) -> RainOut { + if (k >= u32(rp.view.w)) { + return splash(vid, k - u32(rp.view.w)); + } + // across (-1, 1) and along (0 the tail, 1 the head) + let c = vec2(f32(i32(vid & 1u) * 2 - 1), f32(vid >> 1u)); + var out: RainOut; + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + out.uv = vec2(0.0); + out.shape = vec3(0.0); + out.pos = vec3(0.0); + let n0 = u32(rp.fall.z); + let n1 = u32(rp.fall.w); + let layer = select(select(2u, 1u, k < n0 + n1), 0u, k < n0); + let lh = RAIN_LAYERS[layer]; + let size = vec3(2.0 * lh.x, 2.0 * lh.x, lh.z - lh.y); + let h1 = hash4(k * 2u + 3u); + let h2 = hash4(k * 2u + 6007u); + // the drop: its diameter (m), drawn by its cross-section from the rain's sizes, and + // the speed it falls at + let lambda = 3.67 / max(rp.fall.y, 1e-4); + let d = clamp(-log(max(h2.x * h2.y * h2.z, 1e-12)) / lambda, 0.0003, 0.006); + let fall = max(9.65 - 10.3 * exp(-600.0 * d), 0.5); + // its place in the world: where it started, carried by the wind, falling; then the + // copy of the field nearest the camera (in the world's own figures, so that it stays + // put while the render origin moves) + let t = rp.wind.w; + let world_cam = camera.cam_pos.xyz + vec3(camera.world_origin.xy, 0.0); + let vel = vec3(rp.wind.xy, -fall); + let lo = world_cam + vec3(-lh.x, -lh.x, lh.y); + // (the field repeats every `size`: the place wrapped into one copy of it) + let wrapped = (h1.xyz * size + vel * t - lo) / size; + let q = lo + (wrapped - floor(wrapped)) * size; + let p = q - vec3(camera.world_origin.xy, 0.0); + // a denser layer thins out with the distance from the eye, over the whole of its reach, + // into the thinner one round it: faded only at its edges, it stood round the camera as a + // box of dense rain that went wherever the camera went + let rel = q - lo; + let e = min(rel, size - rel) / (lh.x * 0.3); + let edge = clamp(min(min(e.x, e.y), e.z), 0.0, 1.0); + let reach = 1.0 - smoothstep(0.25 * lh.x, lh.x, length((q - world_cam).xy)); + let fade = select(1.0, edge * reach, layer < 2u); + // a drop right at the eye is a blur too wide and faint to see, not a streak + let near = smoothstep(0.6, 1.6, length(p - camera.cam_pos.xyz)); + // the streak: from where the drop was against the eye a streak's time ago to where it is + let ch = camera.view_proj * vec4(p, 1.0); + // (the field reaches all round the camera, most of it out of the picture: a drop well + // beyond its edge - a streak is a few per cent of the picture long - is let go before + // the rest of its work, and so is one too faint to see) + if (fade * near < 0.01 || ch.w < 0.1 || abs(ch.x) > 1.5 * ch.w || abs(ch.y) > 1.5 * ch.w) { + return out; + } + let tail = p - (vel - rp.eye.xyz) * rp.eye.w; + let ct = camera.view_proj * vec4(tail, 1.0); + if (ct.w < 0.1 || in_own_vehicle(p) || under_roof(p, rp.roof, rp.roof_on.x)) { + return out; + } + let cu = camera.view_proj * vec4(p + camera.cam_up.xyz, 1.0); + let half_px = 0.5 * rp.view.xy; + let sh = ch.xy / ch.w * half_px; + let st = ct.xy / ct.w * half_px; + let along = sh - st; + let len = length(along); + let dir = select(vec2(0.0, 1.0), along / max(len, 1e-4), len > 1e-3); + let across = vec2(-dir.y, dir.x); + // as wide as the drop (out of focus close by: its blur as wide as the pupil, some + // 2.5 mm), a pixel at least - and as much fainter as it is narrower than that + let px_per_m = length(cu.xy / cu.w * half_px - sh); + let blur = sqrt(d * d + 0.0025 * 0.0025); + let w = blur * px_per_m; + // and spread along its way: the drop lies on each pixel of its streak for the share of + // the eye's time it takes to cross it - a long streak is a faint one (the drop's lens + // gathers the sky's light, brighter than what is behind it: some six times its width) + let spread = clamp(6.0 * max(w, 1.0) / max(len, 1.0), 0.2, 1.0); + let cover = min(w, 1.0) * (d / blur) * spread * fade * near * rp.view.z * clamp(sqrt(d / 0.002), 0.5, 1.4); + // (a hair under a pixel at the least: a picture drawn smaller and scaled up widened the + // full-pixel lines into the thick white bars of the old sprites) + let hw = max(0.5 * w, 0.4); + let pad = hw + 1.0; + // the quad round the streak (the head's and the tail's clip positions mixed, so that it + // keeps the depth along it) widened in the picture's pixels + let clip = mix(ct, ch, c.y); + let off = across * c.x * pad + dir * (c.y * 2.0 - 1.0) * pad; + out.clip = vec4(clip.xy + off / half_px * clip.w, clip.zw); + out.uv = vec2(c.x * pad, c.y * (len + 2.0 * pad) - pad); + out.shape = vec3(hw, len, cover); + out.pos = p; + return out; +} + +fn streak_alpha(in: RainOut) -> f32 { + let hw = in.shape.x; + let len = in.shape.y; + // a pixel's edge across and at both ends, and a little fainter towards the tail + let a_across = clamp(hw + 0.5 - abs(in.uv.x), 0.0, 1.0); + let a_along = clamp(0.5 + min(in.uv.y, len - in.uv.y), 0.0, 1.0); + let tail = mix(0.55, 1.0, clamp(in.uv.y / max(len, 1.0), 0.0, 1.0)); + // (a splash's round speck) + let speck = clamp(hw + 0.5 - length(in.uv), 0.0, 1.0); + return clamp(in.shape.z * select(a_across * a_along * tail, speck, len < 0.0), 0.0, 1.0); +} + +// the classic picture: water lit as the scene is (envir.cfg's ambient and sun light) +@fragment +fn fs_rain(in: RainOut) -> @location(0) vec4 { + let a = streak_alpha(in); + let light = min(camera.ambient.rgb + camera.sky_color.rgb * 0.5 + camera.sun_color.rgb * 0.3, vec3(1.0)) * vec3(0.68, 0.7, 0.75); + return vec4(light * a, a); +} + + +// ---- The enhanced rainfall +// +// The same field of drops, drawn as rain photographs: each drop the streak it leaves in the +// eye's time, its length and slant its way against the eye (the bus's own motion, the wind +// and its gusts), a soft line as wide as the drop with rounded ends, beaded along a long +// streak where the oscillating drop flickers. A drop is a small ball lens: it carries the +// light of what lies round it turned over - the sky in its lower half, the street in its +// upper - so that by day it is a silvery line, faint against the bright sky and clear +// against a dark street, glows when the sun shines through it from behind, colours the +// rainbow's ring round the antisolar point, and flashes in the lamps and headlights at +// night (`precip_light`). Where the drops land, crowns of water rise and throw droplets; +// beyond the drops' layers the rain is a veil of streaks (`veil_corner`). + +struct RainOutE { + @builtin(position) clip: vec4, + // a drop: across its streak and along it from the tail (px); a splash: across it and up + // it (-1..1, 0..1 and over); the veil: the panel's corner (0..1) + @location(0) uv: vec2, + // a drop: x the streak's half width, y its length (px); a splash: x one pixel in its + // own measure, y its age (0..1); z the cover, w which it is (0 a drop, 1 a splash, 2 the + // veil) + @location(1) @interpolate(flat) shape: vec4, + @location(2) pos: vec3, + // x a number of the particle's own (0..1), y the veil's radius (m), z its ring + @location(3) @interpolate(flat) seed: vec4, +}; + +fn rain_none() -> RainOutE { + var out: RainOutE; + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + out.uv = vec2(0.0); + out.shape = vec4(0.0); + out.pos = vec3(0.0); + out.seed = vec4(0.0); + return out; +} + +@vertex +fn vs_rain_enhanced(@builtin(vertex_index) vid: u32, @builtin(instance_index) k: u32) -> RainOutE { + if (k >= u32(rp.ext.x)) { + return rain_veil(vid, k - u32(rp.ext.x)); + } + if (k >= u32(rp.view.w)) { + return rain_crown(vid, k - u32(rp.view.w)); + } + return rain_drop(vid, k); +} + +fn rain_drop(vid: u32, k: u32) -> RainOutE { + // across (-1, 1) and along (0 the tail, 1 the head) + let c = vec2(f32(i32(vid & 1u) * 2 - 1), f32(vid >> 1u)); + var out = rain_none(); + let n0 = u32(rp.fall.z); + let n1 = u32(rp.fall.w); + let layer = select(select(2u, 1u, k < n0 + n1), 0u, k < n0); + let lh = RAIN_LAYERS[layer]; + let size = vec3(2.0 * lh.x, 2.0 * lh.x, lh.z - lh.y); + let h1 = hash4(k * 2u + 3u); + let h2 = hash4(k * 2u + 6007u); + // the drop's diameter and speed, as `vs_rain` draws them + let lambda = 3.67 / max(rp.fall.y, 1e-4); + let d = clamp(-log(max(h2.x * h2.y * h2.z, 1e-12)) / lambda, 0.0003, 0.006); + let fall = max(9.65 - 10.3 * exp(-600.0 * d), 0.5); + let t = rp.wind.w; + let world_cam = camera.cam_pos.xyz + vec3(camera.world_origin.xy, 0.0); + let lo = world_cam + vec3(-lh.x, -lh.x, lh.y); + let wrapped = (h1.xyz * size + vec3(rp.wind.xy, -fall) * t - lo) / size; + let q0 = lo + (wrapped - floor(wrapped)) * size; + // the gusts carry it on from its place in the field, and slant it as they blow + let g = precip_gust(q0.xy, t, rp.wind.xy, rp.ext.z); + let q = q0 + vec3(rp.wind.xy * g.x, 0.0); + let vel = vec3(rp.wind.xy * (1.0 + g.y), -fall); + let p = q - vec3(camera.world_origin.xy, 0.0); + // every layer fades out at its edges (where its drops come round again, the gusts' + // way at the far side of the field differs from the near side's), the denser ones + // over their whole reach into the thinner round them + let rel = q0 - lo; + let e = min(rel, size - rel) / (lh.x * 0.3); + let edge = clamp(min(min(e.x, e.y), e.z), 0.0, 1.0); + let reach = 1.0 - smoothstep(0.25 * lh.x, lh.x, length((q - world_cam).xy)); + let fade = edge * select(1.0, reach, layer < 2u); + let near = smoothstep(0.5, 1.4, length(p - camera.cam_pos.xyz)); + let ch = camera.view_proj * vec4(p, 1.0); + if (fade * near < 0.01 || ch.w < 0.1 || abs(ch.x) > 1.5 * ch.w || abs(ch.y) > 1.5 * ch.w) { + return out; + } + let tail = p - (vel - rp.eye.xyz) * rp.eye.w; + let ct = camera.view_proj * vec4(tail, 1.0); + if (ct.w < 0.1 || in_own_vehicle(p) || under_roof(p, rp.roof, rp.roof_on.x)) { + return out; + } + let cu = camera.view_proj * vec4(p + camera.cam_up.xyz, 1.0); + let half_px = 0.5 * rp.view.xy; + let sh = ch.xy / ch.w * half_px; + let st = ct.xy / ct.w * half_px; + let along = sh - st; + let len = length(along); + let dir = select(vec2(0.0, 1.0), along / max(len, 1e-3), len > 1e-3); + let across = vec2(-dir.y, dir.x); + // as wide as the drop, a millimetre's blur at the least (crisp close by: the eye is + // focused on the street, a few metres off, and a drop there is sharp), and spread over + // its way as `vs_rain` spreads it + let px_per_m = length(cu.xy / cu.w * half_px - sh); + // (a millimetre and a half at the least: at one millimetre the near drops drew as opaque + // grey lines) + let blur = sqrt(d * d + 0.0015 * 0.0015); + let w = blur * px_per_m; + let spread = clamp(6.0 * max(w, 1.0) / max(len, 1.0), 0.1, 1.0); + let cover = min(w, 1.0) * (d / blur) * spread * fade * near * rp.view.z * clamp(sqrt(d / 0.002), 0.5, 1.4); + let hw = max(0.5 * w, 0.4); + let pad = hw + 1.5; + let clip = mix(ct, ch, c.y); + let off = across * c.x * pad + dir * (c.y * 2.0 - 1.0) * pad; + out.clip = vec4(clip.xy + off / half_px * clip.w, clip.zw); + out.uv = vec2(c.x * pad, c.y * (len + 2.0 * pad) - pad); + out.shape = vec4(hw, len, cover, 0.0); + out.pos = p; + out.seed = vec4(h2.w, 0.0, 0.0, 0.0); + return out; +} + +// Where a drop lands (`splash`'s places): a crown of water rises round the impact for a +// few hundredths of a second, its rim breaks into points, and the points fling droplets +// out on short arcs that fall back - on the street, a kerb, a bus's roof. Upright, it is +// drawn facing the eye. +fn rain_crown(vid: u32, s: u32) -> RainOutE { + // across (-1, 1) and up (0, 1) + let c = vec2(f32(i32(vid & 1u) * 2 - 1), f32(vid >> 1u)); + var out = rain_none(); + let life = 0.24; + let h0 = hash4(s * 3u + 11u); + let cycle = rp.wind.w / life + h0.w; + let age = fract(cycle); + let h = hash4(s * 7919u + u32(floor(cycle)) * 2654435761u); + let size = 28.0; + let world_cam = camera.cam_pos.xy + camera.world_origin.xy; + let lo = world_cam - vec2(0.5 * size); + let wxy = lo + (((h.xy * size - lo) % size) + size) % size; + let xy = wxy - camera.world_origin.xy; + let fade_far = 1.0 - smoothstep(7.0, 16.0, length(xy - camera.cam_pos.xy)); + let m = rp.roof; + let mc = m * vec4(xy, 0.0, 1.0); + let uv = vec2(mc.x * 0.5 + 0.5, 0.5 - mc.y * 0.5); + let side = f32(textureDimensions(roof_map).x); + let top = roof_depth(vec2(clamp(uv, vec2(0.0), vec2(0.9999)) * side)); + let p = vec3(xy, (top - mc.z) / m[2].z + 0.002); + let ch = camera.view_proj * vec4(p, 1.0); + if (rp.roof_on.x < 0.5 || top >= 0.9999 || fade_far <= 0.0 || ch.w < 0.3 || in_own_vehicle(p)) { + return out; + } + let cu = camera.view_proj * vec4(p + camera.cam_up.xyz, 1.0); + let half_px = 0.5 * rp.view.xy; + let px_per_m = length(cu.xy / cu.w * half_px - ch.xy / ch.w * half_px); + // a few centimetres across, the bigger the drops the bigger, and at least a few pixels + // (the crown drawn smaller inside it, its parts no thinner than a pixel) + let scale = clamp(rp.fall.y / 0.0018, 0.6, 1.6) * (0.7 + 0.6 * h.z); + let half_w = 0.045 * scale; + let grow = max(1.0, 2.0 / max(half_w * px_per_m, 1e-3)); + let to_cam = camera.cam_pos.xyz - p; + let flat_side = vec3(-to_cam.y, to_cam.x, 0.0); + let ax = select(vec3(1.0, 0.0, 0.0), normalize(flat_side), length(flat_side) > 1e-4); + let corner = p + ax * (c.x * half_w * grow) + vec3(0.0, 0.0, (c.y * 1.2 * grow - 0.05) * half_w); + out.clip = camera.view_proj * vec4(corner, 1.0); + out.uv = vec2(c.x * grow, (c.y * 1.2 * grow - 0.05)); + out.shape = vec4(1.0 / max(half_w * px_per_m, 1e-3), age, 0.9 * rp.view.z * fade_far, 1.0); + out.pos = p; + out.seed = vec4(h.w, 0.0, 0.0, 0.0); + return out; +} + +fn rain_veil(vid: u32, panel: u32) -> RainOutE { + let c = vec2(f32(vid & 1u), f32(vid >> 1u)); + var out = rain_none(); + let v = veil_corner(panel, c); + let ring = f32(panel / 12u); + // (none in a light rain, whose drops are not seen that far) + if (rp.fall.x < 0.15) { + return out; + } + out.clip = camera.view_proj * vec4(v.xyz, 1.0); + out.uv = c; + // (the rain's streaks are seen beyond the drops only in a fair rain, and as a veil in a + // heavy one; the further rings stand for more rain behind them) + out.shape = vec4(0.0, 0.0, pow(rp.fall.x, 1.5) * 0.085 * (0.8 + 0.2 * ring), 2.0); + out.pos = v.xyz; + out.seed = vec4(0.0, v.w, ring, 0.0); + return out; +} + +fn drop_alpha(in: RainOutE) -> f32 { + let hw = in.shape.x; + let len = in.shape.y; + // across: a soft line, as a lens draws a thin one - at least a pixel's blur + let s = max(hw * 0.85, 0.6); + let across = exp(-0.5 * in.uv.x * in.uv.x / (s * s)); + // along: the drop's way, its ends rounded as wide as the drop + let e = hw + 0.7; + let along = smoothstep(-e, e, in.uv.y) * smoothstep(-e, e, len - in.uv.y); + // a little brighter at the head (where the drop is now), and a long streak beaded: a + // falling drop oscillates a few hundred times a second, its glint flickering on its way + let f = clamp(in.uv.y / max(len, 1.0), 0.0, 1.0); + let beads = 1.0 + 0.22 * sin(in.uv.y * (0.35 + 0.3 * in.seed.x) + in.seed.x * 40.0) * smoothstep(12.0, 40.0, len); + return clamp(in.shape.z * across * along * mix(0.75, 1.0, f) * beads, 0.0, 1.0); +} + +fn crown_alpha(in: RainOutE) -> f32 { + let px = in.shape.x; + let age = in.shape.y; + let seed = in.seed.x; + let uv = in.uv; + // the crown: a thin sheet rising round the impact, a cylinder seen from the side - most + // of it at its outline, where the eye looks along the sheet - its rim pulled into points + let rise = smoothstep(0.0, 0.18, age) * (1.0 - smoothstep(0.3, 0.6, age)); + let r = 0.35 + 0.5 * sqrt(age); + let x = uv.x / r; + let points = 7.0 + floor(seed * 5.0); + let ang = asin(clamp(x, -1.0, 1.0)); + let tips = pow(abs(cos(ang * points * 0.5 + seed * 6.2831853)), 6.0); + let top = rise * (0.5 + 0.35 * tips) * (0.8 + 0.4 * fract(seed * 7.3)); + let outline = 0.3 + 0.7 * smoothstep(0.5, 1.0, abs(x)); + let side = 1.0 - smoothstep(1.0 - px / r, 1.0 + px / r, abs(x)); + let below = 1.0 - smoothstep(top - px, top + px, uv.y); + // (a sheet thinner than a pixel is as faint as it is thin) + let crown = side * below * outline * step(0.0, uv.y) * 0.75 * min(1.0, 0.04 / px); + // the droplets the points fling off, on arcs out and up and back down + var drops = 0.0; + let fly = max(age - 0.14, 0.0); + let rad = max(0.07, px); + for (var i = 0u; i < 5u; i = i + 1u) { + let hi = hash4(u32(seed * 16777216.0) + i * 977u); + let vx = (hi.x * 2.0 - 1.0) * 2.4; + let vy = 2.2 + 2.2 * hi.y; + let q = vec2(sign(vx) * r * 0.9 + vx * fly, 0.5 * rise + vy * fly - 14.0 * fly * fly); + let a = (1.0 - smoothstep(rad - px, rad + px, length(uv - q))) * step(0.0, q.y) * step(0.05, fly); + drops = max(drops, a * (0.07 / rad) * (0.07 / rad) * step(hi.z, 0.8)); + } + return clamp(in.shape.z * max(crown, drops) * (1.0 - age * age), 0.0, 1.0); +} + +fn veil_rain_alpha(in: RainOutE) -> f32 { + let r = in.seed.y; + let ring = in.seed.z; + let d = in.pos - camera.cam_pos.xyz; + let theta = atan2(d.y, d.x); + let t = rp.wind.w; + let tang = vec2(-sin(theta), cos(theta)); + let fall = 7.0; + // (the wind slants the streaks: so many metres sideways for each metre of fall) + let slant = dot(rp.wind.xy, tang) / fall; + // Columns of streaks, a fixed angle apart (a few pixels) and a whole number of them to + // the ring, so that its seam does not show; each column's drops fall at their own + // speed, a streak a stretch of it. + var streaks = 0.0; + for (var j = 0u; j < 2u; j = j + 1u) { + let fj = f32(j); + let cols = round((1400.0 + 216.0 * ring) * (1.0 + 0.37 * fj)); + let cw = 6.2831853 * r / cols; + let x = theta / 6.2831853 * cols - slant * in.pos.z / cw + 0.5 * fj; + let ci = floor(x); + let h = cell_hash(vec2(ci, 97.0 * fj + 13.0 * ring)); + let fx = fract(x) - 0.5 - (h.x - 0.5) * 0.4; + let speed = fall * (0.85 + 0.3 * h.y); + let period = r * (0.07 + 0.05 * h.z); + let v = fract((in.pos.z + speed * t) / period + h.w); + let len = 0.25 + 0.35 * h.x; + let along = smoothstep(0.0, 0.1, v) * (1.0 - smoothstep(len - 0.1, len, v)); + let across = 1.0 - smoothstep(0.06, 0.16, abs(fx)); + streaks = max(streaks, along * across * (0.4 + 0.6 * h.y)); + } + // the gusts sweep through it as a little denser sheets (at the full swing of 0.3 to 1.9 they + // stood in the sky as broad pale bands, sliding across it) + let g = precip_gust(in.pos.xy + camera.world_origin.xy, t, rp.wind.xy, rp.ext.z); + let sweep = clamp(1.0 + 0.6 * g.y, 0.7, 1.3); + // (thinned out towards the ground, where the panel meets it in a line, and above the + // horizon: the veil is the far rain seen edgewise along the ground - looked up at, its + // panels and their tops stood round the eye as a ring of grey sheets in the sky; what the + // rain takes from the view up there is its extinction, the fog's) + let up = in.pos.z - camera.cam_pos.z; + let height = smoothstep(-3.0, 3.0, up) * (1.0 - smoothstep(0.08, 0.3, up / r)); + // (the streaks themselves: a flat grey under them read as a sheet of frosted glass) + return clamp(in.shape.z * (0.12 + 0.88 * streaks) * sweep * height, 0.0, 1.0); +} + +// The light a drop sends to the eye besides the lamps': the sky's and the street's through +// it, and the sun's - refracted forwards (a shower lit from behind shines) and, at 42 and +// 51 degrees round the antisolar point, split into the rainbow's colours. +fn rain_surround(to_eye: vec3, sun: f32) -> vec3 { + let up = sh_irradiance(vec3(0.0, 0.0, 1.0)) / PI; + let down = sh_irradiance(vec3(0.0, 0.0, -1.0)) / PI; + // (a ball lens gathers the light of half the sky into the eye: a drop's streak is a + // little brighter than the overcast behind it - a silvery line - and much brighter + // than the street, the trees and the walls) + let l = mix(down, up, 0.8) * 1.0; + let c = dot(-camera.sun_dir.xyz, to_eye); + let forward = 0.85 * hg_phase(c, 0.82) + 0.15 / (4.0 * PI); + let a = degrees(acos(clamp(-c, -1.0, 1.0))); + let b1 = (a - vec3(42.3, 41.5, 40.7)) / 0.75; + let b2 = (a - vec3(50.3, 51.2, 52.4)) / 1.0; + let bow = exp(-b1 * b1) * 0.12 + exp(-b2 * b2) * 0.045; + return l + enh.sun.rgb * sun * (forward + bow); +} + +@fragment +fn fs_rain_enhanced(in: RainOutE) -> @location(0) vec4 { + let kind = in.shape.w; + var a = 0.0; + if (kind < 0.5) { + a = drop_alpha(in); + } else if (kind < 1.5) { + a = crown_alpha(in); + } else { + a = veil_rain_alpha(in); + } + if (a < 0.002) { + discard; + } + let to_eye = normalize(camera.cam_pos.xyz - in.pos); + var l = rain_surround(to_eye, precip_sun(in.pos)); + // (the lamps for the drops and the crowns alone: the veil's panels cover much of the + // picture, and the lamps' light in the air is the fog's). A drop sends a lamp's light + // every way - the glint of its surface, a small mirror ball, besides what it refracts on + // forwards - so the streaks shine in a street lamp's light however the eye looks at + // them, as rain is seen at night (`precip_light`'s flake lobe, less the light round it, + // which `rain_surround` gives already) + if (kind < 1.5) { + let round = enh.fog_color.rgb / 0.9 + enh.sun.rgb * (0.25 / PI); + + } + return vec4(min(l * enh.exposure.x, vec3(60.0)) * a, a); +} + +// Enhanced graphics: what the enhanced main pass, the sky and the coronas share - the +// light of the physically based sky (see atmosphere.rs), in its units (1 = 10 000 lux), +// and the air between the camera and what it sees. The scene is drawn pre-exposed: +// radiance times `enh.exposure.x`, so that the half-float target keeps its precision by +// night as well as by day. +struct Enhanced { + // x pre-exposure, y the level unlit things are drawn at, z a lit window's radiance + // (pre-exposed), w how bright a light's corona is drawn + exposure: vec4, + // rgb irradiance of the sun after the clouds, w its angular radius (rad) + sun: vec4, + // irradiance from the sky and the ground: order-2 spherical harmonics, rgb + sh: array, 9>, + // rgb radiance of the ground, w the sky table's scale + ground: vec4, + // x weather fog extinction (1/m) at its base, y its height falloff (1/m), z the base + // height (render-origin relative), w clear-air extinction (1/m) at the ground + fog: vec4, + // rgb fog radiance from the light around it (the sun's part is added by angle), + // w the table scale the reflection probe was drawn with + fog_color: vec4, + // x wet roads, y snow cover, z rain, w cloud cover in front of the sun + weather: vec4, + // x mip levels of the probe, y illuminance of a light's core (maplight colour 1), + // z cabin light illuminance, w how much of the sun the clouds let through + lights: vec4, + // rgb the sun disc's irradiance before the clouds, w frame time (s) + sun_disc: vec4, + // x which term the main pass shows alone (OMSI_DEBUG_ENHANCED, 0 = the picture), + // y the puddles' F0, z the envmap photo's strength, w the tone curve's contrast + debug: vec4, + // xyz where the sky cube is drawn from, relative to the camera + eye: vec4, + // x how bright an LED panel's dots burn (0 = off), y whether the LED panels' `\S:n` + // masks keep their mip chain (0: at full resolution, the dots stay visible when small), z 1 + // when lights glare and glow in the night air (the settings' `light_glow`) + led: vec4, + // xyz towards the moon, w its angular radius (rad) + moon: vec4, + // rgb the moon disc's irradiance before the clouds, w how much of the starry sky shows + moon_disc: vec4, + // rgb the sun's irradiance at 1400, 2100 and 2800 m (the cumulus layer) and 7000 m + // (the high thin layer), through the atmosphere from up there + cloud_sun: array, 4>, + // rgb the moonlight on a surface facing the moon (after the clouds), w 1 while the + // shadow maps are the moon's + moon_light: vec4, + // the condensation on the player's bus's panes (optical depths): windscreen, sides, + // rear, and how far the defroster has cleared the windscreen (0..1; omsi-app + // condensation.rs) + condensation: vec4, + // x the cumulus layer's base, y its top (m over the ground), z the altocumulus cover, + // w the storm's activity + layers: vec4, + // the lightning of this frame: x the light it throws on a surface facing it (1 = 10 000 + // lux), yz towards it (horizontal unit vector), w its elevation (rad) + flash: vec4, + // xyz towards the flash (unit vector), w how bright its channel is + flash2: vec4, + // x a number the channel's shape is drawn from + flash3: vec4, + // the clouds' shadow field (cloud_field.rs): xy its middle in cloud space, z one over its + // width, w 1 when there is one + cloud_f1: vec4, + // xy what takes a world point to cloud space, z the height of the plane it is taken on, + // w the share of the sun the main pass has taken off already for the clouds over the camera + cloud_f2: vec4, + // the player's bus's pitch and roll: sin, cos of each (its panes' condensation sits on + // the glass on a slope, `pane_local`) + pane_tilt: vec4, + // Slots of the weather overhaul, one owner each (zero until it fills them): + // the volumetric clouds, the volumetric fog, the precipitation, the bus's panes, the + // surfaces' PBR and the ray tracing, and two spare. + clouds_ext: vec4, + clouds_ext2: vec4, + vol_fog: vec4, + vol_fog2: vec4, + precip_ext: vec4, + glass_ext: vec4, + // (pbr_ext: x the share of the sun's light that still comes as a beam - the rest the + // clouds scatter, `sun_scattered` - y 1 when x is set) + pbr_ext: vec4, + rt_ext: vec4, +}; +@group(0) @binding(11) var enh: Enhanced; +@group(0) @binding(13) var s_lin: sampler; +@group(0) @binding(14) var t_sky_lut: texture_2d; + +const PI: f32 = 3.14159265; + +// Irradiance from the sky and the ground on a surface facing n. +fn sh_irradiance(n: vec3) -> vec3 { + let c = enh.sh; + let e = c[0].rgb * 0.282095 + + c[1].rgb * (0.488603 * n.y) + c[2].rgb * (0.488603 * n.z) + c[3].rgb * (0.488603 * n.x) + + c[4].rgb * (1.092548 * n.x * n.y) + c[5].rgb * (1.092548 * n.y * n.z) + + c[6].rgb * (0.315392 * (3.0 * n.z * n.z - 1.0)) + c[7].rgb * (1.092548 * n.x * n.z) + + c[8].rgb * (0.546274 * (n.x * n.x - n.y * n.y)); + return max(e, vec3(0.0)); +} + +// The lightning's light on a surface facing n: half of it from the cloud overhead and +// round it (a hemisphere), half along the way to the flash itself. +fn flash_irradiance(n: vec3) -> vec3 { + if (enh.flash.x <= 0.0) { + return vec3(0.0); + } + return vec3(0.80, 0.90, 1.0) * enh.flash.x * (0.5 * (0.5 + 0.5 * n.z) + 0.5 * max(dot(n, enh.flash2.xyz), 0.0)); +} + +// Sky radiance towards d (unscaled: times enh.ground.w is the radiance). The table runs +// over the azimuth from the sun (0..π) and the elevation (denser at the horizon). +// The sky table's texture: the table (32 x 48) in its corner and the clouds' shadow field +// (192 x 192) beside it, one texel clear (cloud_field.rs `SKY_TEX_W`, `FIELD_X0`). +const SKY_TEX: vec2 = vec2(225.0, 192.0); +const SKY_TABLE: vec2 = vec2(32.0, 48.0); +const FIELD_ORIGIN: f32 = 33.0; +const FIELD_N: f32 = 192.0; + +fn sky_table_raw(d: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let ls = length(s.xy); + let ld = length(d.xy); + var az = 0.0; + if (ls > 1e-4 && ld > 1e-4) { + az = acos(clamp(dot(s.xy / ls, d.xy / ld), -1.0, 1.0)); + } + let el = asin(clamp(d.z, -1.0, 1.0)); + let v = 0.5 + 0.5 * sign(el) * sqrt(min(abs(el) / 1.5707963, 1.0)); + // (kept a half texel inside the table: its neighbours in the texture are not the sky) + let tx = clamp(vec2(az / PI, v) * SKY_TABLE, vec2(0.5), SKY_TABLE - vec2(0.5)); + return textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).rgb; +} + +// The share of the sun that reaches the point p through the clouds, as against what the main +// pass's sun (`enh.sun`) already has for the camera's own place: the cumulus layer's shadow +// field read where the sun's way through p meets the layer's middle. 1 where there is no +// field, beyond its edge and where the sun is low (the camera's own factor stands there). +fn cloud_shadow_ratio(p: vec3) -> f32 { + let s = camera.sun_dir.xyz; + if (enh.cloud_f1.w < 0.5 || s.z < 0.06) { + return 1.0; + } + let cs = p.xy + s.xy / s.z * (enh.cloud_f2.z - p.z) + enh.cloud_f2.xy; + let uv = (cs - enh.cloud_f1.xy) * enh.cloud_f1.z + vec2(0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + let w = 1.0 - smoothstep(0.36, 0.48, edge); + if (w <= 0.0) { + return 1.0; + } + let tx = vec2(FIELD_ORIGIN, 0.0) + clamp(uv * FIELD_N, vec2(0.5), vec2(FIELD_N - 0.5)); + let f = textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).r; + let ratio = min(f / max(enh.cloud_f2.w, 0.02), 6.0); + return mix(1.0, ratio, w); +} + +fn sky_table(d: vec3) -> vec3 { + return sky_table_raw(d) * enh.ground.w; +} + +// Henyey-Greenstein phase function. +fn hg_phase(c: f32, g: f32) -> f32 { + let g2 = g * g; + return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * c, 1e-4), 1.5)); +} + +// Optical depth of an exponentially thinning layer (extinction sigma at height 0, falling +// off with k per metre) along a straight path of length dist from height h0 to h1. +fn layer_depth(sigma: f32, k: f32, h0: f32, h1: f32, dist: f32) -> f32 { + if (sigma <= 0.0) { + return 0.0; + } + let a = max(h0, 0.0); + let b = max(h1, 0.0); + let dh = b - a; + if (abs(k * dh) < 1e-3) { + return sigma * dist * exp(-k * 0.5 * (a + b)); + } + return sigma * dist * (exp(-k * a) - exp(-k * b)) / (k * dh); +} + +// The air between the camera and a point dist metres away in direction dir (from the +// camera), at heights h0 (camera) and h1 (point) above the fog's base: rgb the light it +// scatters towards the camera (radiance), a what it lets through of the point. +fn air(dir: vec3, dist: f32, h0: f32, h1: f32) -> vec4 { + return air_of(dir, dist, h0, h1, 1.0); +} + +// The same with the clear air's share scaled (0 for the sky, whose table holds it already). +fn air_of(dir: vec3, dist: f32, h0: f32, h1: f32, clear: f32) -> vec4 { + let tau_fog = layer_depth(enh.fog.x, enh.fog.y, h0, h1, dist); + let tau_air = layer_depth(enh.fog.w * clear, 1.0 / 1500.0, h0, h1, dist); + let tau = tau_fog + tau_air; + let t = exp(-tau); + if (tau < 1e-5) { + return vec4(0.0, 0.0, 0.0, 1.0); + } + // clear air takes on the sky's own colour at the horizon in this direction (which + // already holds the glow round the sun); a weather fog glows with the light around it + // and brighter towards the sun + let horizon = sky_table(normalize(vec3(dir.x, dir.y, max(dir.z, 0.0) * 0.3 + 0.03))); + let fog_in = enh.fog_color.rgb + enh.sun.rgb * hg_phase(dot(dir, camera.sun_dir.xyz), 0.55) * 0.9; + let inscatter = mix(horizon, fog_in, tau_fog / tau); + return vec4(inscatter * (1.0 - t), t); +} + +struct PointLight { + pos: vec4, + color: vec4, + dir: vec4, + extra: vec4, +}; +@group(0) @binding(3) var lights: array; +@group(0) @binding(4) var grid: array; +const CELL_CAP: u32 = 32u; + +// `beam_shadow.wgsl` for the shaders without the lamp shadow tiles: nothing stands in a beam. +fn beam_tile(li: u32, l: PointLight) -> u32 { + return 0xffffffffu; +} + +fn beam_reaches(k: u32, x: vec3) -> f32 { + return 1.0; +} + +// Enhanced graphics: the lamps as the scene and the sky share them - a headlamp's beam +// and the light the weather's fog scatters from the lamps towards the camera (needs the +// point lights, their grid and `camera.light_grid`). + +// A headlamp's intensity towards `t` (from the lamp) by the angles of a road lamp, not +// around its axis: wide across, brightest just under the lamp's horizon where it reaches +// far down the road, weak straight down, and with a low beam a sharp cut-off above it. +// `dir` is the lamp's axis in its vehicle's floor: its rise tilts the horizon with the +// vehicle, up a ramp and down (#1897). +fn headlamp(t: vec3, dir: vec3, low: bool) -> f32 { + let fwd = normalize(dir.xy + vec2(1e-6, 0.0)); + let ahead = dot(t.xy, fwd); + if (ahead <= 0.0) { + return 0.0; + } + let across = abs(t.x * fwd.y - t.y * fwd.x) / ahead; + let wide = 0.12 * smoothstep(1.0, 0.45, across) + 0.88 * exp(-across * across / 0.06); + let rise = t.z / max(length(t.xy), 1e-3); + let tilt = dir.z / max(length(dir.xy), 1e-3); + // (the tangent of the angle under that horizon) + let drop = (tilt - rise) / max(1.0 + rise * tilt, 1e-3); + // full out to where the road is 0.06 under the lamp's horizon, then less as the cube of + // the drop and a little more: the road is lit evenly from the bumper on, a little + // brighter as far as the beam reaches, and not as one hot pool where its axis lands + var up = min(1.0, pow(0.06 / max(abs(drop), 1e-4), 3.4)); + if (low) { + up = up * smoothstep(-0.012, 0.025, drop); + return wide * up; + } + // a full beam reaches far: a narrow, bright core along the lamp's horizon + let hot = exp(-across * across / 0.012 - drop * drop / 0.0004); + return wide * up + 6.0 * hot; +} + +// The lamps' light the weather's fog scatters towards the camera (radiance, not +// pre-exposed): single scattering along the view ray from `start` to `len` metres in +// direction `d` - the glow round a street lamp in the mist, its cone under it, a bus's +// beams reaching ahead into the fog or the falling snow. The droplets scatter strongly +// forward (fog and cloud droplets of some ten micrometres: g about 0.8), so the glow is +// brightest looking towards a lamp and a cone shows faintly from the side. +// +// Each lamp is taken once, over the whole stretch of the ray within its reach, in the grid +// cell the ray's point nearest to it lies in (the ray's cells are walked through; every +// cell lists the lamps reaching into it). Along a straight ray past a point source, with +// t - t0 = h tan(phi) (h the ray's distance from the lamp, t0 where it passes nearest), +// the inverse square cancels against the path element: dt / r^2 = dphi / h, and what is +// left is the phase function over the angle, cos(theta) = -sin(phi) - a smooth integral +// taken with five Gauss-Legendre nodes, at each of which a spot's or a headlamp's beam is +// asked how much it sends that way. The fog's extinction dims the light on its way from +// the lamp and to the camera (taken at the nearest point). A beam's light, which reaches +// only part of the way, is summed along the ray instead, its steps staggered by `jitter`. +// The droplets' phase function: a strong forward peak and the back-scattered light a +// fog's lidar ratio of some 18 sr asks for (0.055 per steradian straight back) - a single +// Henyey-Greenstein lobe of g 0.8 gave a tenth of it, and a bus's own headlights lit no +// wall of fog in front of the driver. Two lobes, 0.9 of g 0.85 and 0.1 of g -0.5. +fn fog_phase(c: f32) -> f32 { + return 0.9 * hg_phase(c, 0.85) + 0.1 * hg_phase(c, -0.5); +} +const AIRLIGHT_CELLS: u32 = 16u; + +// The clear night air's own haze, which lights a lamp's halo and a headlamp's beam as the fog's +// droplets do, only fainter: the lowest hundred metres of a city's air hold its dust, exhaust +// and humidity at several times the column's average aerosol extinction (`enh.fog.w`), 1-3e-4 +// per metre (a visibility of 15-40 km). A lamp then has a soft glow round it and a low beam +// a faint cone, as in any night photograph, instead of a lit disc on a black ground. +const GROUND_HAZE_GAIN: f32 = 8.0; + +// `droplets`: how much of the weather's extinction scatters like fog (see `FogLampUniform`). +fn lamp_airlight(c: vec3, d: vec3, start: f32, len: f32, jitter: f32, droplets: f32) -> vec3 { + var sum = vec3(0.0); + let sigma0 = enh.fog.x * droplets + enh.fog.w * GROUND_HAZE_GAIN * enh.led.z; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (sigma0 < 4e-5 || cell <= 0.0 || side == 0u || len <= start) { + return sum; + } + // (past a few optical depths nothing comes back) + let end = min(len, start + 4.0 / sigma0); + let gx = array(-0.9061798, -0.5384693, 0.0, 0.5384693, 0.9061798); + let gw = array(0.2369269, 0.4786287, 0.5688889, 0.4786287, 0.2369269); + // the walk through the grid's cells along the ray's plan + let o = (c.xy - camera.light_grid.xy) / cell; + let dd = d.xy / cell; + var ix = i32(floor(o.x + dd.x * start)); + var iy = i32(floor(o.y + dd.y * start)); + let sx = select(-1, 1, dd.x >= 0.0); + let sy = select(-1, 1, dd.y >= 0.0); + let inv_x = select(1e9, 1.0 / abs(dd.x), abs(dd.x) > 1e-7); + let inv_y = select(1e9, 1.0 / abs(dd.y), abs(dd.y) > 1e-7); + var tx = select((f32(ix) - o.x) / dd.x, (f32(ix + 1) - o.x) / dd.x, dd.x >= 0.0); + var ty = select((f32(iy) - o.y) / dd.y, (f32(iy + 1) - o.y) / dd.y, dd.y >= 0.0); + if (abs(dd.x) <= 1e-7) { tx = 1e9; } + if (abs(dd.y) <= 1e-7) { ty = 1e9; } + var t = start; + for (var k = 0u; k < AIRLIGHT_CELLS; k = k + 1u) { + if (t >= end) { + break; + } + let t_out = min(min(tx, ty), end); + if (ix >= 0 && iy >= 0 && ix < i32(side) && iy < i32(side)) { + let base = (u32(iy) * side + u32(ix)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let to_l = l.pos.xyz - c; + let t0 = dot(to_l, d); + // the ray's point nearest to the lamp: taken in this cell only + let tc = clamp(t0, start, end); + if (tc < t || tc > t_out) { + continue; + } + let range = l.extra.w; + let h = length(to_l - d * t0); + if (h >= range) { + continue; + } + // A beam (a headlamp, a spot) is lit in the weather's fog only: its cone is a sliver of + // sixteen jittered steps at half size, which the fog's density hides and the clear + // air's haze shows as shimmer and soap. The lamps' halo alone has the ground haze. + let beam_lamp = l.extra.z != 0.0 || l.dir.w > -1.5; + let fog_sigma = enh.fog.x * droplets; + if (beam_lamp && enh.fog.x < 2e-4) { + continue; + } + let s0 = select(sigma0, fog_sigma, beam_lamp); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + // (inside its core a lamp is as bright as at the core's edge) + let hh = max(h, select(core * 0.7, 0.4, l.extra.z != 0.0)); + let w = sqrt(range * range - h * h); + let ta = max(start, t0 - w); + let tb = min(end, t0 + w); + if (tb <= ta) { + continue; + } + var acc = 0.0; + var half = 0.0; + if (l.extra.z != 0.0 || l.dir.w > -1.5) { + // a beam (a headlamp, a spot): lit only where its cone or cut-off lets + // it - a sliver of the angles the lamp is seen under, which the five + // nodes missed. Sixteen even steps over that angle instead (dphi = + // h dt / r^2: the inverse square is in the step). (Sixteen even steps + // along the way put the few next to the lamp, where nearly all of its + // light is, a metre or more apart: the pixels' staggered steps came + // out as a coarse checker in the fog round every headlamp.) + let pa = atan((ta - t0) / hh); + let dphi = (atan((tb - t0) / hh) - pa) / 16.0; + let tile_k = beam_tile(li, l); + for (var q = 0u; q < 16u; q = q + 1u) { + let tq = t0 + hh * tan(pa + (f32(q) + jitter) * dphi); + let to = l.pos.xyz - (c + d * tq); + let ld = to * inverseSqrt(max(dot(to, to), 1e-6)); + var beam = 0.0; + if (l.extra.z != 0.0) { + beam = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0); + } else { + beam = smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } + // (the map is looked at only where the beam shines at all, and only for + // the few lamps that have a tile: no shadows, no tile, no tap) + var reach = 1.0; + if (beam > 0.002 && tile_k < 44u) { + reach = beam_reaches(tile_k, c + d * tq); + } + acc = acc + beam * reach * fog_phase(dot(ld, d)) * dphi; + } + half = 1.0; + } else { + let pa = atan((ta - t0) / hh); + let pb = atan((tb - t0) / hh); + half = 0.5 * (pb - pa); + let mid = 0.5 * (pa + pb); + let tile_p = beam_tile(li, l); + for (var q = 0u; q < 5u; q = q + 1u) { + let phi = mid + half * gx[q]; + let tq = t0 + hh * tan(phi); + let ld = normalize(l.pos.xyz - (c + d * tq)); + var beam = 1.0; + if (l.dir.z < -0.5) { + // (a lamp in a housing: see `lamp_light`) + beam = 0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z); + } + // (a lamp with a shadow map: what stands between it and the air + // keeps its light out of that air, as the headlamps' beams) + var reach = 1.0; + if (beam > 0.002 && tile_p < 44u) { + reach = beam_reaches(tile_p, c + d * tq); + } + acc = acc + gw[q] * beam * reach * fog_phase(-sin(phi)); + } + } + // a lamp's irradiance is core^2 / r^2 of its colour's (a headlamp's 1 / r^2) + let strength = select(core * core, 1.0, l.extra.z != 0.0); + let xc = c + d * tc; + let sigma = s0 * exp(-enh.fog.y * max(xc.z - enh.fog.z, 0.0)); + let dl = distance(xc, l.pos.xyz); + let atten = exp(-layer_depth(s0, enh.fog.y, c.z - enh.fog.z, xc.z - enh.fog.z, tc - start) - sigma * dl); + sum = sum + l.color.rgb * (l.color.w * strength * acc * half / hh * sigma * atten); + } + } + t = t_out; + if (tx < ty) { + tx = tx + inv_x; + ix = ix + sx; + } else { + ty = ty + inv_y; + iy = iy + sy; + } + } + return sum * enh.lights.y; +} + +// Enhanced: the light a raindrop or a snowflake sends towards the eye - what it scatters of +// the sky's light, the sun's and the lamps' round it, the drop's strongly forward (a +// streak flashes against a lamp seen through the rain, and is next to invisible in the +// dark between the lamps), the flake's nearly every way. (Drawn at the display's level +// whatever the light, the flakes of a snowfall at night shone white in the dark, far from +// any lamp.) +fn precip_light(x: vec3, to_eye: vec3, snow: bool) -> vec3 { + // the sky's and the ground's light round it, and the sun's on a small sphere + var e = enh.fog_color.rgb * (PI / 0.9) + enh.sun.rgb * 0.25; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell > 0.0 && side > 0u) { + let f = (x.xy - camera.light_grid.xy) / cell; + let gx = i32(floor(f.x)); + let gy = i32(floor(f.y)); + if (gx >= 0 && gy >= 0 && gx < i32(side) && gy < i32(side)) { + let base = (u32(gy) * side + u32(gx)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let dl = l.pos.xyz - x; + let dist2 = dot(dl, dl); + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let ld = dl * inverseSqrt(max(dist2, 1e-6)); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var k = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + if (l.extra.z != 0.0) { + k = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + k = k * smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } else if (l.dir.z < -0.5) { + k = k * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + // (the scattering towards the eye relative to an even one: a drop's light + // goes on forwards, a flake's every way. The angle is the one between the + // light's way from the lamp, -ld, and on to the eye: taken against -to_eye + // it put the forward peak behind the drop, and the drops in a bus's own + // beams, seen from behind the lamps, shone a hundred times too bright as + // white streaks down the road ahead) + let c = dot(-ld, to_eye); + let lobe = select(fog_phase(c), 0.7 * hg_phase(c, 0.3) + 0.3 / (4.0 * PI), snow) * 4.0 * PI; + e = e + l.color.rgb * l.color.w * enh.lights.y * k * lobe; + } + } + } + return e / PI; +} + diff --git a/crates/mx/tests/openomsi/rt_lighting.wgsl b/crates/mx/tests/openomsi/rt_lighting.wgsl new file mode 100644 index 0000000..c52c87a --- /dev/null +++ b/crates/mx/tests/openomsi/rt_lighting.wgsl @@ -0,0 +1,336 @@ +// Enhanced+: what the ray-traced passes share (rt.rs): the parameters, the scene's +// acceleration structure with its geometry records, the ray queries. +enable wgpu_ray_query; + +struct RtParams { + inv_view_proj: mat4x4, + view_proj: mat4x4, + prev_view_proj: mat4x4, + // xyz the camera (render-origin relative), w the frame number + eye: vec4, + // xyz towards the sun, w the tangent of the sun disc's radius as traced (0: no sun) + sun: vec4, + // width, height, 1 / width, 1 / height + size: vec4, + // xy the projection's depth coefficients, z the traced range (m), w the AO radius (m) + proj: vec4, + // x history usable, y the history's least weight, z debug view, w frames accumulated at most + temporal: vec4, + // the player's vehicle now: xyz its origin, w its heading (rad); and a frame ago (in this + // frame's render-origin coordinates); its box half extents (w: 1 = there is one) and centre + vehicle_now: vec4, + vehicle_prev: vec4, + vehicle_box: vec4, + vehicle_centre: vec4, + // the sky light for the reflections' hits: xyz the mean sky irradiance / pi (pre-exposed), + // w the probe's scale + sky: vec4, + // xyz the sun's radiance at the hits (pre-exposed), w the probe's mip count + sun_light: vec4, +}; + +struct Record { + tex: u32, + trans: u32, + // bit 0: alpha-tested (stochastic), bit 1: unlit (shows its own colour), bit 2: the + // coverage is the transmap's alpha, bits 3-4 how its textures are addressed (rt_tex.rs + // `address_mode`), bit 5: opaque all the same (a transmap whose alpha is not taken), + // bit 6: a see-through pane + flags: u32, + // its first triangle's texture coordinates (rt_tex.rs; 0xffffffff: none yet) + uvs: u32, + color: vec4, + // the diffuse texture's coordinates: (uv + yz) * x (a texcoordtrans offset, the ground's + // repeat) + uvt: vec4, +}; + +// One texture's mean colour and its tile in the reflections' atlas (xy its corner, z 1 when +// it is there), 256 bytes apart (written with a dynamic offset, see rt.rs). +struct TexAvg { + c: vec4, + tile: vec4, + pad: array, 14>, +}; + +@group(0) @binding(0) var p: RtParams; +@group(0) @binding(1) var acc: acceleration_structure; +@group(0) @binding(2) var t_depth: texture_depth_2d; +@group(0) @binding(3) var records: array; +@group(0) @binding(4) var tex_avg: array; + +// instance masks: solid shadow casters, solid meshes seen (by the occlusion, the +// reflections), cut-out ones seen, panes +const MASK_SHADOW: u32 = 0x01u; +const MASK_SEEN: u32 = 0x06u; +// see-through panes (their shadow: part of the sun gets through) +const MASK_GLASS: u32 = 0x08u; +// ... and the same panes as the reflections' rays meet them +const MASK_GLASS_SEEN: u32 = 0x10u; +// Ray flags. (Not called RAY_FLAG_*: Direct3D's HLSL has those names built in, and naga +// writes the constants out under their own names - DXC refused the redefinition, the ray +// tracing's pipelines were never made on Windows, and every frame was thrown away.) +const RT_FORCE_OPAQUE: u32 = 0x01u; +const RT_FIRST_HIT: u32 = 0x04u; +const PI: f32 = 3.14159265; +// The roughness up to which a reflection is traced along the mirror direction alone and +// blurred on the screen by its lobe's width (rt_denoise.wgsl `cs_atrous`); above it the +// rays follow the lobe, a new direction every frame, and the frames are averaged. (Rays +// scattered over the lobe of a pane, a polished coat or a wet road - one a pixel, a fresh +// one every frame - left these, where the reflection shows most, as noise that crawled +// whenever anything moved: the history of a lobe that narrow is thrown away at the least +// motion. The blur gives the same soft image of the street, the same every frame.) +const GLOSSY_MIRROR: f32 = 0.25; + +fn world_pos(uv: vec2, depth: f32) -> vec3 { + let h = p.inv_view_proj * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0); + return h.xyz / h.w; +} +fn linear_depth(depth: f32) -> f32 { + return p.proj.y / max(depth + p.proj.x, 1e-7); +} + +// The surface's normal from the depth around it: of the two neighbours on each axis the one +// nearer in depth, so that an edge does not tilt it; turned towards the camera. +fn depth_normal(px: vec2, world: vec3, depth: f32) -> vec3 { + let size = vec2(textureDimensions(t_depth)); + var axes: array, 2>; + for (var i = 0; i < 2; i++) { + let axis = select(vec2(1, 0), vec2(0, 1), i == 1); + let plus = clamp(px + axis, vec2(0), size - vec2(1)); + let minus = clamp(px - axis, vec2(0), size - vec2(1)); + let dp = textureLoad(t_depth, plus, 0); + let dm = textureLoad(t_depth, minus, 0); + let forward = dp > 0.0 && (dm <= 0.0 || abs(dp - depth) < abs(dm - depth)); + let q = select(minus, plus, forward); + let d = select(dm, dp, forward); + axes[i] = (world_pos((vec2(q) + vec2(0.5)) * p.size.zw, d) - world) * select(-1.0, 1.0, forward); + } + var n = cross(axes[0], axes[1]); + if (dot(n, n) < 1e-14) { + n = p.eye.xyz - world; + } + n = normalize(n); + return select(-n, n, dot(n, p.eye.xyz - world) >= 0.0); +} + +// Interleaved gradient noise, moved on every frame (a different sample per frame and pixel +// that spreads evenly over a few frames and pixels). +fn noise(px: vec2, k: f32) -> f32 { + let f = p.eye.w + k * 17.0; + let q = px + vec2(47.0, 17.0) * (f % 64.0) * 0.695; + return fract(52.9829189 * fract(dot(q, vec2(0.06711056, 0.00583715)))); +} + +fn hash3(v: vec3) -> f32 { + var x = v.x * 1664525u + v.y * 22695477u + v.z * 1013904223u; + x = (x ^ (x >> 16u)) * 0x7feb352du; + x = (x ^ (x >> 15u)) * 0x846ca68bu; + x = x ^ (x >> 16u); + return f32(x >> 8u) / 16777216.0; +} + +fn basis(n: vec3) -> mat3x3 { + let s = select(-1.0, 1.0, n.z >= 0.0); + let a = -1.0 / (s + n.z); + let b = n.x * n.y * a; + let t = vec3(1.0 + s * n.x * n.x * a, s * b, -s * n.x); + let bt = vec3(b, s + n.y * n.y * a, -n.y); + return mat3x3(t, bt, n); +} + +// How much of a hit geometry's texels stop a ray: 1 for a solid one, the mean alpha of its +// cut-out texture (or transmap) for an alpha-tested one. +fn coverage(r: Record) -> f32 { + if ((r.flags & 1u) == 0u || p.temporal.z == 3.0 || p.temporal.z == 5.0) { + return 1.0; + } + if (p.temporal.z == 4.0) { + return 0.0; + } + var a = 1.0; + if ((r.flags & 4u) != 0u && r.trans != 0xffffffffu) { + a = tex_avg[r.trans].c.a; + } else if (r.tex != 0xffffffffu) { + a = tex_avg[r.tex].c.a; + } + // (not the material's alpha: the alpha test compares the texture's own) + return clamp(a, 0.0, 1.0); +} + +struct Hit { + t: f32, + record: u32, + front: bool, + tries: u32, +}; + +// One ray query from `start` to `tmax`: its committed intersection. A function of its own, +// called for every ray: naga's Vulkan and Direct3D 12 code keeps a query's initialization +// tracker per function, not per loop iteration, and a query started again in a loop after +// a miss was never traced again there (each later try came back empty). +fn ray_hit(flags: u32, mask: u32, start: f32, tmax: f32, o: vec3, d: vec3) -> RayIntersection { + var rq: ray_query; + rayQueryInitialize(&rq, acc, RayDesc(flags, mask, start, tmax, o, d)); + rayQueryProceed(&rq); + return rayQueryGetCommittedIntersection(&rq); +} + +// The first hit along a ray within `tmax` (t < 0: none). An alpha-tested hit stops the ray by +// its coverage's chance; else the ray goes on past it (Metal's ray queries take no any-hit +// test of their own: the query is started again from there). +fn trace(o: vec3, d: vec3, tmax: f32, mask: u32, seed: vec3, solid_only: bool) -> Hit { + var start = 0.0; + var out: Hit; + out.t = -1.0; + for (var i = 0u; i < 6u; i++) { + out.tries = i + 1u; + let h = ray_hit(RT_FORCE_OPAQUE, mask, start, tmax, o, d); + if (h.kind == RAY_QUERY_INTERSECTION_NONE) { + return out; + } + let ri = h.instance_custom_data + h.geometry_index; + let r = records[ri]; + if ((r.flags & 1u) == 0u || (!solid_only && hash3(seed + vec3(i * 7919u, ri, 0u)) < coverage(r))) { + out.t = h.t; + out.record = ri; + out.front = h.front_face; + return out; + } + start = h.t + 0.002; + } + return out; +} + + +// Enhanced+: ray-traced lighting with hardware ray queries (rt.rs). +// +// Per pixel of the depth prepass, at full size, and the same every frame (nothing noisy that +// needs frames to settle, so nothing that smears or crawls when the camera moves): +// - the sun's shadow: one ray towards a point of the sun's disc (its true size, widened by a +// veil of high cloud: rt.rs), one of 16 of a fixed pattern that repeats every 4 x 4 pixels; +// - ambient occlusion: two rays over the surface's hemisphere, their directions one of 32 of +// a fixed pattern that repeats every 4 x 4 pixels; the filter averages the pattern away +// over 5 x 5 pixels at the same depth. + +// the filter's input: this frame's rays +@group(0) @binding(5) var t_in: texture_2d; +@group(0) @binding(6) var t_raw: texture_2d; +@group(0) @binding(7) var t_out: texture_storage_2d; + +// The k-th of n points of a Hammersley set. +fn hammersley(k: u32, n: u32) -> vec2 { + return vec2((f32(k) + 0.5) / f32(n), f32(reverseBits(k)) * 2.3283064e-10); +} + +@compute @workgroup_size(8, 8) +fn cs_trace(@builtin(global_invocation_id) gid: vec3) { + let px = vec2(gid.xy); + if (f32(px.x) >= p.size.x || f32(px.y) >= p.size.y) { + return; + } + let depth = textureLoad(t_depth, px, 0); + if (depth <= 0.0) { + // the sky: nothing to shade + textureStore(t_out, px, vec4(1.0, 0.0, 1.0, 0.0)); + return; + } + let uv = (vec2(px) + vec2(0.5)) * p.size.zw; + let world = world_pos(uv, depth); + let lin = linear_depth(depth); + let dist = length(world - p.eye.xyz); + if (dist > p.proj.z) { + // beyond the traced range: the shadow map (b < 0) and no occlusion + textureStore(t_out, px, vec4(1.0, lin, -1.0, 0.0)); + return; + } + let n = depth_normal(px, world, depth); + // (off the surface by more than its depth's precision and the normal's error) + let o = world + n * (0.03 + dist * 0.002); + // --- the sun (solid casters only: the cut-out ones are in the shadow map, see the main + // pass) + let cell = u32(px.x & 3) + u32(px.y & 3) * 4u; + var vis = 1.0; + if (p.sun.w > 0.0) { + // (towards one of 16 points of the sun's disc, a pattern of 4 x 4 pixels the filter + // averages: the shadow's edge softens with the distance to its caster, as the + // sun's own does, and nothing is noisy) + let su = hammersley(cell, 16u); + let sb = basis(p.sun.xyz); + let sr = sqrt(su.x) * p.sun.w; + let sd = normalize(p.sun.xyz + sb[0] * cos(6.2831853 * su.y) * sr + sb[1] * sin(6.2831853 * su.y) * sr); + // (a ray that leaves the surface at a slant runs along it for a while: the faceted + // ground, a road's camber and the steps' edges rise a few centimetres into its way + // and laid stripes of shadow over every surface the sun grazes. It starts where it + // has risen 2 cm above the surface: a few decimetres at the lowest suns, where a + // caster that close throws a shadow longer than the gap anyway) + let rise = max(dot(n, sd), 0.04); + let t0 = min(0.02 / rise, 0.5); + vis = select(1.0, 0.0, ray_hit(RT_FORCE_OPAQUE | RT_FIRST_HIT, MASK_SHADOW, t0, 2000.0, o, sd).kind != RAY_QUERY_INTERSECTION_NONE); + if (vis > 0.0) { + // through a bus's or a car's window: tinted glass lets only part of it in + vis = select(1.0, 0.45, ray_hit(RT_FORCE_OPAQUE | RT_FIRST_HIT, MASK_GLASS, t0, 200.0, o, sd).kind != RAY_QUERY_INTERSECTION_NONE); + } + } + // --- the sky's occlusion + let b = basis(n); + var ao = 0.0; + for (var j = 0u; j < 2u; j++) { + let u = hammersley(cell * 2u + j, 32u); + let rr = sqrt(u.x); + let phi = 2.0 * PI * u.y; + let d = b * vec3(rr * cos(phi), rr * sin(phi), sqrt(max(1.0 - u.x, 0.0))); + let h = trace(o, d, p.proj.w, MASK_SEEN, vec3(cell, j, 7u), false); + // (a hit at the far end of the radius takes away less than one right beside it) + ao += select(1.0, mix(0.35, 1.0, smoothstep(0.0, 1.0, h.t / p.proj.w)), h.t >= 0.0); + } + textureStore(t_out, px, vec4(ao * 0.5, lin, vis, 1.0)); +} + +// A workgroup's pixels and a border of two round them, read once. +var tile: array, 144>; + +// The rays filtered at the pixel's own depth over 5 x 5 pixels (the whole pattern of +// directions). The pattern repeats every 4 pixels, so a plain 5 x 5 box counted one row and +// one column of it twice - which ones, by the pixel's place in the pattern: a soft shadow's +// edge kept a fixed 4 x 4 checker on the screen, which crawled over the surfaces as the +// camera moved. The outer row and column on each side weigh a half: they are the same +// pattern cells, and every one of the 16 counts exactly once. +@compute @workgroup_size(8, 8) +fn cs_denoise(@builtin(global_invocation_id) gid: vec3, @builtin(workgroup_id) wid: vec3, @builtin(local_invocation_index) li: u32) { + let origin = vec2(wid.xy) * 8 - vec2(2); + let size = vec2(p.size.xy); + for (var k = i32(li); k < 144; k += 64) { + let q = origin + vec2(k % 12, k / 12); + tile[k] = textureLoad(t_in, clamp(q, vec2(0), size - vec2(1)), 0); + } + workgroupBarrier(); + let px = vec2(gid.xy); + if (f32(px.x) >= p.size.x || f32(px.y) >= p.size.y) { + return; + } + let lp = px - origin; + let c = tile[lp.y * 12 + lp.x]; + if (c.g <= 0.0 || c.b < 0.0 || p.temporal.z == 7.0) { + textureStore(t_out, px, c); + return; + } + let tol = 0.012 * c.g + 0.02; + var ao = 0.0; + var aw = 0.0; + var sun = 0.0; + var sw = 0.0; + for (var j = -2; j <= 2; j++) { + for (var i = -2; i <= 2; i++) { + let s = tile[(lp.y + j) * 12 + lp.x + i]; + if (s.g > 0.0 && s.b >= 0.0 && abs(s.g - c.g) < tol) { + let w = select(1.0, 0.5, abs(i) == 2) * select(1.0, 0.5, abs(j) == 2); + ao += s.r * w; + aw += w; + sun += s.b * w; + sw += w; + } + } + } + textureStore(t_out, px, vec4(ao / max(aw, 1e-4), c.g, sun / max(sw, 1e-4), 1.0)); +} diff --git a/crates/mx/tests/openomsi/rt_reflections.wgsl b/crates/mx/tests/openomsi/rt_reflections.wgsl new file mode 100644 index 0000000..97c45b9 --- /dev/null +++ b/crates/mx/tests/openomsi/rt_reflections.wgsl @@ -0,0 +1,790 @@ +// Enhanced+: what the ray-traced passes share (rt.rs): the parameters, the scene's +// acceleration structure with its geometry records, the ray queries. +enable wgpu_ray_query; + +struct RtParams { + inv_view_proj: mat4x4, + view_proj: mat4x4, + prev_view_proj: mat4x4, + // xyz the camera (render-origin relative), w the frame number + eye: vec4, + // xyz towards the sun, w the tangent of the sun disc's radius as traced (0: no sun) + sun: vec4, + // width, height, 1 / width, 1 / height + size: vec4, + // xy the projection's depth coefficients, z the traced range (m), w the AO radius (m) + proj: vec4, + // x history usable, y the history's least weight, z debug view, w frames accumulated at most + temporal: vec4, + // the player's vehicle now: xyz its origin, w its heading (rad); and a frame ago (in this + // frame's render-origin coordinates); its box half extents (w: 1 = there is one) and centre + vehicle_now: vec4, + vehicle_prev: vec4, + vehicle_box: vec4, + vehicle_centre: vec4, + // the sky light for the reflections' hits: xyz the mean sky irradiance / pi (pre-exposed), + // w the probe's scale + sky: vec4, + // xyz the sun's radiance at the hits (pre-exposed), w the probe's mip count + sun_light: vec4, +}; + +struct Record { + tex: u32, + trans: u32, + // bit 0: alpha-tested (stochastic), bit 1: unlit (shows its own colour), bit 2: the + // coverage is the transmap's alpha, bits 3-4 how its textures are addressed (rt_tex.rs + // `address_mode`), bit 5: opaque all the same (a transmap whose alpha is not taken), + // bit 6: a see-through pane + flags: u32, + // its first triangle's texture coordinates (rt_tex.rs; 0xffffffff: none yet) + uvs: u32, + color: vec4, + // the diffuse texture's coordinates: (uv + yz) * x (a texcoordtrans offset, the ground's + // repeat) + uvt: vec4, +}; + +// One texture's mean colour and its tile in the reflections' atlas (xy its corner, z 1 when +// it is there), 256 bytes apart (written with a dynamic offset, see rt.rs). +struct TexAvg { + c: vec4, + tile: vec4, + pad: array, 14>, +}; + +@group(0) @binding(0) var p: RtParams; +@group(0) @binding(1) var acc: acceleration_structure; +@group(0) @binding(2) var t_depth: texture_depth_2d; +@group(0) @binding(3) var records: array; +@group(0) @binding(4) var tex_avg: array; + +// instance masks: solid shadow casters, solid meshes seen (by the occlusion, the +// reflections), cut-out ones seen, panes +const MASK_SHADOW: u32 = 0x01u; +const MASK_SEEN: u32 = 0x06u; +// see-through panes (their shadow: part of the sun gets through) +const MASK_GLASS: u32 = 0x08u; +// ... and the same panes as the reflections' rays meet them +const MASK_GLASS_SEEN: u32 = 0x10u; +// Ray flags. (Not called RAY_FLAG_*: Direct3D's HLSL has those names built in, and naga +// writes the constants out under their own names - DXC refused the redefinition, the ray +// tracing's pipelines were never made on Windows, and every frame was thrown away.) +const RT_FORCE_OPAQUE: u32 = 0x01u; +const RT_FIRST_HIT: u32 = 0x04u; +const PI: f32 = 3.14159265; +// The roughness up to which a reflection is traced along the mirror direction alone and +// blurred on the screen by its lobe's width (rt_denoise.wgsl `cs_atrous`); above it the +// rays follow the lobe, a new direction every frame, and the frames are averaged. (Rays +// scattered over the lobe of a pane, a polished coat or a wet road - one a pixel, a fresh +// one every frame - left these, where the reflection shows most, as noise that crawled +// whenever anything moved: the history of a lobe that narrow is thrown away at the least +// motion. The blur gives the same soft image of the street, the same every frame.) +const GLOSSY_MIRROR: f32 = 0.25; + +fn world_pos(uv: vec2, depth: f32) -> vec3 { + let h = p.inv_view_proj * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0); + return h.xyz / h.w; +} +fn linear_depth(depth: f32) -> f32 { + return p.proj.y / max(depth + p.proj.x, 1e-7); +} + +// The surface's normal from the depth around it: of the two neighbours on each axis the one +// nearer in depth, so that an edge does not tilt it; turned towards the camera. +fn depth_normal(px: vec2, world: vec3, depth: f32) -> vec3 { + let size = vec2(textureDimensions(t_depth)); + var axes: array, 2>; + for (var i = 0; i < 2; i++) { + let axis = select(vec2(1, 0), vec2(0, 1), i == 1); + let plus = clamp(px + axis, vec2(0), size - vec2(1)); + let minus = clamp(px - axis, vec2(0), size - vec2(1)); + let dp = textureLoad(t_depth, plus, 0); + let dm = textureLoad(t_depth, minus, 0); + let forward = dp > 0.0 && (dm <= 0.0 || abs(dp - depth) < abs(dm - depth)); + let q = select(minus, plus, forward); + let d = select(dm, dp, forward); + axes[i] = (world_pos((vec2(q) + vec2(0.5)) * p.size.zw, d) - world) * select(-1.0, 1.0, forward); + } + var n = cross(axes[0], axes[1]); + if (dot(n, n) < 1e-14) { + n = p.eye.xyz - world; + } + n = normalize(n); + return select(-n, n, dot(n, p.eye.xyz - world) >= 0.0); +} + +// Interleaved gradient noise, moved on every frame (a different sample per frame and pixel +// that spreads evenly over a few frames and pixels). +fn noise(px: vec2, k: f32) -> f32 { + let f = p.eye.w + k * 17.0; + let q = px + vec2(47.0, 17.0) * (f % 64.0) * 0.695; + return fract(52.9829189 * fract(dot(q, vec2(0.06711056, 0.00583715)))); +} + +fn hash3(v: vec3) -> f32 { + var x = v.x * 1664525u + v.y * 22695477u + v.z * 1013904223u; + x = (x ^ (x >> 16u)) * 0x7feb352du; + x = (x ^ (x >> 15u)) * 0x846ca68bu; + x = x ^ (x >> 16u); + return f32(x >> 8u) / 16777216.0; +} + +fn basis(n: vec3) -> mat3x3 { + let s = select(-1.0, 1.0, n.z >= 0.0); + let a = -1.0 / (s + n.z); + let b = n.x * n.y * a; + let t = vec3(1.0 + s * n.x * n.x * a, s * b, -s * n.x); + let bt = vec3(b, s + n.y * n.y * a, -n.y); + return mat3x3(t, bt, n); +} + +// How much of a hit geometry's texels stop a ray: 1 for a solid one, the mean alpha of its +// cut-out texture (or transmap) for an alpha-tested one. +fn coverage(r: Record) -> f32 { + if ((r.flags & 1u) == 0u || p.temporal.z == 3.0 || p.temporal.z == 5.0) { + return 1.0; + } + if (p.temporal.z == 4.0) { + return 0.0; + } + var a = 1.0; + if ((r.flags & 4u) != 0u && r.trans != 0xffffffffu) { + a = tex_avg[r.trans].c.a; + } else if (r.tex != 0xffffffffu) { + a = tex_avg[r.tex].c.a; + } + // (not the material's alpha: the alpha test compares the texture's own) + return clamp(a, 0.0, 1.0); +} + +struct Hit { + t: f32, + record: u32, + front: bool, + tries: u32, +}; + +// One ray query from `start` to `tmax`: its committed intersection. A function of its own, +// called for every ray: naga's Vulkan and Direct3D 12 code keeps a query's initialization +// tracker per function, not per loop iteration, and a query started again in a loop after +// a miss was never traced again there (each later try came back empty). +fn ray_hit(flags: u32, mask: u32, start: f32, tmax: f32, o: vec3, d: vec3) -> RayIntersection { + var rq: ray_query; + rayQueryInitialize(&rq, acc, RayDesc(flags, mask, start, tmax, o, d)); + rayQueryProceed(&rq); + return rayQueryGetCommittedIntersection(&rq); +} + +// The first hit along a ray within `tmax` (t < 0: none). An alpha-tested hit stops the ray by +// its coverage's chance; else the ray goes on past it (Metal's ray queries take no any-hit +// test of their own: the query is started again from there). +fn trace(o: vec3, d: vec3, tmax: f32, mask: u32, seed: vec3, solid_only: bool) -> Hit { + var start = 0.0; + var out: Hit; + out.t = -1.0; + for (var i = 0u; i < 6u; i++) { + out.tries = i + 1u; + let h = ray_hit(RT_FORCE_OPAQUE, mask, start, tmax, o, d); + if (h.kind == RAY_QUERY_INTERSECTION_NONE) { + return out; + } + let ri = h.instance_custom_data + h.geometry_index; + let r = records[ri]; + if ((r.flags & 1u) == 0u || (!solid_only && hash3(seed + vec3(i * 7919u, ri, 0u)) < coverage(r))) { + out.t = h.t; + out.record = ri; + out.front = h.front_face; + return out; + } + start = h.t + 0.002; + } + return out; +} + + +// Enhanced graphics: what the enhanced main pass, the sky and the coronas share - the +// light of the physically based sky (see atmosphere.rs), in its units (1 = 10 000 lux), +// and the air between the camera and what it sees. The scene is drawn pre-exposed: +// radiance times `enh.exposure.x`, so that the half-float target keeps its precision by +// night as well as by day. +struct Enhanced { + // x pre-exposure, y the level unlit things are drawn at, z a lit window's radiance + // (pre-exposed), w how bright a light's corona is drawn + exposure: vec4, + // rgb irradiance of the sun after the clouds, w its angular radius (rad) + sun: vec4, + // irradiance from the sky and the ground: order-2 spherical harmonics, rgb + sh: array, 9>, + // rgb radiance of the ground, w the sky table's scale + ground: vec4, + // x weather fog extinction (1/m) at its base, y its height falloff (1/m), z the base + // height (render-origin relative), w clear-air extinction (1/m) at the ground + fog: vec4, + // rgb fog radiance from the light around it (the sun's part is added by angle), + // w the table scale the reflection probe was drawn with + fog_color: vec4, + // x wet roads, y snow cover, z rain, w cloud cover in front of the sun + weather: vec4, + // x mip levels of the probe, y illuminance of a light's core (maplight colour 1), + // z cabin light illuminance, w how much of the sun the clouds let through + lights: vec4, + // rgb the sun disc's irradiance before the clouds, w frame time (s) + sun_disc: vec4, + // x which term the main pass shows alone (OMSI_DEBUG_ENHANCED, 0 = the picture), + // y the puddles' F0, z the envmap photo's strength, w the tone curve's contrast + debug: vec4, + // xyz where the sky cube is drawn from, relative to the camera + eye: vec4, + // x how bright an LED panel's dots burn (0 = off), y whether the LED panels' `\S:n` + // masks keep their mip chain (0: at full resolution, the dots stay visible when small), z 1 + // when lights glare and glow in the night air (the settings' `light_glow`) + led: vec4, + // xyz towards the moon, w its angular radius (rad) + moon: vec4, + // rgb the moon disc's irradiance before the clouds, w how much of the starry sky shows + moon_disc: vec4, + // rgb the sun's irradiance at 1400, 2100 and 2800 m (the cumulus layer) and 7000 m + // (the high thin layer), through the atmosphere from up there + cloud_sun: array, 4>, + // rgb the moonlight on a surface facing the moon (after the clouds), w 1 while the + // shadow maps are the moon's + moon_light: vec4, + // the condensation on the player's bus's panes (optical depths): windscreen, sides, + // rear, and how far the defroster has cleared the windscreen (0..1; omsi-app + // condensation.rs) + condensation: vec4, + // x the cumulus layer's base, y its top (m over the ground), z the altocumulus cover, + // w the storm's activity + layers: vec4, + // the lightning of this frame: x the light it throws on a surface facing it (1 = 10 000 + // lux), yz towards it (horizontal unit vector), w its elevation (rad) + flash: vec4, + // xyz towards the flash (unit vector), w how bright its channel is + flash2: vec4, + // x a number the channel's shape is drawn from + flash3: vec4, + // the clouds' shadow field (cloud_field.rs): xy its middle in cloud space, z one over its + // width, w 1 when there is one + cloud_f1: vec4, + // xy what takes a world point to cloud space, z the height of the plane it is taken on, + // w the share of the sun the main pass has taken off already for the clouds over the camera + cloud_f2: vec4, + // the player's bus's pitch and roll: sin, cos of each (its panes' condensation sits on + // the glass on a slope, `pane_local`) + pane_tilt: vec4, + // Slots of the weather overhaul, one owner each (zero until it fills them): + // the volumetric clouds, the volumetric fog, the precipitation, the bus's panes, the + // surfaces' PBR and the ray tracing, and two spare. + clouds_ext: vec4, + clouds_ext2: vec4, + vol_fog: vec4, + vol_fog2: vec4, + precip_ext: vec4, + glass_ext: vec4, + // (pbr_ext: x the share of the sun's light that still comes as a beam - the rest the + // clouds scatter, `sun_scattered` - y 1 when x is set) + pbr_ext: vec4, + rt_ext: vec4, +}; + +// Enhanced+: ray-traced reflections (rt.rs), after the main pass. +// +// The enhanced pass left, per pixel, the surface a reflection starts from (its normal, its +// distance from the eye, its roughness) and how much of the reflection lands on the screen +// (GBUF_FORMAT: the split sum's Fresnel and lobe integral, so that a rough dielectric shows a +// few per cent of it and glass, metal and a wet road much), and drew the picture without the +// probe's reflection there. A ray per pixel (or per REFL_DIV x REFL_DIV, from the most +// reflective of them) goes out along a direction of the surface's GGX lobe - the mirror +// direction for a smooth one - and what it meets is +// - on the screen and seen there: the picture's own colour at that place (lit, fogged, +// reflections and all, exactly as drawn); +// - off the screen or hidden: the hit mesh's texel there (its texture's small copy in the +// atlas, rt_tex.rs; the texture's mean colour until that is made) times its material's +// colour, lit by the sun (a shadow ray from there) and the sky about its own normal; +// - nothing: the sky probe. +// The denoiser (rt_denoise.wgsl) gathers the rays over the frames and the pixels round each, +// and the composite adds the result, times the weight, to the picture. + +// The rays' grid: one per REFL_DIV x REFL_DIV pixels (1: every pixel). +override REFL_DIV: i32 = 1; + +@group(0) @binding(5) var t_gbuf: texture_2d; +@group(0) @binding(6) var t_aux: texture_2d; +@group(0) @binding(7) var t_out: texture_storage_2d; +@group(0) @binding(8) var s_lin: sampler; +@group(0) @binding(9) var t_scene: texture_2d; +@group(0) @binding(10) var t_probe: texture_cube; +@group(0) @binding(11) var enh: Enhanced; +@group(0) @binding(12) var t_hist: texture_2d; +// per traced triangle its texture coordinates (rt_uv.wgsl), and the textures' tiles +@group(0) @binding(13) var tri_uv: array>; +@group(0) @binding(14) var t_atlas: texture_2d; + +// the alpha test's threshold (the main pass's `ALPHA_REF`) +const ALPHA_REF: f32 = 128.5 / 255.0; + +// Texture `t`'s texel at `uv`, from its tile in the atlas, addressed by `mode` (0 repeat, +// 1 mirror, 2 clamp, 3 mirror once); w < 0 while the texture has no tile. +fn tile_texel(t: u32, uv: vec2, mode: u32, cut: bool) -> vec4 { + let tile = tex_avg[t].tile; + if (tile.z < 0.5) { + return vec4(-1.0); + } + var w = fract(uv); + if (mode != 0u) { + // (kept off the border, which repeats the other edge: these do not) + w = select(select(abs(uv), uv, mode == 2u), 1.0 - abs(fract(uv * 0.5) * 2.0 - 1.0), mode == 1u); + w = clamp(w, vec2(1.0 / 60.0), vec2(59.0 / 60.0)); + } + if (!cut) { + let at = (tile.xy + vec2(1.0) + w * 30.0) / vec2(textureDimensions(t_atlas)); + return textureSampleLevel(t_atlas, s_lin, at, 0.0); + } + // A cut-out texture's colour filtered by its coverage: the texels the alpha test throws + // away are white or black in most leaves' textures, and filtered in as they were they + // fringed every reflected crown with white specks. + let f = tile.xy + vec2(0.5) + w * 30.0; + let b = vec2(floor(f)); + let fr = f - floor(f); + var rgb = vec3(0.0); + var a = 0.0; + for (var j = 0; j <= 1; j++) { + for (var i = 0; i <= 1; i++) { + let c = textureLoad(t_atlas, b + vec2(i, j), 0); + let k = select(1.0 - fr.x, fr.x, i == 1) * select(1.0 - fr.y, fr.y, j == 1); + rgb += c.rgb * c.a * k; + a += c.a * k; + } + } + let mean = tex_avg[t].c.rgb; + return vec4(select(mean, rgb / max(a, 1e-4), a > 1e-3), a); +} + +// What a hit shows of its textures: rgb the diffuse texture's colour there (white without +// one), a the coverage the alpha test takes; a < 0 while that is not known yet (no +// coordinates or no tile: the mean colour then). +fn hit_texel(r: Record, prim: u32, bary: vec2) -> vec4 { + if (r.uvs == 0xffffffffu) { + return vec4(-1.0); + } + let q = tri_uv[(r.uvs + prim) * 2u]; + let base = vec2(f32(i32(q.w << 16u) >> 16u), f32(i32(q.w) >> 16u)); + let uv = base + unpack2x16float(q.x) * (1.0 - bary.x - bary.y) + unpack2x16float(q.y) * bary.x + unpack2x16float(q.z) * bary.y; + let mode = (r.flags >> 3u) & 3u; + var c = vec4(1.0); + if (r.tex != 0xffffffffu) { + c = tile_texel(r.tex, (uv + r.uvt.yz) * r.uvt.x, mode, (r.flags & 5u) == 1u); + if (c.a < 0.0) { + return c; + } + } + if ((r.flags & 4u) != 0u && r.trans != 0xffffffffu) { + // (the transmap without the offset and the ground's repeat, as the main pass reads it) + let m = tile_texel(r.trans, uv, mode, false); + if (m.a < 0.0) { + return m; + } + c.a = m.a; + } + if ((r.flags & 32u) != 0u) { + c.a = 1.0; + } + return c; +} + +fn sh_irradiance(n: vec3) -> vec3 { + let c = enh.sh; + let e = c[0].rgb * 0.282095 + + c[1].rgb * (0.488603 * n.y) + c[2].rgb * (0.488603 * n.z) + c[3].rgb * (0.488603 * n.x) + + c[4].rgb * (1.092548 * n.x * n.y) + c[5].rgb * (1.092548 * n.y * n.z) + + c[6].rgb * (0.315392 * (3.0 * n.z * n.z - 1.0)) + c[7].rgb * (1.092548 * n.x * n.z) + + c[8].rgb * (0.546274 * (n.x * n.x - n.y * n.y)); + return max(e, vec3(0.0)); +} + +// The sky probe towards d at the blur of roughness `rough` (pre-exposed). +fn sky_probe(d: vec3, rough: f32) -> vec3 { + let lod = rough * (enh.lights.x - 1.0); + return textureSampleLevel(t_probe, s_lin, d.xzy, lod).rgb * enh.fog_color.w; +} + +fn finite(c: vec3) -> vec3 { + let e = bitcast>(c) & vec3(0x7f800000u); + return select(vec3(0.0), clamp(c, vec3(0.0), vec3(6.0e4)), all(e != vec3(0x7f800000u))); +} + +// Heitz's visible-normal sampling of the GGX lobe (in Dupuy and Benyoub's spherical-cap +// form): a microfacet normal round n as the eye at `wo` (towards the eye) sees them, for +// roughness `rough` (alpha = rough^2) and two uniform numbers. Rays reflected about it follow +// the lobe the main pass's split sum integrates, so many frames of them average to the +// same blur the sky probe gives a surface that rough, with the street in it. +fn ggx_vndf(n: vec3, wo: vec3, rough: f32, u: vec2) -> vec3 { + let a = max(rough * rough, 1e-4); + let b = basis(n); + let wl = vec3(dot(wo, b[0]), dot(wo, b[1]), max(dot(wo, n), 1e-4)); + let ws = normalize(vec3(wl.xy * a, wl.z)); + let phi = 2.0 * PI * u.x; + let z = (1.0 - u.y) * (1.0 + ws.z) - ws.z; + let st = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + let hs = vec3(st * cos(phi), st * sin(phi), z) + ws; + let hl = normalize(vec3(hs.xy * a, max(hs.z, 1e-6))); + return normalize(b * hl); +} + +// This frame's two numbers for a pixel: a hash per pixel moved along the R2 sequence every +// frame, so that the rays of a pixel cover its lobe evenly over the frames the history keeps. +fn frame_noise(px: vec2) -> vec2 { + let h = vec2(hash3(vec3(vec2(px), 11u)), hash3(vec3(vec2(px), 23u))); + let f = f32(u32(p.eye.w) % 1024u); + return fract(h + f * vec2(0.7548777, 0.5698403)); +} + +// A unit vector folded onto the octahedron (rt_uv.wgsl) and back. +fn oct_encode(n: vec3) -> vec2 { + let q = n.xy / (abs(n.x) + abs(n.y) + abs(n.z)); + if (n.z >= 0.0) { + return q; + } + return (vec2(1.0) - abs(q.yx)) * select(vec2(-1.0), vec2(1.0), q >= vec2(0.0)); +} +fn oct_decode(e: vec2) -> vec3 { + var n = vec3(e, 1.0 - abs(e.x) - abs(e.y)); + let t = max(-n.z, 0.0); + n = vec3(n.xy + select(vec2(t), vec2(-t), n.xy >= vec2(0.0)), n.z); + return normalize(n); +} + +// The surface's normal where a ray met mesh record `r`'s triangle `prim` (its corners' normals +// mixed by the barycentrics, turned into the world by the instance's transform; length 0 +// while the mesh's normals are not there yet). +fn hit_normal(r: Record, prim: u32, bary: vec2, w2o: mat4x3) -> vec3 { + if (r.uvs == 0xffffffffu) { + return vec3(0.0); + } + let q = tri_uv[(r.uvs + prim) * 2u + 1u]; + let nl = oct_decode(unpack2x16snorm(q.x)) * (1.0 - bary.x - bary.y) + + oct_decode(unpack2x16snorm(q.y)) * bary.x + oct_decode(unpack2x16snorm(q.z)) * bary.y; + // (normals go by the inverse transpose: the world-to-object matrix's rows) + let nw = vec3(dot(w2o[0], nl), dot(w2o[1], nl), dot(w2o[2], nl)); + if (dot(nw, nw) < 1e-12) { + return vec3(0.0); + } + return normalize(nw); +} + +// Where a point a ray along `d` meets is on the screen: x 1 there and seen (the picture's +// colour is its own), 2 there but the picture shows something further (a gap: the ray went +// through a cut-out texel), 3 there behind something nearer - or the picture shows the other +// face of it - 0 off the screen; yz its place. +fn on_screen(pt: vec3, d: vec3) -> vec3 { + let c = p.view_proj * vec4(pt, 1.0); + if (c.w > 0.05) { + let uv = vec2(c.x / c.w * 0.5 + 0.5, 0.5 - c.y / c.w * 0.5); + if (all(uv > vec2(0.002)) && all(uv < vec2(0.998))) { + let q = vec2(uv * p.size.xy); + let dq = textureLoad(t_depth, q, 0); + let seen = select(1e9, linear_depth(dq), dq > 0.0); + let tol = 0.02 * c.w + 0.08; + if (abs(seen - c.w) < tol) { + // (the picture shows the face turned to the camera: a ray that met the + // other one - a car's reflection that went in through the bus's window and + // met the back of a seat, or the bus's side from outside next to the seat + // the camera sees from inside - is not lit as the picture there is; taken + // as it was, every car beside the bus mirrored its red seats) + let qc = (vec2(q) + vec2(0.5)) * p.size.zw; + let ns = depth_normal(q, world_pos(qc, dq), dq); + return vec3(select(3.0, 1.0, dot(ns, d) < 0.0), uv); + } + return vec3(select(3.0, 2.0, seen > c.w + tol), uv); + } + } + return vec3(0.0); +} + +// The light a reflected ray brings back from where it meets the scene (`sc` its place on +// the screen): the picture's own colour there, else the mesh lit as the main pass lights it. +fn hit_light(o: vec3, d: vec3, h: Hit, sc: vec3, texel: vec4, nh: vec3) -> vec3 { + let pt = o + d * h.t; + // (a cut-out mesh - leaves - seen through a gap shows what lies behind it there: the + // picture's colour all the same, the same for the rays beside it; deciding leaf or gap + // one ray at a time sprinkled the glass with light and dark specks, #1907) + let cut = (records[h.record].flags & 1u) != 0u; + if (sc.x == 1.0 || (cut && sc.x == 2.0)) { + let seen = finite(textureSampleLevel(t_scene, s_lin, sc.yz, 0.0).rgb); + // (towards the screen's edge the picture's colour hands over to the mesh's own, + // which is what the rays beyond the edge get: a hard seam ran across the windows + // where the reflected street left the screen) + let edge = min(min(sc.y, 1.0 - sc.y), min(sc.z, 1.0 - sc.z)); + let k = smoothstep(0.0, 0.08, edge); + if (k >= 0.999) { + return seen; + } + return mix(mesh_light(pt, d, h, texel, nh), seen, k); + } + return mesh_light(pt, d, h, texel, nh); +} + +// The sky's light on a surface facing n (as the main pass's `sh_irradiance`) with what the +// clouds scatter of the sun (its `sun_scattered`, the beam's share in `enh.pbr_ext.x`). +fn sky_light(n: vec3) -> vec3 { + var e = sh_irradiance(n); + if (enh.pbr_ext.y > 0.5 && enh.pbr_ext.x < 0.999) { + let s = p.sun.xyz; + let lobe = (1.0 + dot(n, s)) / (1.0 + max(s.z, 0.0)); + e = e + enh.sun.rgb * (1.0 - clamp(enh.pbr_ext.x, 0.0, 1.0)) * max(s.z, 0.0) * mix(0.5 + 0.5 * n.z, lobe, 0.4); + } + return e; +} + +// What a ray finds off the screen or hidden there: the hit mesh's colour (its texel there, +// `hit_texel`, or its texture's mean colour, times its material's) lit as the main pass +// lights a matt surface - the sun's beam by its angle to the surface's own normal (`nh`, +// from the mesh's normals; facing the ray where they are not known yet) where a shadow ray +// finds the sun, the sky and the scattered sun over the hemisphere - and the air along the way. +fn mesh_light(pt: vec3, d: vec3, h: Hit, texel: vec4, nh: vec3) -> vec3 { + let o = pt - d * h.t; + let r = records[h.record]; + var albedo = r.color.rgb; + if (texel.a >= 0.0) { + albedo = albedo * texel.rgb; + } else if (r.tex != 0xffffffffu) { + albedo = albedo * tex_avg[r.tex].c.rgb; + } + if ((r.flags & 2u) != 0u) { + return albedo * enh.exposure.y; + } + // (two-sided: the face the ray met) + var nf = -d; + if (dot(nh, nh) > 0.5) { + nf = select(nh, -nh, dot(nh, d) > 0.0); + } + var sun = vec3(0.0); + let nl = dot(nf, p.sun.xyz); + if (p.sun.w > 0.0 && nl > 0.0) { + if (ray_hit(RT_FORCE_OPAQUE | RT_FIRST_HIT, MASK_SHADOW, 0.0, 1500.0, pt + nf * 0.03 - d * 0.02, p.sun.xyz).kind == RAY_QUERY_INTERSECTION_NONE) { + let beam = select(1.0, clamp(enh.pbr_ext.x, 0.0, 1.0), enh.pbr_ext.y > 0.5); + sun = enh.sun.rgb * beam * nl; + } + } + var l = albedo / PI * (sun + sky_light(nf)) * enh.exposure.x; + // the air along the way: from the eye to the surface and on to the hit + let dist = length(o - p.eye.xyz) + h.t; + let ext = exp(-(enh.fog.x + enh.fog.w) * dist); + l = l * ext + enh.fog_color.rgb * enh.exposure.x * (1.0 - ext); + return finite(l); +} + +// The rays' second output: per ray the surface it left (x its distance from the eye, 0 where +// no ray went; y its roughness; zw its normal folded onto the octahedron), for the denoiser +// (rt_denoise.wgsl) and the composite. +@group(0) @binding(15) var t_meta_out: texture_storage_2d; +@group(0) @binding(16) var t_meta: texture_2d; + +@compute @workgroup_size(8, 8) +fn cs_reflect(@builtin(global_invocation_id) gid: vec3) { + let hp = vec2(gid.xy); + let hsize = vec2(textureDimensions(t_out)); + if (any(hp >= hsize)) { + return; + } + let size = vec2(p.size.xy); + // the most reflective of the pixels the ray stands for + var px = min(hp * REFL_DIV, size - vec2(1)); + var g = vec4(0.0); + for (var j = 0; j < REFL_DIV; j++) { + for (var i = 0; i < REFL_DIV; i++) { + let q = min(hp * REFL_DIV + vec2(i, j), size - vec2(1)); + let s = textureLoad(t_gbuf, q, 0); + if (length(s.xyz) > length(g.xyz)) { + g = s; + px = q; + } + } + } + // (a reflection that hardly shows - a pane seen from the cab, a matt surface at a steep + // angle - is as good from the sky probe: the composite takes that where no ray went) + if (length(g.xyz) < 0.012 || g.w < 1e-4) { + textureStore(t_out, hp, vec4(0.0)); + textureStore(t_meta_out, hp, vec4(0.0)); + return; + } + let aux = textureLoad(t_aux, px, 0); + // (premultiplied by the coverage, gbuf.w: a pane's is 1, a surface's its weight) + let n = normalize(g.xyz); + let dist = aux.r / g.w; + let rough = clamp(aux.g / g.w, 0.0, 1.0); + let uv = (vec2(px) + vec2(0.5)) * p.size.zw; + let view = normalize(world_pos(uv, 0.001) - p.eye.xyz); + let pt = p.eye.xyz + view * dist; + textureStore(t_meta_out, hp, vec4(dist, rough, oct_encode(n))); + var d = reflect(view, n); + // A rough surface (a satin panel, dry plaster) is no mirror: its rays follow the GGX lobe + // of its roughness, a new one every frame, which the denoiser averages over the frames and + // the pixels round it. What is smoother - a pane, a polished coat, a wet road, a puddle - + // takes the one ray along the mirror direction, blurred by its lobe afterwards + // (`GLOSSY_MIRROR`). + if (rough > GLOSSY_MIRROR) { + let hn = ggx_vndf(n, -view, rough, frame_noise(hp)); + let dd = reflect(view, hn); + if (dot(dd, n) > 0.01) { + d = dd; + } + } + // (a reflection into the surface would show what is under it: bent up along it) + let below = dot(d, n); + if (below < 0.02) { + d = normalize(d + n * (0.02 - below)); + } + // (a ray that leaves the scene takes the sky probe at a little of the lobe's blur: the + // rays themselves spread it, the rest keeps the sky's stars and edges from crawling) + let sky_rough = select(rough, rough * 0.5, rough > GLOSSY_MIRROR); + var l: vec3; + // how far the ray went (the reprojection's mirror image is that far behind the surface); + // far for the sky + var reach = 1.0e4; + // (OMSI_DEBUG_RT=11: what each ray found - blue the sky, green the picture, yellow a + // gap in a cut-out on the screen, red a mesh off the screen or hidden) + var dbg = vec3(0.0, 0.0, 1.0); + if (dist > p.proj.z) { + l = sky_probe(d, sky_rough); + } else { + let o = pt + n * (0.02 + dist * 0.0015); + // (a cut-out mesh - leaves, a fence - is taken as solid, and the picture says where + // its texels are: where it shows a gap there, the ray goes on) + var start = 0.0; + l = sky_probe(d, sky_rough); + // A pane first: what it mirrors itself (glass at the slant a reflection meets it + // takes about a tenth) and the inside behind it, seen through its tint. The inside + // is lit only through the panes as well: where the picture does not show it, the + // mean colour lit as if outdoors is dimmed by the tint once more. + var through = 1.0; + var pane = vec3(0.0); + let gh = ray_hit(RT_FORCE_OPAQUE, MASK_SEEN | MASK_GLASS_SEEN, 0.0, 400.0, o, d); + if (gh.kind != RAY_QUERY_INTERSECTION_NONE && (records[gh.instance_custom_data + gh.geometry_index].flags & 64u) != 0u) { + pane = sky_probe(d, sky_rough) * 0.1; + through = 0.45; + start = gh.t + 0.01; + reach = gh.t; + } + // What the ray meets, front to back: a solid mesh ends it; a cut-out one (leaves, a + // fence) where it is not on the screen stops as much of it as its texels' filtered + // coverage there, and the rest goes on. (Taken all or nothing at the alpha test, one + // ray a pixel, every crown's edge in a window was a sprinkle of specks that changed + // with each frame's ray.) + var acc = vec3(0.0); + var left = 1.0; + for (var k = 0; k < 4; k++) { + let ch = ray_hit(RT_FORCE_OPAQUE, MASK_SEEN, start, 400.0, o, d); + if (ch.kind == RAY_QUERY_INTERSECTION_NONE) { + break; + } + var h: Hit; + h.t = ch.t; + h.record = ch.instance_custom_data + ch.geometry_index; + let rec = records[h.record]; + let cut = (rec.flags & 1u) != 0u; + let sc = on_screen(o + d * h.t, d); + let texel = hit_texel(rec, ch.primitive_index, ch.barycentrics); + let hidden = sc.x != 1.0 && sc.x != 2.0; + var a = 1.0; + if (cut && hidden) { + // (its texels not known yet: as much as they cover on average) + a = select(mix(coverage(rec), 1.0, 0.5), smoothstep(ALPHA_REF - 0.3, ALPHA_REF + 0.2, texel.a), texel.a >= 0.0); + } + if (a > 0.01) { + let nh = hit_normal(rec, ch.primitive_index, ch.barycentrics, ch.world_to_object); + var lh = hit_light(o, d, h, sc, texel, nh); + if (through < 1.0 && sc.x != 1.0) { + lh = lh * through; + } + acc += lh * a * left; + if (left > 0.5) { + reach = min(reach, ch.t); + dbg = select(select(vec3(1.0, 0.0, 0.0), vec3(1.0, 1.0, 0.0), sc.x == 2.0), vec3(0.0, 1.0, 0.0), sc.x == 1.0); + } + left *= 1.0 - a; + } + if (left < 0.02) { + break; + } + start = ch.t + 0.002; + } + l = acc + l * left; + l = pane + l * through * select(1.0, 0.9, through < 1.0); + } + // (no single ray brighter than the sky's brightest: the sun's own glint on the surface + // is the main pass's, and a ray that found the sun's disc was a speck of light) + let lum = dot(l, vec3(0.2126, 0.7152, 0.0722)); + let cap = 2.5 * enh.exposure.x * max(dot(sh_irradiance(vec3(0.0, 0.0, 1.0)), vec3(0.2126, 0.7152, 0.0722)), 0.05); + l = l * min(1.0, cap / max(lum, 1e-5)); + if (p.temporal.z == 8.0) { + l = vec3(f32(dist > p.proj.z), rough, 0.0); + } + if (p.temporal.z == 11.0) { + l = dbg; + } + textureStore(t_out, hp, vec4(l, reach)); +} + +// --- the composite: the denoised reflection (rt_denoise.wgsl) times its weight, added to the +// picture (blended additively). Where the rays are fewer than the pixels, from those round +// the pixel on its own surface. +struct VsOut { + @builtin(position) clip: vec4, +}; + +@vertex +fn vs_full(@builtin(vertex_index) i: u32) -> VsOut { + let x = f32(i32(i & 1u) * 4 - 1); + let y = f32(i32(i >> 1u) * 4 - 1); + return VsOut(vec4(x, y, 0.0, 1.0)); +} + +@fragment +fn fs_composite(in: VsOut) -> @location(0) vec4 { + let px = vec2(in.clip.xy); + let g = textureLoad(t_gbuf, px, 0); + // (the reflection's weight is the normal's length: see `cs_reflect`) + let weight = length(g.xyz); + if (weight < 0.002 || g.w < 1e-4) { + discard; + } + let aux = textureLoad(t_aux, px, 0); + let dist = aux.r / g.w; + let rough = clamp(aux.g / g.w, 0.0, 1.0); + let hsize = vec2(textureDimensions(t_hist)); + let hq = (vec2(px) + vec2(0.5)) / f32(REFL_DIV) - vec2(0.5); + let base = vec2(floor(hq)); + let fr = hq - floor(hq); + let tol = (0.02 + rough * 0.06) * dist + 0.05; + var sum = vec3(0.0); + var wsum = 0.0; + // (the four rays round the pixel, bilinear, those on its own surface only) + for (var j = 0; j <= 1; j++) { + for (var i = 0; i <= 1; i++) { + let q = clamp(base + vec2(i, j), vec2(0), hsize - vec2(1)); + let m = textureLoad(t_meta, q, 0); + let k = select(1.0 - fr.x, fr.x, i == 1) * select(1.0 - fr.y, fr.y, j == 1) + 1e-3; + let w = k * select(0.0, 1.0, m.x > 0.0 && abs(m.x - dist) < tol); + sum += textureLoad(t_hist, q, 0).rgb * w; + wsum += w; + } + } + var l: vec3; + if (wsum < 1e-4) { + // (no ray at this distance nearby: the sky probe the way the surface's lobe looks) + let uv = (vec2(px) + vec2(0.5)) * p.size.zw; + let view = normalize(world_pos(uv, 0.001) - p.eye.xyz); + l = sky_probe(reflect(view, normalize(g.xyz)), rough); + } else { + l = sum / wsum; + } + if (p.temporal.z == 11.0) { + return vec4(l * 3.0, 0.0); + } + if (p.temporal.z >= 8.0) { + return vec4(select(l * 0.3, vec3(0.0), p.temporal.z == 10.0) + vec3(0.0, 0.0, weight * 10.0), 0.0); + } + return vec4(l * weight, 0.0); +} diff --git a/crates/mx/tests/openomsi/rt_reflections_denoiser.wgsl b/crates/mx/tests/openomsi/rt_reflections_denoiser.wgsl new file mode 100644 index 0000000..8f442fa --- /dev/null +++ b/crates/mx/tests/openomsi/rt_reflections_denoiser.wgsl @@ -0,0 +1,487 @@ +// Enhanced+: what the ray-traced passes share (rt.rs): the parameters, the scene's +// acceleration structure with its geometry records, the ray queries. +enable wgpu_ray_query; + +struct RtParams { + inv_view_proj: mat4x4, + view_proj: mat4x4, + prev_view_proj: mat4x4, + // xyz the camera (render-origin relative), w the frame number + eye: vec4, + // xyz towards the sun, w the tangent of the sun disc's radius as traced (0: no sun) + sun: vec4, + // width, height, 1 / width, 1 / height + size: vec4, + // xy the projection's depth coefficients, z the traced range (m), w the AO radius (m) + proj: vec4, + // x history usable, y the history's least weight, z debug view, w frames accumulated at most + temporal: vec4, + // the player's vehicle now: xyz its origin, w its heading (rad); and a frame ago (in this + // frame's render-origin coordinates); its box half extents (w: 1 = there is one) and centre + vehicle_now: vec4, + vehicle_prev: vec4, + vehicle_box: vec4, + vehicle_centre: vec4, + // the sky light for the reflections' hits: xyz the mean sky irradiance / pi (pre-exposed), + // w the probe's scale + sky: vec4, + // xyz the sun's radiance at the hits (pre-exposed), w the probe's mip count + sun_light: vec4, +}; + +struct Record { + tex: u32, + trans: u32, + // bit 0: alpha-tested (stochastic), bit 1: unlit (shows its own colour), bit 2: the + // coverage is the transmap's alpha, bits 3-4 how its textures are addressed (rt_tex.rs + // `address_mode`), bit 5: opaque all the same (a transmap whose alpha is not taken), + // bit 6: a see-through pane + flags: u32, + // its first triangle's texture coordinates (rt_tex.rs; 0xffffffff: none yet) + uvs: u32, + color: vec4, + // the diffuse texture's coordinates: (uv + yz) * x (a texcoordtrans offset, the ground's + // repeat) + uvt: vec4, +}; + +// One texture's mean colour and its tile in the reflections' atlas (xy its corner, z 1 when +// it is there), 256 bytes apart (written with a dynamic offset, see rt.rs). +struct TexAvg { + c: vec4, + tile: vec4, + pad: array, 14>, +}; + +@group(0) @binding(0) var p: RtParams; +@group(0) @binding(1) var acc: acceleration_structure; +@group(0) @binding(2) var t_depth: texture_depth_2d; +@group(0) @binding(3) var records: array; +@group(0) @binding(4) var tex_avg: array; + +// instance masks: solid shadow casters, solid meshes seen (by the occlusion, the +// reflections), cut-out ones seen, panes +const MASK_SHADOW: u32 = 0x01u; +const MASK_SEEN: u32 = 0x06u; +// see-through panes (their shadow: part of the sun gets through) +const MASK_GLASS: u32 = 0x08u; +// ... and the same panes as the reflections' rays meet them +const MASK_GLASS_SEEN: u32 = 0x10u; +// Ray flags. (Not called RAY_FLAG_*: Direct3D's HLSL has those names built in, and naga +// writes the constants out under their own names - DXC refused the redefinition, the ray +// tracing's pipelines were never made on Windows, and every frame was thrown away.) +const RT_FORCE_OPAQUE: u32 = 0x01u; +const RT_FIRST_HIT: u32 = 0x04u; +const PI: f32 = 3.14159265; +// The roughness up to which a reflection is traced along the mirror direction alone and +// blurred on the screen by its lobe's width (rt_denoise.wgsl `cs_atrous`); above it the +// rays follow the lobe, a new direction every frame, and the frames are averaged. (Rays +// scattered over the lobe of a pane, a polished coat or a wet road - one a pixel, a fresh +// one every frame - left these, where the reflection shows most, as noise that crawled +// whenever anything moved: the history of a lobe that narrow is thrown away at the least +// motion. The blur gives the same soft image of the street, the same every frame.) +const GLOSSY_MIRROR: f32 = 0.25; + +fn world_pos(uv: vec2, depth: f32) -> vec3 { + let h = p.inv_view_proj * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0); + return h.xyz / h.w; +} +fn linear_depth(depth: f32) -> f32 { + return p.proj.y / max(depth + p.proj.x, 1e-7); +} + +// The surface's normal from the depth around it: of the two neighbours on each axis the one +// nearer in depth, so that an edge does not tilt it; turned towards the camera. +fn depth_normal(px: vec2, world: vec3, depth: f32) -> vec3 { + let size = vec2(textureDimensions(t_depth)); + var axes: array, 2>; + for (var i = 0; i < 2; i++) { + let axis = select(vec2(1, 0), vec2(0, 1), i == 1); + let plus = clamp(px + axis, vec2(0), size - vec2(1)); + let minus = clamp(px - axis, vec2(0), size - vec2(1)); + let dp = textureLoad(t_depth, plus, 0); + let dm = textureLoad(t_depth, minus, 0); + let forward = dp > 0.0 && (dm <= 0.0 || abs(dp - depth) < abs(dm - depth)); + let q = select(minus, plus, forward); + let d = select(dm, dp, forward); + axes[i] = (world_pos((vec2(q) + vec2(0.5)) * p.size.zw, d) - world) * select(-1.0, 1.0, forward); + } + var n = cross(axes[0], axes[1]); + if (dot(n, n) < 1e-14) { + n = p.eye.xyz - world; + } + n = normalize(n); + return select(-n, n, dot(n, p.eye.xyz - world) >= 0.0); +} + +// Interleaved gradient noise, moved on every frame (a different sample per frame and pixel +// that spreads evenly over a few frames and pixels). +fn noise(px: vec2, k: f32) -> f32 { + let f = p.eye.w + k * 17.0; + let q = px + vec2(47.0, 17.0) * (f % 64.0) * 0.695; + return fract(52.9829189 * fract(dot(q, vec2(0.06711056, 0.00583715)))); +} + +fn hash3(v: vec3) -> f32 { + var x = v.x * 1664525u + v.y * 22695477u + v.z * 1013904223u; + x = (x ^ (x >> 16u)) * 0x7feb352du; + x = (x ^ (x >> 15u)) * 0x846ca68bu; + x = x ^ (x >> 16u); + return f32(x >> 8u) / 16777216.0; +} + +fn basis(n: vec3) -> mat3x3 { + let s = select(-1.0, 1.0, n.z >= 0.0); + let a = -1.0 / (s + n.z); + let b = n.x * n.y * a; + let t = vec3(1.0 + s * n.x * n.x * a, s * b, -s * n.x); + let bt = vec3(b, s + n.y * n.y * a, -n.y); + return mat3x3(t, bt, n); +} + +// How much of a hit geometry's texels stop a ray: 1 for a solid one, the mean alpha of its +// cut-out texture (or transmap) for an alpha-tested one. +fn coverage(r: Record) -> f32 { + if ((r.flags & 1u) == 0u || p.temporal.z == 3.0 || p.temporal.z == 5.0) { + return 1.0; + } + if (p.temporal.z == 4.0) { + return 0.0; + } + var a = 1.0; + if ((r.flags & 4u) != 0u && r.trans != 0xffffffffu) { + a = tex_avg[r.trans].c.a; + } else if (r.tex != 0xffffffffu) { + a = tex_avg[r.tex].c.a; + } + // (not the material's alpha: the alpha test compares the texture's own) + return clamp(a, 0.0, 1.0); +} + +struct Hit { + t: f32, + record: u32, + front: bool, + tries: u32, +}; + +// One ray query from `start` to `tmax`: its committed intersection. A function of its own, +// called for every ray: naga's Vulkan and Direct3D 12 code keeps a query's initialization +// tracker per function, not per loop iteration, and a query started again in a loop after +// a miss was never traced again there (each later try came back empty). +fn ray_hit(flags: u32, mask: u32, start: f32, tmax: f32, o: vec3, d: vec3) -> RayIntersection { + var rq: ray_query; + rayQueryInitialize(&rq, acc, RayDesc(flags, mask, start, tmax, o, d)); + rayQueryProceed(&rq); + return rayQueryGetCommittedIntersection(&rq); +} + +// The first hit along a ray within `tmax` (t < 0: none). An alpha-tested hit stops the ray by +// its coverage's chance; else the ray goes on past it (Metal's ray queries take no any-hit +// test of their own: the query is started again from there). +fn trace(o: vec3, d: vec3, tmax: f32, mask: u32, seed: vec3, solid_only: bool) -> Hit { + var start = 0.0; + var out: Hit; + out.t = -1.0; + for (var i = 0u; i < 6u; i++) { + out.tries = i + 1u; + let h = ray_hit(RT_FORCE_OPAQUE, mask, start, tmax, o, d); + if (h.kind == RAY_QUERY_INTERSECTION_NONE) { + return out; + } + let ri = h.instance_custom_data + h.geometry_index; + let r = records[ri]; + if ((r.flags & 1u) == 0u || (!solid_only && hash3(seed + vec3(i * 7919u, ri, 0u)) < coverage(r))) { + out.t = h.t; + out.record = ri; + out.front = h.front_face; + return out; + } + start = h.t + 0.002; + } + return out; +} + + +// Enhanced+: the traced reflections' denoiser (rt.rs), between the rays (rt_reflect.wgsl +// `cs_reflect`) and the composite. +// +// A glossy surface's rays follow its lobe, a new direction every frame: one ray is noise, the +// lobe's average is the reflection. That average is gathered +// - over the frames (`cs_temporal`): each pixel's history is found where its surface was a +// frame ago - or, for a smooth one, where the mirror image of what it reflects was, which +// moves with the reflected scene and not with the mirror - and kept as long as the same +// surface lies there; it is held inside the spread of this frame's rays round the pixel, +// so that nothing that has moved leaves a trail. A mirror keeps no history: its one ray is +// exact. The luminance's first two moments are kept along, for how noisy the pixel still is; +// - over the pixels round it (`cs_atrous`, three passes of an a-trous wavelet 1, 2 and 4 +// pixels apart): only from those on the same surface (distance, normal, roughness), as far +// round as its lobe spreads the reflection on the screen, and less from those whose colour +// differs by more than the pixel's own noise (its variance) explains. + +@group(0) @binding(5) var t_meta: texture_2d; +@group(0) @binding(6) var t_cur: texture_2d; +// the temporal pass: last frame's history and its moments; the a-trous passes: this frame's +// rays (their reach in a) and moments (the first pass's variance in w) +@group(0) @binding(7) var t_prev: texture_2d; +@group(0) @binding(8) var t_prev_m: texture_2d; +@group(0) @binding(9) var t_out: texture_storage_2d; +@group(0) @binding(10) var t_out_m: texture_storage_2d; +// x the a-trous step (pixels), y 1 when the variance is the moments' (the first pass) +@group(0) @binding(11) var pass_step: vec4; + +// The rays' grid: one per REFL_DIV x REFL_DIV pixels. +override REFL_DIV: i32 = 1; + +fn luma(c: vec3) -> f32 { + return dot(c, vec3(0.2126, 0.7152, 0.0722)); +} + +fn to_ycocg(c: vec3) -> vec3 { + return vec3(0.25 * c.r + 0.5 * c.g + 0.25 * c.b, 0.5 * c.r - 0.5 * c.b, -0.25 * c.r + 0.5 * c.g - 0.25 * c.b); +} + +fn from_ycocg(c: vec3) -> vec3 { + return max(vec3(c.x + c.y - c.z, c.x + c.z, c.x - c.y - c.z), vec3(0.0)); +} + +fn oct_decode(e: vec2) -> vec3 { + var n = vec3(e, 1.0 - abs(e.x) - abs(e.y)); + let t = max(-n.z, 0.0); + n = vec3(n.xy + select(vec2(t), vec2(-t), n.xy >= vec2(0.0)), n.z); + return normalize(n); +} + +// The place on the screen a ray's grid cell stands for (uv of its middle). +fn cell_uv(q: vec2) -> vec2 { + return (vec2(q * REFL_DIV) + vec2(0.5 * f32(REFL_DIV))) * p.size.zw; +} + +// A point on the player's vehicle where it was a frame ago (the vehicle moves under the +// camera: its own surfaces stay put on the screen while the world slides past). +fn vehicle_prev(pt: vec3) -> vec3 { + if (p.vehicle_box.w < 0.5) { + return pt; + } + let d = pt - p.vehicle_now.xyz; + let cn = cos(p.vehicle_now.w); + let sn = sin(p.vehicle_now.w); + // (into the vehicle's frame: its heading turned back) + let local = vec3(d.x * cn + d.y * sn, -d.x * sn + d.y * cn, d.z) - p.vehicle_centre.xyz; + if (any(abs(local) > p.vehicle_box.xyz + vec3(0.3))) { + return pt; + } + let l = local + p.vehicle_centre.xyz; + let cp = cos(p.vehicle_prev.w); + let sp = sin(p.vehicle_prev.w); + return p.vehicle_prev.xyz + vec3(l.x * cp - l.y * sp, l.x * sp + l.y * cp, l.z); +} + +fn in_vehicle(pt: vec3) -> bool { + return any(vehicle_prev(pt) != pt); +} + +// How far round (in rays) a surface's reflection is spread on the screen: the lobe's angle +// (about alpha) over what it reflects `reach` metres behind it, seen from `dist` - nothing for +// a mirror, more for a rougher surface and for what it reflects from further away (a +// reflection touching its object stays sharp where it meets it). +fn lobe_radius(uv: vec2, rough: f32, reach: f32, dist: f32) -> f32 { + let a = rough * rough; + let angle = a * reach / (dist + reach); + // (the angle one ray's cell spans) + let v0 = normalize(world_pos(uv, 0.001) - p.eye.xyz); + let v1 = normalize(world_pos(uv + vec2(0.0, p.size.w * f32(REFL_DIV)), 0.001) - p.eye.xyz); + let cell = max(length(v1 - v0), 1e-6); + return min(angle / cell, 24.0); +} + +@compute @workgroup_size(8, 8) +fn cs_temporal(@builtin(global_invocation_id) gid: vec3) { + let q = vec2(gid.xy); + let size = vec2(textureDimensions(t_cur)); + if (any(q >= size)) { + return; + } + let m = textureLoad(t_meta, q, 0); + let cur = textureLoad(t_cur, q, 0); + if (m.x <= 0.0) { + textureStore(t_out, q, vec4(0.0)); + textureStore(t_out_m, q, vec4(0.0)); + return; + } + let dist = m.x; + let rough = m.y; + let uv = cell_uv(q); + let view = normalize(world_pos(uv, 0.001) - p.eye.xyz); + let pt = p.eye.xyz + view * dist; + let clip_w = (p.view_proj * vec4(pt, 1.0)).w; + // --- this frame's rays round the pixel, on its own surface: their mean and spread (in + // YCoCg, where a box round them holds the colours better than in RGB) + let tol = 0.03 * dist + 0.1; + var m1 = vec3(0.0); + var m2 = vec3(0.0); + var lm1 = 0.0; + var lm2 = 0.0; + var cnt = 0.0; + for (var j = -1; j <= 1; j++) { + for (var i = -1; i <= 1; i++) { + let s = clamp(q + vec2(i, j), vec2(0), size - vec2(1)); + let ms = textureLoad(t_meta, s, 0); + if (ms.x > 0.0 && abs(ms.x - dist) < tol) { + let c = textureLoad(t_cur, s, 0).rgb; + let y = to_ycocg(c); + m1 += y; + m2 += y * y; + let l = luma(c); + lm1 += l; + lm2 += l * l; + cnt += 1.0; + } + } + } + m1 /= cnt; + let sigma = sqrt(max(m2 / cnt - m1 * m1, vec3(0.0))); + let spatial_var = max(lm2 / cnt - (lm1 / cnt) * (lm1 / cnt), 0.0); + // --- where the history is: the surface a frame ago and, for a smooth one, the mirror + // image of what it reflects (as far behind the surface as the ray went) + let on_vehicle = in_vehicle(pt); + let prev_pt = vehicle_prev(pt); + let pc = p.prev_view_proj * vec4(prev_pt, 1.0); + var hist = vec4(0.0); + var hist_m = vec2(0.0); + var found = 0.0; + if (p.temporal.x > 0.5 && pc.w > 0.05) { + var puv = vec2(pc.x / pc.w * 0.5 + 0.5, 0.5 - pc.y / pc.w * 0.5); + let mirror = (1.0 - smoothstep(0.1, 0.35, rough)) * select(1.0, 0.0, on_vehicle); + if (mirror > 0.0) { + let vc = p.prev_view_proj * vec4(p.eye.xyz + view * (dist + min(cur.a, 2000.0)), 1.0); + if (vc.w > 0.05) { + let vuv = vec2(vc.x / vc.w * 0.5 + 0.5, 0.5 - vc.y / vc.w * 0.5); + puv = mix(puv, vuv, mirror); + } + } + // (bilinear over the four cells round it, each only where the same surface was) + let f = puv * vec2(size) - vec2(0.5); + let b = vec2(floor(f)); + let fr = f - floor(f); + let ptol = 0.04 * pc.w + 0.15; + var wsum = 0.0; + for (var j = 0; j <= 1; j++) { + for (var i = 0; i <= 1; i++) { + let s = b + vec2(i, j); + if (all(s >= vec2(0)) && all(s < size)) { + let pm = textureLoad(t_prev_m, s, 0); + let w = select(1.0 - fr.x, fr.x, i == 1) * select(1.0 - fr.y, fr.y, j == 1); + if (pm.z > 0.0 && abs(pm.z - pc.w) < ptol && w > 1e-3) { + hist += textureLoad(t_prev, s, 0) * w; + hist_m += pm.xy * w; + wsum += w; + } + } + } + } + if (wsum > 0.05) { + hist /= wsum; + hist_m /= wsum; + found = 1.0; + } + } + // --- the blend: as many frames as the lobe needs (none for a mirror), the history held + // inside the box of this frame's rays (wider for a rough surface, whose rays scatter) + // (a ray along the mirror direction is the same every frame: nothing to average, and no + // history to trail behind what moves) + let most = select(1.0, mix(12.0, 32.0, smoothstep(GLOSSY_MIRROR, 0.5, rough)), rough > GLOSSY_MIRROR); + let count = min(select(0.0, hist.a, found > 0.5) + 1.0, most); + let alpha = 1.0 / count; + var c = cur.rgb; + var lmom = vec2(luma(cur.rgb), luma(cur.rgb) * luma(cur.rgb)); + if (found > 0.5 && count > 1.0) { + let gamma = 1.0 + 2.0 * smoothstep(0.1, 0.6, rough); + let hy = to_ycocg(hist.rgb); + // (clipped towards the box's middle, not clamped per channel: no colour shift) + let dir = hy - m1; + // (not narrower than a few per cent of the brightness: a grey reflection's chroma + // hardly spreads, and a box that thin snapped every history back to the noisy mean) + let ext = max(sigma * gamma, vec3(0.03 * max(m1.x, 0.0) + 1e-3)); + let t = max(abs(dir.x) / ext.x, max(abs(dir.y) / ext.y, abs(dir.z) / ext.z)); + var held = hy; + if (t > 1.0) { + held = m1 + dir / t; + } + c = mix(from_ycocg(held), cur.rgb, alpha); + lmom = mix(hist_m, lmom, alpha); + } + // (the noise left: the moments' once a few frames are in, before that the spread of the + // rays round it) + let temporal_var = max(lmom.y - lmom.x * lmom.x, 0.0); + let variance = mix(spatial_var, temporal_var, smoothstep(2.0, 6.0, count)); + textureStore(t_out, q, vec4(c, count)); + textureStore(t_out_m, q, vec4(lmom, clip_w, variance)); +} + +// One pass of the a-trous wavelet (the B3 spline's 5 x 5 taps, `pass_step.x` rays apart). +@compute @workgroup_size(8, 8) +fn cs_atrous(@builtin(global_invocation_id) gid: vec3) { + let q = vec2(gid.xy); + let size = vec2(textureDimensions(t_cur)); + if (any(q >= size)) { + return; + } + let m = textureLoad(t_meta, q, 0); + let c = textureLoad(t_cur, q, 0); + var var_c = c.a; + if (pass_step.y > 0.5) { + var_c = textureLoad(t_prev_m, q, 0).w; + } + if (m.x <= 0.0) { + textureStore(t_out, q, vec4(0.0)); + return; + } + let dist = m.x; + let rough = m.y; + let n = oct_decode(m.zw); + let step = max(i32(pass_step.x), 1); + // (a mirror, or a lobe narrower than this pass's step: the pixel as it is) + let radius = lobe_radius(cell_uv(q), rough, max(textureLoad(t_prev, q, 0).a, 0.0), dist); + if (rough < 0.03 || radius < 0.5 * f32(step)) { + textureStore(t_out, q, vec4(c.rgb, var_c)); + return; + } + let lc = luma(c.rgb); + let sigma_l = 4.0 * sqrt(max(var_c, 0.0)) + 1e-3; + let k = array(0.375, 0.25, 0.0625); + var sum = vec3(0.0); + var vsum = 0.0; + var wsum = 0.0; + for (var j = -2; j <= 2; j++) { + for (var i = -2; i <= 2; i++) { + let s = q + vec2(i, j) * step; + if (any(s < vec2(0)) || any(s >= size)) { + continue; + } + let ms = textureLoad(t_meta, s, 0); + if (ms.x <= 0.0) { + continue; + } + let cs = textureLoad(t_cur, s, 0); + var vs = cs.a; + if (pass_step.y > 0.5) { + vs = textureLoad(t_prev_m, s, 0).w; + } + let r = length(vec2(f32(i), f32(j))) * f32(step); + let w_space = k[abs(i)] * k[abs(j)] * exp(-r * r / (2.0 * radius * radius)); + let w_depth = exp(-abs(ms.x - dist) / (0.01 * dist * f32(step) + 0.05)); + let w_normal = pow(max(dot(oct_decode(ms.zw), n), 0.0), 32.0); + let w_rough = exp(-abs(ms.y - rough) * 12.0); + let w_luma = exp(-abs(luma(cs.rgb) - lc) / sigma_l); + // (the mirror rays are blurred as wide as the lobe whatever their colours: they + // are not noisy, and the colour's edges are the reflection's own) + let w = w_space * w_depth * w_normal * w_rough * select(w_luma, 1.0, (i == 0 && j == 0) || rough <= GLOSSY_MIRROR); + sum += cs.rgb * w; + vsum += vs * w * w; + wsum += w; + } + } + let out = sum / max(wsum, 1e-5); + textureStore(t_out, q, vec4(out, vsum / max(wsum * wsum, 1e-8))); +} diff --git a/crates/mx/tests/openomsi/rt_texture_coordinates.wgsl b/crates/mx/tests/openomsi/rt_texture_coordinates.wgsl new file mode 100644 index 0000000..5fe3660 --- /dev/null +++ b/crates/mx/tests/openomsi/rt_texture_coordinates.wgsl @@ -0,0 +1,56 @@ +// Enhanced+ (rt_tex.rs): a traced mesh's triangles' texture coordinates and normals, for the +// reflections' hits. Per triangle two records: its three corners' coordinates less an integer +// part they share, as half floats (exact enough over a few repeats of a texture), and that +// integer part (two i16); then its three corners' normals in the mesh's own frame, each +// folded onto an octahedron as two 16-bit signed norms. +struct Job { + first_vertex: u32, + first_index: u32, + tris: u32, + at: u32, +}; + +// the mesh page's vertices (8 floats each: position, normal, uv) and indices +@group(0) @binding(0) var uv_verts: array; +@group(0) @binding(1) var uv_index: array; +@group(0) @binding(2) var uv_out: array>; +@group(0) @binding(3) var job: Job; + +// A unit vector folded onto the octahedron (and its square), -1..1 on each axis. +fn oct_encode(n_in: vec3) -> vec2 { + var n = n_in; + if (dot(n, n) < 1e-12) { + n = vec3(0.0, 0.0, 1.0); + } + let p = n.xy / (abs(n.x) + abs(n.y) + abs(n.z)); + if (n.z >= 0.0) { + return p; + } + return (vec2(1.0) - abs(p.yx)) * select(vec2(-1.0), vec2(1.0), p >= vec2(0.0)); +} + +@compute @workgroup_size(64) +fn cs_tri_uv(@builtin(global_invocation_id) gid: vec3) { + // (rows of 65535 groups of 64) + let t = gid.x + gid.y * 4194240u; + if (t >= job.tris) { + return; + } + var uv: array, 3>; + var nn: array; + for (var k = 0u; k < 3u; k++) { + let v = (job.first_vertex + uv_index[job.first_index + t * 3u + k]) * 8u; + uv[k] = vec2(uv_verts[v + 6u], uv_verts[v + 7u]); + nn[k] = pack2x16snorm(oct_encode(vec3(uv_verts[v + 3u], uv_verts[v + 4u], uv_verts[v + 5u]))); + } + let base = clamp(floor(min(min(uv[0], uv[1]), uv[2])), vec2(-32768.0), vec2(32767.0)); + let b = vec2(base); + let at = (job.at + t) * 2u; + uv_out[at + 1u] = vec4(nn[0], nn[1], nn[2], 0u); + uv_out[at] = vec4( + pack2x16float(uv[0] - base), + pack2x16float(uv[1] - base), + pack2x16float(uv[2] - base), + (u32(b.x) & 0xffffu) | (u32(b.y) << 16u), + ); +} diff --git a/crates/mx/tests/openomsi/scene.wgsl b/crates/mx/tests/openomsi/scene.wgsl new file mode 100644 index 0000000..8f66941 --- /dev/null +++ b/crates/mx/tests/openomsi/scene.wgsl @@ -0,0 +1,5783 @@ +fn srgb_encode(c: vec3) -> vec3 { + let x = max(c, vec3(0.0)); + return select(1.055 * pow(x, vec3(1.0 / 2.4)) - 0.055, x * 12.92, x <= vec3(0.0031308)); +} +fn srgb_decode(c: vec3) -> vec3 { + let x = max(c, vec3(0.0)); + return select(pow((x + 0.055) / 1.055, vec3(2.4)), x / 12.92, x <= vec3(0.04045)); +} + +struct Camera { + view_proj: mat4x4, + cam_pos: vec4, + world_origin: vec4, // world-space origin removed from render coordinates + sun_dir: vec4, // xyz direction to the sun, w intensity + ambient: vec4, // rgb ambient (envir light C) + fog: vec4, // rgb, density + sun_color: vec4, // rgb (envir light A), w night factor 0..1 (nightmap strength) + sky_color: vec4, // rgb secondary light from above (envir light B), w 1 = vanilla (as OMSI 2), 0 = Vanilla+ + light_grid: vec4, // x,y grid origin (render-origin relative), z cell size, w cells per side + sky: vec4, + cam_right: vec4, + cam_up: vec4, + clouds: vec4, + light_view_proj: mat4x4, + light_view_proj_far: mat4x4, + shadow: vec4, // x enabled, y texel size, z near cascade half range + post: vec4, // x enhanced, y time, zw sun ndc + inside_a: vec4, // player vehicle box: origin xyz, sin(heading) + inside_b: vec4, // cos(heading), half extents xyz + inside_c: vec4, // box centre offset xyz, w = 1 when there is a box, 2 with the eye in it + flags: vec4, // x detail texturing, y enhanced graphics, z never set (see fs_main's end), w close cascade half range + light_view_proj_close: mat4x4, + wind: vec4, // the player's vehicle's velocity (m/s, world): the airstream on its glass + // Enhanced: the lamps' shadow maps (the tiles under the far map; zero where nothing is + // drawn) and where the tiles lie: x a tile's side, y tiles to a row, z the far map's + // texture height, w the number of tiles (`LampAtlas::uniform`) + lamp_view_proj: array, 56>, + lamp_atlas: vec4, + // Windy trees: xy the weather's wind (m/s, world; 0 with the setting off), zw how far + // the air has carried the gusts since the start (m, modulo PATTERN_PERIOD) + tree_wind: vec4, + // an articulated bus's rear section (as inside_*): read by the snowfall only - a test of + // it here, inlined into every use of inside_vehicle, brought Apple's M4 shader compiler + // down (see 0.2.21's Metal note) + inside2_a: vec4, + inside2_b: vec4, + inside2_c: vec4, + // Enhanced: the field each light cookie layer covers (xy: the tangents of its half + // angles across and up; z: its first record in the light buffer), see enhanced.wgsl + // `cookie_light` + cookies: array, 8>, + // Enhanced: the lights of the player's saloon that have a shadow map (their places in the + // light buffer, 4 a vector, -1 for none): see `cabin_visibility` + cabin_lamps: array, 4>, + // x: the textures' mip bias (FSR 1: negative, see `CameraUniform::lod`) + lod: vec4, // x mip bias, y ground-prepass flag, z road sunlight glare, w air temperature (degC) + // the classic picture's headlight (`CameraUniform::spot`, see `classic_spot`) + spot: array, 4>, +}; + +// 1 when the point lies inside the player's vehicle (its [boundingbox], shrunk a little so +// that the outer skin, the glass and the roof stay outside): weather stays out of the cab. +// The side/front/back shrink was a bare 0.12 m, which left an interior fixture close to the +// wall (a window sill, the handbrake by the windscreen) just outside the box, wearing the +// up-facing wet/snow coat meant for the body panel beside it (see the `outside` weight +// below). A previous fix WIDENED this margin to 0.6 m, reasoning by analogy with the falling- +// particle exclusion box in `rain.rs` - but that box works the other way round (its margin +// is added, growing the excluded region outward, away from the body) from this one (whose +// margin is subtracted, shrinking the "inside" region inward, toward the body): widening it +// here shrank the cabin's own "inside" zone and threw the *whole* cabin outside it, coating +// the entire interior in snow instead of just the ledge. Narrowed to 0.03 m instead - just +// enough that the true outer skin and glass stay outside, without giving up real interior +// floor space near the wall. +// A normal of no length (a mesh saved with zero normals) is upright instead of NaN: +// normalize(0) is NaN on Vulkan and Metal and the pixel went black. +fn safe_normal(v: vec3) -> vec3 { + let d = dot(v, v); + if (d > 1e-20) { + return v * inverseSqrt(d); + } + return vec3(0.0, 0.0, 1.0); +} + +fn inside_vehicle(world: vec3) -> f32 { + if (camera.inside_c.w < 0.5) { + return 0.0; + } + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let x = d.x * ch - d.y * sh - camera.inside_c.x; + let y = d.x * sh + d.y * ch - camera.inside_c.y; + let z = d.z - camera.inside_c.z; + let h = camera.inside_b.yzw; + let in_x = abs(x) < h.x - 0.03; + let in_y = abs(y) < h.y - 0.03; + let in_z = z > -h.z - 0.6 && z < h.z - 0.03; + return select(0.0, 1.0, in_x && in_y && in_z); +} + +// 1 when the point belongs to the player's vehicle: its `[boundingbox]` grown a little, +// so that the skin and the glass the cab test (`inside_vehicle`) leaves out are in. +fn near_player_vehicle(world: vec3) -> f32 { + if (camera.inside_c.w < 0.5) { + return 0.0; + } + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let x = d.x * ch - d.y * sh - camera.inside_c.x; + let y = d.x * sh + d.y * ch - camera.inside_c.y; + let z = d.z - camera.inside_c.z; + let h = camera.inside_b.yzw + vec3(0.25); + return select(0.0, 1.0, abs(x) < h.x && abs(y) < h.y && abs(z) < h.z); +} + +// How much of the way from the camera to `world` lies outside the player's vehicle: there is +// no fog in the cab. From the driver's seat the whole saloon (seats 2 m away, the doors 5 m +// away) took the fog of that distance and in thick ground fog the interior went milky, the +// door panes nearly opaque - outside the bus there was nothing of the kind. The box is the +// one `inside_vehicle` uses; the part of the ray inside it is taken off the fogged distance. +fn fog_distance(world: vec3) -> f32 { + let full = distance(world, camera.cam_pos.xyz); + if (camera.inside_c.w < 0.5) { + return full; + } + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let to_local = fn_box_local(camera.cam_pos.xyz); + let p1 = fn_box_local(world); + let d = p1 - to_local; + let h = camera.inside_b.yzw; + // slab test of the segment against the box (x, y the plan, z height) + var t0 = 0.0; + var t1 = 1.0; + for (var k = 0; k < 3; k = k + 1) { + let o = to_local[k]; + let dk = d[k]; + let hk = h[k]; + if (abs(dk) < 1e-6) { + if (abs(o) > hk) { + return full; + } + } else { + let a = (-hk - o) / dk; + let b = (hk - o) / dk; + t0 = max(t0, min(a, b)); + t1 = min(t1, max(a, b)); + } + } + if (t1 <= t0) { + return full; + } + return max(full * (1.0 - (t1 - t0)), 0.0); +} + +// A point in the player's vehicle box frame (centred, x across, y along, z up). +fn fn_box_local(world: vec3) -> vec3 { + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + return vec3(d.x * ch - d.y * sh - camera.inside_c.x, d.x * sh + d.y * ch - camera.inside_c.y, d.z - camera.inside_c.z); +} + +fn own_vehicle_blocks(p: vec3, l: vec3) -> bool { + if (camera.inside_c.w < 1.5) { + return false; + } + let a = fn_box_local(l); + let d = fn_box_local(p) - a; + let h = camera.inside_b.yzw - vec3(0.15); + if (all(abs(a) < h)) { + return false; + } + var t0 = 0.0; + var t1 = 1.0; + for (var k = 0; k < 3; k = k + 1) { + let o = a[k]; + let dk = d[k]; + let hk = h[k]; + if (abs(dk) < 1e-6) { + if (abs(o) >= hk) { + return false; + } + } else { + let lo = (-hk - o) / dk; + let hi = (hk - o) / dk; + t0 = max(t0, min(lo, hi)); + t1 = min(t1, max(lo, hi)); + } + } + return t1 > t0; +} + +// 1 where the weather reaches the point. The cab test above reaches 0.6 m below the +// vehicle's box so that the floor stays dry, and that takes in the road under the bus as +// well: the snow on it vanished in a bus-shaped patch of bare asphalt (which read as the +// bus's shadow wiping the snow off). The ground - terrain, roads, painted ground, flagged +// by `terrain` or the instance's surface flag - is never inside a vehicle. +fn weather_outside(world: vec3, terrain: bool, surface: f32) -> f32 { + if (terrain || surface > 0.5) { + return 1.0; + } + return 1.0 - inside_vehicle(world); +} + +// As `weather_outside`, knowing the surface's normal: the bus's own outer skin is outside +// even where it lies inside the box. A side wall leans in towards the roof (and bulges over +// the wheel arches), so the box's side plane cuts through the panel: above the cut the paint +// took the cab's light and stayed dry, below it the sky's - the wall looked half glossy, +// half matt, along a sharp line. A face within 0.35 m of a side, the front, the back or the +// roof of the box and turned out through it is skin, not cabin. +fn weather_outside_n(world: vec3, n: vec3, terrain: bool, surface: f32) -> f32 { + if (terrain || surface > 0.5) { + return 1.0; + } + // a vehicle's part (lib.rs `Instance::roof`): under its roof it is dry, whichever + // vehicle it is - the one the camera is in, another player's, a timetable bus + // (what faces up only: taken for every face below the roof, the whole outer skin of + // every car and bus below the roof's edge was cab - lit by the dim cab light in the + // enhanced picture, dry in the rain - with a hard seam round the body 0.3 m under the + // roof where the sky's light began, #805) + if (surface < -500.0) { + // (the code carries the roof's snow in its ten thousands, see scene/upload.rs) + let code = -surface; + let roof = code - 10000.0 * floor(code / 10000.0) - 5000.0; + if (world.z < roof - 0.3 && n.z > 0.5) { + return 0.0; + } + } + if (inside_vehicle(world) < 0.5) { + return 1.0; + } + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let x = d.x * ch - d.y * sh - camera.inside_c.x; + let y = d.x * sh + d.y * ch - camera.inside_c.y; + let z = d.z - camera.inside_c.z; + let nx = n.x * ch - n.y * sh; + let ny = n.x * sh + n.y * ch; + let h = camera.inside_b.yzw; + let skin_x = h.x - abs(x) < 0.35 && nx * sign(x) > 0.5; + let skin_y = h.y - abs(y) < 0.35 && ny * sign(y) > 0.5; + let skin_z = h.z - z < 0.35 && n.z > 0.5; + return select(0.0, 1.0, skin_x || skin_y || skin_z); +} +@group(0) @binding(0) var camera: Camera; +// Whether this pipeline draws alpha-tested materials. +// Opaque pipelines set the discard overrides false: a fragment +// function that can discard turns the GPU's early depth test off - on Apple's GPUs the +// hidden surface removal as well - for everything it draws, and the heavy shading then +// ran for every covered layer of the city, not once per pixel. +override ALPHA_TEST: bool = true; +// Multisampled cutout pipelines can turn filtered alpha directly into sample coverage. +override ALPHA_TO_COVERAGE: bool = false; +override DETAILED_TREES: bool = false; +@group(0) @binding(5) var t_shadow: texture_depth_2d; +@group(0) @binding(6) var s_shadow: sampler_comparison; +@group(0) @binding(7) var t_shadow_far: texture_depth_2d; +@group(0) @binding(8) var t_ao: texture_2d; +@group(0) @binding(9) var s_ao: sampler; + +// Enhanced+: the traced lighting at a pixel (rt.wgsl, full size; camera.clouds.w 2): x the +// ambient occlusion, z the sun's visibility (< 0 where it was not traced), w 1 where the +// texel lies at this surface's depth (the pixel's own or a neighbour's; 0: the surface is +// not in the depth prepass - a pane, a blended layer - and the shadow map stands in). +fn rt_at(frag: vec2, world: vec3) -> vec4 { + if (camera.clouds.w < 1.5) { + return vec4(1.0, 0.0, -1.0, 0.0); + } + let size = vec2(textureDimensions(t_ao)); + let z = (camera.view_proj * vec4(world, 1.0)).w; + let tol = 0.03 + 0.01 * z; + let px = vec2(frag); + var best = vec4(1.0, 0.0, -1.0, 0.0); + var best_d = tol; + for (var k = 0; k < 5; k = k + 1) { + var o = vec2(0, 0); + switch k { + case 1: { o = vec2(1, 0); } + case 2: { o = vec2(-1, 0); } + case 3: { o = vec2(0, 1); } + case 4: { o = vec2(0, -1); } + default: {} + } + let s = textureLoad(t_ao, clamp(px + o, vec2(0), size - vec2(1)), 0); + let d = abs(s.g - z); + if (s.g > 0.0 && d < best_d) { + best_d = d; + best = vec4(s.r, s.g, s.b, 1.0); + } + if (k == 0 && d < tol * 0.3) { + break; + } + } + return best; +} + +// The ambient occlusion at a pixel of the full picture. It is worked out at half size, and +// a plain bilinear lookup blended the occlusion of the ground behind an edge with that of +// the object in front: every wheel, pole and kerb stood in a pale outline on the shaded +// ground under the bus. Of the four half-size texels around the pixel only those at the +// pixel's own depth count (a depth-aware upsample); none of them: the closest in depth. +// The light the surfaces round a point send back to it (irradiance, rgb), packed by +// ssao.wgsl `bounce_pack` in the AO texture's b and a. +fn bounce_unpack(t: vec4) -> vec3 { + let y = t.b; + let iu = floor(t.a / 32.0 + 0.001); + let iv = t.a - iu * 32.0; + let r = iu / 31.0 * 2.0 * y; + let b = iv / 31.0 * 2.0 * y; + let g = max((y - 0.2126 * r - 0.0722 * b) / 0.7152, 0.0); + return vec3(r, g, b); +} + +// The occlusion (x) and the bounced light (yzw) at a pixel, upsampled by depth as `ao_at`. +fn ao_gi_at(frag: vec2, world: vec3, traced: vec4) -> vec4 { + if (camera.clouds.w > 1.5) { + return vec4(select(traced.x, 1.0, traced.w < 0.5), 0.0, 0.0, 0.0); + } + let size = vec2(textureDimensions(t_ao)); + let z = (camera.view_proj * vec4(world, 1.0)).w; + let f = frag * 0.5 - vec2(0.5); + let base = vec2(floor(f)); + let fr = f - floor(f); + let tol = 0.04 + 0.015 * z; + var sum = 0.0; + var wsum = 0.0; + var best = vec4(1.0, 0.0, 0.0, 0.0); + var best_d = 1e9; + for (var j = 0; j < 2; j = j + 1) { + for (var i = 0; i < 2; i = i + 1) { + let c = clamp(base + vec2(i, j), vec2(0), size - vec2(1)); + let s = textureLoad(t_ao, c, 0); + let bw = select(1.0 - fr.x, fr.x, i == 1) * select(1.0 - fr.y, fr.y, j == 1); + let dz = abs(s.g - z); + let w = bw * (1.0 - smoothstep(0.0, tol, dz)) + 1e-4 * bw; + sum = sum + s.r * w; + wsum = wsum + w; + if (dz < best_d) { + best_d = dz; + best = s; + } + } + } + // no AO sample at this surface's depth: the surface is not in the depth prepass (a + // door or panel drawn in front of what the AO saw) - the AO behind it must not show + if (best_d > tol * 1.5) { + return vec4(1.0, 0.0, 0.0, 0.0); + } + // (the bounced light is smooth already - the blur pass averaged it - so the tap at this + // surface's depth is enough) + return vec4(select(best.r, sum / wsum, wsum > 0.02), bounce_unpack(best)); +} + +fn ao_traced_at(frag: vec2, world: vec3, traced: vec4) -> f32 { + if (camera.clouds.w > 1.5) { + return select(traced.x, 1.0, traced.w < 0.5); + } + return ao_upsampled(frag, world); +} + +fn bounce_at(frag: vec2, world: vec3) -> vec3 { + if (camera.clouds.w > 1.5) { + return vec3(0.0); + } + let size = vec2(textureDimensions(t_ao)); + let z = (camera.view_proj * vec4(world, 1.0)).w; + let base = vec2(floor(frag * 0.5 - vec2(0.5))); + var best = base; + var best_d = 1e9; + for (var j = 0; j < 2; j = j + 1) { + for (var i = 0; i < 2; i = i + 1) { + let c = clamp(base + vec2(i, j), vec2(0), size - vec2(1)); + let dz = abs(textureLoad(t_ao, c, 0).g - z); + if (dz < best_d) { + best_d = dz; + best = c; + } + } + } + if (best_d > (0.04 + 0.015 * z) * 1.5) { + return vec3(0.0); + } + return bounce_unpack(textureLoad(t_ao, best, 0)); +} + +fn ao_at(frag: vec2, world: vec3) -> f32 { + if (camera.clouds.w > 1.5) { + let t = rt_at(frag, world); + return select(t.x, 1.0, t.w < 0.5); + } + return ao_upsampled(frag, world); +} + +fn ao_upsampled(frag: vec2, world: vec3) -> f32 { + let size = vec2(textureDimensions(t_ao)); + let z = (camera.view_proj * vec4(world, 1.0)).w; + let f = frag * 0.5 - vec2(0.5); + let base = vec2(floor(f)); + let fr = f - floor(f); + let tol = 0.04 + 0.015 * z; + var sum = 0.0; + var wsum = 0.0; + var best = 1.0; + var best_d = 1e9; + for (var j = 0; j < 2; j = j + 1) { + for (var i = 0; i < 2; i = i + 1) { + let c = clamp(base + vec2(i, j), vec2(0), size - vec2(1)); + let s = textureLoad(t_ao, c, 0); + let bw = select(1.0 - fr.x, fr.x, i == 1) * select(1.0 - fr.y, fr.y, j == 1); + let dz = abs(s.g - z); + let w = bw * (1.0 - smoothstep(0.0, tol, dz)) + 1e-4 * bw; + sum = sum + s.r * w; + wsum = wsum + w; + if (dz < best_d) { + best_d = dz; + best = s.r; + } + } + } + // no AO sample at this surface's depth: the surface is not in the depth prepass (a + // door or panel drawn in front of what the AO saw) - the AO behind it must not show + if (best_d > tol * 1.5) { + return 1.0; + } + return select(best, sum / wsum, wsum > 0.02); +} +// the tile light maps (`.map.LM.bmp`) of the 5x5 tiles around the camera, north up, and where +// they lie: x, y the south-west corner (render-origin relative), z the side, w 1 when set +@group(0) @binding(18) var t_lmap: texture_2d; +@group(0) @binding(19) var lmap: vec4; + +// The tile light map's light at a world point (black outside the loaded square). +fn light_map_at(p: vec3) -> vec3 { + if (lmap.w < 0.5) { + return vec3(0.0); + } + let uv = vec2((p.x - lmap.x) / lmap.z, 1.0 - (p.y - lmap.y) / lmap.z); + let c = textureSampleLevel(t_lmap, s_ao, clamp(uv, vec2(0.0), vec2(1.0)), 0.0).rgb; + let inside = uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0; + return select(vec3(0.0), c, inside); +} + +// A material lit at night by the tile light map (`[LightMapMapping]`, the splines): the +// unlit flag carries 0.35. +fn light_map_mapped(m: vec4) -> bool { + return m.y > 0.3 && m.y < 0.45; +} +// (the model matrices as their columns, four vec4 each: some phone GPUs (Mali, Adreno) read an +// array of matrices from a storage buffer wrongly, and every mesh came out flat and far away) +@group(0) @binding(1) var models: array>; +// The affine row carries the draw order level and its octahedral geometric normal. +// Neither belongs to the transform used by shading, shadows or motion vectors. +fn model_matrix(e: u32) -> mat4x4 { + let k = e * 4u; + return mat4x4(vec4(models[k].xyz, 0.0), vec4(models[k + 1u].xyz, 0.0), vec4(models[k + 2u].xyz, 0.0), models[k + 3u]); +} +// x: alpha multiplier, y: visible (0/1), zw: uv offset +@group(0) @binding(2) var inst_params: array>; +// the frame's draw list: the per-draw entry of each drawn instance. Draws of the same mesh +// and material are batched, so the instance index points into this list, not at an entry. +@group(0) @binding(10) var draw_list: array; +struct PointLight { + pos: vec4, // xyz relative to the render origin, w radius (0: an enhanced-only light) + color: vec4, // rgb, w intensity + dir: vec4, // spot direction, w cosine of the outer cone (< -1.5: a point light) + extra: vec4, // enhanced path: cosine of the inner cone, core radius, beam gain, radius +}; +@group(0) @binding(3) var lights: array; +// per cell CELL_CAP light indices, 0xffffffff = empty +@group(0) @binding(4) var grid: array; +const CELL_CAP: u32 = 32u; +// The cutout of `[matl_alpha] 1`: Omsi.exe sets ALPHAREF 0x80 with ALPHAFUNC GREATER, so a +// texel of alpha 128 is thrown away. Painters' window layers (a bus's glass unwrapped on its +// own texture to draw on) mark the clear glass with exactly 128: cut below one half, those +// texels stayed and every window was the layer's black. +const ALPHA_REF: f32 = 128.5 / 255.0; + +struct MaterialParams { + color: vec4, + // x: alpha mode (0 opaque, 1 test, 2 blend), y: unlit flag, z: has transmap, w: transmap uses alpha + params: vec4, + // x: terrain material (uv in tile space), y: detail texture repeats per tile (0 = none), + // z: ground texture repeats per tile, w: has nightmap + extra: vec4, + // x: has lightmap, y: envmap factor, z: moisture, w: has [matl_envmap_mask] + params2: vec4, + // emissive colour (the o3d material's or a [matl_allcolor]'s) + emissive: vec4, + // specular colour and power of the D3D material (power in w; 0 = no highlight) + specular: vec4, + // x: [matl_bumpmap] factor, y: has a bump map, z/w: noZwrite/noZcheck + bump: vec4, + // the PBR set beside the diffuse texture: x normal map, y occlusion, z roughness, + // w metalness (1 = the map has it; see mx_tex2d[mx_mat.pbr_normal] / mx_tex2d[mx_mat.pbr_orm]) + pbr: vec4, + // x: one of the bus's own screens (the enhanced glow and FXAA leave it alone) + flags: vec4, + // rgb: the D3D material's ambient colour, which takes the ambient light (C) + ambient: vec4, + // Windy trees: x 1 for foliage that sways, y the height (mesh units) of its pivot - where + // the crown leaves the trunk, nothing below it moves - z the crown's top, w how much the + // tree gives to the wind (1 a broadleaf, less a conifer) + sway: vec4, + // Window wetness mask in mesh X/Z: origin, inverse size; zero disables it. + wipe_bounds: vec4, + // x: [matl_glow] strength (0 = the keyword is not there; the material is its own light - + // its `mx_tex2d[mx_mat.light]` is a greyscale mask of how much shines where, its colour is its own, see + // the enhanced pass), y an LED panel's share of the `Led glow` ([led_glow_effect], + // 1 without it), z/w free + glow: vec4, +}; +@group(1) @binding(2) var material: MaterialParams; +// (the material's textures and samplers by their places in the heap, see `materials_from_heap`) +struct MxMaterial { row: u32, diffuse: u32, sampler: u32, trans: u32, night: u32, light: u32, env: u32, envmask: u32, bump: u32, pbr_normal: u32, pbr_orm: u32, tile_sampler: u32 }; +var mx_mat: MxMaterial; + +// Paint/cut masks and night light maps cover one tile. Wrapping at its edge blends in +// the opposite edge of the SAME tile, opening grass seams even when adjacent masks +// agree. The diffuse/detail textures still repeat through mx_samplers[mx_mat.sampler]. +fn sample_transmap(uv: vec2) -> vec4 { + return sample_transmap_bias(uv, camera.lod.x); +} + +// (`bias`: FSR 1's mip bias for the picture, `camera.lod`; 0 for the shadow and rain maps, +// drawn at their own size) +fn sample_transmap_bias(uv: vec2, bias: f32) -> vec4 { + if (material.extra.x > 0.5 || material.wipe_bounds.z != 0.0) { + return textureSampleBias(mx_tex2d[mx_mat.trans], mx_samplers[mx_mat.tile_sampler], uv, bias); + } + return textureSampleBias(mx_tex2d[mx_mat.trans], mx_samplers[mx_mat.sampler], uv, bias); +} + +fn sample_nightmap(uv: vec2) -> vec4 { + if (material.extra.x > 0.5) { + return textureSampleBias(mx_tex2d[mx_mat.night], mx_samplers[mx_mat.tile_sampler], uv, camera.lod.x); + } + return textureSampleBias(mx_tex2d[mx_mat.night], mx_samplers[mx_mat.sampler], uv, camera.lod.x); +} + +// Some vehicle lamps use a clear diffuse placeholder and put the entire lit +// picture, including its silhouette, in the switched night texture. A transmap +// still owns coverage when the model explicitly supplies one. +fn night_coverage(alpha: f32, night_alpha: f32) -> f32 { + return select(alpha, night_alpha, + (u32(material.params2.w + 0.5) & 16u) != 0u && material.params.z < 0.5); +} + +// The reflection mask of a [matl_envmap] material: the alpha of its [matl_envmap_mask] +// texture when it has one, else the diffuse texture's alpha - which reads 1 for a texture +// without an alpha channel (a 24-bit bitmap, DXT1, a JPEG), so its factor alone decides. +fn has_env_mask() -> bool { + return (u32(material.params2.w + 0.5) & 1u) != 0u; +} + +// [matl_transmap] was given (its file there or not: see MaterialExtra::transmap_declared) +fn has_transmap_declared() -> bool { + return (u32(material.params2.w + 0.5) & 2u) != 0u; +} + +// [matl_texadress_border]: where the diffuse texture's coordinates leave [0, 1] (a roller +// blind's band scrolled away by [texcoordtransX/Y]) Direct3D reads the border colour, not +// the texture's edge (the sampler only clamps). Its rgb comes packed in flags.z. +fn diffuse_border(tex: vec4, uv: vec2) -> vec4 { + let p = u32(material.flags.z + 0.5); + let border = vec4( + f32((p >> 16u) & 0xffu) / 255.0, + f32((p >> 8u) & 0xffu) / 255.0, + f32(p & 0xffu) / 255.0, + material.flags.w, + ); + let outside = any(uv < vec2(0.0)) || any(uv > vec2(1.0)); + return select(tex, border, material.flags.y > 0.5 && material.flags.y < 1.5 && outside); +} + +// [matl_texadress_mirroronce]: Direct3D mirrors the coordinates once about 0 and clamps +// them beyond; the clamping sampler does the rest. +fn tex_address(uv: vec2) -> vec2 { + return select(uv, abs(uv), material.flags.y > 1.5); +} + +fn reflection_mask(uv: vec2, diffuse_a: f32) -> f32 { + let mask = textureSampleBias(mx_tex2d[mx_mat.envmask], mx_samplers[mx_mat.sampler], uv, camera.lod.x).a; + return select(diffuse_a, mask, has_env_mask()); +} + +// The D3DCOLOR Omsi.exe packs for its environment stage (0x7ff8ed): each channel the +// [matl_envmap] factor x 255 x its light (at most 1), truncated, and OR-ed together shifted +// into place without saturation - a factor over 1 spills into the neighbouring channel +// exactly as there (a factor of 10 at full light reads almost white). +fn omsi_texture_factor(factor: f32, light: vec3) -> vec3 { + let m = min(max(light, vec3(0.0)), vec3(1.0)) * max(factor, 0.0) * 255.0; + let r = u32(m.r); + let g = u32(m.g); + let b = u32(m.b); + let packed = (0xffu << 24u) | (r << 16u) | (g << 8u) | b; + return vec3(f32((packed >> 16u) & 0xffu), f32((packed >> 8u) & 0xffu), f32(packed & 0xffu)) / 255.0; +} + +// [matl_bumpmap]: Direct3D's bump-mapped environment stage moves the sphere-map lookup by +// a du/dv map times the factor. Every bump map in the stock and mod content is a grey +// height map, so the du/dv map has to be its slope; it is taken here as the forward +// differences of the height, a byte of height difference counting as a signed-byte step +// (1/127, hence the 2). The stock bodies' noise (factor 0.05-0.1) makes their reflections a +// little wavy, and the panel lines of the O530 Facelift's map (factor 1) break its +// reflection at every seam. +fn bump_offset(uv: vec2) -> vec2 { + let texel = 1.0 / vec2(textureDimensions(mx_tex2d[mx_mat.bump])); + let h = textureSampleBias(mx_tex2d[mx_mat.bump], mx_samplers[mx_mat.sampler], uv, camera.lod.x).a; + let hx = textureSampleBias(mx_tex2d[mx_mat.bump], mx_samplers[mx_mat.sampler], uv + vec2(texel.x, 0.0), camera.lod.x).a; + let hy = textureSampleBias(mx_tex2d[mx_mat.bump], mx_samplers[mx_mat.sampler], uv + vec2(0.0, texel.y), camera.lod.x).a; + return clamp(vec2(h - hx, h - hy) * 2.0, vec2(-1.0), vec2(1.0)) * material.bump.x; +} + +struct VsIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, + @builtin(instance_index) inst: u32, +}; +struct VsOut { + // invariant: the depth prepass and the main pass must compute the same depth to the + // last bit, the main pass tests against the depth the prepass left + @builtin(position) @invariant clip: vec4, + @location(0) world: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + @location(4) @interpolate(flat) params2: vec4, + // the D3D material's highlight, lit at the vertex as Omsi.exe's fixed function lights + // it: from the sun (light A) and from the light above (light B) + @location(5) spec_sun: vec3, + @location(6) spec_sky: vec3, + // where a [matl_envmap] reads its sphere map, made at the vertex (see `sphere_map_uv`) + @location(7) env_uv: vec2, + @location(8) wipe_uv: vec3, + // The classic headlight is lit at the vertices, as OMSI's fixed function light is. + @location(9) spot_diffuse: vec3, + @location(10) spot_ambient: vec3, + // the vertex as its mesh has it: a vehicle's snow lies on the vehicle, not on the + // world it drives through (road_snow.wgsl `vehicle_snow`) + @location(11) local: vec3, +}; +// What the fragment shaders take: VsOut without the invariant on the position. The +// invariant belongs to the vertex output; on a fragment input naga's GLSL writer turns it +// into `invariant gl_FragCoord`, which desktop GL drivers and GLES reject. +struct FsIn { + @builtin(position) clip: vec4, + @location(0) world: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + @location(4) @interpolate(flat) params2: vec4, + @location(5) spec_sun: vec3, + @location(6) spec_sky: vec3, + @location(7) env_uv: vec2, + @location(8) wipe_uv: vec3, + @location(9) spot_diffuse: vec3, + @location(10) spot_ambient: vec3, + @location(11) local: vec3, +}; + +// Direct3D's D3DTSS_TCI_SPHEREMAP, by which Omsi.exe's environment stage reads the sphere +// map of a [matl_envmap] (0x7ff670): at the vertex, from the reflection R in camera space +// (x right, y up, z ahead), u = Rx/m + 0.5 and v = Ry/m + 0.5 with m = 2|R - (0, 0, 1)| - +// as Windows draws it (wine's d3d9 test_generated_texcoords, measured there). What a pane +// facing the camera mirrors is the map's middle, at half the scale of the u = Rx/2 + 0.5 +// taken before (which showed the whole street of the picture across a bus's flank); the +// map's rim is the reflection running on away from the camera, at a grazing angle, where +// the picture swings round between two vertices - the seam the original shows there. +// `eye` is the camera's position, or its mirror image under the road for the player +// vehicle seen in a puddle; the camera's own axes lay the map out either way. +// (The headset: laid out by the bus's heading, level, not by each eye's view.) +fn sphere_map_uv(world: vec3, n: vec3, eye: vec3) -> vec2 { + let r = reflect(normalize(world - eye), n); + let vr_env = camera.cam_up.w > 0.5; + let right = select(camera.cam_right.xyz, vec3(cos(camera.cam_right.w), -sin(camera.cam_right.w), 0.0), vr_env); + let up = select(camera.cam_up.xyz, vec3(0.0, 0.0, 1.0), vr_env); + let rc = vec3(dot(r, right), dot(r, up), dot(r, cross(up, right))); + let m = 2.0 * length(rc - vec3(0.0, 0.0, 1.0)); + return rc.xy / max(m, 1e-6) + 0.5; +} + +// Direct3D's specular term at a vertex (Omsi.exe switches it on in FormActivate, 0x8254e0): +// Omsi.exe's sun (light 0, 0x7089f0: directional, specular = light A) and the light from +// straight above (light 1: specular = light B), each (N.H)^power with the local viewer's +// half vector, only where the light falls on the face, times the material's specular colour +// and clamped at 1 - then interpolated across the face. Computed per pixel instead, every +// small flat part (a gear selector, a switch, a dashboard screen) caught a sharp spot of the +// sun in its middle that the original, lighting only at the corners, never shows. +fn vertex_specular(wp: vec3, n: vec3) -> array, 2> { + var out = array, 2>(vec3(0.0), vec3(0.0)); + if (material.specular.w <= 0.0 || material.params.y >= 0.5) { + return out; + } + let v = normalize(camera.cam_pos.xyz - wp); + let p = material.specular.w; + let l = camera.sun_dir.xyz; + if (dot(n, l) > 0.0) { + out[0] = camera.sun_color.rgb * camera.sun_dir.w * pow(max(dot(n, normalize(v + l)), 0.0), p); + } + let up = vec3(0.0, 0.0, 1.0); + if (n.z > 0.0) { + out[1] = camera.sky_color.rgb * pow(max(dot(n, normalize(v + up)), 0.0), p); + } + let total = out[0] + out[1]; + let k = min(vec3(1.0), total) / max(total, vec3(1e-6)); + out[0] = min(vec3(1.0), out[0] * k * material.specular.rgb); + out[1] = min(vec3(1.0), out[1] * k * material.specular.rgb); + return out; +} + +// Windy trees: how far the wind moves a vertex of a tree's foliage (world, m). `local` is +// the vertex in the mesh, `m` its model matrix, whose origin is the tree's foot. +// +// The tree is bent, not shifted: nothing under its pivot (`material.sway.y`, where the crown +// leaves the trunk) moves, and above it the crown bends over as a cantilever does, by the +// square of the height above the pivot, sinking a little so that its branches keep their +// length. The crown moves as one heavy body - a tree is a lightly damped oscillator, and +// what it does is smooth: no part of the picture moves on its own (each corner of a card +// wobbling in its own phase made the crown jelly). +// +// What bends it is the drag of the air: it grows with the wind speed to the power 1.5 rather +// than 2, as a crown streamlines itself (Vogel's reconfiguration exponent), from a few +// millimetres at 1 m/s to some 3.5 % of the tree's height at 20 m/s, a storm. The gusts are +// a frozen pattern of faster and slower air carried along at the mean wind (Taylor): three +// smooth waves 54 .. 149 m long, a turbulence intensity of 0.3 as over a town, so that +// neighbouring trees bow together as a gust passes and the ones further on follow - and, +// being smooth, the gusts never stop the tree dead as the corners of a value noise did. +// Around that lean the tree swings at its own natural frequency (0.2 .. 1 Hz, lower the +// taller it is), its amplitude and phase wandering slowly as a resonance driven by +// turbulence does, and a little across the wind; the crown's top lags its middle a little. +// With no wind nothing moves. +fn tree_sway(local: vec3, m: mat4x4) -> vec3 { + let sw = material.sway; + let wind = camera.tree_wind.xy; + let speed = length(wind); + if (sw.x < 0.5 || speed < 0.05) { + return vec3(0.0); + } + let h = clamp((local.z - sw.y) / max(sw.z - sw.y, 1e-4), 0.0, 1.0); + if (h <= 0.0) { + return vec3(0.0); + } + let scale = length(m[2].xyz); + let crown = max((sw.z - sw.y) * scale, 0.1); + let height = max(sw.z * scale, crown); + let foot = (m * vec4(0.0, 0.0, 0.0, 1.0)).xyz; + let foot_map = world_pattern_xy(foot); + let t = camera.post.y; + // each tree its own phase + let seed = hash_cell(floor(foot_map * 2.0), 2000.0); + let phase = seed * 6.2831853; + // the gusts at the tree: whole waves per PATTERN_PERIOD (the map position and the + // drift arrive modulo it), 149, 93 and 54 m long - a gust lasts some seconds; their sum has a standard deviation of + // 0.51 (0.6, 0.35, 0.2 over sqrt 2), scaled to the turbulence intensity 0.3 + let gp = (foot_map - camera.tree_wind.zw) * (6.2831853 / PATTERN_PERIOD); + let waves = 0.6 * sin(dot(gp, vec2(6.0, 3.0)) + 1.3) + + 0.35 * sin(dot(gp, vec2(-4.0, 10.0)) + 4.1) + + 0.2 * sin(dot(gp, vec2(17.0, -7.0)) + 2.2); + let gust = max(1.0 + 0.59 * waves, 0.0); + let along = wind / speed; + let across = vec2(-along.y, along.x); + // the lean under the gusting wind, and the tree's swing about it + let give = 0.035 * height * sw.w; + let lean = give * pow(speed * gust / 20.0, 1.5); + // (in strong wind the swing is of the order of the mean lean itself) + let swing_size = 0.7 * give * pow(speed / 20.0, 1.5); + let f0 = clamp(1.6 / sqrt(height), 0.2, 1.0); + let w0 = 6.2831853 * f0 * t + phase + 0.8 * sin(0.17 * t + 9.0 * seed); + let envelope = 0.65 + 0.35 * sin(0.23 * t + 5.0 * seed); + let swing = swing_size * envelope; + // (the top lags the middle by a fraction of a cycle: the crown bends, not only leans) + let lag = 0.35 * h; + let move_xy = along * (lean + swing * sin(w0 - lag)) + across * (0.35 * swing * sin(0.93 * w0 + 1.7 - lag)); + var d = vec3(move_xy * h * h, 0.0); + // the crown's big boughs: lobes about the crown's size swaying at about twice the tree's + // frequency, each with its own slowly wandering phase, harder in a gust - neighbouring + // parts of the picture move nearly together, so the crown stirs rather than wobbles + let lm = (m * vec4(local, 0.0)).xyz; + let bp = dot(lm, vec3(0.45, 0.35, 0.3) * (4.0 / crown)) + phase; + let fb = clamp(2.2 * f0, 0.8, 2.0); + let wb = 6.2831853 * fb * t + bp + 0.6 * sin(0.31 * t + bp); + let bough = 0.25 * give * pow(speed * gust / 20.0, 1.5) * h; + d = d + vec3(along * sin(wb) + across * 0.5 * sin(1.17 * wb + 2.0), 0.25 * sin(0.9 * wb + 1.0)) * bough; + // the bent crown keeps its length: it sinks as it leans + let above = max((local.z - sw.y) * scale, 0.3); + d.z = d.z - 0.5 * dot(d.xy, d.xy) / above; + return d; +} + +// Where a scene vertex lands on the screen: the main pass's and the depth passes' vertex +// shaders (`vs_main`, `vs_depth`) both take it from here, so that their depths agree to the +// last bit (the main pass tests against the depth the prepass left). +fn scene_clip(e: u32, wp: vec4, nw: vec3) -> vec4 { + // Road surfaces (splines, the objects lying on them, a shadow blob) are pulled towards + // the eye along the line of sight - the picture does not move, only the depth - so that + // they win over the flush ground beside them. Code 0.9 keeps the surface shading without + // the pull; painted ground (0.75) stays put. + let surf = inst_params[e * 2u + 1u].w; + var cp = wp.xyz; + if (surf > 0.9) { + let to = wp.xyz - camera.cam_pos.xyz; + let d = length(to); + // The same share of the way to the eye at every vertex (0.3 %, a few millimetres of + // height seen from the cab): the pulled road is still the plane it was, so a spline + // laid a millimetre over another - the rails or markings over a road - stays over it + // however the two are cut into triangles. A fixed 2 cm more along each vertex's own + // line of sight bowed the road's long triangles over the short ones of what lies on + // it, by millimetres near the eye, and the rails went under the road there (#1196). + // (surface objects, 1.25, a little more than the splines under them) + // (a vehicle's shadow blob, 2: drawn without a depth test in the original, right + // over the road it lies on - with the road's own pull alone the two fought for + // every pixel and the road mostly won; a few centimetres more bring it through the + // road and still leave it behind the body and the wheels standing on it) + // The share stops growing at 5 cm. The pull is a depth, not a place - the picture + // does not move - but the pole of a traffic light that a mod's map tagged as a + // surface is pulled with the road under it, and a share still growing at distance + // (a third of a metre at 90 m) carried the pole through the signal head it stands + // beside. Capped, the pole stays behind what it stands by, and the depth a road + // needs over flush ground is a few millimetres at most (a floor raised 3 cm above + // the road is still seen - `surface_bias_keeps_raised_floors_visible_at_a_distance`). + // (a road's painted lines, 1.4, a little more again: a crossing object laid over + // the road covered the lines it overlaps, which in Omsi.exe lie a millimetre over + // the road and win the depth test against it - #1694) + let decal = surf > 1.1 && surf < 1.35; + let paint = surf > 1.35 && surf < 1.5; + let share = select(select(select(0.003, 0.004, decal), 0.0045, paint), 0.005, surf > 1.5); + let fixed = select(select(select(0.0, 0.01, decal), 0.015, paint), 0.05, surf > 1.5); + // The cap on the share is for upright faces, the poles. A flat surface keeps its + // share all the way: pulled by the same part of the way to the eye at every vertex + // the road is still one plane, however long its triangles, and a marking on it keeps + // its place. Capped at 5 cm the pull of a triangle from the eye to the horizon + // stopped growing with the distance and turned the road's plane into a bowl: at + // 40 m from a low eye the road came in front of the lines on it, and they were + // gone, and back as the bus came on (#3085). (Half a metre of it, at 170 m and + // beyond: millimetres of height from a driver's eye.) + let flat = abs(safe_normal(nw).z) > 0.5; + let pull = min(min(share * d, select(0.05, 0.5, flat)) + fixed, d * 0.3); + cp = wp.xyz - to / max(d, 1e-3) * pull; + } + // Omsi.exe draws a model mesh by mesh and subset by subset with LESSEQUAL into a 24-bit + // depth buffer: of two of its surfaces in one plane - a dashboard and the instruments + // printed on it - the later one is seen. Here their depths differed by rounding alone + // and every pixel was a coin toss. A slot lying on an earlier surface of its object + // (`draw_order_level`, 1 to 3; everything else 0) is brought nearer by two steps, each + // the same over a whole plane however it is cut into triangles (a step worked out per + // vertex from its own distance bends the surface): the reversed depth times 1 + 1e-5 a + // level, above the vertices' rounding; and 2e-5 a level over the plane's distance from + // the eye, against the tilt the rasterizer's snapping of each corner to a fraction of a + // pixel gives a triangle's depth, the more the flatter it is seen. Seen from above the + // plane that lifts it by 3e-5 a level times the distance: 0.9 mm at 10 m at level 3. + // (The plane's distance is at least 5 % of the vertex's own: the edge of a curved mesh, + // whose tangent plane runs through the eye, is not pulled metres forward.) + let clip = camera.view_proj * vec4(cp, 1.0); + let level_code = u32(round(models[e * 4u].w)); + var level = f32(level_code & 3u); + if (level <= 0.0) { + return clip; + } + if ((level_code & 4096u) != 0u) { + // Keep the depth step within half the measured gap. + let cap = f32((level_code >> 2u) & 1023u) * 1e-6; + let distance = length(cp - camera.cam_pos.xyz); + level = min(level, cap / max(3e-5 * distance, 1e-9)); + if (level <= 0.0) { + return clip; + } + } + // (the depth of the eye's own point: n f / (f - n), about the near plane) + let at_eye = (camera.view_proj * vec4(camera.cam_pos.xyz, 1.0)).z; + // Use geometric plane normals; lighting normals may be smoothed or authored independently. + let encoded = vec2(models[e * 4u + 1u].w, models[e * 4u + 2u].w); + var depth_n = nw; + if (all(abs(encoded) <= vec2(1.0))) { + var n = vec3(encoded, 1.0 - abs(encoded.x) - abs(encoded.y)); + let t = clamp(-n.z, 0.0, 1.0); + n.x += select(t, -t, n.x >= 0.0); + n.y += select(t, -t, n.y >= 0.0); + depth_n = n; + } + let plane = max(abs(dot(safe_normal(depth_n), cp - camera.cam_pos.xyz)), 0.05 * length(cp - camera.cam_pos.xyz)); + let slant = level * 2e-5 * at_eye * clip.w / plane; + return vec4(clip.x, clip.y, clip.z * (1.0 + level * 1e-5) + slant, clip.w); +} + +fn is_tree_card() -> bool { + return material.params.y > 0.1 && material.params.y < 0.2; +} + +fn detailed_trees() -> bool { + return DETAILED_TREES; +} + +fn tree_crown_normal(local: vec3, m: mat4x4, up: vec3) -> vec3 { + let pivot = select(0.28, material.sway.y, material.sway.x > 0.5); + let centre = mix(pivot, select(1.0, material.sway.z, material.sway.x > 0.5), 0.45); + let out = (m * vec4(local.x, local.y, local.z - centre, 0.0)).xyz; + let crown = smoothstep(pivot * 0.5, pivot + 0.1, local.z); + return safe_normal(mix(up, safe_normal(out), 0.65 * crown)); +} + +fn tree_card_fade(world: vec3) -> f32 { + if (!detailed_trees() || (!is_tree_card() && material.sway.x < 0.5)) { + return 1.0; + } + let c = cross(dpdx(world), dpdy(world)); + let v = (camera.cam_pos.xyz - world).xy; + if (dot(c, c) < 1e-20 || dot(v, v) < 1e-6) { + return 1.0; + } + let n = normalize(c); + let upright = smoothstep(0.6, 0.9, length(n.xy)); + let facing = abs(dot(normalize(n.xy + vec2(1e-6, 0.0)), normalize(v))); + return mix(1.0, smoothstep(0.3, 0.62, facing), upright); +} + +@vertex +fn vs_main(in: VsIn) -> VsOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0); + var out: VsOut; + out.clip = scene_clip(e, wp, (m * vec4(in.normal, 0.0)).xyz); + out.world = wp.xyz; + out.local = in.pos; + out.normal = safe_normal((m * vec4(in.normal, 0.0)).xyz); + if (detailed_trees() && (is_tree_card() || (material.sway.x > 0.5 && material.sway.z - material.sway.y > 2.5))) { + out.normal = tree_crown_normal(in.pos, m, out.normal); + } + let sp = vertex_specular(wp.xyz, out.normal); + out.spec_sun = sp[0]; + out.spec_sky = sp[1]; + // Ray blocking is disabled for exterior cameras; never light our own body or cabin. + // The vehicle surface code keeps roads and scenery in the same box illuminated. + out.spot_diffuse = vec3(0.0); + out.spot_ambient = vec3(0.0); + let own_vehicle = inst_params[e * 2u + 1u].w < -500.0 && near_player_vehicle(wp.xyz) > 0.5; + if (!own_vehicle) { + let spot = classic_spot(wp.xyz, out.normal); + out.spot_diffuse = spot[0]; + out.spot_ambient = spot[1]; + } + out.env_uv = sphere_map_uv(wp.xyz, out.normal, camera.cam_pos.xyz); + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + out.params2 = inst_params[e * 2u + 1u]; + let side_pane = material.wipe_bounds.z < 0.0; + let pane = select(in.pos.xz, in.pos.yz, side_pane); + out.wipe_uv = vec3((pane - material.wipe_bounds.xy) * abs(material.wipe_bounds.zw), select(in.pos.y, in.pos.x, side_pane)); + if (pr.y < 0.5) { + // invisible: collapse the triangle + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +// What the depth-only passes (the depth prepass, the multisampled prefill) take from a +// vertex: its place and what a cut-out or a transmap needs to decide its coverage. The +// highlights, the sphere map and the normal of `vs_main` are not worked out for them. +struct DepthOut { + @builtin(position) @invariant clip: vec4, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + // the instance's surface code (`inst_params` w, see `scene_clip`) + @location(4) surf: f32, + @location(5) world: vec3, +}; +struct DepthIn { + @builtin(position) clip: vec4, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + @location(4) surf: f32, + @location(5) world: vec3, +}; + +struct ShadowOut { + @builtin(position) @invariant clip: vec4, + @location(0) uv: vec2, + @location(1) @interpolate(flat) params: vec4, +}; +struct ShadowIn { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + @location(1) @interpolate(flat) params: vec4, +}; + +@vertex +fn vs_depth(in: VsIn) -> DepthOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0); + var out: DepthOut; + out.clip = scene_clip(e, wp, (m * vec4(in.normal, 0.0)).xyz); + out.world = wp.xyz; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + out.surf = inst_params[e * 2u + 1u].w; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +struct VehicleBox { a: vec4, b: vec4, c: vec4 }; +struct VehicleReflection { plane: vec4, parts: array }; +@group(2) @binding(0) var vehicle_reflection: VehicleReflection; + +@vertex +fn vs_puddle_vehicle(in: VsIn) -> VsOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + var out: VsOut; + out.world = (m * vec4(in.pos, 1.0)).xyz; + out.normal = safe_normal((m * vec4(in.normal, 0.0)).xyz); + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + out.params2 = inst_params[e * 2u + 1u]; + out.spec_sun = vec3(0.0); + out.spec_sky = vec3(0.0); + out.spot_diffuse = vec3(0.0); + out.spot_ambient = vec3(0.0); + let plane = vehicle_reflection.plane; + // the sphere map from the reflected eye fs_puddle_vehicle shades the vehicle from + out.env_uv = sphere_map_uv(out.world, out.normal, camera.cam_pos.xyz - 2.0 * plane.xyz * (dot(plane.xyz, camera.cam_pos.xyz) - plane.w)); + let reflected = out.world - 2.0 * plane.xyz * (dot(plane.xyz, out.world) - plane.w); + out.clip = camera.view_proj * vec4(reflected, 1.0); + if (out.params.y < 0.5) { out.clip = vec4(0.0, 0.0, 2.0, 1.0); } + return out; +} + +// Close an open legacy underbody with one depth-tested face in the same reflected +// view. Wheels and authored panels occlude it normally; no screen-space bands. +@vertex +fn vs_puddle_chassis(@builtin(vertex_index) i: u32, @builtin(instance_index) part: u32) -> @builtin(position) vec4 { + let corners = array, 6>(vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), + vec2(-1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, 1.0)); + let box = vehicle_reflection.parts[part]; + let local = corners[i] * max(box.b.yz - vec2(0.12, 0.18), vec2(0.0)) + box.c.xy; + let sh = box.a.w; + let ch = box.b.x; + let xy = box.a.xy + vec2(local.x * ch + local.y * sh, -local.x * sh + local.y * ch); + let plane = vehicle_reflection.plane; + let road_z = (plane.w - dot(plane.xy, xy)) / plane.z; + let z = max(road_z + 0.18, box.a.z + box.c.z - box.b.w + 0.04); + let world = vec3(xy, z); + let reflected = world - 2.0 * plane.xyz * (dot(plane.xyz, world) - plane.w); + return camera.view_proj * vec4(reflected, 1.0); +} + +// Shadow map passes: depth from the sun, alpha-tested materials cut out by their texture. +// A surface that casts - a spline standing clear of the ground, a bridge deck - casts from +// half a metre further away from the sun: what lies right under it (the embankment object +// under a railway, the ground a ramp touches down on) is no darker for it, while the ground +// metres below a deck gets its shadow. +fn shadow_caster_pos(e: u32, wp: vec4) -> vec4 { + if (abs(inst_params[e * 2u + 1u].w - 1.0) < 0.01) { + return vec4(wp.xyz - camera.sun_dir.xyz * 0.5, wp.w); + } + return wp; +} + +@vertex +fn vs_shadow(in: VsIn) -> ShadowOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = shadow_caster_pos(e, m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0)); + var out: ShadowOut; + out.clip = camera.light_view_proj * wp; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +@vertex +fn vs_shadow_close(in: VsIn) -> ShadowOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = shadow_caster_pos(e, m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0)); + var out: ShadowOut; + out.clip = camera.light_view_proj_close * wp; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +@vertex +fn vs_shadow_far(in: VsIn) -> ShadowOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = shadow_caster_pos(e, m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0)); + var out: ShadowOut; + out.clip = camera.light_view_proj_far * wp; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +// Enhanced: a lamp's shadow map (one of the tiles under the far map). The draw list names +// the tile above the entry's own bits (`LAMP_ENTRY_BITS` in lamp_slots.rs), and the tile's +// matrix looks down from a street lamp's head or along the road from a vehicle's headlamps. +const LAMP_ENTRY_BITS: u32 = 26u; + +@vertex +fn vs_shadow_lamp(in: VsIn) -> ShadowOut { + let raw = draw_list[in.inst]; + let e = raw & ((1u << LAMP_ENTRY_BITS) - 1u); + let k = raw >> LAMP_ENTRY_BITS; + let m = model_matrix(e); + let wp = m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0); + var out: ShadowOut; + out.clip = camera.lamp_view_proj[k] * wp; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +@fragment +fn fs_shadow(in: ShadowIn) { +} + +// Reflection rays need the window surface as well as the opaque interior behind it. +// This writes a private hit-depth texture after colour compositing; ordinary depth and +// AO still leave glass transparent. Reject absent/fully faded layers and texture holes. +@fragment +fn fs_puddle_glass_depth(in: FsIn) { + // From the cabin we see the street through our own pane. Treating that pane as + // an SSR hit terminates every ray at the window instead of the outside vehicle. + if (inside_vehicle(camera.cam_pos.xyz) * near_player_vehicle(in.world) > 0.5) { + discard; + } + var a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], tex_address(in.uv), camera.lod.x), in.uv).a; + if (material.params.z > 0.5) { + let tm = sample_transmap(tex_address(in.uv - in.params.zw)); + a = select(1.0, tm.a, material.params.w > 0.5); + } + if (a * material.color.a * in.params.x < 0.002) { + discard; + } +} + +// (the shadow and rain maps, drawn at their own size: their textures' mips as they are) +@fragment +fn fs_shadow_test(in: ShadowIn) { + cutout_coverage(in.uv, in.params, 0.0, 1.0); +} + +// the depth-only passes' (`vs_depth`) fragment shaders: plain, cut out, a transmap's +// opaque part +@fragment +fn fs_depth(in: DepthIn) { +} + +// (the picture's depth: its textures read with the colour pass's mip bias, `camera.lod` - +// a cut-out's edge the prepass took from a blurrier mip than the colour pass wrote depth +// where the colour then discarded, and the sky showed through) +@fragment +fn fs_depth_test(in: DepthIn) { + cutout_coverage(in.uv, in.params, camera.lod.x, tree_card_fade(in.world)); +} + +// (a transmap's opaque part, see `transmap_coverage`) +@fragment +fn fs_depth_transmap(in: DepthIn) { + transmap_coverage(in.uv, in.params, camera.lod.x); +} + +//MS @group(3) @binding(0) var t_pane_depth: texture_depth_multisampled_2d; + +//MS @fragment +//MS fn fs_depth_masked(in: DepthIn, @builtin(sample_index) sample: u32) { +//MS if (in.clip.z <= textureLoad(t_pane_depth, vec2(in.clip.xy), i32(sample))) { +//MS discard; +//MS } +//MS } + +// The multisampled prefill's cut-outs (foliage): their depth only where the colour pass +// is sure to cover every sample - the alpha-to-coverage of an alpha of 1 (`shade_enhanced`: +// the texture's alpha past the cutoff's smoothed edge, a plain material at full opacity, +// no pane, LED panel, transmap, ground or shadow blob). The edges, which alpha-to-coverage +// covers in part, are left to the colour pass: a sample laid here that the colour then +// left uncovered would hide what lies behind it (the sky showed through the houses). +@fragment +fn fs_depth_cover(in: DepthIn) { + let mode = material.params.x; + if (mode < 0.5 || mode > 1.5 || material.params.z > 0.5 || material.extra.x > 0.5 + || material.wipe_bounds.z != 0.0 || abs(material.emissive.w) > 1.5 + || material.color.a < 1.0 || in.params.x < 1.0 || in.surf > 1.5) { + discard; + } + let duv = tex_address(in.uv); + let a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv).a * tree_card_fade(in.world); + let aa = max(fwidth(a) * 0.5, 1.0 / 255.0); + if (a < ALPHA_REF + aa + 4.0 / 255.0) { + discard; + } +} + +// A cut-out's texel: kept where its alpha reaches the cutoff (`bias`: the mip bias its +// pass reads the textures with, the colour pass's for the picture's depth). +fn cutout_coverage(uv: vec2, params: vec4, bias: f32, fade: f32) { + var duv = tex_address(uv); + if (material.extra.x > 0.5) { + duv = uv * material.extra.z; + } + // Use the light-pass footprint for cutout coverage. Forcing mip 0 here aliases dense + // foliage and alpha layers into a checkerboard when the light projection moves by a + // texel; the mip-aware sample keeps the caster coverage coherent with its resolution. + // For a material promoted to the shadow pass from Blend, diffuse alpha is commonly a + // paint/gloss value rather than coverage (vehicle bodies use values such as 0.03). Only + // alpha-test materials use diffuse alpha as a cutout; blended bodies are solid unless a + // real transmap supplies coverage. + var a = select(diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, bias), duv).a, 1.0, material.params.x > 1.5 && material.params.z < 0.5); + if (material.params.z > 0.5) { + // (the transmap stays where it is: [texcoordtransX/Y] only moves the diffuse stage) + let tm = sample_transmap_bias(tex_address(uv - params.zw), bias); + a = select(1.0, tm.a, material.params.w > 0.5); + } + if (a * fade < ALPHA_REF) { + discard; + } +} + +// Roads with feathered alpha borders stay blended while their overlaps compose. +// Once the surface phases are complete, only fully covered diffuse pixels occlude +// later scenery. The transparent borders must not become invisible depth walls. +@fragment +fn fs_surface_depth(in: FsIn) -> @location(0) vec4 { + let a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], tex_address(in.uv), camera.lod.x), in.uv).a + * material.color.a * in.params.x; + if (a < 0.999) { + discard; + } + return vec4(0.0); +} + +// A vehicle body and its windows are often one mesh/material. OMSI represents that +// material as alpha-blended because the transmap contains the window opacity, but the +// alpha-tested body pixels still have to occlude vehicles behind them. The normal depth prepass +// deliberately skips all blended materials, so those pixels would otherwise have no depth +// until the colour pass (where blend order can expose the bus through the car). Keep only +// the effectively opaque part of a transmap in a separate depth-only pass; window pixels +// remain out of the prepass and are composited normally. +fn transmap_coverage(uv: vec2, params: vec4, bias: f32) { + if (material.params.z < 0.5) { + discard; + } + let tm = sample_transmap_bias(tex_address(uv - params.zw), bias); + let a = select(1.0, tm.a, material.params.w > 0.5) * params.x; + // Only what the colour pass will cover completely may hide what lies behind it: a + // texel that is merely more opaque than not (the dimmer and anti-aliased dots of a + // display's text layer, whose transmap is its script texture) wrote depth here, the + // display's backplate behind it was then rejected, and the half-transparent text was + // blended over the sky - holes in the display. + if (a < 0.99) { + discard; + } +} + +// 1 = lit by the sun, 0 = in shadow. Three cascades: the close one (the bus and what is +// next to it), the near one around the camera and the far one covering the rest of the +// visible street. + +// Depth bias of the sun shadow, in metres along the sun's ray. The maps' depth runs over +// the light box's 2199 m, and the comparison used to take off 0.0015 (near) and 0.004 (far) +// of that: 3.3 m and 8.8 m. Nothing closer to the ground than that along the ray cast a +// shadow - not a car (1.4 m), not a bus (3 m; only its roof's shadow at a low sun, +// which lay detached and offset from the bus) - and the grass and kerbs had none either. +// The receiver plane below takes care of what the big constant stood in for. +const SHADOW_DEPTH_RANGE: f32 = 2199.0; +const SHADOW_BIAS_NEAR: f32 = 0.06; +const SHADOW_BIAS_FAR: f32 = 0.3; +const SHADOW_BIAS_CLOSE: f32 = 0.025; + +// How the receiver's depth in the shadow map changes across the map (per unit of uv), from +// its normal: the PCF taps around the pixel compare against the surface's own depth at the +// tap instead of the centre's, so a surface at a slant to the sun does not shadow itself +// within the filter radius (acne), which a big constant bias used to hide. `lvp` is the +// cascade's light matrix (orthographic, so the map from the world is affine). +fn shadow_receiver_slope(lvp: mat4x4, n: vec3) -> vec2 { + let a = select(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), abs(n.x) > 0.9); + let t1 = normalize(cross(n, a)); + let t2 = cross(n, t1); + let p1 = (lvp * vec4(t1, 0.0)).xyz; + let p2 = (lvp * vec4(t2, 0.0)).xyz; + // (uv = 0.5 x + 0.5, 0.5 - 0.5 y) + let d1 = vec3(p1.x * 0.5, -p1.y * 0.5, p1.z); + let d2 = vec3(p2.x * 0.5, -p2.y * 0.5, p2.z); + let det = d1.x * d2.y - d2.x * d1.y; + if (abs(det) < 1e-12) { + return vec2(0.0); + } + let g = vec2(d1.z * d2.y - d2.z * d1.y, d1.x * d2.z - d2.x * d1.z) / det; + // a surface seen edge-on by the sun: keep the slope finite (it is in shadow of itself + // there anyway, by its normal) + return clamp(g, vec2(-2.0), vec2(2.0)); +} + +// The filter's half width in texels. A tent of 2 texels covers 4 x 4 texels, two gathers a +// side - four in all, fewer texture reads than the Poisson kernel's five (sixteen on an +// edge) - and spreads an edge about as the old kernel did in the near and close cascades +// (0.82 of a texel's standard deviation against 0.9 and 1.0; a fifth sharper in the far one). +const SHADOW_TENT: f32 = 2.0; +// Percentage-closer filtering with a tent of `SHADOW_TENT` texels, every texel of the map +// under it compared and weighted by the tent at its centre: four gathers of 2 x 2 texels, +// the whole 4 x 4 footprint read. The sparse Poisson kernel this replaces (16 bilinear taps +// 1.6 to 2.2 texels apart, and only its 5 outermost-and-middle taps when those agreed) +// sampled the map coarser than its texels: a lit gap between leaves, a few texels wide, came +// out as a copy of the kernel - an X of five magnified texels - and a feature lying between +// the taps vanished and reappeared as the receiver moved by a texel, which made the shadows +// shimmer. Read in full, the result is a continuous function of the receiver's position. +// `widen` (Enhanced: a veil of high cloud enlarging the sun) spreads the four gathers that +// many texels apart, a tent as much wider, without reading more. +// `uv`: the receiver in the cascade's own 0..1; `size`: the cascade's texels a side; +// `origin`: where its first texel lies in the texture; `slope`: its receiver plane (per uv). +// The shadow maps' size, texels a side, from the uniforms (`camera.shadow.y` is a texel): the +// near map an atlas of two cascades side by side, the far one taller by the lamps' tiles under +// it (`camera.lamp_atlas.z` is its texture's height). (Asked of the textures with +// textureDimensions in every inlined use of the sun's shadow, they brought Apple's M4 shader +// compiler down on every scene pipeline.) +fn shadow_map_size() -> f32 { + return 1.0 / max(camera.shadow.y, 1e-6); +} + +fn shadow_tent_place(uv: vec2, size: f32, widen: f32) -> vec4 { + let k = max(1.0, floor(widen + 0.5)); + // (texel i of the cascade has its centre at p = i; the first texel the tent reaches) + let p = uv * size - vec2(0.5); + let lo = floor(p - vec2(SHADOW_TENT * k)) + vec2(1.0); + return vec4(p, lo); +} + +// The tent's weights of a gather's four texels starting at `t0` (gather order: (0, 1), +// (1, 1), (1, 0), (0, 0) of the quad). +fn shadow_tent_weights(t0: vec2, p: vec2, r: f32) -> vec4 { + let w0 = max(vec2(0.0), vec2(1.0) - abs(t0 - p) / r); + let w1 = max(vec2(0.0), vec2(1.0) - abs(t0 + vec2(1.0) - p) / r); + return vec4(w0.x * w1.y, w1.x * w1.y, w1.x * w0.y, w0.x * w0.y); +} + +fn shadow_tent_near(uv: vec2, size: f32, origin: vec2, z: f32, slope: vec2, widen: f32, bias: f32) -> f32 { + let dims = vec2(2.0, 1.0) * shadow_map_size(); + let pl = shadow_tent_place(uv, size, widen); + let k = max(1.0, floor(widen + 0.5)); + let r = SHADOW_TENT * k; + var sum = 0.0; + var wsum = 0.0; + for (var q = 0; q < 4; q = q + 1) { + let t0 = pl.zw + vec2(f32(q & 1), f32(q >> 1u)) * 2.0 * k; + let a = (origin + t0 + vec2(1.0)) / dims; + let zr = z + dot(slope, (t0 + vec2(0.5) - pl.xy) / size) - bias; + let w = shadow_tent_weights(t0, pl.xy, r); + sum = sum + dot(textureGatherCompare(t_shadow, s_shadow, a, zr), w); + wsum = wsum + w.x + w.y + w.z + w.w; + } + return sum / max(wsum, 1e-6); +} + +fn shadow_tent_far(uv: vec2, size: f32, z: f32, slope: vec2, widen: f32, bias: f32) -> f32 { + let dims = vec2(shadow_map_size(), camera.lamp_atlas.z); + let pl = shadow_tent_place(uv, size, widen); + let k = max(1.0, floor(widen + 0.5)); + let r = SHADOW_TENT * k; + var sum = 0.0; + var wsum = 0.0; + for (var q = 0; q < 4; q = q + 1) { + let t0 = pl.zw + vec2(f32(q & 1), f32(q >> 1u)) * 2.0 * k; + let a = (t0 + vec2(1.0)) / dims; + let zr = z + dot(slope, (t0 + vec2(0.5) - pl.xy) / size) - bias; + let w = shadow_tent_weights(t0, pl.xy, r); + sum = sum + dot(textureGatherCompare(t_shadow_far, s_shadow, a, zr), w); + wsum = wsum + w.x + w.y + w.z + w.w; + } + return sum / max(wsum, 1e-6); +} + +// The near map is an atlas two cascades wide: the near cascade in its left half, the close +// one (`camera.light_view_proj_close`) from the top left of its right half, drawn no bigger +// than 2048 texels (`SHADOW_CLOSE_MAX` in lib.rs). `widen`: how much wider than the +// cascade's own the filter is (Enhanced: a veil of high cloud enlarging the sun). +fn shadow_pcf_near(uv: vec2, z: f32, slope: vec2, widen: f32) -> f32 { + let size = shadow_map_size(); + return shadow_tent_near(uv, size, vec2(0.0), z, slope, widen, SHADOW_BIAS_NEAR / SHADOW_DEPTH_RANGE); +} + +fn shadow_pcf_close(uv: vec2, z: f32, slope: vec2) -> f32 { + // (camera.post.w: the close map's size over the near map's) + let half = shadow_map_size(); + let size = half * select(1.0, camera.post.w, camera.post.w > 0.0); + return shadow_tent_near(uv, size, vec2(half, 0.0), z, slope, 1.0, SHADOW_BIAS_CLOSE / SHADOW_DEPTH_RANGE); +} + +fn shadow_push_close(n: vec3, ndl: f32) -> vec3 { + return n * (0.015 + 0.03 * (1.0 - ndl)); +} + +// The close cascade's value and weight at a point (weight 0 outside it): it fades into the +// near cascade between 60 and 90 % of its range from the camera. +fn shadow_close(world: vec3, n: vec3, ndl: f32, thin: bool) -> vec2 { + let range = camera.flags.w; + if (range <= 0.0) { + return vec2(1.0, 0.0); + } + let radial = distance(world, camera.cam_pos.xyz); + let w = 1.0 - smoothstep(range * 0.6, range * 0.9, radial); + if (w <= 0.001) { + return vec2(1.0, 0.0); + } + let lp = camera.light_view_proj_close * vec4(world + shadow_push_close(n, ndl), 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + if (edge >= 0.48 || lp.z < 0.0 || lp.z > 1.0) { + return vec2(1.0, 0.0); + } + let slope = select(shadow_receiver_slope(camera.light_view_proj_close, n), vec2(0.0), thin); + return vec2(shadow_pcf_close(uv, lp.z, slope), w); +} + +// The far map takes the top of its texture (its texels are the texture's first rows); the +// lamps' tiles lie under it (`LampAtlas` in lights.rs). +fn shadow_pcf_far(uv: vec2, z: f32, slope: vec2, widen: f32) -> f32 { + let size = shadow_map_size(); + return shadow_tent_far(uv, size, z, slope, widen, SHADOW_BIAS_FAR / SHADOW_DEPTH_RANGE); +} + +// The shadow lookup point: pushed off the surface along its normal by about a texel of the +// cascade (0.14 m near, 0.68 m far), more where the surface turns away from the sun. +fn shadow_push_near(n: vec3, ndl: f32) -> vec3 { + return n * (0.06 + 0.12 * (1.0 - ndl)); +} + +fn shadow_push_far(n: vec3, ndl: f32) -> vec3 { + return n * (0.3 + 0.6 * (1.0 - ndl)); +} + +// `thin`: an alpha-tested card (leaves, fences), whose normal says nothing about its plane +// (OMSI points a tree's normals up): no receiver plane, the lookup moves half a metre +// towards the sun instead, which keeps a crown from speckling itself. +fn sun_shadow(world_in: vec3, n: vec3, thin: bool) -> f32 { + if (camera.shadow.x < 0.5) { + return 1.0; + } + let world = world_in + select(vec3(0.0), camera.sun_dir.xyz * 0.5, thin); + let ndl = clamp(dot(n, camera.sun_dir.xyz), 0.0, 1.0); + let close = shadow_close(world, n, ndl, thin); + if (close.y >= 0.999) { + return close.x; + } + let near_lp = camera.light_view_proj * vec4(world + shadow_push_near(n, ndl), 1.0); + let near_uv = vec2(near_lp.x * 0.5 + 0.5, 0.5 - near_lp.y * 0.5); + let inside = max(abs(near_uv.x - 0.5), abs(near_uv.y - 0.5)); + if (inside < 0.48 && near_lp.z >= 0.0 && near_lp.z <= 1.0) { + let nv = shadow_pcf_near(near_uv, near_lp.z, select(shadow_receiver_slope(camera.light_view_proj, n), vec2(0.0), thin), 1.0); + return mix(nv, close.x, close.y); + } + let lp = camera.light_view_proj_far * vec4(world + shadow_push_far(n, ndl), 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || lp.z < 0.0 || lp.z > 1.0) { + return 1.0; + } + let sum = shadow_pcf_far(uv, lp.z, select(shadow_receiver_slope(camera.light_view_proj_far, n), vec2(0.0), thin), 1.0); + let edge = clamp((0.5 - max(abs(uv.x - 0.5), abs(uv.y - 0.5))) * 12.0, 0.0, 1.0); + return mix(1.0, sum, edge); +} + +// Sum of the point lights registered in the grid cell of `p`. A light is registered in +// every cell its range touches, so the point's own cell holds every light that reaches it; +// looking into the neighbouring cells as well counted a light up to four times, and how +// often depended on where the cell edges fell - lamp pools brightened and dimmed as the +// camera moved. +// `map_k`: how much of the map's lamps a surface takes (0 on a light-mapped road in the +// classic picture, whose lamps are in its light map); a vehicle's own lights (dir.x 1, see +// lib.rs `gpu_light`) always shine - the headlights lit no road at all in vanilla. +fn point_lights(p: vec3, n: vec3, map_k: f32) -> vec3 { + var sum = vec3(0.0); + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell <= 0.0 || side == 0u) { + return sum; + } + let f = (p.xy - camera.light_grid.xy) / cell; + let x = i32(floor(f.x)); + let y = i32(floor(f.y)); + if (x >= 0 && y >= 0 && x < i32(side) && y < i32(side)) { + let base = (u32(y) * side + u32(x)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let d = l.pos.xyz - p; + let dist = length(d); + if (dist >= l.pos.w) { + continue; + } + if (!(l.dir.w < -1.5 && l.dir.z < -0.5) && own_vehicle_blocks(p, l.pos.xyz)) { + continue; + } + if (l.dir.w >= -1.5 && l.extra.z != 0.0) { + // a Direct3D spot of the classic picture (lights.rs `push_classic_spot`): a + // vehicle's [spotlight] (its range negative) is the player's alone, lit by + // `classic_spot` at the vertices; another - a [spotlight_2], a cookie's + // cone - is lit so here, its ambient light with the diffuse + if (l.extra.z < 0.0) { + continue; + } + let s = d3d_spot(p, n, l.pos.xyz, l.dir, l.extra.x, l.extra.z, l.color.rgb * l.color.w); + sum = sum + s[0] + s[1]; + continue; + } + // full intensity within 1/8 of the range, then inverse-square, cut off at the range; + // the strength was set by eye while a street lamp was still counted about three + // times (see above), so it is three times what it was, to keep the lamp pools + let r0 = l.pos.w * 0.125; + let att = min(1.0, (r0 * r0) / max(dist * dist, 0.01)) * clamp(1.0 - dist / l.pos.w, 0.0, 1.0) * 3.75; + let ndl = max(dot(n, d / max(dist, 0.01)), 0.15); + var k = select(map_k, 1.0, l.dir.x > 0.5 && l.dir.w < -1.5); + if (l.dir.w >= -1.5) { + // a spot (a vehicle's [spotlight], as Direct3D lights with it): full inside + // the inner cone, fading to nothing at the outer one; nothing behind it + let c = dot(-d / max(dist, 0.01), l.dir.xyz); + k = smoothstep(l.dir.w, max(l.extra.x, l.dir.w + 1e-3), c); + } + sum = sum + l.color.rgb * l.color.w * att * ndl * k; + } + } + return sum; +} + +// [interiorlight]: the light of a vehicle's saloon lamps on a mesh that names them in its +// [illumination_interior], 1 = a lamp's full light on a seat under it. `code` is the +// instance's lamp code (lib.rs `Instance::interior_lamps`): the first of its lamp slots in +// `lights` times 64 plus how many; below 1 it is a plain brightness (a passenger standing in +// a lit bus). Each lamp is OMSI's Direct3D point light: attenuation +// 1 / (d² / core²) with `core` the lamp's [interiorlight] range, no cut-off short of 100 m, +// times N·L; the sum saturates, as Direct3D's vertex colour does. +fn interior_lamps(p: vec3, n: vec3, code: f32) -> vec3 { + if (code < 1.0) { + return vec3(1.0, 0.96, 0.84) * clamp(code, 0.0, 1.0); + } + let c = u32(code + 0.5); + // (LAMP_CODE_STRIDE: 64 - up to 63 lamps a mesh) + let first = c >> 6u; + let count = c & 63u; + var sum = vec3(0.0); + for (var i = 0u; i < count; i = i + 1u) { + let l = lights[first + i]; + let r = l.extra.w; + let d = l.pos.xyz - p; + let dist2 = max(dot(d, d), 1e-4); + if (l.color.w <= 0.0 || dist2 >= r * r) { + continue; + } + let core = max(l.extra.y, 0.01); + let att = core * core / dist2; + let ndl = max(dot(n, d * inverseSqrt(dist2)), 0.0); + sum = sum + l.color.rgb * l.color.w * att * ndl; + } + return min(sum, vec3(1.0)); +} + + +// A Direct3D spot light of the classic picture at `p` (normal `n`), as Omsi.exe sets its +// up for a vehicle's [spotlight] (0x708acc, see lights.rs `push_classic_spot`): `source` +// is the spotlight's own world position; attenuation 1 / (0.2 + d / R + 40 d² / R²) +// (R the declared range), the cone (`dir`: direction and the cosine of half the outer cone; +// `inner` the inner one's) with a falloff of 2, 0.3 x `color` as diffuse light (times N.L) +// and 0.1 x as ambient light, which lights the material's ambient colour whichever way the +// surface faces. [0] the diffuse light, [1] the ambient light. +fn d3d_spot(p: vec3, n: vec3, source: vec3, dir: vec4, inner: f32, range: f32, color: vec3) -> array, 2> { + let to_light = source - p; + let dl = max(length(to_light), 0.01); + let att = 1.0 / (0.2 + dl / range + 40.0 * dl * dl / (range * range)); + let rho = dot(-to_light / dl, dir.xyz); + let cone = pow(clamp((rho - dir.w) / (max(inner, dir.w + 1e-4) - dir.w), 0.0, 1.0), 2.0); + let lit = color * att * cone; + return array, 2>(lit * 0.3 * max(dot(n, to_light / dl), 0.0), lit * 0.1); +} + +// The classic picture's headlight at a vertex: Omsi.exe's one Direct3D spot light, the +// player's [spotlight] (`camera.spot`, see setup.rs `classic_spot`), lit at the vertices as +// its fixed function lights them. Across a road, whose vertices lie at its edges, the pool +// is spread as OMSI 2 spreads it: lit per pixel it was brightest on the crown of the road +// in front of the bus and gone far sooner. `vs_main` excludes the player's own vehicle. +// [0] is the vehicle-face origin for occlusion; [3] is the declared source for lighting. +// Nothing beyond 4 x its range, as Direct3D cuts it off. +fn classic_spot(p: vec3, n: vec3) -> array, 2> { + let s = camera.spot; + let none = array, 2>(vec3(0.0), vec3(0.0)); + if (s[0].w <= 0.0 || distance(s[3].xyz, p) >= 4.0 * s[0].w || own_vehicle_blocks(p, s[0].xyz)) { + return none; + } + return d3d_spot(p, n, s[3].xyz, s[1], s[2].w, s[0].w, s[2].rgb); +} +// Value noise in three octaves: the "fractal" detail (the `detail_textures` setting) laid +// over the ground and the road surfaces close by, so that a blurred texture keeps some grain. +// +// The lattice cell is hashed as an integer. The old `fract(sin(dot(q, …)) * 43758.5)` +// hash took the cell's map coordinate - two and a half million at Spandau's 892 km - into +// a sine: in 32-bit floats its argument is a multiple of 64 there, and what came out was +// not noise but a ramp that repeated along straight lines, so every road wore thin +// diagonal streaks at an exact spacing. Cells are wrapped at `PATTERN_PERIOD` (the pattern +// coordinate is taken modulo that on the CPU, see `world_pattern_xy`), which keeps the +// hash's input small and the pattern seamless across the wrap. +const PATTERN_PERIOD: f32 = 1000.0; + +fn hash_cell(c: vec2, cells: f32) -> f32 { + // the cell index modulo the lattice's cells per period, as an exact integer + let w = c - cells * floor(c / cells); + var v = vec2(w) * 1664525u + vec2(1013904223u); + // (a PCG-style mix: two rounds of multiply, cross-add and xor-shift) + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + return f32(v.x >> 8u) / 16777215.0; +} + +// `freq`: lattice cells per metre of `p` (a whole number of cells per `PATTERN_PERIOD`). +fn vnoise_f(p: vec2, freq: f32, offset: vec2) -> f32 { + let q = p * freq + offset; + let cells = round(PATTERN_PERIOD * freq); + let i = floor(q); + let f = q - i; + let u = f * f * (3.0 - 2.0 * f); + let a = hash_cell(i, cells); + let b = hash_cell(i + vec2(1.0, 0.0), cells); + let c = hash_cell(i + vec2(0.0, 1.0), cells); + let d = hash_cell(i + vec2(1.0, 1.0), cells); + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); +} + + +fn detail_noise(p: vec2, near: f32) -> f32 { + // Anti-alias: point-sampling a lattice this fine aliases wherever one pixel's + // footprint spans more than about one cell of it - looking down a street at a + // grazing angle, or just driving away, constantly changes that footprint, and the + // alias pattern with it, which reads as the "fractal" texture re-rendering itself as + // the view angle changes. `fwidth` gives the footprint in the same units as `p`; an + // octave fades to its own mean (0.5, the hash is uniform 0..1) once a pixel can no + // longer resolve it, which is what an infinitely dense filter of it would give anyway. + let w = max(fwidth(p).x, fwidth(p).y); + let seen = select(0.0, 1.0, near > 0.0); + let fade0 = (1.0 - smoothstep(0.3, 1.2, w * 2.9)) * seen; + let fade1 = (1.0 - smoothstep(0.3, 1.2, w * 0.73)) * seen; + let fade2 = (1.0 - smoothstep(0.3, 1.2, w * 0.19)) * seen; + var n0 = 0.5; + var n1 = 0.5; + var n2 = 0.5; + if (fade0 > 0.0) { + n0 = mix(0.5, vnoise_f(p, 2.9, vec2(0.0)), fade0); + } + if (fade1 > 0.0) { + n1 = mix(0.5, vnoise_f(p, 0.73, vec2(0.0)), fade1); + } + if (fade2 > 0.0) { + n2 = mix(0.5, vnoise_f(p, 0.19, vec2(0.0)), fade2); + } + return n0 * 0.5 + n1 * 0.3 + n2 * 0.2; +} + +fn world_pattern_xy(p: vec3) -> vec2 { + // Geometry is relative to the floating render origin for f32 precision. Procedural + // patterns are not: reconstruct their stable map-space coordinate so crossing the + // renderer's 100 m origin cell cannot re-seed the asphalt/ground pattern. The origin + // arrives modulo PATTERN_PERIOD (lib.rs), so this stays a small, exact number: the map + // coordinate itself (892 km at Spandau) has a 6 cm step in 32 bits, a fifth of the + // finest noise cell. + return p.xy + camera.world_origin.xy; +} + +// Whether every component is a finite number, tested on the bits: Metal's fast maths takes +// `x != x` and comparisons with a NaN as it likes (a NaN colour happened to come out as +// something on the Mac), Direct3D 12 keeps the NaN and draws it black. +fn all_finite(v: vec3) -> bool { + let e = bitcast>(v) & vec3(0x7f800000u); + return all(e != vec3(0x7f800000u)); +} + +fn finite_or(v: vec3, fallback: vec3) -> vec3 { + return select(fallback, v, all_finite(v)); +} + +// The side of a tracked pane's wetness mask (`window_wipers::SIZE`). A constant, not the +// texture's own size: with `textureDimensions(mx_tex2d[mx_mat.trans])` in these functions Apple's Metal +// compiler crashed on the scene shader (the pipelines failed and the renderer fell back to +// 1x MSAA without snowfall and lamp shadows). +const WIPE_MASK_SIZE: i32 = 128; + +fn window_wetness(in: FsIn) -> f32 { + if (material.wipe_bounds.z != 0.0) { + // The mask packs the pane depth into R/G (high and low byte) and the wetness into + // B (the pane's unwiped wetness) and A (the local wetness). A filtered sample mixes + // the depth bytes of neighbouring texels into a depth that belongs to neither, so + // the pane test flickered between A and B from texel to texel: a staircase along + // every texel row where the raked glass changes depth. Read the four texels + // unfiltered, test each by its own depth, and blend the results bilinearly. + let dims = vec2(WIPE_MASK_SIZE); + let inside = all(in.wipe_uv.xy >= vec2(0.0)) && all(in.wipe_uv.xy <= vec2(1.0)); + let p = in.wipe_uv.xy * vec2(dims) - 0.5; + let base = vec2(floor(p)); + let f = p - floor(p); + var wet = 0.0; + for (var k = 0; k < 4; k++) { + let o = vec2(k & 1, k >> 1); + let w = select(1.0 - f.x, f.x, o.x == 1) * select(1.0 - f.y, f.y, o.y == 1); + let texel = textureLoad(mx_tex2d[mx_mat.trans], clamp(base + o, vec2(0), dims - 1), 0); + let depth = dot(texel.rg, vec2(256.0, 1.0)) * (64.0 / 257.0) - 32.0; + let local = (texel.a * 255.0 - 8.0) * (2.0 / 247.0); + wet += w * select(texel.b, local, inside && abs(depth - in.wipe_uv.z) <= 0.1); + } + return wet; + } + return in.params.x; +} + +// The snow variant of a tracked pane (`wipe_bounds.w` < 0): the snow the mask holds while it +// snows, drawn instead of water drops (scene/08_rain_glass.wgsl `glass_snow_with`). The mask +// value is the cover: 0 clear glass, up to 1 a pane closed by snow, above 1 the bank a blade +// pushed to the end of its sweep, below 0 glass a blade has just cleared. +fn is_snow_pane() -> bool { + return material.wipe_bounds.z != 0.0 && material.wipe_bounds.w < 0.0; +} + +// Smooth value noise (0..1) from the cell hash: the corners' values blended with a +// smoothstep, so it has no seams at the cell edges. +fn snow_noise(p: vec2) -> f32 { + let i = floor(p); + let f = p - i; + let u = f * f * (3.0 - 2.0 * f); + let a = rain_hash(i).x; + let b = rain_hash(i + vec2(1.0, 0.0)).x; + let c = rain_hash(i + vec2(0.0, 1.0)).x; + let d = rain_hash(i + vec2(1.0, 1.0)).x; + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); +} + +// By day in a downpour some of the houses' windows are lit, as people switch the light on when +// it gets that dark (`camera.wind.w` - 1: the share, `Lighting::rain_lights`, 0 with the +// setting off): the night maps of a few rooms here and there, chosen by a cell of the +// object's own frame some four metres wide and three high (`local`: the same rooms of a +// house stay lit, and a bus driving by does not flicker as it crosses cells of the world), +// each fading in at its own point of the rain. What a night map shows: the night's own +// strength or, where such a room is lit, the full light. +fn rain_lit_windows(local: vec3) -> f32 { + let night = clamp(camera.sun_color.w, 0.0, 1.0); + let share = clamp(camera.wind.w - 1.0, 0.0, 1.0); + if (share <= 0.0) { + return night; + } + let cell = floor(vec3(local.xy / 4.0, local.z / 3.0)); + let h = rain_hash(cell.xy + vec2(cell.z * 17.3, cell.z * 5.1)); + // (some a third of the rooms at the heaviest rain) + let lit = smoothstep(h.x, h.x + 0.08, share * 0.38); + return max(night, lit * (0.75 + 0.25 * h.y)); +} +fn rain_hash(p: vec2) -> vec2 { + // Integer mixing keeps neighbouring cells independent without the precision loss and + // repeated sine evaluations of a floating-point hash. + let cell = bitcast>(vec2(floor(p))); + var a = cell.x * 0x9e3779b9u ^ cell.y * 0x85ebca6bu; + a = (a ^ (a >> 16u)) * 0x7feb352du; + a = (a ^ (a >> 15u)) * 0x846ca68bu; + a = a ^ (a >> 16u); + var b = a ^ 0x68bc21ebu; + b = (b ^ (b >> 16u)) * 0x7feb352du; + b = (b ^ (b >> 15u)) * 0x846ca68bu; + b = b ^ (b >> 16u); + return vec2(f32(a), f32(b)) * (1.0 / 4294967296.0); +} + +// Smooth noise for water-film refraction and residual wiper streaks (0..1). +fn rain_patches(q: vec2) -> vec2 { + let c = floor(q); + let f = q - c; + let w = f * f * (3.0 - 2.0 * f); + let a = rain_hash(c); + let b = rain_hash(c + vec2(1.0, 0.0)); + let d = rain_hash(c + vec2(0.0, 1.0)); + let e = rain_hash(c + vec2(1.0, 1.0)); + return mix(mix(a, b, w.x), mix(d, e, w.x), w.y); +} + +// A grid of its own for each layer of drops: turned by its own angle and shifted, so that +// no two layers line up and none runs along the glass's edges. +fn rain_turn(q: vec2, a: f32) -> vec2 { + let cs = vec2(cos(a), sin(a)); + return vec2(q.x * cs.x - q.y * cs.y, q.x * cs.y + q.y * cs.x); +} + +// What a drop shows in the classic picture: the sky from the weather's colours, the +// horizon in the fog's, the ground darker. +fn rain_env_vanilla(d: vec3) -> vec3 { + let zenith = camera.sky_color.rgb + camera.ambient.rgb * 0.5; + let horizon = max(camera.fog.rgb, camera.ambient.rgb); + let ground = camera.ambient.rgb * 0.4 + camera.sun_color.rgb * camera.sun_dir.w * 0.06; + let sky = mix(horizon, zenith, smoothstep(0.0, 0.5, d.z)); + let c = mix(ground, sky, smoothstep(-0.06, 0.04, d.z)); + return select(c, srgb_decode(c), camera.sky_color.w > 0.5); +} + +// --- The rain on a pane as all the pictures draw it (the enhanced film, enhanced/07_glass.wgsl +// `glass_film`, and the classic one, scene/09_vanilla.wgsl `glass_film_classic`): the drops laid +// out in the vehicle's own frame (`FsIn.local`), so they stay on the glass however the body +// rolls and pitches and on a door that swings open. The modellers' texture coordinates of a +// film are no measure of the glass: on the windscreen of the NL202 they run half as fast +// again one way as the other and at sixty degrees to each other, from triangle to triangle +// anew, and every drop drawn in them came out a slanting streak (the classic pictures' old +// `rain_glass` did, and was replaced by this). So a pane is laid flat by the axes of the +// vehicle (`pane_proj`). + +// The glass at a pixel: the position and the flat normal in the vehicle's frame, the +// normal on the rain's side in the world, the pixel's footprint on the glass (m, its longer +// side and the side of a square of its area), and the screen derivatives of both positions. +struct PaneBase { + l: vec3, + nl: vec3, + out: vec3, + px: f32, + px_area: f32, + dlx: vec3, + dly: vec3, + dwx: vec3, + dwy: vec3, + ok: bool, +}; + +fn pane_base(world: vec3, local: vec3, n: vec3, outside_in: bool) -> PaneBase { + var b: PaneBase; + b.l = local; + b.dlx = dpdx(local); + b.dly = dpdy(local); + b.dwx = dpdx(world); + b.dwy = dpdy(world); + // the film faces the eye unless the eye is in the bus behind it (the triangle's own + // normal: a film mesh's vertex normals are not to be relied on, many have none, and + // the drops' size followed their noise) + let eye = normalize(camera.cam_pos.xyz - world); + let gn = cross(b.dwx, b.dwy); + var out = select(safe_normal(n), gn / max(length(gn), 1e-20), dot(gn, gn) > 1e-24); + out = select(-out, out, dot(out, eye) >= 0.0); + out = select(out, -out, outside_in); + b.out = out; + b.px = max(max(length(b.dwx), length(b.dwy)), 1e-5); + b.px_area = max(sqrt(length(cross(b.dwx, b.dwy))), 1e-5); + let c = cross(b.dlx, b.dly); + let cl = length(c); + b.ok = cl > 1e-12; + b.nl = select(vec3(0.0, 1.0, 0.0), c / max(cl, 1e-20), b.ok); + return b; +} + +// A direction on the glass in the vehicle's frame, in the world (through the two positions' +// screen derivatives). +fn pane_to_world(b: PaneBase, t: vec3) -> vec3 { + let g = vec3(dot(b.dlx, b.dlx), dot(b.dlx, b.dly), dot(b.dly, b.dly)); + let det = g.x * g.z - g.y * g.y; + if (abs(det) < 1e-24) { + return vec3(0.0); + } + let r = vec2(dot(b.dlx, t), dot(b.dly, t)); + let a = (g.z * r.x - g.y * r.y) / det; + let c = (g.x * r.y - g.y * r.x) / det; + return a * b.dwx + c * b.dwy; +} + +// The pane laid flat along two of the vehicle's axes (`axis`: 0 across and up, the +// windscreen and the rear window; 1 along and up, the side windows; 2 the plan, a roof +// light): where the pixel is (m: x across, y down), how an offset there is taken back onto +// the glass (`m`: metres along `side_w` and `down_w`, the glass's own across and down in +// the world), and the projection's screen derivatives (for the wiper's ridge). +struct PaneProj { + q: vec2, + m: mat2x2, + side_w: vec3, + down_w: vec3, + dqx: vec2, + dqy: vec2, + steep: bool, +}; + +fn pane_proj(b: PaneBase, axis: i32) -> PaneProj { + var p: PaneProj; + var ea = vec3(1.0, 0.0, 0.0); + var eb = vec3(0.0, 0.0, -1.0); + var ec = vec3(0.0, 1.0, 0.0); + if (axis == 1) { + ea = vec3(0.0, 1.0, 0.0); + ec = vec3(1.0, 0.0, 0.0); + } else if (axis == 2) { + eb = vec3(0.0, 1.0, 0.0); + ec = vec3(0.0, 0.0, 1.0); + } + let nl = b.nl; + let nc = dot(nl, ec); + let ncs = select(nc, select(-1e-3, 1e-3, nc >= 0.0), abs(nc) < 1e-3); + p.q = vec2(dot(b.l, ea), dot(b.l, eb)); + p.dqx = vec2(dot(b.dlx, ea), dot(b.dlx, eb)); + p.dqy = vec2(dot(b.dly, ea), dot(b.dly, eb)); + // the glass under a step of the projection's two axes + let t1 = ea - ec * (dot(nl, ea) / ncs); + let t2 = eb - ec * (dot(nl, eb) / ncs); + // the glass's own down (the steepest way on it) and across, in the vehicle's frame + p.steep = axis != 2; + var dl = vec3(0.0, 0.0, -1.0) + nl * nl.z; + dl = select(normalize(t2), dl / max(length(dl), 1e-6), dot(dl, dl) > 0.02 && p.steep); + var sl = t1 - dl * dot(t1, dl); + sl = sl / max(length(sl), 1e-6); + p.m = mat2x2(vec2(dot(t1, sl), dot(t1, dl)), vec2(dot(t2, sl), dot(t2, dl))); + // the same two ways in the world, square to the normal on the rain's side + var sw = pane_to_world(b, sl); + sw = sw - b.out * dot(sw, b.out); + var dw = pane_to_world(b, dl); + dw = dw - b.out * dot(dw, b.out); + p.side_w = sw / max(length(sw), 1e-6); + dw = dw - p.side_w * dot(dw, p.side_w); + p.down_w = dw / max(length(dw), 1e-6); + return p; +} + +// The water on a pane at a pixel: the surface's normal (world, out of the water), how much +// of the pixel a drop or a bead covers and how far out on it the pixel lies (0 its middle, +// 1 its rim), the drop's radius in pixels, the pane's normal on the rain's side, the fine +// mist of droplets under a millimetre, and how much of the view through the pane the +// connected water scatters into a soft blur (`veil`). +struct GlassWater { + n: vec3, + cover: f32, + out: vec3, + mist: f32, + veil: f32, + rim: f32, + size_px: f32, +}; + +// One drop of radius `r` (m) at `d` (m on the glass, across / down): the slope of its dome +// (the normal's part along the glass), its cover of the pixel (`px`: the pixel's size on +// the glass) and how far out on it the pixel lies. A shallow cap, as water spreading on +// glass makes; a drop smaller than the pixel keeps its share of it, its slopes flattened +// to their average. +fn glass_dome(d: vec2, r: f32, px: f32) -> vec4 { + let rr = length(d) / max(r, 1e-6); + let aa = clamp(px / max(r, 1e-6), 0.02, 1.0); + let cover = 1.0 - smoothstep(1.0 - aa, 1.0 + aa, rr); + let seen = smoothstep(0.0, 0.8, r / px); + let cap = mix(0.15, 0.55, smoothstep(0.7, 2.5, r / px)); + let s = d / max(r, 1e-6) * cap * (0.6 + 0.4 * rr * rr); + return vec4(s, cover * seen, min(rr, 1.0)); +} + +// What covers the pixel, gathered over the layers: the cover, the slope, the rim and the +// drop's size in pixels of the drop on top. +struct DropAcc { + cover: f32, + slope: vec2, + rim: f32, + size_px: f32, + track: f32, + // the cover of the drops too small for the pixel to see one by one, as their average + // (taken into the mist, so that they read as an even haze, not as random specks) + avg: f32, +}; + +fn drop_take(a: ptr, d: vec4, r: f32, px: f32) { + if (d.z > (*a).cover) { + (*a).cover = d.z; + (*a).slope = d.xy; + (*a).rim = d.w; + (*a).size_px = r / px; + } +} + +// One layer of the drops that sit on the glass: a jittered grid of cells `cell` metres +// wide (of the projection), each holding a drop now and then (`occ` the share of cells +// that hold one). A drop lands, spreads to its size within a moment and sits; after its +// own while it is gone again, taken by a runner or merged into a neighbour, and the next +// lands somewhere else in the cell - all fading, nothing popping. +fn glass_bead(a: ptr, p: PaneProj, layer: f32, cell: f32, occ: f32, r0: f32, size: f32, t: f32, px: f32) { + // (a layer whose drops are smaller than the pixel, or cells no wider than it - a mirror's + // small picture, the glass seen from afar - is taken at its average cover: sampled one + // random cell a pixel, it drew white noise) + let fine = max(1.0 - smoothstep(0.7, 1.5, r0 * size / px), 1.0 - smoothstep(1.0, 2.5, cell / px)); + if (fine > 0.0) { + let rr = 1.6 * r0 * size / cell; + (*a).avg = (*a).avg + fine * occ * min(3.14159 * rr * rr, 1.0); + if (fine > 0.99) { + return; + } + } + let turn = 0.61 + layer * 1.37; + let g2 = rain_turn(p.q, turn) / cell + vec2(layer * 17.3, layer * 5.1); + let c = floor(g2); + let timing = rain_hash(c + vec2(3.7, 9.2 + layer)); + let life = (9.0 + layer * 4.0) * (1.0 + timing.y); + let cycle = t / life + timing.x; + let ph = fract(cycle); + let arrival = c + floor(cycle) * vec2(17.0, 43.0); + let h = rain_hash(arrival); + // (a share of cells rising with the wetness: a drop fades in over a small rise of it) + let shown = clamp((occ - h.x) * 20.0, 0.0, 1.0) * smoothstep(0.0, 0.03, ph) * (1.0 - smoothstep(0.9, 1.0, ph)) * (1.0 - fine); + if (shown <= 0.0) { + return; + } + // (`r0` the layer's smallest drop, the largest twice that: rain on glass sits as drops of + // half a millimetre to four across - drawn up to a share of the cell they made drops of a + // centimetre and more, few and far between) + let radius = r0 * (1.0 + h.y * h.y) * mix(0.6, 1.0, smoothstep(0.0, 0.2, ph)) * size; + // (anywhere in the cell the largest still fits in - on the glass it is never smaller + // than in the projection - and the same place whatever its size: the size follows the + // wetness, which changes across the glass) + let room = min(r0 * 3.0 / cell, 0.45); + let centre = c + vec2(room) + rain_hash(arrival + 9.1) * (1.0 - 2.0 * room); + let dq = rain_turn((g2 - centre) * cell, -turn); + if (length(dq) > radius * 1.3) { + return; + } + var d = p.m * dq; + // No drop is a circle: its rim wanders where the glass held it as it spread, and its + // weight draws it a little fuller below than above. + let h3 = rain_hash(arrival + 23.9); + let dl = max(length(d), 1e-7); + let u = d / dl; + let c2 = u.x * u.x - u.y * u.y; + let s2 = 2.0 * u.x * u.y; + let c3 = u.x * (4.0 * u.x * u.x - 3.0); + let s3 = u.y * (3.0 - 4.0 * u.y * u.y); + let p2 = h3 * 2.0 - 1.0; + let wave = (s2 * p2.x + c2 * p2.y) * 0.7 + 0.45 * (s3 * p2.y - c3 * p2.x); + d = d / (1.0 + (0.03 + 0.05 * h.y) * wave); + d.y = d.y * select(1.06, 0.94, d.y > 0.0); + let dome = glass_dome(d, radius, px); + drop_take(a, vec4(dome.xy, dome.z * shown, dome.w), radius, px); +} + +// A runner's sideways wander as it goes down (m): a smooth random path of its own. +fn glass_meander(s: f32, seed: vec2, amp: f32) -> f32 { + let w = rain_patches(vec2(s * 9.0 + seed.x, seed.y)); + return amp * ((w.x - 0.5) * 1.5 + (w.y - 0.5) * 0.5); +} + +// The runners in a lattice of lanes (`qr`: the projection turned so they run down +y, `mr` +// taking its offsets onto the glass): now and then a drop grown heavy breaks loose and +// slides a hand's breadth or two down, in fits and starts, wandering a little from side to +// side, and stops again. It sweeps a narrow clear track through the small drops, which +// fill in again as the rain falls on it; behind it lies a short wet trail that drains +// within a second, and a few beads it left. One chance a cell of 4.5 cm x 1.2 m; a pixel +// looks at its own cell and the one above, whose drop may have slid into it. +fn glass_runners(a: ptr, qr: vec2, mr: mat2x2, seed: f32, wet: f32, heavy: f32, blow: f32, size: f32, t: f32, px: f32) { + // (lanes of 4.5 cm and cells 1.2 m tall, few of them running at once: with lanes of 2 cm + // and cells of 0.8 m nearly every lane ran in a downpour, and their tracks cut the glass + // into wide clear stripes, #4153) + let lane_w = 0.045; + let seg_h = 1.2; + let lane = floor(qr.x / lane_w); + let seg0 = floor(qr.y / seg_h); + for (var k = 0; k < 2; k = k + 1) { + let seg = seg0 - f32(k); + let key = vec2(lane * 1.7 + seed * 101.0, seg * 2.3 + seed * 37.0); + let h1 = rain_hash(key + vec2(3.0, 11.0)); + if (h1.x >= wet * (0.15 + 0.15 * heavy + 0.1 * blow)) { + continue; + } + let h2 = rain_hash(key + vec2(8.1, 5.1)); + // (it gathers a while, runs, and its trail fills in with new rain) + // (a drop grown heavy on upright glass runs off at some ten to twenty centimetres a + // second, most of the way down the pane) + let sit = 0.6 + 2.4 * h2.y; + let v = (0.08 + 0.16 * h1.y * h1.y) * (1.0 + 0.8 * blow) * (1.0 + 0.4 * heavy); + let run_len = 0.12 + 0.4 * h2.x; + let run_t = run_len / v; + let refill = mix(3.0, 1.5, wet); + let period = sit + run_t + refill; + let cycle = t / period + h2.x; + let tau = fract(cycle) * period; + let h3 = rain_hash(key + vec2(1.3, 29.7) + floor(cycle) * vec2(13.0, 41.0)); + // stick and slip: v s - v P / 2 pi sin(2 pi s / P) halts once a pulse P + let pulse = 0.3 + 0.4 * h3.x; + let st = clamp(tau - sit, 0.0, run_t * 1.05); + let travel = min(v * st - v * pulse * 0.1591549 * sin(6.283185 * st / pulse), run_len); + let vis = smoothstep(0.0, 0.6, tau) * (1.0 - smoothstep(period - 1.0, period, tau)); + let y0 = (seg + 0.02 + 0.32 * h3.x) * seg_h; + let x0 = (lane + 0.3 + 0.4 * h3.y) * lane_w; + let wseed = h3 * 57.0; + let amp = 0.002 + 0.002 * h2.y; + if (abs(qr.x - x0) > lane_w * 0.5 + amp * 1.5 || qr.y < y0 - 0.01 || qr.y > y0 + run_len + 0.01) { + continue; + } + // (a downpour's runners are heavier; a drop gathers before it goes) + let rh = size * (0.0012 + 0.0008 * h1.y) * (1.0 + 0.3 * heavy) * mix(0.6, 1.0, smoothstep(0.0, sit, tau)); + var head_d = mr * vec2(qr.x - (x0 + glass_meander(travel, wseed, amp)), qr.y - (y0 + travel)); + // (drawn out a little behind, full in front) + head_d.y = head_d.y * select(0.8, 1.0, head_d.y > 0.0); + let head = glass_dome(head_d, rh, px); + // (once stopped it sits at the end of its run and is taken into the new rain) + let head_vis = vis * (1.0 - smoothstep(sit + run_t, sit + run_t + refill * 0.8, tau)); + drop_take(a, vec4(head.xy, head.z * head_vis, head.w), rh, px); + let along = qr.y - y0; + if (along > 0.0 && along < travel - rh * 0.5) { + let dxq = qr.x - (x0 + glass_meander(along, wseed, amp)); + let dx = (mr * vec2(dxq, 0.0)).x; + // how long ago the head passed here + let age = max(tau - sit - along / v, 0.0); + let hw = rh * 0.9; + let cleared = (1.0 - smoothstep(hw * 0.6, hw * 1.1, abs(dx))) * (1.0 - smoothstep(refill * 0.4, refill, age)) * vis; + (*a).track = max((*a).track, cleared); + // the thin wet trail it draws, draining within a second: a faint lens, no strip + let tw = rh * 0.45 * exp(-age * 2.0); + let trail = glass_dome(vec2(dx, 0.0), max(tw, 1e-5), px); + let trail_cover = trail.z * 0.35 * (1.0 - smoothstep(0.2, 1.0, age)) * vis; + drop_take(a, vec4(trail.xy * 0.4, trail_cover, trail.w), tw, px); + // ... and a few beads, left behind where the trail broke + let bc = floor(along / 0.009); + let bh = rain_hash(vec2(lane * 3.1 + bc, seg * 1.9 + 41.0 + seed * 7.0)); + if (bh.x < 0.3) { + let bcen = vec2((bh.y - 0.5) * hw * 0.8, ((bc + 0.5) * 0.009 - along) * (mr * vec2(0.0, 1.0)).y); + let br = 0.0004 + 0.0005 * bh.y; + let bead = glass_dome(vec2(dx, 0.0) - bcen, br, px); + let bead_cover = bead.z * smoothstep(0.4, 1.0, age) * (1.0 - smoothstep(refill * 0.5, refill, age)) * vis; + drop_take(a, vec4(bead.xy, bead_cover, bead.w), br, px); + } + } + } +} + +// The drops on one projection of the pane (`w` its share, see `glass_water`). +fn glass_drops(a: ptr, b: PaneBase, p: PaneProj, w: f32, wet: f32, heavy: f32, bank: f32, size: f32, world: vec3, t: f32) { + // --- the airstream: a drop's drag grows with the speed squared, and at some 40 km/h it + // matches its weight. Along the glass the air drives the water back; where it meets the + // glass head on (the windscreen) it parts, up and out. The runners go where weight and + // air take them together; the drops that sit hold on. + var flow = vec2(0.0, 1.0); + var blow = 0.0; + if (camera.wind.w > 0.5 && near_player_vehicle(world) > 0.5) { + let air = -camera.wind.xyz; + var aw = vec2(dot(air, p.side_w), dot(air, p.down_w)); + aw.y = aw.y - abs(dot(air, b.out)) * 0.6; + let v2 = dot(aw, aw); + blow = clamp(v2 / 130.0, 0.0, 3.0); + flow = flow + aw / max(sqrt(v2), 1e-4) * blow; + } + if (p.steep) { + // The runners' lanes are laid along the way the water runs, in sixteenths of a turn + // (turned freely, a degree moved every lane a metre off by its width). Between two + // such ways the two lattices cross-fade, so a change of speed fades the runners + // over instead of jumping them. (`flow` is on the glass; the lanes in the + // projection, whose down is the glass's down.) + let fstep = 0.3926991; + let fa = atan2(flow.x, flow.y) / fstep; + let f0 = floor(fa); + let fw = smoothstep(0.35, 0.65, fa - f0); + for (var k = 0; k < 2; k = k + 1) { + let wk = select(1.0 - fw, fw, k == 1) * w; + if (wk < 0.01) { + continue; + } + let ang = (f0 + f32(k)) * fstep; + let cs = vec2(cos(ang), sin(ang)); + let mr = p.m * mat2x2(vec2(cs.x, -cs.y), vec2(cs.y, cs.x)); + glass_runners(a, rain_turn(p.q, ang), mr, f0 + f32(k), wet * wk, heavy, blow, size, t, b.px_area); + } + } + // --- the drops that sit: four sizes, a great many small ones and fewer large ones (radius + // 1 to 2, 1.6 to 3.2, 2.4 to 4.8 and 3.4 to 6.8 mm: smaller ones, true to a drizzle's, + // were under a pixel from the driver's seat and drew the windscreen as an even grain), + // all fewer in the runners' fresh + // tracks and under the bank + let room = (1.0 - (*a).track) * (1.0 - bank) * w; + for (var layer = 0; layer < 4; layer = layer + 1) { + let fl = f32(layer); + var cell = 0.0068; + var r0 = 0.001; + var occ = 0.85 * smoothstep(0.02, 0.25, wet); + if (layer == 1) { + cell = 0.0108; + r0 = 0.0016; + occ = 0.75 * smoothstep(0.05, 0.4, wet); + } else if (layer == 2) { + cell = 0.016; + r0 = 0.0024; + occ = 0.6 * smoothstep(0.15, 0.6, wet); + } else if (layer == 3) { + cell = 0.023; + r0 = 0.0034; + occ = 0.4 * smoothstep(0.35, 0.9, wet); + } + glass_bead(a, p, fl, cell, occ * room, r0, size, t, b.px_area); + } +} + +// The rain on a pane at a pixel (see the head of this file). `water` is the pane's +// wetness (0..1; below 0 a blade has just wiped it, above 1 the bank a blade pushed), +// `t` the animation clock, `outside_in` true for the eye in the bus. +fn glass_water(world: vec3, local: vec3, n: vec3, water: f32, t: f32, outside_in: bool) -> GlassWater { + let b = pane_base(world, local, n, outside_in); + let wdx = dpdx(water); + let wdy = dpdy(water); + var g: GlassWater; + g.n = b.out; + g.out = b.out; + g.cover = 0.0; + g.mist = 0.0; + g.veil = 0.0; + g.rim = 0.0; + g.size_px = 0.0; + let wet = clamp(water, 0.0, 1.0); + let wiped = clamp(-water * 25.0, 0.0, 1.0); + let bank = clamp((water - 1.0) * 0.18, 0.0, 1.0); + if (!b.ok || (wet <= 0.01 && wiped <= 0.01 && bank <= 0.0)) { + return g; + } + // Which way the pane is laid flat: by the larger of its normal's parts across and along + // the vehicle, the two cross-faded over a band round 45 degrees (a windscreen's curved + // corner), each drop of either set coming or going whole; a pane facing up is a roof's. + let an = abs(b.nl); + let roof = an.z > max(an.x, an.y) * 2.0; + let w_front = select(smoothstep(-0.12, 0.12, an.y - an.x), 1.0, roof); + let main_axis = select(select(1, 0, w_front >= 0.5), 2, roof); + let p = pane_proj(b, main_axis); + // the wetness's gradient on the glass (from its screen derivatives) + let jd = p.dqx.x * p.dqy.y - p.dqx.y * p.dqy.x; + var grad = vec2(0.0); + if (abs(jd) > 1e-14) { + grad = vec2(wdx * p.dqy.y - wdy * p.dqx.y, wdy * p.dqx.x - wdx * p.dqy.x) / jd; + } + if (wiped > 0.01) { + // Just wiped: fine streaks along the blade's sweep (the age gradient follows it) + // bend the view for a moment, without bringing the drops back. + var along = vec2(0.0, 1.0); + if (length(grad) > 0.01) { + along = normalize(grad); + } + let across = vec2(-along.y, along.x); + let streak = rain_patches(vec2(dot(p.q, across) * 600.0, dot(p.q, along) * 4.0)); + g.cover = wiped * (0.012 + 0.018 * streak.x); + g.veil = wiped * 0.06; + g.size_px = 4.0; + g.n = normalize(b.out + (p.side_w * across.x + p.down_w * across.y) * (streak.y - 0.5) * wiped * 0.003); + return g; + } + let heavy = smoothstep(0.55, 1.0, wet); + // (a drizzle leaves beads, a downpour full drops; on an upright side pane, which the rain + // meets edge on and the airstream sweeps, they stay smaller than on a raked windscreen) + let size = mix(0.85, 1.1, smoothstep(0.1, 0.8, wet)) * mix(0.8, 1.0, smoothstep(0.0, 0.4, abs(b.out.z))); + var acc: DropAcc; + acc.cover = 0.0; + acc.slope = vec2(0.0); + acc.rim = 0.0; + acc.size_px = 0.0; + acc.track = 0.0; + acc.avg = 0.0; + // the bank a blade pushed: its ridge bends the view + if (bank > 0.0) { + acc.cover = bank; + acc.slope = clamp(-0.00005 * grad, vec2(-0.15), vec2(0.15)) * bank; + acc.size_px = 8.0; + } + let w_main = select(select(1.0 - w_front, w_front, main_axis == 0), 1.0, roof); + glass_drops(&acc, b, p, w_main, wet, heavy, bank, size, world, t); + var side_w = p.side_w; + var down_w = p.down_w; + if (w_main < 0.99) { + let p2 = pane_proj(b, 1 - main_axis); + glass_drops(&acc, b, p2, 1.0 - w_main, wet, heavy, bank, size, world, t); + } + // --- the mist: droplets of a millimetre and less, too many to draw one by one far off + var grain = 0.0; + { + let mg = rain_turn(p.q, 0.33) / 0.0024; + let mc = floor(mg); + let mh = rain_hash(mc + 71.0); + let mr = 0.1 + 0.16 * mh.y; + let at = mc + vec2(mr) + rain_hash(mc + 5.3) * (1.0 - 2.0 * mr); + grain = step(mh.x, wet * 0.3) * (1.0 - smoothstep(mr * 0.6, mr, length(mg - at))); + } + // (seen from further than a millimetre a pixel: their average) + let mist = mix(wet * 0.3 * 0.12, grain, smoothstep(0.0015, 0.0006, b.px)); + g.mist = clamp((mist + 0.6 * acc.avg) * (1.0 - acc.track), 0.0, 1.0); + // The connected water between the drops scatters some of the view into a soft haze + // (the veil, drawn from the picture's blurred levels), the same on every pane as wet. + // A runner's fresh track is a clear sheet of water, sharper than the rest. + let film = smoothstep(0.03, 0.4, wet) * (1.0 - 0.3 * acc.track); + // (by the air's temperature, `camera.lod.w`: on cold glass the water spreads into a film + // and a fine mist of droplets that scatter the view - near freezing the sleet's slush on + // top - while in a warm summer rain it beads up and runs off, the glass between the drops + // nearly clear) + let cold = 1.0 - smoothstep(2.0, 24.0, camera.lod.w); + // (light: a strong veil hid the drops behind a uniform fog) + g.veil = film * mix(0.12, 0.25, heavy) * mix(0.7, 1.2, cold); + g.cover = acc.cover; + g.rim = acc.rim; + g.size_px = acc.size_px; + let slope = acc.slope; + let nz = sqrt(max(1.0 - dot(slope, slope), 0.02)); + g.n = normalize(b.out * nz + side_w * slope.x + down_w * slope.y); + return g; +} + +// The picture behind the glass (`glass_mips.rs`, pre-exposed radiance) at `uv`, blurred to +// level `lod`: five reads round the point a texel of that level apart, so the small levels' +// texels do not show as blocks when they are spread over many pixels. +fn glass_blur(uv: vec2, lod: f32) -> vec3 { + let dims = vec2(textureDimensions(mx_tex2d[mx_mat.env])); + let o = exp2(lod) * 0.75 / dims; + let c = clamp(uv, vec2(0.001), vec2(0.999)); + var s = textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], c, lod).rgb * 2.0; + s = s + textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], clamp(c + vec2(o.x, o.y * 0.5), vec2(0.001), vec2(0.999)), lod).rgb; + s = s + textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], clamp(c + vec2(-o.x * 0.5, o.y), vec2(0.001), vec2(0.999)), lod).rgb; + s = s + textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], clamp(c + vec2(-o.x, -o.y * 0.5), vec2(0.001), vec2(0.999)), lod).rgb; + s = s + textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], clamp(c + vec2(o.x * 0.5, -o.y), vec2(0.001), vec2(0.999)), lod).rgb; + return s / 6.0; +} + +// The snow a wiped pane holds while it snows (see enhanced/07_glass.wgsl `glass_snow`): +// `defrost` how far the windscreen's defroster has cleared it (0..0.85), `fz` the height on +// the glass in the bus's frame (-1 its bottom, 1 its top), for the drift along the bottom. +fn glass_snow_with(in: FsIn, cover: f32, defrost: f32, fz: f32) -> vec4 { + if (cover <= 0.0) { + return vec4(1.0, 1.0, 1.0, 0.0); + } + // (laid out on the glass as the drops are, `pane_proj`: the film's own coordinates + // drew the crystals and the drifts out long on the windscreen) + let b = pane_base(in.world, in.local, in.normal, false); + let an = abs(b.nl); + let axis = select(select(1, 0, an.y >= an.x), 2, an.z > max(an.x, an.y) * 2.0); + let m = pane_proj(b, axis).q; + let t = camera.post.y; + let front = material.wipe_bounds.z > 0.0; + let heat = select(0.15, 0.45 + 0.55 * clamp(defrost / 0.85, 0.0, 1.0), front); + var flakes = 0.0; + var melt_water = 0.0; + for (var layer = 0; layer < 2; layer = layer + 1) { + let fl = f32(layer); + let cell = select(0.012, 0.022, layer == 1); + let p = m / cell + fl * 37.0; + let c = floor(p); + let tm = rain_hash(c + vec2(5.0, 1.0 + fl)); + let life = mix(40.0, 7.0, heat) * (0.6 + 0.8 * tm.y); + let cycle = t / life + tm.x; + let ph = fract(cycle); + let arrival = c + floor(cycle) * vec2(19.0, 47.0); + let h = rain_hash(arrival); + let h2 = rain_hash(arrival + vec2(91.0, 13.0)); + // (a crystal shows once the cover passes its own threshold: they come one by one) + let shown = clamp((cover * select(1.15, 0.85, layer == 1) - h2.y) * 12.0, 0.0, 1.0) * smoothstep(0.0, 0.02, ph); + // the second half of its while it melts: it rounds off, shrinks and goes clear + let melt = smoothstep(0.45, 0.95, ph); + let d = p - (c + 0.25 + 0.5 * h); + let dl = length(d); + let r = (0.16 + 0.2 * h2.x) * (1.0 - 0.5 * melt); + // six arms, the rim reaching out along them + let arm = pow(abs(cos(3.0 * atan2(d.y, d.x) + h.x * 6.283185)), 4.0); + let rr = r * (0.55 + 0.45 * mix(arm, 1.0, melt)); + let edge = 1.0 - smoothstep(rr * 0.7, rr, dl); + flakes = max(flakes, shown * edge * (0.6 + 0.4 * h.x) * (1.0 - melt)); + melt_water = max(melt_water, shown * edge * melt * (1.0 - smoothstep(0.92, 1.0, ph))); + } + // settled snow is never even: a smooth noise of a few centimetres and a finer one break + // up where the layer closes and give the bank and the drifts their ragged edges + let lumps = snow_noise(m / 0.045) * 0.65 + snow_noise(m / 0.012 + 7.0) * 0.35; + var drift = 0.0; + if (front) { + // (by the height in the bus's own frame, not by the wiper mask's `wipe_uv`: a + // windscreen's film is several slots - each wiper's field and the glass round them - + // each with its own mask and its own 0 .. 1, and a bank laid along their edges drew + // seams down the middle of the windscreen and round the wipers' arcs) + if (camera.inside_c.w > 0.5) { + let low = 1.0 - (fz * 0.5 + 0.5); + drift = smoothstep(0.5, 0.75, low + 0.12 * (lumps - 0.5)) * smoothstep(0.1, 0.6, cover); + } + } + let c = cover * (0.7 + 0.6 * lumps) * (1.0 - 0.3 * heat) + drift * 0.9; + let sheet = smoothstep(0.5, 1.2, c) * 0.75 + smoothstep(1.0, 1.7, c) * 0.22; + let white = mix(vec3(0.9, 0.92, 0.96), vec3(0.97, 0.98, 1.0), smoothstep(1.0, 1.8, c)); + let solid = max(flakes * 0.92, sheet); + // (the melt water: a faint clear bead, the street a shade darker through it) + let wet = melt_water * 0.16 * (1.0 - solid); + let alpha = clamp(solid + wet, 0.0, 0.97); + let col = (white * solid + vec3(0.5, 0.55, 0.6) * wet) / max(solid + wet, 1e-4); + return vec4(col, alpha); +} + +// The rain on a pane that has no film of its own to carry it (`glass_film`): the windows of +// the traffic's cars and buses, seen from the street. OMSI gives only some buses a rain film, +// and only the player's own wets it, so every other window stayed dry and clear in a downpour. +// The same drops and runners (`glass_water`), as wet as the roads (`camera.shadow.w`); none +// on the player's own bus, whose films carry its rain. +fn pane_rain(world: vec3, local: vec3, n: vec3) -> GlassWater { + let wet = clamp(camera.shadow.w * 1.3, 0.0, 1.0); + let own = near_player_vehicle(world) > 0.5; + let far = distance(world, camera.cam_pos.xyz) > 80.0; + let w = select(wet, 0.0, own || far); + return glass_water(world, local, n, w, camera.post.y, false); +} + +// The pane's colour `rgb` and cover `a` under that rain (`vn` towards the eye): the drops, +// small lenses darker than the glass round them with the sky mirrored on their domes +// (`refl`, what the dome mirrors), and between them the wet film, a little milky +// (`haze`, the daylight it scatters) and less see-through. +fn pane_rain_compose(g: GlassWater, rgb: vec3, a: f32, vn: vec3, refl: vec3, haze: vec3) -> vec4 { + let cosv = clamp(abs(dot(g.n, vn)), 0.0, 1.0); + let f = 0.02 + 0.98 * pow(1.0 - cosv, 5.0); + let drop = mix(rgb * 0.7, refl, clamp(f * 3.0, 0.15, 0.8)); + var c = mix(rgb, drop, g.cover * 0.85); + let film = clamp(g.veil * 0.35 + g.mist * 0.2, 0.0, 0.5); + c = mix(c, haze, film); + let a2 = clamp(a + (1.0 - a) * (g.cover * 0.5 + film), a, 1.0); + return vec4(c, a2); +} + +@fragment +fn fs_main(in: FsIn) -> @location(0) vec4 { + var unused = 0.0; + return shade_vanilla(in, &unused, camera.cam_pos.xyz); +} + +// Shared with Enhanced and the wheel splash mask: pools spread as the road soaks. +fn road_puddle_coverage(world: vec3, normal: vec3, wet: f32) -> f32 { + let xy = world_pattern_xy(world); + let pn = vnoise_f(xy, 0.35, vec2(17.3, -9.1)) * 0.6 + + vnoise_f(xy, 1.6, vec2(-4.0, 8.0)) * 0.3 + + vnoise_f(xy, 5.0, vec2(2.7, 11.3)) * 0.1; + // The pools spread from the lowest spots as the road soaks, but they stay pools: a road + // wet through has standing water on about a fifth of it (PUDDLE_SPREAD in enhanced.wgsl, + // the same in `omsi-app/src/puddles.rs`) and wet asphalt between. + let threshold = 1.0 - wet * PUDDLE_SPREAD; + return smoothstep(threshold - 0.02, threshold + 0.02, pn) * smoothstep(0.75, 0.95, normal.z); +} + +@fragment +fn fs_vanilla_reflections(in: FsIn) -> EnhancedOut { + var weight = 0.0; + let c = shade_vanilla(in, &weight, camera.cam_pos.xyz); + let coverage = select(c.a, 0.0, in.params2.w > 1.5); + var out: EnhancedOut; + out.color = c; + out.mask = vec4(0.0, weight * 0.49, weight, coverage); + return out; +} + +fn shade_vanilla(in: FsIn, puddle_weight: ptr, eye: vec3) -> vec4 { + // (the pane's water, read once for the uses below) + let film_water = window_wetness(in); + if (material.emissive.w > 1.5) { + // a pane's film of water: drops, not the sliding texture (`glass_film_classic`) + return glass_film_classic(in, film_water); + } + var duv = tex_address(in.uv); + if (material.extra.x > 0.5) { + // terrain: uv is tile space; the ground texture repeats extra.z times per tile + duv = in.uv * material.extra.z; + } + var tex = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv); + if (is_snow_pane()) { + // (as the enhanced picture lays it, `glass_snow_with`: no cabin air here, so no + // defroster, and the height on the glass by the bus's level frame) + let fz = clamp((in.world.z - camera.inside_a.z - camera.inside_c.z) / max(camera.inside_b.w, 0.1), -1.0, 1.0); + tex = glass_snow_with(in, film_water, 0.0, fz); + } + // The texture coordinates without the [texcoordtransX/Y] offset: in Omsi.exe's + // fixed-function pipeline the texture transform is the diffuse stage's alone, the + // transmap, night map and light map stay in place under a scrolling roller blind. + let buv = tex_address(in.uv - in.params.zw); + if (material.extra.x > 0.5 && material.extra.y > 0.0) { + // the ground texture's detail texture, repeated finer than the texture itself and + // modulated over it as the original's terrain pass does. The stock detail maps are + // bright (noise_low averages 242, gras_det 179), so they are meant to be multiplied + // in plainly: doubling like a grey-centred D3D detail map blows the ground out. + let det = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], in.uv * material.extra.y, camera.lod.x); + tex = vec4(clamp(tex.rgb * det.rgb, vec3(0.0), vec3(1.0)), tex.a); + } + if (material.params.z > 0.5) { + // [matl_transmap]: alpha comes from a separate map, its alpha channel (a map without one + // is opaque, as D3D samples it: the WH UK AI cars' paint layer has a black 24-bit + // `transmap_null.tga`, read as luminance the paint was invisible); + // for terrain the map is the per-tile surface mask in tile space + let tm = sample_transmap(buv); + tex.a = select(1.0, tm.a, material.params.w > 0.5); + if (material.extra.x > 0.5 && material.params.x > 1.5) { + // A painted ground layer. The brush mask is coarse (0.6-3 m per texel) and + // binary; the loader smooths it into a soft ramp around a smooth curve + // (`smooth_paint_mask` in scene.rs). Sharpen only that coverage ramp: + // diffuse/detail mip colours change with viewing angle, and including + // their luminance made covered ground fade into lower layers at a slant. + tex.a = smoothstep(0.32, 0.68, tex.a); + } + } + // One night-map read supplies both coverage and lighting. Keep the tile map + // in its north-up UVs; vehicle maps use the unscrolled material UVs. + var night_sample = vec4(0.0); + if (material.extra.w > 0.5) { + let nuv = select(buv, vec2(in.uv.x, 1.0 - in.uv.y), material.extra.x > 0.5); + night_sample = sample_nightmap(nuv); + } + tex.a = night_coverage(tex.a, night_sample.a) * tree_card_fade(in.world); + let mode = material.params.x; + // Mip-filtered alpha is the fraction of the pixel covered by leaves or fence wires. + // Tighten the transition around the cutout edge before MSAA turns it into sample + // coverage. The depth prepass leaves these draws out so its binary cutoff cannot hide + // the scene behind samples that the colour pass leaves open. + if (ALPHA_TEST && mode > 0.5 && mode < 1.5) { + if (ALPHA_TO_COVERAGE) { + let aa = max(fwidth(tex.a) * 0.5, 1.0 / 255.0); + // (not `ALPHA_REF - aa`: a layer whose clear glass is alpha 128 kept a third of + // its samples there, a moire of the layer's paint over every window) + if (tex.a < ALPHA_REF) { + discard; + } + tex.a = smoothstep(ALPHA_REF - aa, ALPHA_REF + aa, tex.a); + } else if (tex.a < ALPHA_REF) { + discard; + } + } + // (a blended slot that keeps Omsi.exe's alpha test, `MaterialExtra::alpha_cut`: a + // livery's clear glass is cut away, its tinted glass blended) + tex.a = select(tex.a, 0.0, mode > 2.5 && tex.a < ALPHA_REF); + let n = safe_normal(in.normal); + let ndl = max(dot(n, camera.sun_dir.xyz), 0.0); + // three lights like the original: direct sun (A), light from above (B), ambient (C) + let from_above = 0.5 + 0.5 * n.z; + let shadow = sun_shadow(in.world, n, mode > 0.5 && mode < 1.5); + // screen-space ambient occlusion darkens the indirect light (sky and ambient) in + // corners, under the bus, between the seats - not the sun, which the shadow map handles + var ao = 1.0; + // (not on a blended surface: the AO is the opaque depth's, and a translucent door + // showed the shade of what stood behind it) + if (camera.clouds.w > 0.5 && mode < 1.5) { + ao = ao_at(in.clip.xy, in.world); + } + var diffuse = camera.sun_color.rgb * camera.sun_dir.w * ndl * shadow + (camera.sky_color.rgb * from_above * (0.6 + 0.4 * shadow) + camera.ambient.xyz) * ao; + var albedo = tex.rgb; + if (camera.flags.x > 0.5 && (material.extra.x > 0.5 || in.params2.w > 0.5)) { + // detail texturing (setting): procedural grain on the ground and the roads, fading out with distance + let dist0 = distance(in.world, camera.cam_pos.xyz); + let k = clamp(1.0 - (dist0 - 25.0) / 120.0, 0.0, 1.0); + let nz = detail_noise(world_pattern_xy(in.world), k); + albedo = albedo * (1.0 + (nz - 0.5) * 0.42 * k); + } + // ([nomaplighting]: params.y 0.25 - not lit by the map's lamps) + // (a light-mapped road or plate takes the map's lamps only in Vanilla+: as OMSI 2 shows + // it, the vanilla picture lights it from the tile light map alone) + let lm_only = light_map_mapped(material.params) && camera.sky_color.w > 0.5; + // (and a [tree]'s leaf cards, params.y 0.15: OMSI 2 leaves a tree dark even right under + // a street lamp, where the lamp's 40 m core lit the crown up yellow-green) + let tree_unlamped = camera.sky_color.w > 0.5 && material.params.y > 0.1 && material.params.y < 0.2; + let map_lamps = select(1.0, 0.0, (material.params.y > 0.2 && material.params.y < 0.3) || lm_only || tree_unlamped); + let lamp_light = point_lights(in.world, n, map_lamps); + // The headlight is lit at the vertices: see `classic_spot`. + var light = diffuse + lamp_light + in.spot_diffuse + in.spot_ambient; + // D3D lights the material's diffuse colour with the sun, the light from above and the + // lamps, and its ambient colour with the ambient light (C) and the headlight's ambient + // light. Omsi.exe makes every o3d slot's ambient white (0x7c62f8), so a white sign + // texture on a green material shows white in the shade, not green. + let ambient_light = camera.ambient.xyz * ao + in.spot_ambient; + let mat_light = material.color.rgb * (light - ambient_light) + material.ambient.rgb * ambient_light; + let light_mapped = material.params2.x > 0.5 && material.extra.x < 0.5; + // The low-range Vanilla+ target has no exposure/tonemapping. Saturate the + // diffuse light before modulating the texture, as the classic path does: + // overlapping lamps must not clip a coloured texture into a white patch. + // The light is OMSI's - the envir.cfg's sun, sky and ambient and its lamps - and those + // numbers are what Direct3D multiplies into the gamma-encoded texture: it is laid on the + // encoded texture here too, as in the classic picture below. Multiplied in linear light, + // a light L showed as L^(1/2.2): the night's 0.06 as 0.28, every night, dusk and shade + // in Vanilla+ several times as bright as in OMSI 2 (#300, #1612). + var lit = srgb_decode(srgb_encode(albedo) * clamp(mat_light, vec3(0.0), vec3(1.0))); + // The vanilla picture: Omsi.exe's texture stages multiply the gamma-encoded texture by + // the vertex light (clamped at 1); here the texture is sampled linear and the target + // encodes again, so multiplied here a light L showed as L^(1/2.2) - a night at 0.06 + // looked like 0.28, a late dusk (#300). So the product is made on the encoded texture + // and decoded again, with the light map laid on encoded as well. (Through the sRGB curve + // itself: taken as a power of 2.2, t v^2.2, the curve's linear foot below 0.0031 put a + // night wall at a quarter of OMSI 2's - a texture of 0.66 under a light of 0.05 came out + // at 2 of 255 instead of 8.) + let classic = camera.sky_color.w > 0.5; + // (the terrain's night map is its tile light map: light, not a glow - see below) + let terrain_map = material.params.y < 0.5 + && material.extra.x > 0.5 + && material.extra.w > 0.5 + && material.extra.w < 1.5; + let terrain_night = classic && terrain_map; + if (classic && material.params.y < 0.5) { + var v = clamp(material.emissive.rgb + mat_light + material.color.rgb * interior_lamps(in.world, n, in.params2.z), vec3(0.0), vec3(1.0)); + if (light_mapped) { + let lm = srgb_encode(textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], buv, camera.lod.x).rgb) * clamp(in.params2.x, 0.0, 1.0); + v = v + lm * (vec3(1.0) - v); + } + if (terrain_night) { + // the terrain's tile light map lights the ground as the lamps' own light: added + // to the vertex light before the texture is multiplied in. Laid over the lit + // ground instead, as a night map glows, its faint fringe (0.01, linear) put + // one beige veil over cobbles and grass alike, a whole car park the colour of + // sand where OMSI 2 shows it dark grey. + let nm = srgb_encode(night_sample.rgb); + v = min(v + nm * camera.sun_color.w * clamp(in.params2.y, 0.0, 1.0), vec3(1.0)); + } + if (lm_only) { + // a road, a plate or a [LightMapMapping] object: the same tile light map, the + // same way as the ground beside it (Omsi.exe lights both from it alone - its + // `[maplight]`s only bake the map, 0x7903e0). Added after the texture in linear + // light instead, the pools that lay bright on the verges hardly showed on the + // asphalt between them: the street lamps lit everything but the road (#847). + let lm = srgb_encode(light_map_at(in.world)); + v = min(v + lm * camera.sun_color.w, vec3(1.0)); + } + lit = srgb_decode(srgb_encode(albedo) * v); + } else if (light_mapped) { + // [matl_lightmap], as Omsi.exe's texture stages have it (0x7fe4d3..0x7fe604): the + // light map is laid onto the vertex light with D3DTOP_ADDSMOOTH (light + map x (1 - + // light)) before the texture is multiplied in - a lit saloon glows at night and + // hardly shows in daylight. The vertex light is D3D's: the material's emissive and + // its colour times every light - the saloon lamps (`[interiorlight]`, D3D lights + // too, 0x5fa8f0) among them - clamped at 1. (Added once more after the map, the + // saloon lamps lit a cabin twice over, flat white where the map was full; and the + // material's colour took the map down with it.) + let lm = srgb_encode(textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], buv, camera.lod.x).rgb) * clamp(in.params2.x, 0.0, 1.0); + let v = clamp(material.emissive.rgb + mat_light + material.color.rgb * interior_lamps(in.world, n, in.params2.z), vec3(0.0), vec3(1.0)); + lit = srgb_decode(srgb_encode(albedo) * (v + lm * (vec3(1.0) - v))); + } + // the D3D material's own highlight (specular colour and power of the o3d file or a + // [matl_allcolor]), lit at the vertices (see `vertex_specular`) and added after the + // texture as D3D's specular is; the sun's not in its shadow + let specular = in.spec_sun * shadow + in.spec_sky; + if (classic) { + // D3D adds its vertex specular after the encoded texture stages. Adding + // it in linear light encoded it again at the target and washed out dusk. + lit = srgb_decode(min(srgb_encode(lit) + specular, vec3(1.0))); + } else { + lit = lit + specular; + } + if (material.params.y > 0.5) { + lit = tex.rgb * material.color.rgb; + } + if ((!light_mapped && !classic) || material.params.y > 0.5) { + lit = lit + tex.rgb * material.emissive.rgb; + } + // [interiorlight]: the saloon lamps on the meshes and passengers they illuminate (in + // a light-mapped material's vertex light already, above) + if (!light_mapped && !classic) { + lit = lit + tex.rgb * interior_lamps(in.world, n, in.params2.z); + } + // (Vanilla+: the map's lamps light the ground, as they light the roads) + if (material.extra.w > 0.5 && !terrain_map) { + // [matl_nightmap]: self-illumination that fades in with the night + // terrain: the tile light map in tile space (north at the top row) + // a [matl_item] night map is switched by its variable (warning lamps, displays): + // it glows whenever that is on, by day as well; the others fade in with the night + let night = select(rain_lit_windows(in.local), 1.0, material.extra.w > 1.5); + lit = lit + night_sample.rgb * night * select(clamp(in.params2.y, 0.0, 1.0), 1.0, material.extra.w > 1.5); + } + if (material.params2.y > 0.0) { + // [matl_envmap]: sphere map reflection, masked by the diffuse alpha like the original + let vdir = normalize(in.world - eye); + var env_uv = in.env_uv; + if (material.bump.y > 0.5) { + env_uv = env_uv + bump_offset(duv); + } + let env = textureSample(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], env_uv); + let diffuse_a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv).a; + if (material.params.x < 1.5) { + // rain: a painted body goes darker and glossier when it is wet, so the bus + // stands out against a grey street instead of fading into it + let env_night = select(1.0 - 0.85 * clamp(camera.sun_color.w, 0.0, 1.0), 1.0, camera.sky_color.w > 0.5); + let env_light = clamp(camera.sun_color.r * camera.sun_dir.w + camera.sky_color.r + camera.ambient.r, 0.05, 1.0) * env_night; + let wet = camera.shadow.w * weather_outside_n(in.world, n, false, in.params2.w); + lit = lit * (1.0 - 0.30 * wet); + // the water film mirrors the (overcast) sky a little, mostly at grazing + // angles; kept faint - a strong rim read as a white outline round the bus + let facing = clamp(abs(dot(vdir, n)), 0.0, 1.0); + let sheen = wet * min(material.params2.y, 1.0) * (0.05 + 0.22 * pow(1.0 - facing, 5.0)); + lit = mix(lit, camera.sky_color.rgb * env_light, sheen); + } + // Omsi.exe's environment stage (0x7fd6c4 at 0x7ff626, fixed function), for paint + // and glass alike: the sphere map's colour as it is, over what the stages before + // made of the lit texture - D3DTOP_LERP by the texture factor when the material has + // neither a [matl_transmap] nor a [matl_envmap_mask], D3DTOP_BLENDCURRENTALPHA when + // it has one - and the alpha left as the stages before made it (ALPHAARG1 CURRENT, + // SELECTARG1, 0x7ff98a): a clear pane shows its reflection as faintly as it shows + // itself. (A glass path of our own - a quarter reflection at least, a Fresnel rim + // and the pane made opaque where it reflected - mirrored the street in every + // window far more than the original does.) The factor is [matl_envmap]'s times + // the ambient light plus `g` (the light the vehicle stands in: the lamps of the + // tile's light map and the sky), each at most 1, packed into a D3DCOLOR without + // saturation (0x7ff8ed: a factor over 1 spills its bits into the next channel, as + // there). The alpha it blends by is the mask's, or the diffuse texture's times `g` + // (0x7feacc, 0x7ff092) - never the diffuse alpha of a material without one of + // them: taken as a reflection mask, a body whose texture carries an alpha channel + // for other purposes was mirrored (dark) where that alpha was high. + // `g` (0x861ca0, set per vehicle at 0x7d8735): the mean of the light the tile's + // light map throws on it plus the day's light A (weather +0xac = the mean of + // lightcolor A, 0x75333f - by it the stars fade), at most 1 + let g = clamp(dot(lamp_light, vec3(1.0 / 3.0)) + dot(camera.sun_color.rgb, vec3(1.0 / 3.0)), 0.0, 1.0); + var kk = vec3(0.0); + if (has_transmap_declared() || has_env_mask()) { + let a = select(diffuse_a, textureSampleBias(mx_tex2d[mx_mat.envmask], mx_samplers[mx_mat.sampler], duv, camera.lod.x).a, has_env_mask()); + kk = vec3(a * g); + } else { + kk = omsi_texture_factor(material.params2.y, camera.ambient.rgb + vec3(g)); + } + // The lerp is made on the encoded values, as the stage makes it, like the texture x + // light product above: made on linear ones it showed the reflection about twice as + // bright over a dark surface - since the nights got dark (#300) the instrument glass + // of the MAN NL/NG (Fenster.tga, factor 0.5, the sky at the sphere map's bottom) lay + // milky white over the unlit gauges. (Vanilla+ as well: its linear lerp laid the + // sphere map as a grey sheen over every dark window band and chassis, #780.) + // The sphere map's colour as it is, as the stage takes it: the night already weakens + // the reflection through the factor (`kk`, the ambient light and `g`). Darkened once + // more by that light, as a photograph lit by the night, the reflection went twice + // and the paint and the windows lost their shine at dusk and by night, which they + // keep in OMSI (#2284). + lit = srgb_decode(mix(srgb_encode(lit), srgb_encode(env.rgb), kk * camera.cam_pos.w)); + } + // wet road: a surface whose texture carries [moisture] darkens under rain and starts + // to mirror the sky, strongest where you look along it (the Fresnel sheen that makes a + // wet street read as wet) + let outside = weather_outside_n(in.world, n, material.extra.x > 0.5, in.params2.w); + let wet = camera.shadow.w * material.params2.z * outside * (1.0 - clamp(camera.ambient.w, 0.0, 1.0)); + if (wet > 0.0) { + let vdir = normalize(in.world - eye); + let facing = clamp(-dot(vdir, n), 0.0, 1.0); + let fresnel = pow(1.0 - facing, 4.0); + let puddle = road_puddle_coverage(in.world, n, wet); + let water = 0.02 + 0.98 * pow(1.0 - facing, 5.0); + let weight = clamp(mix(fresnel * wet * 0.85, water * wet, puddle), 0.0, 0.9); + let sheen = camera.sky_color.rgb * 0.5 + camera.sun_color.rgb * camera.sun_dir.w * 0.35; + if (classic) { + // Vanilla blends encoded weather colours, but asphalt darkening + // must stay in linear light to avoid turning the road black. + lit = srgb_decode(mix(srgb_encode(lit * mix(1.0, 0.75, wet)), sheen, weight)); + } else { + lit = mix(lit * mix(1.0, 0.55, wet), sheen, weight); + } + *puddle_weight = weight * puddle; + } + // snow: the ground, the roads and every upward-facing surface whiten under it + // (not on a shadow blob: whitened, it lit the snow under the bus instead of shading it) + // (not in vanilla: OMSI 2 shows snow only through the season's WinterSnow textures) + // (nor on a texture that is the season's snow picture: the map's own WinterSnow + // textures show the snow as OMSI 2 does, and whitened over, the snowy grass and the + // grey road went one flat white, the lane markings left standing in it, #879) + let snow_ok = outside * select(1.0, 0.0, in.params2.w > 1.5 || camera.sky_color.w > 0.5 || material.ambient.w > 0.5); + // a carriageway (a [moisture] texture that is not the terrain) under snow that builds + // up: its own cover, the ruts of the lanes and the tyres' tracks (road_snow.wgsl) + let carriageway = material.extra.x < 0.5 && material.params2.z > 0.0 && road_snow_dynamic(); + var rs = vec3(0.0); + if (carriageway && snow_ok > 0.0) { + rs = road_snow(in.world); + } + // a vehicle's part: the snow its own roof has gathered, where that is kept (another + // player's bus keeps the weather's) + let vehicle = vehicle_snow_kept(in.params2.w); + var on_vehicle = 0.0; + if (vehicle && snow_ok > 0.0) { + on_vehicle = vehicle_snow(in.params2.w, in.local); + } + let snow = select(select(camera.ambient.w, rs.x, carriageway), on_vehicle, vehicle) * snow_ok; + if (snow > 0.0 || rs.y > 0.0) { + let up = clamp(n.z, 0.0, 1.0); + let ground = select(0.0, 1.0, material.extra.x > 0.5 || material.params2.z > 0.0); + // (a road kept clear - "snow on road" off - stays asphalt, #1362; built-up snow + // brings its own cover) + let cleared = select(1.0, 0.0, !carriageway && camera.post.z > 0.5 && material.extra.x < 0.5 && material.params2.z > 0.0); + // only surfaces that really face up get a cover; a soft threshold keeps the snow + // off the sides and off the grazing rims that showed as a white outline + let cover = cleared * snow * clamp(max(ground, smoothstep(0.78, 0.95, up) * 0.8), 0.0, 1.0); + let light = camera.sun_color.rgb * camera.sun_dir.w * ndl * shadow * 0.6 + camera.sky_color.rgb * 0.7 + camera.ambient.xyz; + let white = vec3(0.92, 0.94, 0.98) * light * ao; + // (a vehicle's gathered snow lies thick enough to hide the paint: the ground's + // dusting lets the texture show through) + lit = mix(lit, white, min(cover * select(0.55 + 0.35 * tex.a, 1.2, vehicle), 1.0)); + // the slush in the ruts and the tracks: wet, grey, darker than the snow beside it + lit = mix(lit, lit * 0.6 + white * 0.12, rs.y * snow_ok); + } + let dist = distance(in.world, camera.cam_pos.xyz); + let f = 1.0 - exp(-fog_distance(in.world) * camera.fog.w); + *puddle_weight *= 1.0 - clamp(f, 0.0, 1.0); + var rgb = mix(lit, camera.fog.xyz, clamp(f, 0.0, 1.0)); + if (classic) { + // D3D's fixed-function fog blends the encoded vertex fog colour too. + // Treating that colour as linear raised a mid-grey fog from 128 to 188. + rgb = srgb_decode(mix(srgb_encode(lit), camera.fog.xyz, clamp(f, 0.0, 1.0))); + } + if (camera.flags.z > 0.0) { + // Never taken: flags.z (the old enhanced look's aerial perspective) is always 0 + // now - the enhanced path has its own fragment shader (enhanced.wgsl). The branch + // stays because Metal's fast-math contracts the fog mix above differently without + // it, and the vanilla picture is to stay what it was to the last code value. + let vdir = normalize(in.world - camera.cam_pos.xyz); + let towards_sun = clamp(dot(vdir, camera.sun_dir.xyz), 0.0, 1.0); + let k = (1.0 - exp(-dist * 0.00045)) * camera.flags.z * (0.55 + 0.45 * clamp(camera.sun_dir.w, 0.0, 1.0)); + let scatter = mix(camera.sky_color.rgb * 1.4 + camera.ambient.rgb * 0.5, camera.sun_color.rgb * camera.sun_dir.w + camera.sky_color.rgb, towards_sun * towards_sun); + rgb = mix(rgb, scatter, clamp(k * 0.6, 0.0, 0.5)); + } + // (a NaN anywhere above - a zero-length vector normalised, 0 x infinity - was a black + // patch on Windows, e.g. an EN92's headlights while off, and invisible on the Mac) + rgb = finite_or(rgb, finite_or(albedo * material.color.rgb * diffuse, albedo)); + var a = tex.a * material.color.a; + if (mode < 0.5) { + a = 1.0; + } + if (!is_snow_pane()) { + a = a * clamp(film_water, 0.0, 1.0); + } + if (mode > 1.5 && min(material.emissive.r, min(material.emissive.g, material.emissive.b)) > 0.99 && material.emissive.w < 1.5) { + a = encoded_blend_alpha(rgb, a, light); + } + if (material.emissive.w > 0.5 && material.emissive.w < 1.5) { + // a pane in the rain without a film of its own (`pane_rain`): the traffic's windows + let g = pane_rain(in.world, in.local, in.normal); + if (g.cover > 0.001 || g.veil > 0.001 || g.mist > 0.001) { + let vn = normalize(camera.cam_pos.xyz - in.world); + let o = pane_rain_compose(g, rgb, a, vn, rain_env_vanilla(reflect(-vn, g.n)), rain_env_vanilla(vec3(0.0, 0.0, 0.5)) * 0.9); + rgb = o.rgb; + a = o.a; + } + } + return vec4(rgb, a); +} + +// What lies under a self-lit layer, for `encoded_blend_alpha`: a surface of this encoded +// brightness lit by the light at the layer (the road's asphalt under the KVB Citaro's +// light cone is 0.44 - 0.49 encoded). +const BLEND_GROUND_ENCODED: f32 = 0.45; + +// A self-lit blended layer (emissive white: a light cone laid on the road, a glow) as +// Omsi.exe blends it: Direct3D 9 mixes the gamma-encoded colours, the sRGB target here mixes +// linear ones, and a faint layer came out far brighter - the KVB Citaro's `lichtkegel.o3d` +// (alpha 0.14 on average) a flat beige sheet over the road where OMSI 2 shows a soft pool, +// 120 of 255 against its 85. The target cannot be read, so what is under the layer is taken +// to be ground lit by the light here (`light`, the vertex light the layer would have): +// the alpha is the one that gives Omsi.exe's encoded mix over it, never more than the +// layer's own. +fn encoded_blend_alpha(rgb: vec3, a: f32, light: vec3) -> f32 { + let w = vec3(0.2126, 0.7152, 0.0722); + let s = max(rgb, vec3(0.0)); + if (a <= 0.0) { + return a; + } + let d_enc = clamp(light, vec3(0.0), vec3(1.0)) * BLEND_GROUND_ENCODED; + let d = dot(srgb_decode(d_enc), w); + let over = dot(srgb_decode(srgb_encode(s) * a + d_enc * (1.0 - a)), w); + let span = dot(s, w) - d; + if (span < 1e-4) { + return a; + } + return clamp((over - d) / span, 0.0, a); +} + +// The rain film on a pane in the classic pictures: the drops, the runners and the blur of the +// wet glass as the enhanced picture draws them (`glass_water`, enhanced/07_glass.wgsl +// `glass_film`), lit by the classic picture's own sky (`rain_env_vanilla`). Without the +// cabin's air there is no condensation behind them. +fn glass_film_classic(in: FsIn, water: f32) -> vec4 { + let v = camera.cam_pos.xyz - in.world; + let dist = length(v); + let vn = v / max(dist, 1e-4); + let in_cab = inside_vehicle(camera.cam_pos.xyz) * near_player_vehicle(in.world) > 0.5; + let g = glass_water(in.world, in.local, in.normal, water, camera.post.y, in_cab); + if (g.cover <= 0.001 && g.mist <= 0.001 && g.veil <= 0.001) { + return vec4(0.0); + } + let has_picture = camera.flags.z < -0.5; + let dims = vec2(textureDimensions(mx_tex2d[mx_mat.env])); + let uv0 = in.clip.xy / dims; + let mist_col = rain_env_vanilla(vec3(0.0, 0.0, 0.5)) * 0.9; + // the view through the wet glass between the drops, softened by the film of water + let veil_lod = log2(max(dims.y * mix(0.002, 0.006, clamp(g.veil / 0.3, 0.0, 1.0)), 1.0)); + var behind = mist_col; + if (has_picture) { + behind = finite_or(glass_blur(uv0, veil_lod), mist_col); + } + // a drop: a small lens, the street small and upside down in it, darker at its rim + var drop_col = behind; + var a_drop = 0.0; + if (g.cover > 0.001) { + // (bent by the dome, the way out of the drop is looked up where it meets the street a + // few metres on - not a fixed share of the screen aside, which from the driver's seat + // landed on the dark dashboard and the pillars and drew every drop as a black speck: + // the classic pictures keep no depth to tell those from the street) + let tilt = g.n - g.out * dot(g.n, g.out); + let thr = normalize(-vn - tilt * 0.9); + var seen = behind; + let cp = camera.view_proj * vec4(in.world + thr * 6.0, 1.0); + if (has_picture && cp.w > 0.05) { + let ndc = cp.xy / cp.w; + let uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + let inside = smoothstep(0.0, 0.06, min(min(uv.x, 1.0 - uv.x), min(uv.y, 1.0 - uv.y))); + let far = finite_or(glass_blur(clamp(uv, vec2(0.001), vec2(0.999)), 0.8 + 1.5 * g.mist), behind); + seen = mix(behind, far, inside); + } + let rim = smoothstep(0.55, 1.0, g.rim); + let facing = dot(g.out, vn) > 0.0; + let cosv = clamp(abs(dot(g.n, vn)), 0.0, 1.0); + let f = select(0.02, 0.02 + 0.98 * pow(1.0 - cosv, 5.0), facing); + var c = seen * (1.0 - 0.45 * rim) * (1.0 - f) + rain_env_vanilla(reflect(-vn, g.n)) * f; + if (facing) { + let r = reflect(-vn, g.n); + c = c + camera.sun_color.rgb * camera.sun_dir.w * pow(max(dot(r, camera.sun_dir.xyz), 0.0), 900.0) * f * 60.0; + } + let detail = smoothstep(0.5, 1.6, g.size_px); + drop_col = mix(behind * 0.93, c, detail); + a_drop = g.cover * mix(select(0.15, 0.5, has_picture), 0.95, detail) * (1.0 - smoothstep(5.0, 15.0, dist)); + } + let a_mist = g.mist * 0.5; + var a_veil = 0.0; + if (g.veil > 0.001 && has_picture) { + a_veil = g.veil * (1.0 - smoothstep(25.0, 60.0, dist)); + } + let a_under = a_veil + a_mist * (1.0 - a_veil); + let under = (behind * a_veil + mix(mist_col, behind, 0.9) * a_mist * (1.0 - a_veil)) / max(a_under, 1e-4); + let a = a_drop + a_under * (1.0 - a_drop); + if (a <= 1e-4) { + return vec4(0.0); + } + let col = (drop_col * a_drop + under * a_under * (1.0 - a_drop)) / a; + return vec4(min(col, vec3(1.5)), a); +} + +// Snow on the carriageways: how far it has built up, the ruts the traffic keeps in it and +// the fresh tracks the tyres press into it (see `Renderer::set_snow_track_rect`). +// +// The field is a square of `place.z` metres that wraps around the world (a torus): texel +// (i, j) holds the world's point (x, y) where floor(x / texel) and floor(y / texel) are i and +// j modulo its size, so the app only rewrites the tiles the camera moves into. It is kept +// tile after tile (`TRACK_TILE` texels a side), each row after row, a texel an RGBA8 word: +// r: the ruts of the lanes' wheel tracks (0..1) +// g: a tyre has pressed the snow here (how much of the texel it covered) +// b, a: how much snow had fallen when a tyre last ran here (16 bits, see `state.y`; for +// a rut no tyre has run in yet, a moment as long ago as its lane's traffic makes +// likely): the track and the rut fill as more falls + +struct SnowTrack { + // xy: the render origin modulo the field's side (m), z: the side (m), w: 1 while the + // field holds the area around the camera + place: vec4, + // x: how far the snow covers the roads (0..1; below 0 the weather's "snow on road" + // decides, as before), y: the snow fallen so far (thousandths of a full cover, modulo + // 65536), z: how deep the lanes' ruts show (0..1), w: how far it thaws to slush (0..1; + // Enhanced alone, 0 on the other paths) + state: vec4, +}; + +@group(0) @binding(20) var snow_track_px: array; +@group(0) @binding(21) var snow_track: SnowTrack; + +const TRACK_TEXELS: i32 = 2048; +const TRACK_TILE: i32 = 256; + +// One texel's rut and fresh track, each filled by the snow fallen since a tyre last ran +// over it. +fn snow_track_texel(p: vec2) -> vec2 { + let q = ((p % TRACK_TEXELS) + TRACK_TEXELS) % TRACK_TEXELS; + let tile = (q.y / TRACK_TILE) * (TRACK_TEXELS / TRACK_TILE) + q.x / TRACK_TILE; + let i = (tile * TRACK_TILE + q.y % TRACK_TILE) * TRACK_TILE + q.x % TRACK_TILE; + let t = unpack4x8unorm(snow_track_px[i]); + let then = round(t.b * 255.0) * 256.0 + round(t.a * 255.0); + let since = (snow_track.state.y - then + 65536.0) % 65536.0; + // (a track begins to blur after 8 % of a cover has fallen on it and is gone at 28 %; a + // rut, worn deeper by the traffic, begins to fill at 15 % and is gone at 52 % - in a + // heavy snowfall (Starker Schneefall) one or two minutes, and four or seven, without a + // car: a driver who waits that long at a stop sees it happen) + let fresh = t.g * (1.0 - smoothstep(80.0, 280.0, since)); + let rut = t.r * (1.0 - smoothstep(150.0, 520.0, since)); + return vec2(rut, fresh); +} + +// The rut (x) and the fresh track (y) at a point of the render frame, blended between the +// four texels around it (each decoded first: the fill time does not blend). +// +// Faded out from 75 m off and not read beyond 90: the tiles the field takes as the camera +// moves lie 96 m off and more, and hold what they held before until their ruts are drawn +// a few frames later (see `SnowTracks::update`) - and a rut that far is a pixel or two. +fn snow_track_at(world: vec2) -> vec2 { + let fade = 1.0 - smoothstep(75.0, 90.0, distance(world, camera.cam_pos.xy)); + if (snow_track.place.w < 0.5 || fade <= 0.0) { + return vec2(0.0); + } + let q = (world + snow_track.place.xy) * (f32(TRACK_TEXELS) / snow_track.place.z) - 0.5; + let b = floor(q); + let f = q - b; + let i = vec2(b); + let a00 = snow_track_texel(i); + let a10 = snow_track_texel(i + vec2(1, 0)); + let a01 = snow_track_texel(i + vec2(0, 1)); + let a11 = snow_track_texel(i + vec2(1, 1)); + return mix(mix(a00, a10, f.x), mix(a01, a11, f.x), f.y) * fade; +} + +// Whether a part's surface code carries its roof's own snow (`vehicle_snow`) rather than +// leaving it to the weather's (a roof the roads' snow does not keep: another player's bus). +fn vehicle_snow_kept(code: f32) -> bool { + return code < -10000.0 && road_snow_dynamic(); +} + +// The snow on a vehicle's part (`code`: its instance's surface code, whose ten thousands +// carry how much snow its roof has gathered, 1..41 for 0..1, see upload.rs `roof_code`), +// at `local`, the point in the part's own mesh: patches at first, a closed layer as it +// goes on, laid out on the vehicle so that they ride with it. +fn vehicle_snow(code: f32, local: vec3) -> f32 { + let amount = (floor(-code / 10000.0) - 1.0) / 40.0; + let level = amount * 1.3 - 0.12; + // (bare, or closed over whatever the patches: no noise to sample) + if (amount <= 0.0) { + return 0.0; + } + if (level >= 1.08) { + return 1.0; + } + let p = local.xy; + let p2 = vec2(p.x * 0.8 - p.y * 0.6, p.x * 0.6 + p.y * 0.8); + let patches = vnoise_f(p, 0.9, vec2(4.3, 1.9)) * 0.65 + vnoise_f(p2, 3.1, vec2(8.1, 6.7)) * 0.35; + return smoothstep(patches - 0.3, patches + 0.08, level); +} + +// Whether the roads' snow is the built-up kind (`state.x` at or above 0) rather than the +// weather's on/off "snow on road". +fn road_snow_dynamic() -> bool { + return snow_track.state.x >= 0.0; +} + +// The snow on a carriageway at `world` (render frame): x the cover (0..1), y the slush in +// the ruts (0..1: the wheels keep it wet and grey), z a fresh tyre track (0..1). +fn road_snow(world: vec3) -> vec3 { + let base = clamp(snow_track.state.x, 0.0, 1.0); + if (base <= 0.0) { + return vec3(0.0); + } + // the map's own coordinates (modulo the pattern's period): the patches stay put + let m = world.xy + camera.world_origin.xy; + // It does not settle evenly: first a dusting in patches a stride or two across and in + // the grain of the asphalt, which close up as it goes on falling. + // (three octaves, the finer ones turned against the coarse: a single lattice's cells + // showed as square blots where the cover's edge ran through them) + // (once the cover has closed - its level over the patches' highest - every pixel of the + // road paid for three octaves of noise that changed nothing) + let m2 = vec2(m.x * 0.8 - m.y * 0.6, m.x * 0.6 + m.y * 0.8); + let level = base * 1.35 - 0.15; + var cover = 1.0; + if (level < 1.1) { + let m3 = vec2(m.x * 0.28 + m.y * 0.96, m.y * 0.28 - m.x * 0.96); + let patches = vnoise_f(m, 0.45, vec2(3.1, 7.7)) * 0.55 + vnoise_f(m2, 1.3, vec2(11.3, 2.9)) * 0.3 + vnoise_f(m3, 3.7, vec2(5.9, 13.1)) * 0.15; + cover = smoothstep(patches - 0.35, patches + 0.1, level); + } + let tracks = snow_track_at(world.xy); + // The ruts: the wheels of the traffic keep two strips of each lane down to slush, the + // more of it the more snow there is to churn; with a mere dusting they show the asphalt. + let rut = tracks.x * snow_track.state.z; + let slush = rut * smoothstep(0.15, 0.7, base); + cover = cover * (1.0 - rut * 0.85); + // A fresh track: the tread pressed the snow flat and grey. Its edge sharpened from the + // texels' blend (a soft ramp over a whole texel read as a blur), and the pressed snow + // grainy - the tread's blocks, as fine as the eye can still tell apart. + let edge = smoothstep(0.2, 0.75, tracks.y); + var track = 0.0; + if (edge > 0.0) { + track = edge * (0.75 + 0.25 * vnoise_f(m2, 14.0, vec2(1.7, 9.3))); + } + cover = cover * (1.0 - track * 0.6); + var wet = max(slush, track * 0.5 * base); + // Thawing (rain on it, or a wet road, while no fresh snow falls): what is left goes grey + // and soaked, and it breaks up - the thin patches first, in the grain of a smooth noise + // a few strides across - into slush over the wet asphalt. + let thaw = clamp(snow_track.state.w, 0.0, 1.0); + if (thaw > 0.0 && cover > 0.0) { + let n = vnoise_f(m, 1.1, vec2(6.1, 2.3)) * 0.6 + vnoise_f(m2, 4.3, vec2(9.7, 4.1)) * 0.4; + let bare = smoothstep(n - 0.06, n + 0.06, thaw * 0.6 - 0.08 + 0.3 * (1.0 - base)); + let left = cover * (1.0 - bare); + wet = max(wet, (cover - left) * 0.7 + left * thaw * 0.8); + cover = left * (1.0 - 0.55 * thaw); + } + return vec3(cover, wet, track); +} + +// Enhanced graphics: what the enhanced main pass, the sky and the coronas share - the +// light of the physically based sky (see atmosphere.rs), in its units (1 = 10 000 lux), +// and the air between the camera and what it sees. The scene is drawn pre-exposed: +// radiance times `enh.exposure.x`, so that the half-float target keeps its precision by +// night as well as by day. +struct Enhanced { + // x pre-exposure, y the level unlit things are drawn at, z a lit window's radiance + // (pre-exposed), w how bright a light's corona is drawn + exposure: vec4, + // rgb irradiance of the sun after the clouds, w its angular radius (rad) + sun: vec4, + // irradiance from the sky and the ground: order-2 spherical harmonics, rgb + sh: array, 9>, + // rgb radiance of the ground, w the sky table's scale + ground: vec4, + // x weather fog extinction (1/m) at its base, y its height falloff (1/m), z the base + // height (render-origin relative), w clear-air extinction (1/m) at the ground + fog: vec4, + // rgb fog radiance from the light around it (the sun's part is added by angle), + // w the table scale the reflection probe was drawn with + fog_color: vec4, + // x wet roads, y snow cover, z rain, w cloud cover in front of the sun + weather: vec4, + // x mip levels of the probe, y illuminance of a light's core (maplight colour 1), + // z cabin light illuminance, w how much of the sun the clouds let through + lights: vec4, + // rgb the sun disc's irradiance before the clouds, w frame time (s) + sun_disc: vec4, + // x which term the main pass shows alone (OMSI_DEBUG_ENHANCED, 0 = the picture), + // y the puddles' F0, z the envmap photo's strength, w the tone curve's contrast + debug: vec4, + // xyz where the sky cube is drawn from, relative to the camera + eye: vec4, + // x how bright an LED panel's dots burn (0 = off), y whether the LED panels' `\S:n` + // masks keep their mip chain (0: at full resolution, the dots stay visible when small), z 1 + // when lights glare and glow in the night air (the settings' `light_glow`) + led: vec4, + // xyz towards the moon, w its angular radius (rad) + moon: vec4, + // rgb the moon disc's irradiance before the clouds, w how much of the starry sky shows + moon_disc: vec4, + // rgb the sun's irradiance at 1400, 2100 and 2800 m (the cumulus layer) and 7000 m + // (the high thin layer), through the atmosphere from up there + cloud_sun: array, 4>, + // rgb the moonlight on a surface facing the moon (after the clouds), w 1 while the + // shadow maps are the moon's + moon_light: vec4, + // the condensation on the player's bus's panes (optical depths): windscreen, sides, + // rear, and how far the defroster has cleared the windscreen (0..1; omsi-app + // condensation.rs) + condensation: vec4, + // x the cumulus layer's base, y its top (m over the ground), z the altocumulus cover, + // w the storm's activity + layers: vec4, + // the lightning of this frame: x the light it throws on a surface facing it (1 = 10 000 + // lux), yz towards it (horizontal unit vector), w its elevation (rad) + flash: vec4, + // xyz towards the flash (unit vector), w how bright its channel is + flash2: vec4, + // x a number the channel's shape is drawn from + flash3: vec4, + // the clouds' shadow field (cloud_field.rs): xy its middle in cloud space, z one over its + // width, w 1 when there is one + cloud_f1: vec4, + // xy what takes a world point to cloud space, z the height of the plane it is taken on, + // w the share of the sun the main pass has taken off already for the clouds over the camera + cloud_f2: vec4, + // the player's bus's pitch and roll: sin, cos of each (its panes' condensation sits on + // the glass on a slope, `pane_local`) + pane_tilt: vec4, + // Slots of the weather overhaul, one owner each (zero until it fills them): + // the volumetric clouds, the volumetric fog, the precipitation, the bus's panes, the + // surfaces' PBR and the ray tracing, and two spare. + clouds_ext: vec4, + clouds_ext2: vec4, + vol_fog: vec4, + vol_fog2: vec4, + precip_ext: vec4, + glass_ext: vec4, + // (pbr_ext: x the share of the sun's light that still comes as a beam - the rest the + // clouds scatter, `sun_scattered` - y 1 when x is set) + pbr_ext: vec4, + rt_ext: vec4, +}; +@group(0) @binding(11) var enh: Enhanced; +@group(0) @binding(13) var s_lin: sampler; +@group(0) @binding(14) var t_sky_lut: texture_2d; + +const PI: f32 = 3.14159265; + +// Irradiance from the sky and the ground on a surface facing n. +fn sh_irradiance(n: vec3) -> vec3 { + let c = enh.sh; + let e = c[0].rgb * 0.282095 + + c[1].rgb * (0.488603 * n.y) + c[2].rgb * (0.488603 * n.z) + c[3].rgb * (0.488603 * n.x) + + c[4].rgb * (1.092548 * n.x * n.y) + c[5].rgb * (1.092548 * n.y * n.z) + + c[6].rgb * (0.315392 * (3.0 * n.z * n.z - 1.0)) + c[7].rgb * (1.092548 * n.x * n.z) + + c[8].rgb * (0.546274 * (n.x * n.x - n.y * n.y)); + return max(e, vec3(0.0)); +} + +// The lightning's light on a surface facing n: half of it from the cloud overhead and +// round it (a hemisphere), half along the way to the flash itself. +fn flash_irradiance(n: vec3) -> vec3 { + if (enh.flash.x <= 0.0) { + return vec3(0.0); + } + return vec3(0.80, 0.90, 1.0) * enh.flash.x * (0.5 * (0.5 + 0.5 * n.z) + 0.5 * max(dot(n, enh.flash2.xyz), 0.0)); +} + +// Sky radiance towards d (unscaled: times enh.ground.w is the radiance). The table runs +// over the azimuth from the sun (0..π) and the elevation (denser at the horizon). +// The sky table's texture: the table (32 x 48) in its corner and the clouds' shadow field +// (192 x 192) beside it, one texel clear (cloud_field.rs `SKY_TEX_W`, `FIELD_X0`). +const SKY_TEX: vec2 = vec2(225.0, 192.0); +const SKY_TABLE: vec2 = vec2(32.0, 48.0); +const FIELD_ORIGIN: f32 = 33.0; +const FIELD_N: f32 = 192.0; + +fn sky_table_raw(d: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let ls = length(s.xy); + let ld = length(d.xy); + var az = 0.0; + if (ls > 1e-4 && ld > 1e-4) { + az = acos(clamp(dot(s.xy / ls, d.xy / ld), -1.0, 1.0)); + } + let el = asin(clamp(d.z, -1.0, 1.0)); + let v = 0.5 + 0.5 * sign(el) * sqrt(min(abs(el) / 1.5707963, 1.0)); + // (kept a half texel inside the table: its neighbours in the texture are not the sky) + let tx = clamp(vec2(az / PI, v) * SKY_TABLE, vec2(0.5), SKY_TABLE - vec2(0.5)); + return textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).rgb; +} + +// The share of the sun that reaches the point p through the clouds, as against what the main +// pass's sun (`enh.sun`) already has for the camera's own place: the cumulus layer's shadow +// field read where the sun's way through p meets the layer's middle. 1 where there is no +// field, beyond its edge and where the sun is low (the camera's own factor stands there). +fn cloud_shadow_ratio(p: vec3) -> f32 { + let s = camera.sun_dir.xyz; + if (enh.cloud_f1.w < 0.5 || s.z < 0.06) { + return 1.0; + } + let cs = p.xy + s.xy / s.z * (enh.cloud_f2.z - p.z) + enh.cloud_f2.xy; + let uv = (cs - enh.cloud_f1.xy) * enh.cloud_f1.z + vec2(0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + let w = 1.0 - smoothstep(0.36, 0.48, edge); + if (w <= 0.0) { + return 1.0; + } + let tx = vec2(FIELD_ORIGIN, 0.0) + clamp(uv * FIELD_N, vec2(0.5), vec2(FIELD_N - 0.5)); + let f = textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).r; + let ratio = min(f / max(enh.cloud_f2.w, 0.02), 6.0); + return mix(1.0, ratio, w); +} + +fn sky_table(d: vec3) -> vec3 { + return sky_table_raw(d) * enh.ground.w; +} + +// Henyey-Greenstein phase function. +fn hg_phase(c: f32, g: f32) -> f32 { + let g2 = g * g; + return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * c, 1e-4), 1.5)); +} + +// Optical depth of an exponentially thinning layer (extinction sigma at height 0, falling +// off with k per metre) along a straight path of length dist from height h0 to h1. +fn layer_depth(sigma: f32, k: f32, h0: f32, h1: f32, dist: f32) -> f32 { + if (sigma <= 0.0) { + return 0.0; + } + let a = max(h0, 0.0); + let b = max(h1, 0.0); + let dh = b - a; + if (abs(k * dh) < 1e-3) { + return sigma * dist * exp(-k * 0.5 * (a + b)); + } + return sigma * dist * (exp(-k * a) - exp(-k * b)) / (k * dh); +} + +// The air between the camera and a point dist metres away in direction dir (from the +// camera), at heights h0 (camera) and h1 (point) above the fog's base: rgb the light it +// scatters towards the camera (radiance), a what it lets through of the point. +fn air(dir: vec3, dist: f32, h0: f32, h1: f32) -> vec4 { + return air_of(dir, dist, h0, h1, 1.0); +} + +// The same with the clear air's share scaled (0 for the sky, whose table holds it already). +fn air_of(dir: vec3, dist: f32, h0: f32, h1: f32, clear: f32) -> vec4 { + let tau_fog = layer_depth(enh.fog.x, enh.fog.y, h0, h1, dist); + let tau_air = layer_depth(enh.fog.w * clear, 1.0 / 1500.0, h0, h1, dist); + let tau = tau_fog + tau_air; + let t = exp(-tau); + if (tau < 1e-5) { + return vec4(0.0, 0.0, 0.0, 1.0); + } + // clear air takes on the sky's own colour at the horizon in this direction (which + // already holds the glow round the sun); a weather fog glows with the light around it + // and brighter towards the sun + let horizon = sky_table(normalize(vec3(dir.x, dir.y, max(dir.z, 0.0) * 0.3 + 0.03))); + let fog_in = enh.fog_color.rgb + enh.sun.rgb * hg_phase(dot(dir, camera.sun_dir.xyz), 0.55) * 0.9; + let inscatter = mix(horizon, fog_in, tau_fog / tau); + return vec4(inscatter * (1.0 - t), t); +} + +// The water normal shared by shading and scene reflections. The integer hash and the +// 1000 m period match shader.wgsl, keeping the rings fixed through floating-origin moves. +fn puddle_hash(c: vec2) -> f32 { + let cells = 8000.0; + let w = c - cells * floor(c / cells); + var v = vec2(w) * 1664525u + vec2(1013904223u); + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + return f32(v.x >> 8u) / 16777215.0; +} + +// The rings the rain makes on standing water (Enhanced): xy the water's slope (a horizontal +// offset to its normal), z how much it is stirred (0..1, for its roughness as well). +// +// A falling drop sends out a short train of capillary waves: two or three rings close +// together, running out at a few decimetres a second and dying away within a hand's +// breadth. Three lattices of cells of 18 to 27 cm, turned against each other so that no grid +// shows, each take a drop now and then - the harder it rains the more often, and in more +// of them - every drop at a new place in its cell. A ring is a wave packet on its circle +// (a cosine under a Gaussian), its slope worked out exactly, and it stays inside its cell +// (no ring is cut off at a cell's edge). +fn puddle_ripple(pattern_xy: vec2, time: f32, rain: f32, coverage: f32) -> vec3 { + if (rain <= 0.001 || coverage <= 0.0) { + return vec3(0.0); + } + var slope = vec2(0.0); + var stir = 0.0; + let rate = 0.7 + 1.6 * rain; + let amp = min(1.0, 0.45 + rain) * coverage; + for (var i = 0; i < 3; i = i + 1) { + let fi = f32(i); + let size = 0.18 + 0.045 * fi; + let cs = vec2(cos(fi * 1.93), sin(fi * 1.93)); + let turned = vec2(pattern_xy.x * cs.x - pattern_xy.y * cs.y, pattern_xy.x * cs.y + pattern_xy.y * cs.x); + let q = turned / size + vec2(fi * 17.0, fi * 5.0); + let cell = floor(q); + let seed = puddle_hash(cell + vec2(fi * 311.0, 0.0)); + let tt = time * rate * (0.8 + 0.4 * seed) + seed * 7.0; + let n = floor(tt); + let age = tt - n; + let h = puddle_hash(cell + vec2(n - 97.0 * floor(n / 97.0) + 401.0, fi * 13.0 + 7.0)); + let hit = step(fract(h * 31.7), 0.3 + 0.65 * rain); + let centre = vec2(0.3) + 0.4 * vec2(h, fract(h * 13.7)); + let local = fract(q) - centre; + let r = length(local); + let radius = 0.05 + 0.24 * sqrt(age); + let d = r - radius; + let w = 0.045; + let k = 6.2831853 / 0.07; + let env = exp(-(d * d) / (w * w)); + let a = (1.0 - age) * (1.0 - age) * hit; + // the height is a * env * cos(k d): its slope along the radius + let dh = a * env * (-2.0 * d / (w * w) * cos(k * d) - k * sin(k * d)); + slope = slope - local / max(r, 1e-4) * dh / k; + stir = stir + a * env; + } + return vec3(slope * 0.03 * amp, clamp(stir * amp, 0.0, 1.0)); +} + +// The rings as a picture whose pixel covers `fp` metres of the water sees them: their +// slopes are a few centimetres long, and a pixel (or a puddle ray standing for several) +// wider than half of that lands on a ring's crest one frame and its trough the next - the +// water's picture trembled and broke into blocks. Faded out there, the rings leave their +// stir (the roughness) and the reflection keeps still. +fn puddle_ripple_seen(pattern_xy: vec2, time: f32, rain: f32, coverage: f32, fp: f32) -> vec3 { + let fade = 1.0 - smoothstep(0.012, 0.035, fp); + let r = puddle_ripple(pattern_xy, time, rain, coverage); + return vec3(r.xy * fade, r.z); +} + +// The classic rings (Vanilla+'s puddle reflections): one lattice of 12.5 cm cells. +fn puddle_ripple_classic(pattern_xy: vec2, time: f32, rain: f32, coverage: f32) -> vec3 { + let cell = floor(pattern_xy * 8.0); + let seed = puddle_hash(cell); + let phase = fract(time * (0.8 + seed * 0.9) + seed * 13.0); + let local = fract(pattern_xy * 8.0) - vec2(0.5); + let ring = abs(length(local) - phase * 0.4); + let hit = step(1.0 - clamp(0.25 + 0.6 * rain, 0.0, 0.9), fract(seed * 31.7)); + let strength = (1.0 - smoothstep(0.0, 0.06, ring)) * (1.0 - phase) * rain * coverage * hit; + // Shallow rain rings disturb the image gently; steep normals break neighbouring + // reflection rays apart and make otherwise still puddles look like rough waves. + let bump = normalize(local + vec2(1e-5, 0.0)) * strength * 0.018; + return vec3(bump, strength); +} + +// `beam_shadow.wgsl` for the shaders without the lamp shadow tiles: nothing stands in a beam. +fn beam_tile(li: u32, l: PointLight) -> u32 { + return 0xffffffffu; +} + +fn beam_reaches(k: u32, x: vec3) -> f32 { + return 1.0; +} + +// Enhanced graphics: the lamps as the scene and the sky share them - a headlamp's beam +// and the light the weather's fog scatters from the lamps towards the camera (needs the +// point lights, their grid and `camera.light_grid`). + +// A headlamp's intensity towards `t` (from the lamp) by the angles of a road lamp, not +// around its axis: wide across, brightest just under the lamp's horizon where it reaches +// far down the road, weak straight down, and with a low beam a sharp cut-off above it. +// `dir` is the lamp's axis in its vehicle's floor: its rise tilts the horizon with the +// vehicle, up a ramp and down (#1897). +fn headlamp(t: vec3, dir: vec3, low: bool) -> f32 { + let fwd = normalize(dir.xy + vec2(1e-6, 0.0)); + let ahead = dot(t.xy, fwd); + if (ahead <= 0.0) { + return 0.0; + } + let across = abs(t.x * fwd.y - t.y * fwd.x) / ahead; + let wide = 0.12 * smoothstep(1.0, 0.45, across) + 0.88 * exp(-across * across / 0.06); + let rise = t.z / max(length(t.xy), 1e-3); + let tilt = dir.z / max(length(dir.xy), 1e-3); + // (the tangent of the angle under that horizon) + let drop = (tilt - rise) / max(1.0 + rise * tilt, 1e-3); + // full out to where the road is 0.06 under the lamp's horizon, then less as the cube of + // the drop and a little more: the road is lit evenly from the bumper on, a little + // brighter as far as the beam reaches, and not as one hot pool where its axis lands + var up = min(1.0, pow(0.06 / max(abs(drop), 1e-4), 3.4)); + if (low) { + up = up * smoothstep(-0.012, 0.025, drop); + return wide * up; + } + // a full beam reaches far: a narrow, bright core along the lamp's horizon + let hot = exp(-across * across / 0.012 - drop * drop / 0.0004); + return wide * up + 6.0 * hot; +} + +// The lamps' light the weather's fog scatters towards the camera (radiance, not +// pre-exposed): single scattering along the view ray from `start` to `len` metres in +// direction `d` - the glow round a street lamp in the mist, its cone under it, a bus's +// beams reaching ahead into the fog or the falling snow. The droplets scatter strongly +// forward (fog and cloud droplets of some ten micrometres: g about 0.8), so the glow is +// brightest looking towards a lamp and a cone shows faintly from the side. +// +// Each lamp is taken once, over the whole stretch of the ray within its reach, in the grid +// cell the ray's point nearest to it lies in (the ray's cells are walked through; every +// cell lists the lamps reaching into it). Along a straight ray past a point source, with +// t - t0 = h tan(phi) (h the ray's distance from the lamp, t0 where it passes nearest), +// the inverse square cancels against the path element: dt / r^2 = dphi / h, and what is +// left is the phase function over the angle, cos(theta) = -sin(phi) - a smooth integral +// taken with five Gauss-Legendre nodes, at each of which a spot's or a headlamp's beam is +// asked how much it sends that way. The fog's extinction dims the light on its way from +// the lamp and to the camera (taken at the nearest point). A beam's light, which reaches +// only part of the way, is summed along the ray instead, its steps staggered by `jitter`. +// The droplets' phase function: a strong forward peak and the back-scattered light a +// fog's lidar ratio of some 18 sr asks for (0.055 per steradian straight back) - a single +// Henyey-Greenstein lobe of g 0.8 gave a tenth of it, and a bus's own headlights lit no +// wall of fog in front of the driver. Two lobes, 0.9 of g 0.85 and 0.1 of g -0.5. +fn fog_phase(c: f32) -> f32 { + return 0.9 * hg_phase(c, 0.85) + 0.1 * hg_phase(c, -0.5); +} +const AIRLIGHT_CELLS: u32 = 16u; + +// The clear night air's own haze, which lights a lamp's halo and a headlamp's beam as the fog's +// droplets do, only fainter: the lowest hundred metres of a city's air hold its dust, exhaust +// and humidity at several times the column's average aerosol extinction (`enh.fog.w`), 1-3e-4 +// per metre (a visibility of 15-40 km). A lamp then has a soft glow round it and a low beam +// a faint cone, as in any night photograph, instead of a lit disc on a black ground. +const GROUND_HAZE_GAIN: f32 = 8.0; + +// `droplets`: how much of the weather's extinction scatters like fog (see `FogLampUniform`). +fn lamp_airlight(c: vec3, d: vec3, start: f32, len: f32, jitter: f32, droplets: f32) -> vec3 { + var sum = vec3(0.0); + let sigma0 = enh.fog.x * droplets + enh.fog.w * GROUND_HAZE_GAIN * enh.led.z; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (sigma0 < 4e-5 || cell <= 0.0 || side == 0u || len <= start) { + return sum; + } + // (past a few optical depths nothing comes back) + let end = min(len, start + 4.0 / sigma0); + let gx = array(-0.9061798, -0.5384693, 0.0, 0.5384693, 0.9061798); + let gw = array(0.2369269, 0.4786287, 0.5688889, 0.4786287, 0.2369269); + // the walk through the grid's cells along the ray's plan + let o = (c.xy - camera.light_grid.xy) / cell; + let dd = d.xy / cell; + var ix = i32(floor(o.x + dd.x * start)); + var iy = i32(floor(o.y + dd.y * start)); + let sx = select(-1, 1, dd.x >= 0.0); + let sy = select(-1, 1, dd.y >= 0.0); + let inv_x = select(1e9, 1.0 / abs(dd.x), abs(dd.x) > 1e-7); + let inv_y = select(1e9, 1.0 / abs(dd.y), abs(dd.y) > 1e-7); + var tx = select((f32(ix) - o.x) / dd.x, (f32(ix + 1) - o.x) / dd.x, dd.x >= 0.0); + var ty = select((f32(iy) - o.y) / dd.y, (f32(iy + 1) - o.y) / dd.y, dd.y >= 0.0); + if (abs(dd.x) <= 1e-7) { tx = 1e9; } + if (abs(dd.y) <= 1e-7) { ty = 1e9; } + var t = start; + for (var k = 0u; k < AIRLIGHT_CELLS; k = k + 1u) { + if (t >= end) { + break; + } + let t_out = min(min(tx, ty), end); + if (ix >= 0 && iy >= 0 && ix < i32(side) && iy < i32(side)) { + let base = (u32(iy) * side + u32(ix)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let to_l = l.pos.xyz - c; + let t0 = dot(to_l, d); + // the ray's point nearest to the lamp: taken in this cell only + let tc = clamp(t0, start, end); + if (tc < t || tc > t_out) { + continue; + } + let range = l.extra.w; + let h = length(to_l - d * t0); + if (h >= range) { + continue; + } + // A beam (a headlamp, a spot) is lit in the weather's fog only: its cone is a sliver of + // sixteen jittered steps at half size, which the fog's density hides and the clear + // air's haze shows as shimmer and soap. The lamps' halo alone has the ground haze. + let beam_lamp = l.extra.z != 0.0 || l.dir.w > -1.5; + let fog_sigma = enh.fog.x * droplets; + if (beam_lamp && enh.fog.x < 2e-4) { + continue; + } + let s0 = select(sigma0, fog_sigma, beam_lamp); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + // (inside its core a lamp is as bright as at the core's edge) + let hh = max(h, select(core * 0.7, 0.4, l.extra.z != 0.0)); + let w = sqrt(range * range - h * h); + let ta = max(start, t0 - w); + let tb = min(end, t0 + w); + if (tb <= ta) { + continue; + } + var acc = 0.0; + var half = 0.0; + if (l.extra.z != 0.0 || l.dir.w > -1.5) { + // a beam (a headlamp, a spot): lit only where its cone or cut-off lets + // it - a sliver of the angles the lamp is seen under, which the five + // nodes missed. Sixteen even steps over that angle instead (dphi = + // h dt / r^2: the inverse square is in the step). (Sixteen even steps + // along the way put the few next to the lamp, where nearly all of its + // light is, a metre or more apart: the pixels' staggered steps came + // out as a coarse checker in the fog round every headlamp.) + let pa = atan((ta - t0) / hh); + let dphi = (atan((tb - t0) / hh) - pa) / 16.0; + let tile_k = beam_tile(li, l); + for (var q = 0u; q < 16u; q = q + 1u) { + let tq = t0 + hh * tan(pa + (f32(q) + jitter) * dphi); + let to = l.pos.xyz - (c + d * tq); + let ld = to * inverseSqrt(max(dot(to, to), 1e-6)); + var beam = 0.0; + if (l.extra.z != 0.0) { + beam = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0); + } else { + beam = smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } + // (the map is looked at only where the beam shines at all, and only for + // the few lamps that have a tile: no shadows, no tile, no tap) + var reach = 1.0; + if (beam > 0.002 && tile_k < 44u) { + reach = beam_reaches(tile_k, c + d * tq); + } + acc = acc + beam * reach * fog_phase(dot(ld, d)) * dphi; + } + half = 1.0; + } else { + let pa = atan((ta - t0) / hh); + let pb = atan((tb - t0) / hh); + half = 0.5 * (pb - pa); + let mid = 0.5 * (pa + pb); + let tile_p = beam_tile(li, l); + for (var q = 0u; q < 5u; q = q + 1u) { + let phi = mid + half * gx[q]; + let tq = t0 + hh * tan(phi); + let ld = normalize(l.pos.xyz - (c + d * tq)); + var beam = 1.0; + if (l.dir.z < -0.5) { + // (a lamp in a housing: see `lamp_light`) + beam = 0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z); + } + // (a lamp with a shadow map: what stands between it and the air + // keeps its light out of that air, as the headlamps' beams) + var reach = 1.0; + if (beam > 0.002 && tile_p < 44u) { + reach = beam_reaches(tile_p, c + d * tq); + } + acc = acc + gw[q] * beam * reach * fog_phase(-sin(phi)); + } + } + // a lamp's irradiance is core^2 / r^2 of its colour's (a headlamp's 1 / r^2) + let strength = select(core * core, 1.0, l.extra.z != 0.0); + let xc = c + d * tc; + let sigma = s0 * exp(-enh.fog.y * max(xc.z - enh.fog.z, 0.0)); + let dl = distance(xc, l.pos.xyz); + let atten = exp(-layer_depth(s0, enh.fog.y, c.z - enh.fog.z, xc.z - enh.fog.z, tc - start) - sigma * dl); + sum = sum + l.color.rgb * (l.color.w * strength * acc * half / hh * sigma * atten); + } + } + t = t_out; + if (tx < ty) { + tx = tx + inv_x; + ix = ix + sx; + } else { + ty = ty + inv_y; + iy = iy + sy; + } + } + return sum * enh.lights.y; +} + +// Enhanced: the light a raindrop or a snowflake sends towards the eye - what it scatters of +// the sky's light, the sun's and the lamps' round it, the drop's strongly forward (a +// streak flashes against a lamp seen through the rain, and is next to invisible in the +// dark between the lamps), the flake's nearly every way. (Drawn at the display's level +// whatever the light, the flakes of a snowfall at night shone white in the dark, far from +// any lamp.) +fn precip_light(x: vec3, to_eye: vec3, snow: bool) -> vec3 { + // the sky's and the ground's light round it, and the sun's on a small sphere + var e = enh.fog_color.rgb * (PI / 0.9) + enh.sun.rgb * 0.25; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell > 0.0 && side > 0u) { + let f = (x.xy - camera.light_grid.xy) / cell; + let gx = i32(floor(f.x)); + let gy = i32(floor(f.y)); + if (gx >= 0 && gy >= 0 && gx < i32(side) && gy < i32(side)) { + let base = (u32(gy) * side + u32(gx)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let dl = l.pos.xyz - x; + let dist2 = dot(dl, dl); + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let ld = dl * inverseSqrt(max(dist2, 1e-6)); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var k = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + if (l.extra.z != 0.0) { + k = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + k = k * smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } else if (l.dir.z < -0.5) { + k = k * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + // (the scattering towards the eye relative to an even one: a drop's light + // goes on forwards, a flake's every way. The angle is the one between the + // light's way from the lamp, -ld, and on to the eye: taken against -to_eye + // it put the forward peak behind the drop, and the drops in a bus's own + // beams, seen from behind the lamps, shone a hundred times too bright as + // white streaks down the road ahead) + let c = dot(-ld, to_eye); + let lobe = select(fog_phase(c), 0.7 * hg_phase(c, 0.3) + 0.3 / (4.0 * PI), snow) * 4.0 * PI; + e = e + l.color.rgb * l.color.w * enh.lights.y * k * lobe; + } + } + } + return e / PI; +} + + +// Enhanced graphics: the main pass's own lighting model, the usual metal/roughness one: +// GGX (Trowbridge-Reitz) microfacets with height-correlated Smith visibility and Schlick's +// Fresnel (F0 4 % for a dielectric, its colour for a metal), their multiple scattering given +// back (Fdez-Aguera), and Lambert diffuse with the share the specular part leaves it, so that +// nothing sends out more light than falls on it. Lit by the sun (soft shadows whose penumbra +// grows with the distance to the blocker; what the clouds scatter of it as a shadowless light +// of the sky's kind), the sky and the ground (spherical harmonics, occluded by the SSAO or +// the traced occlusion), a reflection probe of the sky for the reflections (the split sum +// with Karis' analytic DFG, occluded by the AO as Lagarde has it and by the horizon of a +// normal map), point and spot lights falling off with the square of the distance, and the +// air in between. Roughness is widened by the normal's spread across the pixel (specular +// antialiasing) and held off zero for the sun's disc. OMSI's material data +// decides the surface: [matl_envmap] factor x mask is how much it reflects and how smooth +// it is, the o3d specular power how rough a surface without one is, [matl_bumpmap] bends +// the normal. Everything is drawn pre-exposed into the high-range target. + +// Only painted terrain may skip empty brush-mask pixels. +override TERRAIN_PAINT: bool = false; + +@group(0) @binding(12) var t_probe: texture_cube; + +fn d_ggx(nh: f32, a: f32) -> f32 { + let a2 = a * a; + let d = nh * nh * (a2 - 1.0) + 1.0; + return a2 / (PI * d * d); +} + +// The microfacets of a film of water over a road: the slopes of a water surface are +// Gaussian (Cox and Munk 1954), the Beckmann distribution. Its tail falls off as +// exp(-tan^2 / a^2), where GGX's falls as a^2 / tan^4: under GGX a headlamp - a hundred +// thousand candela towards the road - kept a highlight brighter than the lit road some ten +// degrees off its mirror direction, and its reflection ran as one white line from the lamp +// down to the camera. +fn d_beckmann(nh: f32, a: f32) -> f32 { + let c2 = max(nh * nh, 1e-4); + let a2 = a * a; + return exp(-(1.0 - c2) / (c2 * a2)) / (PI * a2 * c2 * c2); +} + +// Height-correlated Smith visibility (G / (4 n.l n.v)). +fn v_smith(nv: f32, nl: f32, a: f32) -> f32 { + let a2 = a * a; + let gv = nl * sqrt(nv * nv * (1.0 - a2) + a2); + let gl = nv * sqrt(nl * nl * (1.0 - a2) + a2); + return 0.5 / max(gv + gl, 1e-5); +} + +// A diffuse surface's albedo under a film of water (n = 1.33; Lekner and Dorf 1988): the +// film lets in 1 - 0.066 of diffuse light, and of what the surface scatters back up only +// 1 - 0.472 leaves through the film's top, the rest returns to the surface. +fn wet_albedo(a: vec3) -> vec3 { + return 0.934 * a * 0.528 / (vec3(1.0) - 0.472 * a); +} + +fn f_schlick(f0: vec3, c: f32) -> vec3 { + let f = pow(1.0 - clamp(c, 0.0, 1.0), 5.0); + return f0 + (vec3(1.0) - f0) * f; +} + +// The split-sum's integral of the GGX lobe over the hemisphere for a white and a black F0 +// (Karis' analytic fit of the DFG table): the reflectance is f0 * x + y. +fn dfg_ab(rough: f32, nv: f32) -> vec2 { + let c0 = vec4(-1.0, -0.0275, -0.572, 0.022); + let c1 = vec4(1.0, 0.0425, 1.04, -0.04); + let r = c0 * rough + c1; + let a004 = min(r.x * r.x, pow(2.0, -9.28 * nv)) * r.x + r.y; + return vec2(-1.04, 1.04) * a004 + r.zw; +} + +// The split-sum environment term, single scattering only. +fn env_brdf(f0: vec3, rough: f32, nv: f32) -> vec3 { + let ab = dfg_ab(rough, nv); + return f0 * ab.x + vec3(ab.y); +} + +// What a surface reflects specularly towards the eye of light from every direction, with the +// light its microfacets pass on to each other before it leaves (Fdez-Aguera 2019, after +// Kulla and Conty): rgb that reflectance (the probe's weight; one minus it is what is left +// for the diffuse part, so the two never add up to more than came in), w the factor by which +// the single-scattering lobe of a direct light falls short of it. Without the multiple +// scattering a rough metal lost up to half its light and went dark grey. +fn spec_ms(f0: vec3, rough: f32, nv: f32) -> vec4 { + let ab = dfg_ab(rough, nv); + let ess = clamp(ab.x + ab.y, 0.05, 1.0); + let fss = f0 * ab.x + vec3(ab.y); + let ems = 1.0 - ess; + let favg = f0 + (vec3(1.0) - f0) / 21.0; + let fms = fss * favg / (vec3(1.0) - ems * favg); + let comp = 1.0 + dot(f0, vec3(0.2126, 0.7152, 0.0722)) * (1.0 / ess - 1.0); + return vec4(min(fss + fms * ems, vec3(1.0)), comp); +} + +// Specular antialiasing (Tokuyoshi and Kaplanyan 2019): the spread of the normal across the +// pixel widens the lobe, so that a mirror-smooth finish on a curved, faceted or normal-mapped +// surface does not sparkle and crawl where it is smaller than a pixel. Returns the +// perceptual roughness. +fn rough_aa(rough: f32, n: vec3) -> f32 { + let dx = dpdx(n); + let dy = dpdy(n); + let variance = 0.25 * (dot(dx, dx) + dot(dy, dy)); + let kernel = min(2.0 * variance, 0.18); + let a = rough * rough; + return sqrt(sqrt(clamp(a * a + kernel, 0.0, 1.0))); +} + +// Horizon occlusion (Jimenez et al. 2016): a normal map can turn a reflection below the +// surface the geometry really has; that part of the lobe sees the surface itself, not the sky. +fn horizon_occlusion(r: vec3, geo_n: vec3) -> f32 { + let h = clamp(1.0 + 1.3 * dot(r, geo_n), 0.0, 1.0); + return h * h; +} + +// The sun's light through the clouds that is no longer a beam (`enh.pbr_ext.x` the beam's +// share, lighting/enhanced.rs `sun_directness`): what a veil or a thin deck scatters round the +// sun lies on the street as a bright dome overhead with a glow towards the sun, casting no +// shadow. It is the flux the beam would have brought to the ground (its share on a horizontal +// surface), spread so: a cloudy day's light is flat, not a weaker sun with sharp shadows. +fn sun_scattered(n: vec3, e: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let dome = 0.5 + 0.5 * n.z; + let lobe = (1.0 + dot(n, s)) / (1.0 + max(s.z, 0.0)); + return e * max(s.z, 0.0) * mix(dome, lobe, 0.4); +} + +// The beam's share of the sun's light (1 under a clear sky; 0 while the pass has not set it). +fn sun_beam_share() -> f32 { + return select(1.0, clamp(enh.pbr_ext.x, 0.0, 1.0), enh.pbr_ext.y > 0.5); +} + +// Ambient occlusion that lets bright surfaces bounce some light back into their own +// corners (Jimenez' multi-bounce fit), so white walls do not get grey creases. +fn ao_bounce(ao: f32, albedo: vec3) -> vec3 { + let a = 2.0404 * albedo - vec3(0.3324); + let b = -4.7951 * albedo + vec3(0.6417); + let c = 2.7552 * albedo + vec3(0.6903); + return max(vec3(ao), ((a * ao + b) * ao + c) * ao); +} + +// World direction to the probe's cube coordinates (and back: the swap is its own inverse). +fn to_cube(d: vec3) -> vec3 { + return vec3(d.x, d.z, d.y); +} + +// What a raindrop on a pane shows (`glass_film`): the sky probe that way, blurred a little +// by the drop's small lens, and low down the street's light in place of the probe's +// horizon (see the reflections in `shade_enhanced`). +fn rain_env_enhanced(d: vec3, lod: f32) -> vec3 { + let e = textureSampleLevel(t_probe, s_lin, to_cube(d), lod).rgb * enh.fog_color.w; + let surround = enh.fog_color.rgb * (0.25 / 0.9); + return mix(surround, e, smoothstep(-0.05, 0.35, d.z)); +} + +// A fixed, deterministic PCF kernel (shader.wgsl's `shadow_tent`). The old PCSS blocker +// search was unstable for alpha-tested foliage: a few leaves entering or leaving its +// 12-sample search changed the penumbra radius, producing checkerboard patches and +// camera-driven strips. The filter is fixed in shadow-map space, so the only thing that +// can change is the actual caster. `thin`: foliage, whose normals OMSI points up for even +// lighting - no receiver plane can be taken from them, a leaf compares at its own depth. +fn sun_shadow_soft(world_in: vec3, n: vec3, thin: bool) -> f32 { + if (camera.shadow.x < 0.5) { + return 1.0; + } + // (half a metre towards the sun for a leaf, as in `sun_shadow`) + let world = world_in + select(vec3(0.0), camera.sun_dir.xyz * 0.5, thin); + let ndl = clamp(dot(n, camera.sun_dir.xyz), 0.0, 1.0); + // (a veil of high cloud spreads the sun into an aureole a few degrees wide: the light + // comes from a larger source, and the shadow's edge widens with it) + // (the tent's four gathers step apart for it: see `shader.wgsl`'s `shadow_tent_near`) + let widen = 1.0 + 3.0 * enh.cloud_sun[1].w; + let close = shadow_close(world, n, ndl, thin); + if (close.y >= 0.999) { + return close.x; + } + let near_lp = camera.light_view_proj * vec4(world + shadow_push_near(n, ndl), 1.0); + let near_uv = vec2(near_lp.x * 0.5 + 0.5, 0.5 - near_lp.y * 0.5); + let near_edge = max(abs(near_uv.x - 0.5), abs(near_uv.y - 0.5)); + let near_valid = near_edge < 0.48 && near_lp.z >= 0.0 && near_lp.z <= 1.0; + var near_slope = shadow_receiver_slope(camera.light_view_proj, n); + var far_slope = shadow_receiver_slope(camera.light_view_proj_far, n); + if (thin) { + near_slope = vec2(0.0); + far_slope = vec2(0.0); + } + // Blend cascades by radial distance, not by the near map's projected square. The + // projected-edge test made the blend factor change when the camera moved sideways or + // turned, even for a stationary receiver; that reads as a full shadow shimmer at the + // cascade boundary. The light boxes still validate coverage above, while this gives + // the overlap a camera-centred, continuous transition. + let radial = distance(world, camera.cam_pos.xyz); + let near_weight = select( + 0.0, + 1.0 - smoothstep(camera.shadow.z * 0.62, camera.shadow.z * 0.92, radial), + near_valid, + ); + // Each cascade is filtered only where it counts: sampling both everywhere (32 compares + // a pixel) halved the enhanced picture's frame rate against shadows off. + var near_value = 1.0; + if (near_weight > 0.001) { + near_value = shadow_pcf_near(near_uv, near_lp.z, near_slope, widen); + } + near_value = mix(near_value, close.x, close.y); + if (near_weight >= 0.999) { + return near_value; + } + let flp = camera.light_view_proj_far * vec4(world + shadow_push_far(n, ndl), 1.0); + let fuv = vec2(flp.x * 0.5 + 0.5, 0.5 - flp.y * 0.5); + let far_valid = fuv.x >= 0.0 && fuv.x <= 1.0 && fuv.y >= 0.0 && fuv.y <= 1.0 && flp.z >= 0.0 && flp.z <= 1.0; + var far_safe = 1.0; + if (far_valid) { + let far_value = shadow_pcf_far(fuv, flp.z, far_slope, widen); + let far_edge = max(abs(fuv.x - 0.5), abs(fuv.y - 0.5)); + far_safe = mix(1.0, far_value, clamp((0.5 - far_edge) * 12.0, 0.0, 1.0)); + } + return mix(far_safe, near_value, near_weight); +} + +// Enhanced+: the solid casters' shadow where no traced one is there for a surface. The close +// and near maps hold only the cut-out casters then (`shadow_plan`), and such a surface - a +// pane, the edge of a step or a handrail thinner than a pixel of the depth prepass - lay in +// the sun under a roof: bright specks and stair-stepped lines along the edges, flickering +// as the camera moved and the traced texel was found or not. The far map keeps them all. +fn sun_shadow_far(world: vec3, n: vec3) -> f32 { + if (camera.shadow.x < 0.5) { + return 1.0; + } + let ndl = clamp(dot(n, camera.sun_dir.xyz), 0.0, 1.0); + let flp = camera.light_view_proj_far * vec4(world + shadow_push_far(n, ndl), 1.0); + let fuv = vec2(flp.x * 0.5 + 0.5, 0.5 - flp.y * 0.5); + if (fuv.x < 0.0 || fuv.x > 1.0 || fuv.y < 0.0 || fuv.y > 1.0 || flp.z < 0.0 || flp.z > 1.0) { + return 1.0; + } + return shadow_pcf_far(fuv, flp.z, shadow_receiver_slope(camera.light_view_proj_far, n), 1.0); +} + +// The sun's shadow at a point by one compare in the finest cascade that holds it (the close +// one, else the near one; lit beyond): for glass (see fs_enhanced). +fn sun_shadow_hard(world: vec3, n: vec3) -> f32 { + if (camera.shadow.x < 0.5) { + return 1.0; + } + let ndl = clamp(dot(n, camera.sun_dir.xyz), 0.0, 1.0); + let range = camera.flags.w; + if (range > 0.0 && distance(world, camera.cam_pos.xyz) < range * 0.75) { + let lp = camera.light_view_proj_close * vec4(world + shadow_push_close(n, ndl), 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (max(abs(uv.x - 0.5), abs(uv.y - 0.5)) < 0.48 && lp.z >= 0.0 && lp.z <= 1.0) { + let scale = select(1.0, camera.post.w, camera.post.w > 0.0); + let a = vec2(uv.x * 0.5 * scale + 0.5, uv.y * scale); + return textureSampleCompareLevel(t_shadow, s_shadow, a, lp.z - SHADOW_BIAS_CLOSE / SHADOW_DEPTH_RANGE); + } + } + let lp = camera.light_view_proj * vec4(world + shadow_push_near(n, ndl), 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (max(abs(uv.x - 0.5), abs(uv.y - 0.5)) < 0.48 && lp.z >= 0.0 && lp.z <= 1.0) { + return textureSampleCompareLevel(t_shadow, s_shadow, vec2(uv.x * 0.5, uv.y), lp.z - SHADOW_BIAS_NEAR / SHADOW_DEPTH_RANGE); + } + return 1.0; +} + +// What a surface reflects and scatters: diffuse albedo, specular colour at normal +// incidence, perceptual roughness. +struct Surface { + albedo: vec3, + f0: vec3, + rough: f32, + // what the specular reflection leaves the diffuse part (`spec_ms`), and the factor + // that gives the specular lobe back the light of its multiple scattering + kd: vec3, + comp: f32, +}; + +// How much of lamp `li` reaches the point (1 for a lamp without a shadow map): its map is +// one of the tiles under the far shadow map (lib.rs `LampShadow`), which the light's record +// names (`light_marks`): looking down from a street lamp's head, or along the road from a +// vehicle's headlamps; a few taps of it soften the edge, as the lamp's glowing bowl does. +// (the player's headlamps - marked so - share one map from between them along the road, +// `passes::headlamp_shadow`; it is read once for the pair, `own_shadow`) +var own_shadow: f32; +fn lamp_shadow_at(li: u32, p: vec3, n: vec3, thin: bool) -> f32 { + let marks = light_marks(lights[li]); + let own = marks.x > 0.5; + if (marks.z < 0.5) { + return 1.0; + } + var k = u32(marks.z - 0.5); + if (own && own_shadow >= 0.0) { + return own_shadow; + } + let to_lamp = p - lights[li].pos.xyz; + // a lamp that shines every way has a block of six tiles, one a direction (+x -x +y -y +z -z, + // lib.rs `CUBE_SLOTS`): the one the lit point lies in + if (k >= 44u) { + let a = abs(to_lamp); + var face = select(5u, 4u, to_lamp.z > 0.0); + if (a.x >= a.y && a.x >= a.z) { + face = select(1u, 0u, to_lamp.x > 0.0); + } else if (a.y >= a.z) { + face = select(3u, 2u, to_lamp.y > 0.0); + } + k = k + face; + } + let d = length(to_lamp); + // (off the surface by a texel or so of the map there; a leaf card towards the lamp) + let off = select(n * (0.03 + 0.012 * d), normalize(lights[li].pos.xyz - p) * 0.3, thin); + let q = camera.lamp_view_proj[k] * vec4(p + off, 1.0); + if (q.w <= 0.0) { + return 1.0; + } + let ndc = q.xyz / q.w; + if (abs(ndc.x) >= 1.0 || abs(ndc.y) >= 1.0 || ndc.z >= 1.0 || ndc.z <= 0.0) { + return 1.0; + } + + let tuv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + // (the far map's texture: its width, its height with the tiles under it; the tile's + // texels in the atlas's terms, kept a texel off its edges) + let dims = vec2(1.0 / camera.shadow.y, camera.lamp_atlas.z); + let tile = camera.lamp_atlas.x; + let cols = camera.lamp_atlas.y; + let tx = clamp(tuv * tile, vec2(1.5), vec2(tile - 1.5)); + let base = vec2(f32(k % u32(cols)) * tile, dims.x + f32(k / u32(cols)) * tile) + tx; + // (nine taps; a saloon's lamp - tiles 28 on - four: its tile's texels are three centimetres + // and every pixel of a saloon takes a handful of lamps) + // (two loops of fixed bounds: one bounded by the tile's kind was not unrolled) + let saloon = k >= 28u && k < 44u; + let zr = ndc.z - 0.00002; + var sum = 0.0; + var taps = 9.0; + if (saloon) { + for (var y = 0; y <= 1; y = y + 1) { + for (var x = 0; x <= 1; x = x + 1) { + let a = (base + (vec2(f32(x), f32(y)) - vec2(0.5)) * 1.25) / dims; + sum = sum + textureSampleCompareLevel(t_shadow_far, s_shadow, a, zr); + } + } + taps = 4.0; + } else { + for (var y = -1; y <= 1; y = y + 1) { + for (var x = -1; x <= 1; x = x + 1) { + let a = (base + vec2(f32(x), f32(y)) * 1.25) / dims; + sum = sum + textureSampleCompareLevel(t_shadow_far, s_shadow, a, zr); + } + } + } + let lit = sum / taps; + if (own) { + own_shadow = lit; + } + return lit; +} + +const CABIN_FILL: f32 = 0.2; + +// How much of the player's saloon lamps' light reaches a point past what stands in it, 1 where +// nothing does: each lamp that has a shadow map (`camera.cabin_lamps`: the first sixteen, by +// their records in the light buffer, -1 for none) weighs by what it would give the point +// unshadowed. The saloon's meshes are lit by the sets of lamps their models name and by light +// maps made for the lamps; this is what lets a handrail or a seat shade what it stands over +// in both. +fn cabin_visibility(p: vec3, n: vec3) -> f32 { + var open_light = 0.0; + var seen_light = 0.0; + for (var i = 0u; i < 16u; i = i + 1u) { + let at = camera.cabin_lamps[i / 4u][i % 4u]; + if (at < 0.0) { + break; + } + let li = u32(at); + let l = lights[li]; + let d = l.pos.xyz - p; + let dist2 = max(dot(d, d), 1e-4); + let ndl = dot(n, d * inverseSqrt(dist2)); + if (ndl <= 0.0 || l.color.w <= 0.0) { + continue; + } + let core = max(l.extra.y, 0.01); + let share = (l.color.r + l.color.g + l.color.b) * l.color.w * core * core / dist2 * ndl; + open_light = open_light + share; + seen_light = seen_light + share * lamp_shadow_at(li, p, n, false); + } + // (the light a closed room's lining sends back where the lamps do not reach: a saloon's + // walls, ceiling and seats, a third reflecting, lit by the lamps again and again - about + // a fifth of what the lit parts have) + let direct = clamp(seen_light / max(open_light, 1e-6), 0.0, 1.0); + return select(1.0, mix(CABIN_FILL, 1.0, direct), open_light > 1e-4); +} + +// A light cookie layer's texels a side (lib.rs `cookies::COOKIE_SIZE`). +const COOKIE_SIZE: u32 = 32u; + +// The enhanced path's marks on a light (lib.rs `prepare_lights`, carried in `pos.w` below +// zero, in steps of 32 for its tile and the low bits below): x 1 for one of the player's +// headlamps, y 1 + the layer of its beam's picture (0: none), z 1 + its shadow map's tile +// (0: none, see `LAMP_MARK`). +fn light_marks(l: PointLight) -> vec3 { + let m = max(-l.pos.w, 0.0); + let tile = floor(m / 32.0); + let rest = m - tile * 32.0; + let own = select(0.0, 1.0, rest > 15.5); + return vec3(own, rest - own * 16.0, tile); +} + +// A light cookie's texel (x, y) of the layer whose records start at `base`. +fn cookie_texel(base: u32, x: u32, y: u32) -> vec3 { + let i = min(y, COOKIE_SIZE - 1u) * COOKIE_SIZE + min(x, COOKIE_SIZE - 1u); + let rec = lights[base + i / 4u]; + let k = i % 4u; + return select(select(rec.pos.xyz, rec.color.xyz, k == 1u), select(rec.dir.xyz, rec.extra.xyz, k == 3u), k >= 2u); +} + +// What a lamp with a picture of its beam (`[spotlight_cookie]`) sends towards `t` (unit, +// from the lamp): the picture's light there, as the beam would show on a wall square to +// the lamp - the picture's right towards the lamp's right as seen from behind it, its top +// up - and nothing outside the field it covers (`camera.cookies`: x, y its half angles' +// tangents, z where its layer starts in the light buffer, four linear texels a record), +// filtered between its four nearest texels. +fn cookie_light(t: vec3, l: PointLight) -> vec3 { + let f = l.dir.xyz; + let ahead = dot(t, f); + let rc = cross(f, vec3(0.0, 0.0, 1.0)); + let r = select(vec3(1.0, 0.0, 0.0), normalize(rc), dot(rc, rc) > 1e-8); + let layer = camera.cookies[min(u32(light_marks(l).y - 0.5), 7u)]; + let q = vec2(dot(t, r), dot(t, cross(r, f))) / (max(ahead, 1e-3) * max(layer.xy, vec2(1e-3))); + let st = clamp(vec2(q.x * 0.5 + 0.5, 0.5 - q.y * 0.5) * f32(COOKIE_SIZE) - vec2(0.5), vec2(0.0), vec2(f32(COOKIE_SIZE) - 1.0)); + let c0 = vec2(st); + let w = st - floor(st); + let base = u32(layer.z); + let top = mix(cookie_texel(base, c0.x, c0.y), cookie_texel(base, c0.x + 1u, c0.y), w.x); + let bottom = mix(cookie_texel(base, c0.x, c0.y + 1u), cookie_texel(base, c0.x + 1u, c0.y + 1u), w.x); + return select(vec3(0.0), mix(top, bottom, w.y), ahead > 1e-3 && all(abs(q) < vec2(1.0))); +} + +// The radiance of the street round the point as the lamps light it (`lamp_light` leaves it +// here): what a reflection pointing at the street and the walls beside it sees at night. +var lamp_ground: vec3; + +// The point and spot lights of the pixel's grid cell: diffuse and specular. +// `thin`: foliage, lit from whichever side the lamp is on (see the sun below). +// `film`: a wet road's film of water - x how much of the surface it is (0: none), y how +// rough it is, z the share of it that mirrors - with which the lamps are reflected as the +// sky is (`refl_rough`, `wet_share` in fs_enhanced), not by the dry surface's own lobe. +fn lamp_light(p: vec3, n: vec3, v: vec3, sf: Surface, thin: bool, shadows: bool, film: vec3, back: bool) -> vec3 { + var sum = vec3(0.0); + lamp_ground = vec3(0.0); + own_shadow = -1.0; + // the lamps' light on the ground round the point (a horizontal surface's, unshadowed: + // the ground the point looks down at is wider than its own shadow) + var ground_e = vec3(0.0); + + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell <= 0.0 || side == 0u) { + return sum; + } + let f = (p.xy - camera.light_grid.xy) / cell; + let x = i32(floor(f.x)); + let y = i32(floor(f.y)); + if (x < 0 || y < 0 || x >= i32(side) || y >= i32(side)) { + return sum; + } + let a = max(sf.rough * sf.rough, 0.02); + let a_film = max(film.y * film.y, 0.02); + let nv = max(dot(n, v), 1e-4); + let facing = select(1.0, 0.0, back); + let base = (u32(y) * side + u32(x)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let d = l.pos.xyz - p; + let dist2 = dot(d, d); + // (pos.w is 0 on a spot light, which the vanilla shader is to pass by) + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let dist = sqrt(dist2); + let ld = d / max(dist, 1e-3); + // inverse-square beyond the core with a soft knee at it, not flat within it; windowed to zero at + // the range so the grid cut-off does not show + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var e = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + // (a lamp's picture of its beam: its colour that way, see `cookie_light`) + var tint = vec3(1.0); + if (l.extra.z != 0.0) { + e = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + let cd = dot(-ld, l.dir.xyz); + if (light_marks(l).y > 0.5) { + tint = cookie_light(-ld, l); + e = e * step(1e-4, max(tint.r, max(tint.g, tint.b))); + } else { + e = e * smoothstep(l.dir.w, l.extra.x, cd); + } + } else if (l.dir.z < -0.5) { + // a lamp in a housing (a street lamp's head, a platform's light): its reflector + // sends the light down and out, its housing keeps it from the sky - a few per + // cent above its horizon, what the bowl and the pole scatter (the upward light + // ratio of road lighting, EN 13201 / CIE 115). Shining evenly every way, every + // lamp lit the crowns of the trees and the upper floors over it as brightly + // as the street. + e = e * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + if (e <= 0.0 || (!(l.extra.z == 0.0 && l.dir.w < -1.5 && l.dir.z < -0.5) && own_vehicle_blocks(p, l.pos.xyz))) { + continue; + } + var irr = l.color.rgb * tint * l.color.w * enh.lights.y * e; + let nl = dot(n, ld); + ground_e = ground_e + irr * max(ld.z, 0.0); + // Ground bounce is unshadowed. A lamp behind an ordinary surface contributes + // no direct light, so it must not sample its shadow map before being rejected. + if (!thin && nl <= 0.0) { + continue; + } + // the lamps' own shadow maps (the few lighting the view most, see `lamp_shadow_at`) + if (shadows) { + irr = irr * lamp_shadow_at(li, p, n, thin); + } + if (thin) { + // a headlamp skims the grass: it lights the tips, not a crown's every side + let wrap = select(0.45 + 0.25 * nl, 0.15 + 0.6 * max(nl, 0.0), l.extra.z != 0.0); + sum = sum + irr * wrap * sf.albedo / PI; + continue; + } + let h = normalize(ld + v); + let nh = max(dot(n, h), 0.0); + let fr = f_schlick(sf.f0, dot(v, h)); + var spec = d_ggx(nh, a) * v_smith(nv, nl, a) * fr; + if (film.x > 0.0) { + spec = mix(spec, d_beckmann(nh, a_film) * v_smith(nv, nl, a_film) * fr * film.z, film.x); + } + spec = spec * facing * sf.comp; + sum = sum + irr * nl * (sf.albedo / PI * sf.kd + spec); + } + // What the lit ground throws back up: a diffuse reflector of the street's albedo (asphalt + // and paving about 0.18, under water darker, fresh snow 0.75), seen by a surface over the + // lower half of its view, (1 - n.z) / 2 of it - a wall half, the underside of a shelter's + // roof all, the ground itself nothing. Without it the lamps lit only what faces them, and + // a facade or a bus's flank beside a lit street stood black. + let snow = clamp(enh.weather.y, 0.0, 1.0); + let rho = mix(0.18, 0.75, snow) * mix(1.0, 0.6, clamp(enh.weather.x, 0.0, 1.0) * (1.0 - snow)); + let seen = select((1.0 - clamp(n.z, -1.0, 1.0)) * 0.5, 0.5, thin); + sum = sum + ground_e * rho * seen * sf.albedo / PI; + lamp_ground = ground_e * rho / PI; + return sum; +} + +// The relief a rough surface has under its microfacets - asphalt's grit and chippings, a +// paving stone's dressing, a cobble's dome (slopes of a quarter and more, at millimetres to +// centimetres) - shadows and masks itself (Smith's function for that slope spread, +// height-correlated) towards a light and an eye low over it. GGX's own roughness is the +// grain under that; on its own it let a low sun's grazing glint off every rough road and +// wall shine white towards the camera, where a real road keeps it dull. The spread grows +// with the rougher surface, and with the patch the pixel covers: farther off, the road's +// waves and ruts are under the pixel too. A smooth surface is left as it is. +fn relief_masking(nl: f32, nv: f32, rough: f32, footprint: f32) -> f32 { + let s2 = 0.0625 * smoothstep(0.45, 0.85, rough) + 0.02 * smoothstep(0.01, 0.12, footprint) * smoothstep(0.45, 0.7, rough); + if (s2 <= 0.0) { + return 1.0; + } + // (Smith's Lambda for a slope variance s2: (sqrt(1 + s2 tan^2) - 1) / 2) + let ml = clamp(nl, 1e-3, 1.0); + let mv = clamp(nv, 1e-3, 1.0); + let ll = 0.5 * (sqrt(1.0 + s2 * (1.0 - ml * ml) / (ml * ml)) - 1.0); + let lv = 0.5 * (sqrt(1.0 + s2 * (1.0 - mv * mv) / (mv * mv)) - 1.0); + return 1.0 / (1.0 + ll + lv); +} + +// The light inside a cab relative to the average light outside: a bus's big windows let in +// most of the sky, and the dashboard lies right under the windscreen. +const CAB_AMBIENT: f32 = 1.15; + +// How far the puddle threshold drops with the wetness: see the puddle mask in `shade_enhanced`. +const PUDDLE_SPREAD: f32 = 0.37; + +/// The mip level a pixel's footprint asks for, in levels of the texture whose size is +/// `texels` (the usual `log2` of the larger derivative, held at 0 and up). An LED panel is +/// sampled with this, held at `enh.led.y` (`Lighting::led_mips`): 0 point-samples it, which +/// is the sharpest and shimmers worst - a regular dot grid is the worst case for a point +/// sample - and every level the chain is allowed to take is a 2x2 average that a point +/// sample of the level below does not have. (The derivatives have to be taken in uniform +/// control flow: the panels are per draw, so a call inside the material's branch is not.) +fn led_lod(uv: vec2, texels: vec2) -> f32 { + let dx = dpdx(uv) * texels; + let dy = dpdy(uv) * texels; + return max(0.5 * log2(max(dot(dx, dx), dot(dy, dy))), 0.0); +} + +// A tangent-space normal `tn` (a PBR normal map's) turned into the world about the +// surface normal `n`, with the tangent frame taken from how the position and the uv change +// across the pixel (no tangents in OMSI's meshes). `tn.y` down the texture, as Direct3D's +// normal maps have it. +fn perturb_normal(n: vec3, p: vec3, uv: vec2, tn: vec3) -> vec3 { + let dp1 = dpdx(p); + let dp2 = dpdy(p); + let duv1 = dpdx(uv); + let duv2 = dpdy(uv); + let dp2perp = cross(dp2, n); + let dp1perp = cross(n, dp1); + let t = dp2perp * duv1.x + dp1perp * duv2.x; + let b = dp2perp * duv1.y + dp1perp * duv2.y; + let m = max(dot(t, t), dot(b, b)); + if (m < 1e-20) { + return n; + } + let k = inverseSqrt(m); + return safe_normal(t * k * tn.x + b * k * tn.y + n * max(tn.z, 0.05)); +} + +// The enhanced pass's two targets: the picture, and the screen mask (r: 1 on the bus's own +// screens, carried by the coverage of what is drawn over them; g: 1 on an LED panel's own +// dots, 0.25 on other screens, see MASK_FORMAT; b is wet puddles' reflected-light weight). +struct EnhancedOut { + @location(0) color: vec4, + @location(1) mask: vec4, + //RT @location(2) gbuf: vec4, + //RT @location(3) aux: vec4, +}; + +// Enhanced+ (the window's picture, camera.clouds.w 2): the surface the traced reflections +// start from - its normal and how much of the reflection lands on the screen (w), its +// distance from the eye and its roughness, all times that weight (see GBUF_FORMAT). The +// probe's reflection is left out of the colour there: the traced one is added in its place. +var rt_gbuf: vec4; +var rt_aux: vec4; + +fn enhanced_surface(in: FsIn) -> EnhancedOut { + rt_gbuf = vec4(0.0); + rt_aux = vec4(0.0); + var puddle_weight = vec2(0.0); + let c = shade_enhanced(in, &puddle_weight, false, camera.cam_pos.xyz); + let screen = material.flags.x > 0.5; + // an LED panel's dots stay in the glow's source (`post.wgsl`), the other screens' + // letters stay out of it + let led = select(0.0, 1.0, material.emissive.w < -1.5); + var out: EnhancedOut; + out.color = c; + // Non-LED screens carry g = r / 4. The ratio survives a clear pane's coverage + // blending, so a faded screen marker cannot be mistaken for condensation. + // Water keeps its occluded sky weight in g and reflection weight in b. + // A vehicle's shadow is light blocked from the road, not a new dry surface. Its + // colour still blends normally, but it must preserve the road's reflection mask. + // A transparent screen layer must leave the masks underneath intact. Otherwise + // unused LED colour layers make the whole panel's background bloom as lit dots. + let coverage = select(c.a, 0.0, in.params2.w > 1.5); + // (r under 0.5: how much light the player's bus's misted glass scatters there, for the + // tone mapping's blur - post.wgsl `misted`. The mask is blended by the coverage, so the + // share is divided by it to land as MIST_MASK x the share over what lies behind; + // a misted pane's coverage is at least half its share, see `shade_enhanced`) + let mist = select(0.0, glass_fog * MIST_MASK / max(coverage, 1e-3), glass_fog > 0.001); + let screen_code = select(0.25, 1.0, led > 0.5); + out.mask = vec4(select(min(mist, 0.49), 1.0, screen), select(max(led, puddle_weight.y * 0.49), screen_code, screen), puddle_weight.x, coverage); + //RT out.gbuf = rt_gbuf; + //RT out.aux = rt_aux; + return out; +} + +@fragment +fn fs_enhanced(in: FsIn) -> EnhancedOut { + return enhanced_surface(in); +} + +// A headset uses mapped shadows, not screen-space ray reflections. Its colour +// pass needs only colour and the screen mask, even on an Enhanced+ renderer. +struct EnhancedColorOut { + @location(0) color: vec4, + @location(1) mask: vec4, +}; + +@fragment +fn fs_enhanced_color(in: FsIn) -> EnhancedColorOut { + let surface = enhanced_surface(in); + return EnhancedColorOut(surface.color, surface.mask); +} + +// A self-lit picture (a display, a light-mapped surface lit fully) at its own colour after +// the tone curve (post.wgsl `natural_tone`): it bleaches what is brighter than its knee - +// a display's yellow-green text came out olive - and gives the middle tones the contrast +// of `enh.debug.w` about mid grey. So the colour is kept under the knee and the contrast +// undone in advance (with the small black offset the text has always been drawn with). +// A display's own brightness for the light round it: as a bus's screens dim at night, to +// 15 % of the day's, and never lifted over their own colour by the dark-adapted metering. +fn display_dim(lift: f32) -> f32 { + let night = clamp(camera.sun_color.w, 0.0, 1.0); + return mix(lift, min(lift, 1.0) * 0.15, night); +} + +fn display_level(t: vec3) -> vec3 { + let peak = max(t.r, max(t.g, t.b)); + let tk = t * min(1.0, 0.64 / max(peak, 1e-3)); + let c = max(enh.debug.w, 1.0); + let x = 0.18 * pow(tk / 0.18 + vec3(1e-7), vec3(1.0 / c)); + return x + 0.04 * smoothstep(vec3(0.0), vec3(0.08), x); +} + +// [matl_glow] (see MaterialExtra::glow): the material is its own light. `buv` is where its +// mask is read (the light map's own coordinate, the slot it rides in) and `col` the colour +// the light is drawn in - the material's own, so a destination panel keeps the colour its +// display draws. The mask is a greyscale picture of how much shines where (white full, black +// none). The strength is the mod's own (the .cfg value x0.25, on the scale of the LED +// panels' `Led glow`) and is held against the metering as an LED panel's dots are; the +// glare round it comes from how bright it is, as every light's does (post.wgsl). +fn matl_glow_light(buv: vec2, col: vec3) -> vec3 { + let gm = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], buv, camera.lod.x); + return col * dot(gm.rgb, vec3(0.299, 0.587, 0.114)) * material.glow.x * max(enh.exposure.z * 2.0, 0.8); +} + +// How much of the light crossing the player's bus's pane its condensation scatters (0..1, +// 07_glass.wgsl `glass_condensation`), for the screen mask. +var glass_fog: f32; +// The screen mask's r for a pane scattering all the light (post.wgsl `MIST_MASK`). +const MIST_MASK: f32 = 0.24; +// Heading, pitch and roll: with the heading alone the film slid along the glass on a hill (#3958). +fn pane_local(world: vec3) -> vec3 { + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let v = vec3(d.x * ch - d.y * sh, d.x * sh + d.y * ch, d.z); + let t = enh.pane_tilt; + let p = vec3(v.x, v.y * t.y + v.z * t.x, v.z * t.y - v.y * t.x); + let b = vec3(p.x * t.w - p.z * t.z, p.y, p.z * t.w + p.x * t.z); + return b - camera.inside_c.xyz; +} + +fn shade_enhanced(in: FsIn, puddle_weight: ptr>, capture: bool, eye: vec3) -> vec4 { + // (the pane's water, read once for the uses below) + let film_water = window_wetness(in); + if (material.emissive.w > 1.5) { + // a pane's film of water: drops laid out on the glass, each a lens that mirrors the + // sky probe and shows the street upside down through itself, and the haze of the wet + // glass between them (07_glass.wgsl `glass_film`) + return glass_film(in, film_water); + } + // --- the surface's texture and alpha, exactly as the vanilla pass reads them + let terrain = material.extra.x > 0.5; + var duv = tex_address(in.uv); + if (terrain) { + duv = in.uv * material.extra.z; + } + // (without the [texcoordtransX/Y] offset: the transmap, night map and light map stay + // in place, see fs_main) + let buv = tex_address(in.uv - in.params.zw); + let msk_lod = led_lod(buv, vec2(textureDimensions(mx_tex2d[mx_mat.trans]))); + // Empty paint also needs no tiled diffuse or detail samples. Its brush mask + // replaces diffuse alpha, so coverage can be checked before those reads. + if (TERRAIN_PAINT && material.params.x > 1.5 && material.params.z > 0.5 + && material.params.w > 0.5 && enh.debug.x <= 0.5 && material.ambient.w <= 1.5) { + var coverage = sample_transmap(buv).a; + if (material.emissive.w < -1.5 && enh.led.y < msk_lod) { + coverage = textureSampleLevel(mx_tex2d[mx_mat.trans], mx_samplers[mx_mat.sampler], buv, enh.led.y).a; + } + coverage = smoothstep(0.32, 0.68, coverage); + if (coverage * material.color.a * in.params.x == 0.0) { + discard; + } + } + // An LED panel is sampled at the level its screen footprint asks for, held at + // `enh.led.y` (`Led mip strength`): its dots keep their gaps much further out than the + // full chain allows, and the shimmer is a fraction of a full-resolution sample's. The + // levels are worked out here and not inside the branch: derivatives are undefined in + // non-uniform control flow, and which of the two samples runs is per draw. When the + // setting does not bite, the plain (anisotropic) sample of the hardware is the better + // one and stays. + let pic_lod = led_lod(duv, vec2(textureDimensions(mx_tex2d[mx_mat.diffuse]))); + let led_pic = material.emissive.w < -1.5 && enh.led.y < pic_lod; + // The painted ground's albedo comes from the picture `fs_ground` laid (the base's and its + // layers', the frame's `camera.lod.y`): the terrain's base is lit once for all of them. + // (A condition of the draw alone, so the texture reads below stay in uniform control flow; + // `Renderer::plan_ground` has seen to it that every draw this holds for is in that picture.) + let from_ground = camera.lod.y > 0.5 && terrain && !TERRAIN_PAINT && !capture && material.params.x < 0.5 && material.params.z < 0.5; + var tex = vec4(1.0); + if (from_ground) { + tex = vec4(textureLoad(t_ao, vec2(in.clip.xy), 0).rgb, 1.0); + } else { + tex = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv); + if (is_snow_pane()) { + tex = glass_snow(in, film_water); + } + if (led_pic) { + tex = diffuse_border(textureSampleLevel(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, enh.led.y), duv); + } + } + let diffuse_a = tex.a; + if (terrain && !from_ground && material.extra.y > 0.0) { + let det = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], in.uv * material.extra.y, camera.lod.x); + tex = vec4(clamp(tex.rgb * det.rgb, vec3(0.0), vec3(1.0)), tex.a); + } + if (material.params.z > 0.5) { + // (an LED panel's `\S:n` mask is taken the same way: the dots stay dots when the + // panel is small, without the full-resolution shimmer) + var tm = sample_transmap(buv); + if (material.emissive.w < -1.5 && enh.led.y < msk_lod) { + tm = textureSampleLevel(mx_tex2d[mx_mat.trans], mx_samplers[mx_mat.sampler], buv, enh.led.y); + } + tex.a = select(1.0, tm.a, material.params.w > 0.5); + if (terrain && material.params.x > 1.5) { + // Coverage belongs to the brush mask, not the angle-dependent diffuse mip. + tex.a = smoothstep(0.32, 0.68, tex.a); + } + } + // One night-map read supplies both coverage and lighting. Keep the tile map + // in its north-up UVs; vehicle maps use the unscrolled material UVs. + var night_sample = vec4(0.0); + if (material.extra.w > 0.5) { + let nuv = select(buv, vec2(in.uv.x, 1.0 - in.uv.y), terrain); + night_sample = sample_nightmap(nuv); + } + tex.a = night_coverage(tex.a, night_sample.a) * tree_card_fade(in.world); + let mode = material.params.x; + // Keep the filtered fractional coverage, but tighten its transition around the cutout + // edge before MSAA turns it into sample coverage. The MSAA depth prepass skips these + // draws so uncovered samples keep the depth and colour of the scene behind them. + if ((ALPHA_TEST || capture) && mode > 0.5 && mode < 1.5) { + if (ALPHA_TO_COVERAGE) { + let aa = max(fwidth(tex.a) * 0.5, 1.0 / 255.0); + // (not `ALPHA_REF - aa`: a layer whose clear glass is alpha 128 kept a third of + // its samples there, a moire of the layer's paint over every window) + if (tex.a < ALPHA_REF) { + discard; + } + tex.a = smoothstep(ALPHA_REF - aa, ALPHA_REF + aa, tex.a); + } else if (tex.a < ALPHA_REF) { + discard; + } + } + // (a blended slot that keeps Omsi.exe's alpha test, `MaterialExtra::alpha_cut`: a + // livery's clear glass is cut away, its tinted glass blended) + tex.a = select(tex.a, 0.0, mode > 2.5 && tex.a < ALPHA_REF); + var alpha = tex.a * material.color.a; + if (mode < 0.5) { + alpha = 1.0; + } + if (!is_snow_pane()) { + alpha = alpha * clamp(film_water, 0.0, 1.0); + } + // Sparse brush masks still cover the whole tile mesh. Empty pixels contribute + // neither colour nor reflection coverage, so avoid lighting them. Keep fractional + // edges, debug views, and water (whose Fresnel can raise zero alpha) unchanged. + if (TERRAIN_PAINT && alpha == 0.0 && enh.debug.x <= 0.5 && material.ambient.w <= 1.5) { + discard; + } + let pre = enh.exposure.x; + let to_cam = eye - in.world; + let dist = length(to_cam); + let v = to_cam / max(dist, 1e-4); + let h_cam = camera.cam_pos.z - enh.fog.z; + let h_pt = in.world.z - enh.fog.z; + // (no fog inside the cab: only the part of the way outside the bus is misty) + // (the lamps' light in the fog is added over the whole picture afterwards: fog_lamps.wgsl) + let aer = air(-v, fog_distance(in.world), h_cam, h_pt); + if (in.params2.w > 1.5) { + // A vehicle's shadow blob is no surface: it is the sky light the body keeps off the + // road, a layer that only darkens what lies under it (as OMSI blends it). Shaded as + // a black surface it took the sky, the wet road's sheen and the lamps on top and + // hardly darkened anything. The air in front of it stays (the road's own fog, under + // the blob, is darkened with it as in the original). + return vec4(aer.rgb * pre, alpha * aer.a); + } + if (material.params.y > 0.5) { + // unlit (mirror glass, script and text textures): shown at their own brightness, + // under the tone curve's knee (`display_level`), and `exposure.y` undoes the + // metering (see ExposureLog in lib.rs) + let t = tex.rgb * material.color.rgb; + // A mirror (params.y 0.9) is no display: its picture is the street drawn a moment + // ago, dark at night. Brightened like a display by the metering (up to 1.6 in the + // dark) it showed a street far brighter than the one through the windscreen. + let lift = select(display_dim(enh.exposure.y), min(enh.exposure.y, 1.0), material.params.y < 0.95); + // (no [matl_glow] here: an unlit slot is drawn at its own brightness already, and + // reading the light map's slot in this branch failed Metal's shader compiler) + let c = display_level(t) * lift; + return vec4(c * aer.a + aer.rgb * pre, alpha); + } + let outside = weather_outside_n(in.world, safe_normal(in.normal), terrain, in.params2.w); + // the normal as the content gives it: never turned towards the viewer (Direct3D does + // not either, and OMSI's foliage points every leaf's normal up so the whole crown is lit + // evenly - turned round, the crown went dark above the horizon line) + var n = safe_normal(in.normal); + // the map's water (`MaterialExtra::water`): small waves running over it ripple its + // normal - fading with the distance, where they would only flicker - so that what it + // mirrors breaks up as on a lake instead of standing in it as in a pane of glass (#841) + let is_water = material.ambient.w > 1.5; + if (is_water) { + n = normalize(n + vec3(water_ripple(world_pattern_xy(in.world), camera.post.y) * clamp(1.0 - dist / 250.0, 0.2, 1.0), 0.0)); + } + // Leaves and fences transmit light. A terrain road-cut mask only removes ground: + // its remaining pixels must shade like the uncut ground on terrain-mapped splines. + // (people's cut-out hair and clothes are bodies: material flag 8) + let thin = !terrain && mode > 0.5 && mode < 1.5 && (u32(material.params2.w + 0.5) & 8u) == 0u; + let has_env = material.params2.y > 0.0; + // A blended transmap body is a masked paint surface, not glass. Traffic cars often + // use this material layout for their body; depth-disabled blends remain glass. + // Window assets are not consistent about carrying an envmap. The reliable signal + // is an explicitly named window, or a depth-disabled blended layer with env/transmap + // data that identifies a pane rather than a dirt/text overlay. This keeps bus + // panes on the reflection/transmission path after the material-depth repair. + // Painted terrain also blends a transmap without writing depth. It is never glass: + // Fresnel opacity on its empty mask pixels darkens every lower layer at grazing angles. + // A script's screen is never a pane, though it is laid out as one - blended, not writing + // depth, its letters a `\S:n` transparency map: the EMT Citaro's Krueger matrix + // (Mallorca) was taken for glass, which gives no light of its own, and its letters stayed + // grey at night while its light map lit them in Vanilla+ (#2927). + let glass = !terrain && mode > 1.5 && (material.bump.z > 0.5 || material.emissive.w > 0.5) && + (has_env || material.params.z > 0.5 || material.emissive.w > 0.5) && material.flags.x < 0.5; + // An envmap on opaque vehicle paint is legacy material data, not a request to make + // the whole body behave like glass. Keep the diffuse/sun response, but use the + // ordinary rough dielectric path for the body. + // Foliage and other alpha-tested assets are diffuse silhouettes, not polished surfaces. + // Letting the generic probe term reflect them creates white sparkles at grazing angles; + // the photographed envmap is reserved for materials that explicitly request it. + // (opaque materials reflect as well - chrome handrails, bumpers and wheel trims are + // opaque with a sphere map, and left out they showed no reflection at all in the + // enhanced picture, #266 - but through the clear-coat path below: metal only where a + // mask of its own says so) + // (not the water: its sphere map is OMSI's stand-in for the sky it mirrors, which the + // probe holds itself - drawn as paint's photo, it lay on the water as green specks) + // (a body painted through a [matl_transmap] too - most mod buses' and cars' paint, + // the W123's: its alpha is the transmap's, the envmap's mask the texture's own, as in + // the vanilla picture; left out, their paint showed no reflection at all while their + // windows did) + let reflective_env = has_env && !thin && !is_water; + // see-through glass is seen from either side: from inside the bus its normal points + // away (the vanilla pass takes the angle either way round too); taken as it is, the + // grazing Fresnel turned the whole windscreen into a milky mirror + var geo_n = n; + if (glass && dot(n, v) < 0.0) { + n = -n; + geo_n = n; + } + var face_n = n; + var face_v = 0.0; + var face_w = 1.0; + if (reflective_env && !glass && !terrain) { + let c = cross(dpdx(in.world), dpdy(in.world)); + if (dot(c, c) > 1e-14) { + let face = normalize(c) * select(-1.0, 1.0, dot(c, v) >= 0.0); + face_n = face; + face_v = dot(face, v); + face_w = smoothstep(0.5, 0.9, dot(n, face)); + } + } + if (reflective_env && material.bump.y > 0.5) { + // [matl_bumpmap]: the height map's slope bends the normal (tangent frame from the + // screen-space derivatives of position and texture coordinate) + let slope = bump_offset(duv); + let dp1 = dpdx(in.world); + let dp2 = dpdy(in.world); + let du1 = dpdx(duv); + let du2 = dpdy(duv); + let dp2p = cross(dp2, n); + let dp1p = cross(n, dp1); + let t = dp2p * du1.x + dp1p * du2.x; + let b = dp2p * du1.y + dp1p * du2.y; + let inv = inverseSqrt(max(max(dot(t, t), dot(b, b)), 1e-12)); + n = normalize(n - (t * inv * slope.x + b * inv * slope.y) * 0.6); + } + var albedo = select(tex.rgb * material.color.rgb, tex.rgb, from_ground); + // OMSI materials have separate diffuse and ambient colours. Some interiors have + // black diffuse but white ambient: using diffuse for both made them pitch black. + // Keep the direct response, and weather both colours with the same surface effects. + // A slot without a texture (ambient.w -1) takes its diffuse colour for both: Omsi.exe's + // white ambient of every o3d slot under a strong sky turned a coloured model white (#1737). + var ambient_albedo = select(tex.rgb * material.ambient.rgb, albedo, material.ambient.w < -0.5 || from_ground); + var detail_factor = 1.0; + if (camera.flags.x > 0.5 && (terrain || in.params2.w > 0.5)) { + let k = clamp(1.0 - (dist - 25.0) / 120.0, 0.0, 1.0); + let pattern_xy = world_pattern_xy(in.world); + detail_factor = 1.0 + (detail_noise(pattern_xy, k) - 0.5) * 0.42 * k; + albedo = albedo * detail_factor; + ambient_albedo = ambient_albedo * detail_factor; + } + // --- the material in physical terms + var refl = 0.0; + if (reflective_env) { + // (with a mask of its own or a [matl_transmap] the share is the mask's alone, as + // Omsi.exe's stage takes it - the factor counts only where there is none) + let by_mask = material.params.z > 0.5 || (u32(material.params2.w + 0.5) & 1u) != 0u; + refl = clamp(select(min(material.params2.y, 1.0), 1.0, by_mask) * reflection_mask(duv, diffuse_a), 0.0, 1.0); + } + var metal = 0.0; + var f0 = vec3(0.04); + var rough = 0.8; + let probe_only = camera.clouds.w < 1.5; + if (terrain) { + rough = 0.92; + f0 = vec3(0.03); + } else if (glass) { + // OMSI's window materials are deliberately very transparent. Raise the base + // dielectric reflection slightly so the outside scene remains readable through + // the pane instead of leaving a flat pale surface at normal incidence. + rough = 0.04; + // the pane's [matl_envmap] factor says how much it mirrors (its alpha is its + // transparency, never a mask): from glass's own 4 % up to 12 % for a factor of 1 + // (0.4 on the Scania's panes). Up to 26 % as before, every window of every bus + // was a mirror - far more than the original's panes reflect (issue #176). + // ... measured against the vanilla picture: Omsi.exe lays the sphere map over the + // pane by its factor and the pane shows that as faintly as it shows itself - the + // share it mirrors is the pane's alpha times the factor (0.25 .. 0.5 on the stock + // windows), at every angle, with no Fresnel term. Taken as the reflectance + // averaged over the angles (Schlick's mean, f0 + (1 - f0) / 21, as for the paint), + // the pane mirrors as much as there and rises towards grazing as glass does; 4 to + // 12 % at the normal, and three quarters of that, left the windows showing the + // saloon where the vanilla picture shows the street. + let share = clamp(alpha * min(material.params2.y, 1.0), 0.0, 1.0) * camera.cam_pos.w; + f0 = vec3(select(clamp((share - 1.0 / 21.0) * 21.0 / 20.0, 0.04, 0.9), 0.04, probe_only)); + } else if (reflective_env) { + // Paint reflects its few per cent through a smooth clear coat; much more than a few + // per cent is polished metal - but only where the model says so with a mask of its + // own ([matl_envmap_mask]). Nearly every car body carries `[matl_envmap] … 1` with + // no mask, which OMSI takes as "reflect the sphere map fully" and not as chrome: + // read as metalness it made a Golf's bonnet a mirror, in which the envmap photo's + // trees stood as contour lines across the paint at close range. + // + // The paint itself is a clear coat: a lacquer of refractive index 1.5 (4 % at normal + // incidence, Fresnel's 100 % at grazing) polished smooth, which mirrors the street + // as sharply as the windows do. How much of the sphere map OMSI lays over a + // material says how glossy it is: the stock bodies carry 1 or 10, the cabin's + // panels, frames and plastic trim 0.05 .. 0.2 - satin, a blurred sheen; the mask + // (the texture's alpha) says where. (Roughness + // 0.22 for every body, against the photo's contour lines on a car's bonnet, left + // the paint matte beside its sharp windows.) + let masked = (u32(material.params2.w + 0.5) & 1u) != 0u; + let metal_ok = (u32(material.params2.w + 0.5) & 4u) != 0u; + metal = select(0.0, smoothstep(0.3, 0.85, refl), masked || metal_ok); + // The coat is as smooth as lets it mirror, averaged over the angles, the share + // Omsi.exe lays over it: a polished 4 % coat mirrors 8.7 % on average (Fresnel's + // rise at grazing), a rough one less (2.5 % at 0.8, its grazing light scattered and + // shadowed by its own roughness). So a share of 8.7 % and more is smooth lacquer, the + // stock bodies' few per cent - the MAN NL's 15 of 255 - a satin one (taken as rough + // up to a share of a half they came out matte, #2067; smooth from 4 %, a body meant + // to mirror barely shone like glass against the light, #2474), and where the mask + // says nothing reflects - a tyre or a seal - the rough rubber or plastic it is. + // Between those and chrome, the share says how much the paint mirrors, not how + // sharply: Omsi.exe lays a soft sphere map over it, a blurred sheen of the sky. Taken + // as polished glass from 8.7 % on (0.2.42), the many mod bodies whose texture alpha + // holds a tenth to a half mirrored the grey sky like chrome - silver buses and AI + // cars that glowed (#2563, #2301). Only a share near the whole is a sharp mirror. + let coat_rough = max(clamp(0.06 + (0.087 - refl) * 11.9, 0.06, 0.8), mix(0.3, 0.06, smoothstep(0.5, 0.95, refl))); + // Where the model says how much it mirrors - a [matl_envmap_mask], or the texture's + // alpha under a [matl_transmap] (most mod bodies) - Omsi.exe lays the sphere map + // over the paint by that share at every angle (shader.wgsl's environment stage): + // OMSI has no Fresnel term, so the share is the reflectance averaged over the angles + // the surface is seen at. A Fresnel reflectance with that average (Schlick's, whose + // hemispherical mean is f0 + (1 - f0) / 21) mirrors as much as the vanilla picture + // and rises towards grazing as a real coat does. (A plain 4 % coat left those + // bodies far fainter than in the vanilla picture.) A body with neither keeps the + // lacquer's 4 %: there Omsi.exe's lerp by the factor alone made every Golf a mirror. + let authored = masked || material.params.z > 0.5; + let coat = select(0.04, clamp((refl - 1.0 / 21.0) * 21.0 / 20.0, 0.04, 0.95), authored); + f0 = mix(vec3(coat), mix(albedo, vec3(1.0), 0.4) * refl, metal); + rough = mix(coat_rough, 0.14, metal); + } else if (!thin && material.specular.w > 0.0 && dot(material.specular.rgb, vec3(1.0)) > 0.05) { + // the o3d material's Blinn-Phong power as GGX roughness + rough = clamp(sqrt(sqrt(2.0 / (material.specular.w + 2.0))), 0.4, 0.9); + } else if (thin) { + rough = 0.7; + } + if (is_water) { + // water: a dielectric of 2 % at normal incidence, nearly a mirror where it is seen + // flat, smooth but for its waves + f0 = vec3(0.02); + rough = 0.06; + metal = 0.0; + } + // --- a PBR set beside the diffuse texture (`foo_n.png`, `foo_r` / `_m` / `_ao` or + // `foo_orm`: see omsi_texture::pbr): the normal map bends the normal, the packed map + // gives the occlusion, roughness and metalness in place of the guesses above + var pbr_ao = 1.0; + if (material.pbr.x > 0.5 && !terrain) { + var tn = textureSampleBias(mx_tex2d[mx_mat.pbr_normal], mx_samplers[mx_mat.sampler], duv, camera.lod.x).xyz * 2.0 - vec3(1.0); + // (an OpenGL-style map, green up: `_gl` in its name) + if (material.pbr.x > 1.5) { + tn.y = -tn.y; + } + n = perturb_normal(n, in.world, duv, tn); + } + if (material.pbr.y + material.pbr.z + material.pbr.w > 0.5 && !terrain) { + let orm = textureSampleBias(mx_tex2d[mx_mat.pbr_orm], mx_samplers[mx_mat.sampler], duv, camera.lod.x).rgb; + if (material.pbr.y > 0.5) { + pbr_ao = orm.r; + } + if (material.pbr.z > 0.5) { + rough = clamp(orm.g, 0.03, 1.0); + } + if (material.pbr.w > 0.5) { + metal = orm.b; + f0 = mix(vec3(0.04), albedo, metal); + } + } + // rain: roads with [moisture] turn dark and smooth, everything outside a little glossier + // (not under snow: a snowy road took the rain's gloss and the snow on it shone like + // plastic in every headlight) + let dry_snow = 1.0 - clamp(enh.weather.y, 0.0, 1.0); + let wet_road = camera.shadow.w * material.params2.z * outside * dry_snow; + let wet_any = camera.shadow.w * outside * select(0.35, 0.0, glass) * dry_snow; + var puddle = 0.0; + if (wet_road > 0.0) { + albedo = albedo * mix(1.0, 0.5, wet_road); + ambient_albedo = ambient_albedo * mix(1.0, 0.5, wet_road); + rough = mix(rough, 0.12, wet_road); + f0 = mix(f0, vec3(0.02), wet_road); + // Puddles: standing water pools in low, flat spots rather than spreading evenly + // over the whole carriageway the way the sheen above does. A world-space mask at a + // frequency of its own (unrelated to the road's detail noise, so the two do not + // look tied together) picks out patches that grow with the wetness and vanish again + // as the road dries; a puddle goes glass-flat and mirrors what is above it. While it + // is actually raining rather than merely wet, and never while it is snow settling + // instead (`enh.weather.z` is fed by any precipitation, `.y` singles snow back out), + // concentric rings cross a puddle where drops land, fading as they widen - the other + // half of the wheel splashes in `puddles.rs`. + let pattern_xy = world_pattern_xy(in.world); + // (the pools: see `road_puddle_coverage`, shared with the classic picture) + puddle = road_puddle_coverage(in.world, n, wet_road); + if (puddle > 0.001) { + // A drop is a few millimetres across and its ring dies away within a hand's + // breadth, so the shared ripple grid is 12.5 cm wide and a ring grows + // to RIPPLE_MAX of a cell, about 5 cm: at 2 m cells with rings a metre and a half + // across, every drop looked like a puddle of its own. Cells run at their own pace + // and only some of them carry a drop at a time, so the surface reads as many small + // impacts rather than one pulsing pattern. + let raining = enh.weather.z * (1.0 - enh.weather.y); + // (faded out where the pixel is wider than half a ring's wave: past a few + // metres they only made the water shimmer) + let ripple_fp = max(length(dpdx(in.world)), length(dpdy(in.world))); + let ripple = puddle_ripple_seen(pattern_xy, camera.post.y, raining, puddle, ripple_fp); + // Standing water hides most of the fine asphalt grain. Keep dry and damp + // asphalt's detail, but let the reflected image read across a filled pool. + albedo = albedo * (1.0 - 0.68 * puddle) / mix(1.0, detail_factor, puddle * 0.8); + ambient_albedo = ambient_albedo * (1.0 - 0.68 * puddle) / mix(1.0, detail_factor, puddle * 0.8); + rough = clamp(mix(rough, 0.03, puddle) - ripple.z * 0.12, 0.02, 1.0); + f0 = mix(f0, vec3(enh.debug.y), puddle); + n = normalize(mix(n, geo_n, puddle) + vec3(ripple.xy, 0.0)); + } + } else if (wet_any > 0.0) { + // (a body's paint wears a film of water as smooth as glass: the street and the sky + // mirror in a wet bus as sharply as in its windows) + // (Lagarde's wet surfaces: the water stands on what faces up and runs off a wall, + // so a wall only darkens where a ledge or a step goes glossy) + let up = smoothstep(0.1, 0.9, geo_n.z); + // (the rougher, the more porous - soil, plaster, unglazed stone - and the more water + // it takes in; a smooth, sealed surface keeps its colour under the film) + let porous = smoothstep(0.25, 0.7, rough); + if (!terrain) { + rough = mix(rough, select(mix(rough * 0.75, min(rough, 0.2), up), min(rough, 0.04), reflective_env), select(wet_any, min(wet_any * 2.6, 1.0), reflective_env)); + } + // Soaked by the rain, a porous surface - soil, a paving stone, plaster, bark - + // turns darker and deeper in colour: the light that enters the water film and is + // scattered back by the surface under it is partly reflected down again at the + // film's top (total internal reflection), and meets the surface once more, which + // absorbs a share of it each time (Lekner and Dorf, "Why some things are darker + // when wet", Applied Optics 1988). Painted metal, glass and leaves shed the water. + let soak = camera.shadow.w * outside * dry_snow * select(0.75, 1.0, terrain) * mix(0.3, 1.0, porous) + * mix(0.45, 1.0, clamp(n.z, 0.0, 1.0)) * select(1.0, 0.0, reflective_env || glass || is_water || thin || metal > 0.5); + albedo = mix(albedo, wet_albedo(albedo), soak); + ambient_albedo = mix(ambient_albedo, wet_albedo(ambient_albedo), soak); + } + // snow lies on what faces up + // (not on a shadow blob: whitened, it lit the snow under the bus instead of shading it) + // (nor on a texture that is the season's snow picture, which shows the map's own snow + // as OMSI 2 does: see the vanilla shader, #879) + let snow_ok = outside * select(1.0, 0.0, in.params2.w > 1.5 || material.ambient.w > 0.5); + // a carriageway under snow that builds up: its own cover, ruts and tracks (road_snow.wgsl) + let carriageway = !terrain && material.params2.z > 0.0 && road_snow_dynamic(); + var rs = vec3(0.0); + if (carriageway && snow_ok > 0.0) { + rs = road_snow(in.world); + } + // a vehicle's part: the snow its own roof has gathered, where that is kept (another + // player's bus keeps the weather's) + let vehicle = vehicle_snow_kept(in.params2.w); + var on_vehicle = 0.0; + if (vehicle && snow_ok > 0.0) { + on_vehicle = vehicle_snow(in.params2.w, in.local); + } + let snow = select(select(enh.weather.y, rs.x, carriageway), on_vehicle, vehicle) * snow_ok; + if (rs.y > 0.0) { + // the slush in the ruts and the tracks: wet and grey, darker than the snow, glossy + let slush = rs.y * snow_ok; + albedo = mix(albedo, albedo * 0.55 + vec3(0.08), slush); + ambient_albedo = mix(ambient_albedo, ambient_albedo * 0.55 + vec3(0.08), slush); + rough = mix(rough, 0.35, slush); + } + if (snow > 0.0) { + let up = clamp(n.z, 0.0, 1.0); + let ground = select(0.0, 1.0, terrain || material.params2.z > 0.0); + // (a road kept clear - "snow on road" off - stays asphalt: whitened, it turned the + // roads white exactly when the weather says they are cleared, #1362; built-up snow + // brings its own cover) + let cleared = select(1.0, 0.0, !carriageway && camera.post.z > 0.5 && !terrain && material.params2.z > 0.0); + // (a vehicle's gathered snow lies thick enough to hide the paint) + let cover = min(cleared * snow * clamp(max(ground, smoothstep(0.78, 0.95, up) * 0.8), 0.0, 1.0) * select(0.55 + 0.35 * tex.a, 1.2, vehicle), 1.0); + albedo = mix(albedo, vec3(0.82, 0.84, 0.88), cover); + ambient_albedo = mix(ambient_albedo, vec3(0.82, 0.84, 0.88), cover); + // fresh snow is all but matte: it scatters the light and shows no highlight + rough = mix(rough, 0.95, cover); + f0 = mix(f0, vec3(0.02), cover); + metal = metal * (1.0 - cover); + } + // specular antialiasing: where the normal turns quickly across a pixel (a low-poly + // bonnet close up, a curved body far away) the surface cannot reflect sharper than that + // spread, or the interpolated normals show as bands in a mirror-like finish + if (reflective_env && !glass) { + let dndx = dpdx(n); + let dndy = dpdy(n); + let spread = min((dot(dndx, dndx) + dot(dndy, dndy)) * 2.0, 0.4); + rough = sqrt(min(rough * rough + spread, 1.0)); + } else if (!thin && !glass) { + rough = rough_aa(rough, n); + } + let env_share = select(1.0, camera.cam_pos.w, reflective_env && !glass); + var sf: Surface; + sf.albedo = albedo * (1.0 - metal); + ambient_albedo = ambient_albedo * (1.0 - metal); + sf.f0 = f0; + sf.rough = rough; + let nv = clamp(mix(face_v, dot(n, v), face_w), 1e-4, 1.0); + // the specular reflectance over the hemisphere, its multiple scattering included: one + // minus it is the share the diffuse part gets, so a surface never sends out more than falls + // on it (and a rough metal is not darker than its colour) + let spec_e = spec_ms(f0, rough, nv); + sf.kd = vec3(1.0) - spec_e.rgb; + sf.comp = spec_e.w; + // (how wide a patch of the surface the pixel covers, m: see `relief_masking`) + let relief_footprint = length(dpdx(in.world)) + length(dpdy(in.world)); + // The same depth-aware traced sample feeds the sun, AO and the debug view. Repeating + // rt_at here and inside ao_gi_at overflowed the optimizer's stack in the DX12 FXC + // fallback (used when dxcompiler.dll cannot be loaded); DXC compiles either form. + // Read it once after the early material returns, with the same taps and their order, + // so that the fallback can compile fs_enhanced too. + let surface_rt = rt_at(in.clip.xy, in.world); + // --- the sun + let s = camera.sun_dir.xyz; + let nl = dot(n, s); + var direct = vec3(0.0); + if (enh.lights.w > 0.0 && max(enh.sun.r, enh.sun.g) > 1e-5) { + var shadow = 0.0; + // (Enhanced+ without a traced shadow for the surface: the far map's as well, below - + // one call of it for both cases: two, each inlined, made the scene shader too big for + // Apple's M4 compiler, whose service crashed on every scene pipeline) + var far = false; + if (glass && nl > 0.0) { + // a pane lets nearly all of it through: the sun on it is its glint, for which one + // compare says enough (the soft filter over a cab's windscreen, doors and side + // windows was a millisecond of the frame) + shadow = sun_shadow_hard(in.world, n); + far = camera.clouds.w > 1.5; + } else if (nl > 0.0 || thin) { + // Enhanced+: the traced shadow where there is one for this surface + // (whose cut-out leaves and fences the shadow map holds alone: see `render_inner`) + let traced = surface_rt; + shadow = sun_shadow_soft(in.world, n, thin); + if (traced.w > 0.5 && traced.z >= 0.0) { + shadow = shadow * traced.z; + } else { + far = camera.clouds.w > 1.5 && traced.w < 0.5; + } + } + if (far) { + shadow = shadow * sun_shadow_far(in.world, n); + } + // (only the beam casts the shadow: what the clouds scatter of it is the sky's, below) + let e_sun = enh.sun.rgb * (shadow * cloud_shadow_ratio(in.world) * sun_beam_share()); + if (thin) { + // foliage: a crown of leaves facing every way, whose normals OMSI points up + // only to light it evenly - lit by the sun from any side (the shadow map + // darkens its far side), a little through the leaves as well. A crown is + // hundreds of leaves at every angle: on average about half of the sun falls on + // them square on, whatever the sun's height (with the up-pointing normals alone a + // low sun left every tree dull and dark while the walls beside it glowed). Seen + // against the sun a leaf glows with what comes through it - yellow-green, the + // light having passed the leaf's colour twice. + let through = pow(clamp(dot(-v, s), 0.0, 1.0), 3.0); + let leaf = sf.albedo / PI; + direct = e_sun * (leaf * (0.42 + 0.3 * max(nl, 0.0) + 0.08 * max(-nl, 0.0)) + + leaf * min(sf.albedo * 2.2, vec3(1.0)) * through * 0.45); + } else if (nl > 0.0) { + // the sun is a disc, not a point: no highlight sharper than it + let a = max(rough * rough, 0.012); + let h = normalize(s + v); + var spec = d_ggx(max(dot(n, h), 0.0), a) * v_smith(nv, nl, a) * f_schlick(f0, dot(v, h)); + // (a rough, unpolished surface's own relief hides its glint from a low sun: see + // `relief_masking`; glass, paint, chrome, water and a wet film keep theirs) + if (!glass && !reflective_env && !is_water && metal < 0.5) { + spec = spec * relief_masking(nl, nv, rough, relief_footprint); + } + // Optional road glare: only the specular sun highlight on terrain or roads. + // Diffuse sunlight, wet reflections and vehicle paint remain unchanged. + if ((terrain || material.params2.z > 0.0) && !is_water) { + spec = spec * camera.lod.z; + } + spec = select(spec, vec3(0.0), dot(geo_n, v) < 0.0 && !is_water); + direct = e_sun * nl * (sf.albedo / PI * sf.kd + spec * sf.comp); + } + } + // --- the moon: by night a directional light as the sun is, with its shadow when the + // maps are drawn along it + let em = enh.moon_light.rgb; + if (max(em.r, em.g) > 1e-9) { + let m = enh.moon.xyz; + let nlm = dot(n, m); + if (nlm > 0.0 || thin) { + var ms = 1.0; + if (enh.moon_light.w > 0.5) { + ms = sun_shadow_soft(in.world, n, thin); + } + let leaf = sf.albedo / PI; + if (thin) { + direct = direct + em * ms * leaf * (0.42 + 0.3 * max(nlm, 0.0)); + } else { + direct = direct + em * ms * nlm * leaf; + } + } + } + // --- sky and ground + var ao = 1.0; + let screen_ao = camera.clouds.w > 0.5 && !capture; + var bounce = vec3(0.0); + if (screen_ao) { +//VK ao = ao_traced_at(in.clip.xy, in.world, surface_rt); + let ag = ao_gi_at(in.clip.xy, in.world, surface_rt); + ao = ag.x; + bounce = ag.yzw; + } + // AO is generated from the opaque depth buffer. A transparent bus pane therefore + // samples the seats/dashboard behind it and makes their dark outlines crawl across the + // glass as the camera moves. The pane has its own transmission/reflection path; it must + // not inherit occlusion belonging to geometry on the far side of the window. + // (nor any other blended surface: a van's translucent door showed the shade of what + // stood behind it) + if (glass || mode > 1.5) { + ao = 1.0; + } + ao = ao * pbr_ao; + let fr = f_schlick(f0, nv); + // inside the player's vehicle the light comes in through the windows and off the + // cabin's own walls: less of it, and neither as blue nor as directional as the sky's + let in_cab = 1.0 - outside; + // The cab's light is one even ambient already (cab_e below); the screen-space occlusion + // on top of it went black in the hollow under the windscreen - the steering wheel and + // the dashboard stood dark beside a brightly lit cash desk. Inside the cab it is taken + // at a third of its strength. + ao = mix(ao, 1.0 - (1.0 - ao) * 0.35, in_cab); + let avg_e = enh.fog_color.rgb * (PI / 0.9); + let cab_e = vec3(dot(avg_e, vec3(0.2126, 0.7152, 0.0722))) * vec3(1.0, 0.98, 0.95); + // (the sun the clouds scatter: shadowless, a light of the sky's kind) + var sky_e = sh_irradiance(n); + let beam = sun_beam_share(); + if (beam < 0.999 && enh.lights.w > 0.0) { + sky_e = sky_e + sun_scattered(n, enh.sun.rgb * cloud_shadow_ratio(in.world) * (1.0 - beam)); + } + var e_amb = mix(sky_e, cab_e * CAB_AMBIENT, 0.6 * in_cab) * ao_bounce(ao, ambient_albedo) + + flash_irradiance(n) * ao * (1.0 - 0.7 * in_cab); +//VK if (screen_ao && in_cab < 1.0) { +//VK e_amb = e_amb + bounce_at(in.clip.xy, in.world) * mix(1.0, ao, 0.5) * (1.0 - in_cab); +//VK } + e_amb = e_amb + bounce * mix(1.0, ao, 0.5) * (1.0 - in_cab); + var ambient = e_amb * ambient_albedo / PI * (vec3(1.0) - spec_e.rgb * env_share); + // --- reflections: the sky probe, as sharp as the surface is smooth + var r = reflect(-v, normalize(mix(face_n, n, face_w))); + let bend_n = normalize(mix(face_n, geo_n, face_w)); + let horizon = horizon_occlusion(r, bend_n); + // a reflection pointing into the surface would show the probe's ground: bend it up + let below = dot(r, bend_n); + if (below < 0.0) { + r = normalize(r - bend_n * below * 1.02); + } + // A wet road, a wet pavement is no mirror: a soft, dim sheen of what stands round it, a + // puddle a blurred picture of it (panes, envmapped paint and still water keep their own + // smoothness). Its reflection is taken this rough, at this share. + let wet_only = !(reflective_env || glass || is_water || ((material.pbr.z > 0.5 || material.pbr.w > 0.5) && !terrain)); + let refl_rough = select(rough, max(rough, mix(0.2, 0.16, puddle)), wet_only); + let wet_share = select(1.0, mix(0.6, 0.7, puddle), wet_only); + let lod = refl_rough * (enh.lights.x - 1.0); + var env = textureSampleLevel(t_probe, s_lin, to_cube(r), lod).rgb * enh.fog_color.w; + // the probe holds only the sky: in a street the low sky is hidden behind houses and + // trees, which reflect about as much light as a quarter-white wall (without this every + // surface wore a milky sheen of the bright horizon, strongest against a low sun) + let surround = enh.fog_color.rgb * (0.25 / 0.9); + let open = smoothstep(-0.05, 0.35, r.z); + env = mix(surround, env, mix(open, 1.0, select(0.25, 0.5, reflective_env && !(glass && probe_only)))); + // the cabin reflects the cabin, not the sky - and so does the bus's own glass seen + // from the driver's seat + let cab_view = max(in_cab, near_player_vehicle(in.world) * inside_vehicle(camera.cam_pos.xyz)); + // From inside the player bus the pane is near the cabin, but it must still show the + // outside sky/street. Using the opaque-surface cabin weight here made every window a + // flat pale patch and hid the useful reflection while driving. + // A pane is the boundary between the cabin and the outside. Mixing the cabin + // irradiance into its reflection made every windscreen look like a pale grey sheet + // from the driver's seat; the interior is already behind the alpha-blended pane. + let cabin_reflection = select(0.85, 0.0, glass); + env = mix(env, cab_e * 0.35 / PI, cabin_reflection * cab_view); + // ... but the inner face of the bus's own glass cannot mirror the sky, which lies + // behind it: it mirrors the cab, far darker than the street seen through it. Taken as + // the sky, the doors (seen at a grazing angle from the driver's seat) went a milky + // grey sheet in fog and snow, when the probe is bright all round. + let own_pane = select(0.0, near_player_vehicle(in.world) * inside_vehicle(camera.cam_pos.xyz), glass); + if (reflective_env) { + // OMSI's photographed environment gives the reflection its structure (trees, + // houses, the street), the probe its light + // A pane looks it up by the reflection's direction in the world, not in the + // camera's frame as Direct3D's sphere map does: taken from the camera, what a + // standing bus's windows mirrored changed whenever the view turned, trees sliding + // in from nowhere over the street seen through them. Height gives the photo's rows + // (sky, the horizon's trees and houses, the ground), the compass direction a + // gentle drift across it that stays put in the world. + let az = atan2(r.y, r.x); + var env_uv = vec2(0.5 + 0.3 * sin(az), 0.5 + 0.45 * clamp(r.z, -1.0, 1.0)); + // The paint reads the photo as Omsi.exe's environment stage lays it on: Direct3D's + // sphere map of the reflection in the camera's frame (`sphere_map_uv`, 0x7ff670 sets + // D3DTSS_TCI_SPHEREMAP and no texture matrix), so the picture on a body turns with + // the camera's yaw and pitch as it does in OMSI. (A pane keeps the world's: through + // it the street itself is seen, and the photo turning over it read as a smear.) + if (!glass) { + env_uv = in.env_uv; + } + if (material.bump.y > 0.5) { + env_uv = env_uv + bump_offset(duv); + } + // (with the mip level its footprint needs on top of the blur: a fixed level showed + // the photo's trees as contour lines across a car's curved bonnet close up, and + // paint takes it as blurred as the vanilla path does) + let photo = textureSampleBias(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], env_uv, max(rough * 16.0, select(2.0, 0.0, glass))).rgb; + let photo_avg = textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], vec2(0.5, 0.5), 12.0).rgb; + let lum_avg = max(dot(photo_avg, vec3(0.2126, 0.7152, 0.0722)), 0.02); + // (a tint, not a picture: an unbounded ratio drew the photo's trees as bands) + // (the photo's own contrast, as the vanilla picture shows it, held only off black + // and off a blinding white; clamped to 0.35 .. 2 and laid on at two thirds, the + // windows mirrored a flat grey where the vanilla ones mirror trees and sky) + let ratio = clamp(photo / lum_avg, vec3(0.12), vec3(select(3.5, 1.0, glass && probe_only))); + let band = 1.0 - smoothstep(0.25, 0.7, abs(r.z)); + // Only a smooth surface mirrors the photo; a satin one a quarter of its contrast. + // (A car's bonnet is a handful of triangles: the photo's mip level by its footprint + // above keeps its trees from turning into contour lines across it close up.) + let sharpness = 1.0 - smoothstep(0.05, 0.25, rough); + // ... and only as far as the reflection is of the outside at all: the driver's own + // windscreen reflects the cab, and the photo's trees drawn over that stood as + // contour lines across everything seen through it (a car's bonnet close up) + let outside_env = 1.0 - cab_view; + // ... and not in a fog: there is nothing sharp out there to mirror. The photo's + // trees stood as flat grey silhouettes on every pane in fog, in front of the real + // (fogged) trees behind the glass - outlines of trees that are not there + let clear_air = exp(-enh.fog.x * 150.0); + env = env * mix(vec3(1.0), ratio, band * mix(0.25, 1.0, sharpness) * outside_env * clear_air * enh.debug.z); + } + // what the SSAO darkens, it also keeps reflections out of + let spec_occ = clamp(pow(nv + ao, exp2(-16.0 * rough - 1.0)) - 1.0 + ao, 0.0, 1.0); + // (a PBR set's roughness or metalness map says how it reflects: the probe, as for an envmap) + let pbr_reflects = (material.pbr.z > 0.5 || material.pbr.w > 0.5) && !terrain; + // (a wet road mirrors the sky probe as well; and what reflects nothing keeps the light + // the Fresnel term took off its ambient above - at a grazing angle that term is near 1, + // and the far road and ground went dark with no reflection in its place, #374) + // Every solid surface reflects its few per cent: a dielectric's 4 % at normal incidence + // rising towards grazing, by its roughness and the light its microfacets pass on (the + // diffuse part took that share off above). Leaves and fences are left out: alpha-tested + // silhouettes, whose grazing sheen was white sparkle. A wet road's film reflects at its + // own share. + let reflects = !thin; + var refl_f = spec_e.rgb * spec_occ * horizon * select(1.0, mix(1.0, wet_share, wet_road), wet_only); + if (!reflects) { + ambient = e_amb * ambient_albedo / PI; + } + if (glass) { + // Transparent bus panes need a readable outside reflection from the driver's + // viewpoint; opaque paint must never receive this boost. + refl_f = refl_f * (1.0 - 0.85 * own_pane); + } + refl_f = refl_f * env_share; + var reflection = select(vec3(0.0), env * refl_f, reflects); + // Enhanced+: traced instead (rough surfaces keep the probe, which is as good as a + // ray there): the windows, the chrome and the paint's clear coat mirror the real street + // round them - the coat as sharply as the glass, where it is polished (`coat_rough`) + // (a dry plain surface - plaster, plastic, a satin wall - is traced up to a lesser + // roughness: its few per cent of a blurred street are as good from the probe, and the rays + // are spent where the reflection is seen; between the two the traced one fades in) + let trace_top = select(0.75, 0.5, wet_only && wet_road <= 0.0); + let trace_k = 1.0 - smoothstep(trace_top - 0.15, trace_top, refl_rough); + // (not the player's own panes seen from inside: their faint reflection of the cab is the + // glass's own, and the street behind them - a wet road through the windscreen - keeps + // its traced one, see below) + let traced = camera.clouds.w > 1.5 && reflects && trace_k > 0.0 && !capture && !(glass && own_pane > 0.5); + if (traced) { + var w = dot(refl_f, vec3(0.2126, 0.7152, 0.0722)) * aer.a * trace_k; + if (glass) { + // A pane mirrors what the rays find as glass does: 4 % at the normal, Fresnel's + // rise towards grazing (a tinted one a little more against what little comes + // through it). The share above is the vanilla picture's, which lays a dim photo + // over the pane; the traced street at that share - a fifth to a half - turned + // every window into a mirror of the bright sky. + let f0_glass = vec3(mix(0.04, 0.07, clamp(alpha * 1.5, 0.0, 1.0))); + w = dot(spec_ms(f0_glass, rough, nv).rgb, vec3(0.2126, 0.7152, 0.0722)) * spec_occ * horizon * env_share * aer.a * trace_k; + w = w * smoothstep(0.0, 0.05, alpha); + } else if (mode > 1.5) { + // (a blended layer reflects only where it is there: a painted ground's brush mask) + w = w * clamp(alpha, 0.0, 1.0); + } + let rough_t = refl_rough; + if (w > 0.002) { + reflection = reflection * (1.0 - trace_k); + rt_gbuf = vec4(n * w, w); + rt_aux = vec4(dist * w, rough_t * w, 0.0, w); + if (glass) { + // A pane takes the pixel's surface over (coverage 1, its weight in the + // normal's length, rt_reflect.wgsl): blended over the seats behind it by its + // own few per cent, the saloon's surfaces had weighed nine tenths - the rays + // left from a point between the pane and the seats along a normal halfway + // between theirs, and the window wore white blotches of the sky with the + // seats' outlines. + rt_gbuf = vec4(n * w, 1.0); + rt_aux = vec4(dist, rough_t, 0.0, 1.0); + } + } + } + // --- the lamps, the cabin light and what glows by itself + // ([nomaplighting] objects are not lit by the map's lamps; light-mapped roads are, with + // the tile light map on top) + // (no shadows inside the player's own vehicle, whose cab the depth hardly shows, nor in + // the probe's capture) + let film = select(vec3(0.0), vec3(wet_road, refl_rough, wet_share), wet_only && wet_road > 0.0); + // A clear pane scatters nothing: what lights it shows only in what it mirrors (the + // lamps' glints, the sky, the street) and in the little its tint takes from the daylight + // through it. Lit as a grey Lambertian layer, every lamp and the cab's own lamps laid a + // milky veil over the windows at night, over everything seen through them. + var sf_lit = sf; + if (glass) { + sf_lit.albedo = vec3(0.0); + } + if ((terrain || material.params2.z > 0.0) && !is_water) { + sf_lit.f0 = sf_lit.f0 * camera.lod.z; + } + let lamps = lamp_light(in.world, n, v, sf_lit, thin, !capture, film, dot(geo_n, v) < 0.0 && !is_water) * select(1.0, 0.0, material.params.y > 0.2 && material.params.y < 0.3); + // [interiorlight]: OMSI adds its lamps' light to the lit meshes whatever the daylight, + // so a switched-on saloon is brighter by day as well and only stands out more at night. + // Taken as a lamp against the daylight exposure it vanished by day altogether. + // (in the picture's own terms, as the vanilla pass adds it: scaled with the metering it + // grew with the night and whitened the saloon) + // (the lamps' light does not reach into the gaps under the seats and round the + // handrails either: without the ambient occlusion on it they glowed through there) + // A sphere-mapped pane or body mirrors the street round it: at night that is lit by the + // lamps, not by the sky the probe holds (dark then). The street's radiance under them + // (`lamp_ground`) is laid into the reflection where it points at the street and the + // walls: a bus's windows and paint under a street lamp show the lit street, the ones on + // an unlit road stay dark. (Not through the photo's structure: its bright rows are the + // day's sky, which the lamps do not light.) + if ((reflective_env || glass) && !traced) { + let lit_round = lamp_ground * (1.0 - open); + reflection = reflection + lit_round * refl_f * (1.0 - cab_view); + } + // (in the player's saloon: what its lamps' light meets on the way, see `cabin_visibility`) + var cabin_vis = 1.0; + if (in_cab > 0.5 && camera.lamp_atlas.w > 0.5) { + cabin_vis = cabin_visibility(in.world, n); + } + let cabin_light = interior_lamps(in.world, n, in.params2.z) * cabin_vis; + let cabin = sf_lit.albedo * cabin_light * mix(1.0, ao, 0.85); + var rgb = (direct + ambient + lamps) * pre + cabin; + // A material's own emissive colour ([matl_allcolor], an .x's emissive) is the texture at + // full brightness in Omsi.exe: shown at the screen's white, not scaled with the eye's + // night adaptation - a texture lit that way by [matl_allcolor] glared at several times + // white at night (#1228, #1236). (The night maps of lit windows keep their light.) + // (not a pane's: glass gives off no light of its own, see `sf_lit`) + var emit = select(tex.rgb * material.emissive.rgb * clamp(enh.exposure.z * 2.0, 0.8, 1.0), vec3(0.0), glass); + // (the tile light map on the splines and [LightMapMapping] objects is the vanilla + // path's: here the map's lamps light them, tinted from that map, as they light every + // other surface - added on top it lit the roads twice, with a hard edge where a road + // met a square that is an object) + if (material.extra.w > 0.5) { + let switched = material.extra.w > 1.5; + let night = select(rain_lit_windows(in.local), 1.0, switched); + // (a switched one is the display's own state: not dimmed with the instance's night + // lighting, which is 0 by day and left the Procity's pressure screen black) + let nm = night_sample.rgb * night * select(clamp(in.params2.y, 0.0, 1.0), 1.0, switched); + // (The ground gets no light from the tile's light map here: it is the lamps' pools as + // OMSI bakes them, a `[maplight]`'s colour times (radius / distance)^2 out to sixteen + // radii, taken through every wall and roof, with no shadow of anything and with a + // tail past where the lamp itself reaches. The lamps are lights of their own in this + // picture - the same inverse square, cut off where their reach ends, shadowed by the + // maps of `LampShadow` - and what the map added three times over was a snow-covered + // lawn in a courtyard lit orange by floodlights across a building, or the ground of a + // whole street glowing with one lamp's tail.) + if (!terrain) { + // lit windows and signs; a switched lamp or display holds up against daylight + // as the self-illuminated materials do + // (a window lit from inside shows some 80 cd/m² - a room's 300 lux off its + // walls and through a curtain - an illuminated sign more: over the dark street + // round it, a little over the screen's white, so that it keeps its colour) + emit = emit + nm * select(min(enh.exposure.z * 3.6, 1.2), mix(max(enh.exposure.z * 2.0, 0.8), 0.8, near_player_vehicle(in.world) * inside_vehicle(camera.cam_pos.xyz) * (1.0 - outside)), switched); + } + } + if (material.params2.x > 0.5 && !terrain && !glass) { + // [matl_lightmap]: laid onto the light with ADDSMOOTH in Omsi.exe (see the vanilla + // shader), so it adds what the surface's own light leaves: little by day, fully at + // night, and less where the saloon lamps light the surface already. (As an emission + // at 0.6 of the texture by day and on top of the lamps at night, a switched-on + // cabin's light-mapped parts were flat white.) + let lm = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], buv, camera.lod.x).rgb * clamp(in.params2.x, 0.0, 1.0); + if (material.emissive.w < -1.5) { + let night = clamp(camera.sun_color.w, 0.0, 1.0); + let left = (vec3(1.0) - clamp(cabin_light, vec3(0.0), vec3(1.0))) * (0.12 + 0.88 * night); + emit = emit + tex.rgb * lm * left * max(enh.exposure.z * 2.0, 0.6); + } else { + // (By day as by night: ADDSMOOTH lifts the surface to its texture's colour by the + // map whatever light it has, and what the light already gives - the day's, the + // saloon lamps' - is taken off below. Lifted by an eighth of that by day, a + // display in the cab's shade was far darker than in Vanilla+, #2051.) + // ... and as there it lifts the surface to its texture's own colour at the + // most, shown as a display is (see the unlit path): taken as a light of the + // night's level on top, a white light map (`weiss.bmp`, laid on a display so + // it shows at night) went past the tone curve's knee and bleached its colours - + // the Procity's red and blue gauges pink and lavender (#827). (An LED panel's + // light map stays as it was: its dots are meant to burn above their colour.) + // The map's script variable controls its backlight. Dimming every light-mapped + // surface as a cab screen hid instrument backlights even with the lights on. + // (the lift is the saloon lamps' light: where their light does not reach for a + // handrail or a seat standing in it, the map does not lift the surface either) + emit = emit + max(display_level(tex.rgb) * enh.exposure.y - rgb, vec3(0.0)) * lm * cabin_vis; + } + } + if (material.emissive.w < -1.5) { + // an LED panel (see MaterialExtra::led): the lit dots - the alpha the `\S:n` script + // texture carries, in the colour of the panel's own texture - are the panel's own + // light, drawn as bright as the settings ask for (`Led glow`, 16 levels, 0 = off). + // The glow takes them where it leaves every other screen out of its source + // (`post.wgsl`) and blooms a halo around the panel. (Kept at their own brightness + // however the metering treats the scene, as a display's text is.) Its light is its + // white light map's, so it goes out with that map's variable (the busbar, the + // lights) as the Omsi.exe stage does. + let lm_gate = select(1.0, clamp(in.params2.x, 0.0, 1.0), material.params2.x > 0.5); + // (in the cab - a dashboard's LCD lit by a white map reads as a panel - it dims at night; + // not a page's destination sign (-3), which is read from the street through the windscreen) + let cab_dim = select(1.0 - outside, 0.0, material.emissive.w < -2.5); + // (`material.glow.y`: the share of it the modeller gives the panel, `[led_glow_effect]`) + emit = emit + tex.rgb * enh.led.x * material.glow.y * alpha * lm_gate * max(enh.exposure.z * 2.0, 0.8) * mix(1.0, display_dim(1.0), cab_dim); + } else if (material.emissive.w < -0.5) { + // a display's text (see MaterialExtra::display) + emit = emit + tex.rgb * 0.35 * max(enh.exposure.z * 2.0, 0.8) * display_dim(1.0); + } + if (material.glow.x > 0.0) { + // [matl_glow] (see `matl_glow_light`): the material is its own light, drawn in HDR. + // The classic picture does not know the keyword (`params2.x` is off, see + // `add_material_extra`). + emit = emit + matl_glow_light(buv, tex.rgb); + } + rgb = rgb + emit; + if (enh.debug.x > 0.5) { + // OMSI_DEBUG_ENHANCED: one term alone, as it lands on the screen + let dm = i32(enh.debug.x); + var dc = vec3(0.0); + switch dm { + case 1: { + let tr = surface_rt; + let sm = sun_shadow_soft(in.world, n, thin); + dc = select(vec3(sm), vec3(tr.z * sm, tr.z * sm, tr.z * 0.6 + 0.4), tr.w > 0.5 && tr.z >= 0.0); + } + case 2: { dc = vec3(ao); } + case 3: { dc = n * 0.5 + vec3(0.5); } + case 4: { dc = vec3(aer.a); } + case 5: { dc = e_amb * pre * 0.1; } + case 6: { dc = reflection * pre; } + case 7: { dc = sf.albedo; } + case 8: { dc = direct * pre; } + case 9: { dc = aer.rgb * pre; } + case 11: { dc = vec3(fract(dist / 10.0), dist / 1000.0, in.clip.z * 100.0); } + case 12: { dc = vec3(mode * 0.5, f32(terrain), in.params2.w); } + case 13: { dc = vec3(in_cab, ao, spec_occ); } + case 14: { dc = (ambient + direct) * pre; } + case 15: { dc = lamps * pre; } + case 16: { dc = emit; } + case 17: { dc = vec3(rough, f0.g * 10.0, metal); } + default: { dc = vec3(alpha, f32(glass), f32(has_env)); } + } + return vec4(dc, 1.0); + } + if (glass) { + // see-through glass: the reflection is added on top of what shows through, so + // the blend keeps it where the glass itself is faint - but not where the texture + // is not there at all: Omsi.exe leaves the alpha as the texture has it, so a + // see-through part of a blended layer (the clear ground of a sticker on the + // cab's wall, #861) shows no reflection; made up to a quarter opaque by it, the + // whole rectangle of the sticker mirrored the sky + let cover = smoothstep(0.0, 0.05, alpha); + // (or, from inside the player's bus, the lit cabin it mirrors: `glass_reflection`) + let refl_rgb = glass_reflection(in.world, n, v, reflection * pre) * cover; + let rl = dot(refl_rgb, vec3(0.2126, 0.7152, 0.0722)); + // (a pane passes most light: a reflection making it up to 60 % opaque laid a grey + // veil over the destination display behind the windscreen and the saloon) + var a2 = clamp(alpha + (1.0 - alpha) * clamp(rl * 0.25 + fr.g, 0.0, 0.25) * (1.0 - 0.85 * own_pane) * cover, alpha, 1.0); + var c = (rgb * alpha + refl_rgb) / max(a2, 1e-3); + // the rain on a pane without a film of its own (`pane_rain`): the traffic's windows + { + let pr = pane_rain(in.world, in.local, in.normal); + if ((pr.cover > 0.001 || pr.veil > 0.001 || pr.mist > 0.001) && cover > 0.0) { + let o = pane_rain_compose(pr, c, a2, v, rain_env_enhanced(reflect(-v, pr.n), 1.0) * pre, sh_irradiance(pr.out) / PI * 0.9 * pre); + c = o.rgb; + a2 = o.a; + } + } + // the condensation on the player's bus's panes (omsi-app condensation.rs): a film of + // droplets, each many wavelengths wide, takes twice its shadow out of the light + // (the extinction paradox): half of what it scatters is diffracted a degree or two + // forward - what lies behind goes soft, in the tone mapping (post.wgsl `misted`) - + // and half is refracted and reflected every way, a milky veil lit by the street + // through the glass and, the part the droplets send back, by the cabin + let fog = glass_condensation(in.world, n) * cover; + glass_fog = fog; + if (fog > 0.001) { + // (of the widely scattered half, some 30 % goes back: a fully misted pane sends + // some 15 % of the light back, Briscoe and Galvin 1991) + let back = 0.3; + let lit_street = avg_e / PI * pre; + let lit_cabin = cab_e * CAB_AMBIENT / PI * pre + cabin_light; + let milky = lit_street * (1.0 - back) + lit_cabin * back; + let veil = 0.5 * fog; + let a3 = a2 + (1.0 - a2) * veil; + c = (c * a2 * (1.0 - veil) + milky * veil) / max(a3, 1e-3); + a2 = a3; + } + return vec4(c * aer.a + aer.rgb * pre, a2); + } + rgb = rgb + reflection * pre; + // The later screen-space pass replaces only this fraction of the sky reflection. + // A miss adds zero, so the existing sky, Fresnel and fog stay the fallback. Colour + // and coverage are resolved together, including terrain painting and glass over roads. + if (!glass && !reflective_env) { + // (a pool mirrors by its Fresnel term and its share of the road; so does the sheen of a wet + // road, at the Fresnel term of water a little under full - the lamps' and the cars' + // streaks down a wet street at night, which come from the light's own brightness and so + // need no more than that share - and still water as a whole) + let fresnel = 0.02 + 0.98 * pow(1.0 - clamp(nv, 0.0, 1.0), 5.0); + let pool = puddle * env_brdf(f0, rough, nv).g * select(wet_road, 1.0, pbr_reflects) * wet_share * aer.a; + let sheen = select(0.8 * smoothstep(0.55, 0.95, wet_road), 1.0, is_water) * fresnel * aer.a; + let weight = clamp(max(pool, sheen), 0.0, 1.0); + *puddle_weight = vec2(weight, weight * spec_occ); + } + // water hides what lies under it as far as it reflects (Fresnel): see-through from + // above, a mirror of the sky towards the horizon + let a_out = select(alpha, clamp(alpha + (1.0 - alpha) * fr.g, alpha, 1.0), is_water); + return vec4(rgb * aer.a + aer.rgb * pre, a_out); +} + +// Small waves on the water at map point `p` (m) and time `t` (s): the slope of four wave +// trains of 1.3 to 4.7 m running different ways. +fn water_ripple(p: vec2, t: f32) -> vec2 { + var g = vec2(0.0); + let dirs = array, 4>(vec2(0.8, 0.6), vec2(-0.45, 0.89), vec2(0.96, -0.28), vec2(-0.7, -0.71)); + let lens = array(4.7, 2.9, 1.9, 1.3); + for (var i = 0; i < 4; i = i + 1) { + let k = 6.2831853 / lens[i]; + // deep-water waves: their speed goes with the square root of their length + let w = sqrt(9.81 * k); + g = g + dirs[i] * cos(dot(p, dirs[i]) * k - w * t) * 0.045; + } + return g; +} + +// Shade the complete local vehicle from the reflected eye. Main-camera ambient +// occlusion is not applicable to this view beneath the road. +@fragment +fn fs_puddle_vehicle(input: FsIn) -> @location(0) vec4 { + // One reflected camera for the complete vehicle, including its transparent panes. + let plane = vehicle_reflection.plane; + let height = dot(plane.xyz, input.world) - plane.w; + if (height < 0.0 || material.emissive.w > 1.5) { discard; } + var unused = vec2(0.0); + let eye = camera.cam_pos.xyz - 2.0 * plane.xyz * (dot(plane.xyz, camera.cam_pos.xyz) - plane.w); + if (camera.post.x < 0.5) { + var unused_vanilla = 0.0; + return shade_vanilla(input, &unused_vanilla, eye); + } + return shade_enhanced(input, &unused, true, eye); +} + +@fragment +fn fs_puddle_chassis() -> @location(0) vec4 { + if (camera.post.x < 0.5) { return vec4(camera.ambient.rgb * 0.025, 1.0); } + return vec4(sh_irradiance(vec3(0.0, 0.0, -1.0)) * enh.exposure.x * 0.025, 1.0); +} + +// The painted ground's albedo (`Renderer::encode_ground`): the terrain's base and its paint +// layers laid over each other into one picture of what the surface is made of - texture, +// detail and tint, blended by each layer's coverage - which the main pass then lights once +// (`from_ground` in `shade_enhanced`) instead of lighting every layer in full and blending +// the lit colours. The base writes it, the layers blend into it (the pipeline's blend: the +// coverage over what is there; the alpha channel is left as the base wrote it). +@fragment +fn fs_ground(in: FsIn) -> @location(0) vec4 { + let duv = in.uv * material.extra.z; + let buv = tex_address(in.uv - in.params.zw); + let mode = material.params.x; + // (a brush mask that covers nothing here: the layer's texture need not be read) + if (TERRAIN_PAINT && mode > 1.5 && material.params.z > 0.5 && material.params.w > 0.5) { + let cover = smoothstep(0.32, 0.68, sample_transmap(buv).a); + if (cover * material.color.a * in.params.x == 0.0) { + discard; + } + } + var tex = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv); + if (material.extra.y > 0.0) { + let det = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], in.uv * material.extra.y, camera.lod.x); + tex = vec4(clamp(tex.rgb * det.rgb, vec3(0.0), vec3(1.0)), tex.a); + } + var cover = tex.a; + if (material.params.z > 0.5) { + cover = select(1.0, sample_transmap(buv).a, material.params.w > 0.5); + if (mode > 1.5) { + cover = smoothstep(0.32, 0.68, cover); + } + } + var alpha = cover * material.color.a; + if (mode < 0.5) { + alpha = 1.0; + } + alpha = alpha * clamp(in.params.x, 0.0, 1.0); + if (TERRAIN_PAINT && alpha == 0.0) { + discard; + } + return vec4(tex.rgb * material.color.rgb, alpha); +} + +// The bus's windows in the enhanced picture: the rain on their outer face, the snow that +// settles there and the condensation on their inner face. (The drops and the snow are the classic pictures' too: scene/08_rain_glass.wgsl.) + +// The pane at a pixel, in the vehicle's own frame (the film's vertices as its mesh has them, +// `FsIn.local`): the drops are laid out there, so they stay on the glass however the body +// rolls and pitches and on a door that swings open. The modellers' texture coordinates of +// a film are no measure of the glass: on the windscreen of the NL202 they run half as fast +// again one way as the other and at sixty degrees to each other, from triangle to triangle +// anew, and every drop drawn in them came out a slanting streak. So a pane is laid flat by +// the axes of the vehicle (`pane_proj`): the windscreen and the rear window onto its +// across and up, the side windows onto its along and up, a roof light onto its plan. A +// raked or curved pane is foreshortened in that projection; a drop is drawn round all the +// same, its offsets taken back onto the glass (`m`) before its shape is worked out. The +// drops' grid alone stays in the projection: on a pane at an angle to it a cell covers +// more glass, and the drops are a little fewer there. + +// (The drops on a pane, the runners, the blur's picture and the pane's own frame - +// `glass_water`, `glass_blur` - are the classic pictures' too: scene/08_rain_glass.wgsl.) + +// The rain film on a pane (the enhanced pass's `emissive.w` 2 layer), drawn over the +// clean picture of the frame: the drops, each a small lens that shows the street behind +// it upside down, a shade darker at its rim where the light is bent away, with the sky's +// glint on it, and between them the soft blur of the wet glass. +fn glass_film(in: FsIn, water: f32) -> vec4 { + let v = camera.cam_pos.xyz - in.world; + let dist = length(v); + let vn = v / max(dist, 1e-4); + let in_cab = inside_vehicle(camera.cam_pos.xyz) * near_player_vehicle(in.world) > 0.5; + let g = glass_water(in.world, in.local, in.normal, water, camera.post.y, in_cab); + if (g.cover <= 0.001 && g.mist <= 0.001 && g.veil <= 0.001) { + return vec4(0.0); + } + let pre = enh.exposure.x; + let has_picture = camera.flags.z < -0.5; + let dims = vec2(textureDimensions(mx_tex2d[mx_mat.env])); + let uv0 = in.clip.xy / dims; + let mist_col = sh_irradiance(g.out) / PI * 0.9 * pre; + // the view through the wet glass between the drops: softened by the film of water + // (a running film scatters the light by a fraction of a degree: some 0.7 % of the + // picture's height in a downpour, a third of that in a drizzle) + let veil_lod = log2(max(dims.y * mix(0.002, 0.006, clamp(g.veil / 0.3, 0.0, 1.0)), 1.0)); + var behind = mist_col; + if (has_picture) { + behind = finite_or(glass_blur(uv0, veil_lod), mist_col); + } + // --- a drop: a small lens. Through it the street shows small and upside down (each + // point of the drop looks out along its own bent way, `tilt` across the screen), the + // more bent the further out on it; at its rim the light is bent so far that little of + // it reaches the eye, a darker ring. + var drop_col = behind; + var a_drop = 0.0; + if (g.cover > 0.001) { + let tilt = g.n - g.out * dot(g.n, g.out); + let right = camera.cam_right.xyz; + let up = camera.cam_up.xyz; + // (a drop is a wide lens: from its rim it looks out some 30 degrees aside, the sky + // in the bottom of a drop against a wall) + let o = vec2(dot(tilt, right), -dot(tilt, up)) * 0.3; + var seen = behind; + if (has_picture) { + var uv = clamp(uv0 - o, vec2(0.001), vec2(0.999)); + // (only what lies beyond the glass: where the bent way lands on the cab's own + // dashboard or pillar, in front of the pane, the drop shows what is straight + // behind it instead) + if (camera.clouds.w > 0.5 && camera.clouds.w < 1.5) { + let asz = vec2(textureDimensions(t_ao)); + let z = textureLoad(t_ao, min(vec2(uv * asz), vec2(asz) - vec2(1)), 0).g; + let zg = (camera.view_proj * vec4(in.world, 1.0)).w; + let beyond = select(smoothstep(zg + 0.05, zg + 0.4, z), 1.0, z <= 0.0); + uv = mix(uv0, uv, beyond); + } + seen = finite_or(glass_blur(uv, 0.8 + 1.5 * g.mist), behind); + } + let rim = smoothstep(0.55, 1.0, g.rim); + let facing = dot(g.out, vn) > 0.0; + let cosv = clamp(abs(dot(g.n, vn)), 0.0, 1.0); + let f = select(0.02, 0.02 + 0.98 * pow(1.0 - cosv, 5.0), facing); + let mirrored = rain_env_enhanced(reflect(-vn, g.n), 1.0) * pre; + var c = seen * (1.0 - 0.45 * rim) * (1.0 - f) + mirrored * f; + // the sun: a pinpoint where the dome mirrors it + if (facing) { + let r = reflect(-vn, g.n); + c = c + enh.sun.rgb / PI * pre * pow(max(dot(r, camera.sun_dir.xyz), 0.0), 900.0) * f * 60.0; + } + // A drop of a pixel or less is no lens one can see: its many ways average to the + // view behind it, a little dimmer for its rim - a faint grain, not a dark speck. + let detail = smoothstep(0.5, 1.6, g.size_px); + drop_col = mix(behind * 0.93, c, detail); + a_drop = g.cover * mix(select(0.15, 0.5, has_picture), 0.95, detail); + } + // Drops a few pixels across are a pane's sparkle close up; seen from the street they + // fade out over the first fifteen metres. The haze stays further. + let aer = air(-vn, fog_distance(in.world), camera.cam_pos.z - enh.fog.z, in.world.z - enh.fog.z); + a_drop = a_drop * (1.0 - smoothstep(5.0, 15.0, dist)); + // the fine mist of droplets: a faint grey scatter of the light about + let a_mist = g.mist * 0.5; + var a_veil = 0.0; + if (g.veil > 0.001 && has_picture) { + a_veil = g.veil * (1.0 - smoothstep(25.0, 60.0, dist)); + } + let a_under = a_veil + a_mist * (1.0 - a_veil); + let under = (behind * a_veil + mix(mist_col, behind, 0.9) * a_mist * (1.0 - a_veil)) / max(a_under, 1e-4); + var a = a_drop + a_under * (1.0 - a_drop); + if (a <= 1e-4) { + return vec4(0.0); + } + let col = (drop_col * aer.a * a_drop + under * a_under * (1.0 - a_drop)) / a; + // From inside, the rain is seen through the condensation on the glass's inner face + // (drawn with the pane before this film): a misted pane shows the drops behind it as + // soft shadows, not sharp lenses. + if (in_cab) { + a = a * (1.0 - 0.5 * glass_condensation(in.world, g.out)); + } + return vec4(col, a); +} + +// The snow a wiped pane holds while it snows (`is_snow_pane`; the mask's cover: 0 clear +// glass, up to 1 a pane closed by snow, above 1 the bank a blade pushed to the end of its +// sweep, below 0 glass a blade has just cleared). Crystals land one by one and stick, hold +// a while and melt into a little water - soon on the windscreen, whose glass the warm air +// of the defroster heats, slowly on a side window. As the cover grows they close into a +// milky layer, and it lies deepest along the windscreen's bottom edge and in its lower +// corners, where the blades and the airstream do not reach. +fn glass_snow(in: FsIn, cover: f32) -> vec4 { + // (the windscreen's defroster from the cabin's air, the height on the glass in the bus's + // own frame with the body's tilt: see `glass_snow_with`, which the classic pictures + // share) + let l = pane_local(in.world); + let fz = clamp(l.z / max(camera.inside_b.w, 0.1), -1.0, 1.0); + return glass_snow_with(in, cover, enh.condensation.w, fz); +} + +// A direction in the frame of the bus the camera is in (`pane_local` without the shift). +fn pane_dir(d: vec3) -> vec3 { + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let v = vec3(d.x * ch - d.y * sh, d.x * sh + d.y * ch, d.z); + let t = enh.pane_tilt; + let p = vec3(v.x, v.y * t.y + v.z * t.x, v.z * t.y - v.y * t.x); + return vec3(p.x * t.w - p.z * t.z, p.y, p.z * t.w + p.x * t.z); +} + +// How close the edge of the pane at `world` (normal `n`) is: 1 against it, falling to 0 +// some 25 cm in; -1 where it cannot be told. A pane's edge is where its frame begins - the +// rubber, the pillar, the trim, the dashboard under the windscreen: opaque and in the depth +// prepass, lying on the glass's own plane, where the glass is not. So points on the pane's +// plane round the pixel, in eight ways out to 26 cm, are looked up in the prepass's depth +// (the ambient occlusion's texture keeps it): where an opaque surface lies there on the +// plane - within a centimetre or two of it, not a wiper's arm a hand's breadth outside - the +// pane has ended. The nearest such end in each way, averaged over the ways: in a corner +// two ways find it close, along an edge one, in the middle of a pane none. +fn glass_frame_near(world: vec3, n: vec3) -> f32 { + if (camera.clouds.w < 0.5 || camera.clouds.w > 1.5) { + return -1.0; + } + let size = vec2(textureDimensions(t_ao)); + let nn = safe_normal(n); + let up0 = vec3(0.0, 0.0, 1.0) - nn * nn.z; + let a = select(vec3(1.0, 0.0, 0.0), normalize(up0), dot(up0, up0) > 0.04); + let b = cross(nn, a); + var sum = 0.0; + for (var i = 0; i < 8; i = i + 1) { + let ang = f32(i) * 0.7853982 + 0.2; + let dir = a * cos(ang) + b * sin(ang); + var near = 0.0; + for (var k = 0; k < 6; k = k + 1) { + let dist = 0.03 + 0.046 * f32(k); + let c = camera.view_proj * vec4(world + dir * dist, 1.0); + if (c.w <= 0.05) { + break; + } + let uv = vec2(c.x / c.w * 0.5 + 0.5, 0.5 - c.y / c.w * 0.5); + if (any(uv < vec2(0.0)) || any(uv > vec2(1.0))) { + break; + } + let z = textureLoad(t_ao, min(vec2(uv * size), vec2(size) - vec2(1)), 0).g; + if (z > 0.0 && abs(z - c.w) < 0.015 + 0.006 * c.w) { + near = 1.0 - (dist - 0.03) / 0.26; + break; + } + } + sum = sum + near; + } + return clamp(sum / 3.0, 0.0, 1.0); +} + +// How much of the light crossing the player's bus's pane at `world` (normal `n`) its +// condensation scatters (0..1). One cabin air mists all the glass much alike: each +// window's film (enh.condensation: the optical depths of the windscreen's, the side +// windows' and the rear window's, omsi-weather condensation.rs) is taken two thirds from +// their mean. The film starts where the glass is coldest and the air stillest, in a pane's +// corners and along its frame (and low down), and grows inward as it thickens, its front +// wandering with the glass's own patchiness, until it closes over the pane. A heavy film +// gathers into drops that trickle down and leave clear tracks; on the windscreen the +// defroster's warm air clears it from the bottom up. +fn glass_condensation(world: vec3, n: vec3) -> f32 { + if (camera.inside_c.w < 0.5) { + return 0.0; + } + let l = pane_local(world); + let h = camera.inside_b.yzw; + if (any(abs(l) >= h + vec3(0.25))) { + return 0.0; + } + let nl = safe_normal(pane_dir(n)); + let gap = h - abs(l); + // (the panes in the body's skin only, by the way they face: not the instruments' glass + // behind the windscreen or a partition in the saloon) + var own = -1.0; + var front = false; + if (abs(nl.y) > 0.55 && gap.y < 0.45) { + front = l.y > 0.0; + own = select(enh.condensation.z, enh.condensation.x, front); + } else if (abs(nl.x) > 0.5 && gap.x < 0.35) { + own = enh.condensation.y; + } + if (own < 0.0) { + return 0.0; + } + let depth = mix((enh.condensation.x + enh.condensation.y + enh.condensation.z) / 3.0, own, 0.35); + if (depth <= 0.001) { + return 0.0; + } + // the pane's own frame in metres: across, and up the glass + let up0 = vec3(0.0, 0.0, 1.0) - nl * nl.z; + let up = select(vec3(1.0, 0.0, 0.0), normalize(up0), dot(up0, up0) > 0.04); + let s = vec2(dot(l, cross(up, nl)), dot(l, up)); + let fz = clamp(l.z / max(h.z, 0.1), -1.0, 1.0); + let low = 1.0 - clamp(fz * 0.5 + 0.5, 0.0, 1.0); + let edge_seen = glass_frame_near(world, n); + let edge = select(edge_seen, 0.15 + 0.3 * low, edge_seen < 0.0); + let n1 = snow_noise(s * 3.0 + vec2(11.0, 3.0)); + let n2 = snow_noise(s * 9.0 + vec2(3.0, 17.0)); + let patchy = n1 * 0.7 + n2 * 0.3; + // (the front: into the corners and along the frame at first, the glass's patchiness + // breaking its line, over the whole pane at a depth of two; a soft front, the film + // thinning out over a few centimetres) + let grow = 1.0 - exp(-depth * 1.3); + let potential = 0.45 * edge + 0.15 * low + 0.45 * patchy; + let front_line = 1.0 - grow * 1.3; + let covered = smoothstep(front_line - 0.18, front_line + 0.18, potential); + var amount = covered * (1.0 - exp(-depth * (0.9 + 0.5 * patchy))); + // the fine grain of the droplets themselves + amount = amount * (0.92 + 0.08 * snow_noise(s * 140.0)); + if (depth > 1.4) { + // trickles: drops grown heavy run down a few centimetres a minute, each clearing a + // narrow track below where it started + let lane = floor(s.x / 0.03); + let h1 = rain_hash(vec2(lane, 71.0)); + if (h1.x < clamp((depth - 1.4) * 0.35, 0.0, 0.6)) { + let h2 = rain_hash(vec2(lane, 13.0)); + let x0 = (lane + 0.3 + 0.4 * h2.x) * 0.03 + 0.003 * sin(s.y * 40.0 + h2.y * 6.283185); + let period = 90.0 + 120.0 * h1.y; + let tau = fract(camera.post.y / period + h2.y) * period; + let start = h.z * (0.75 - 0.9 * h2.x); + let end = start - min(tau * 0.004, 0.6); + let fade = smoothstep(0.0, 5.0, tau) * (1.0 - smoothstep(period - 10.0, period, tau)); + let dx = abs(s.x - x0); + let in_track = step(end, s.y) * step(s.y, start) * (1.0 - smoothstep(0.0012, 0.0025, dx)); + let head = 1.0 - smoothstep(0.0018, 0.0028, length(vec2(dx, s.y - end))); + amount = amount * (1.0 - 0.8 * max(in_track, head) * fade); + } + } + if (front && enh.condensation.w > 0.02) { + // the defroster's warm air clears the windscreen from its bottom edge up, first in + // the middle over its outlets + let u = clamp((fz + 0.35) / 1.2, 0.0, 1.0); + let fx = l.x / max(h.x, 0.1); + let reach = enh.condensation.w / 0.85 * 1.15 - 0.2 * fx * fx + 0.06 * (n1 - 0.5); + amount = amount * smoothstep(reach - 0.12, reach, u); + } + return clamp(amount, 0.0, 1.0); +} + +// The reflection a pane adds over what shows through it (pre-exposed `reflection`): the +// street and the sky it mirrors, seen from outside or on another vehicle; none on the inner +// face of the player's own bus's glass. (A box-projected cube of the cabin was mirrored +// there; it lagged behind the camera, shook with the head and showed a blurred picture, and +// was taken out on the user's word, 2026-11-22.) +fn glass_reflection(world: vec3, n: vec3, v: vec3, reflection: vec3) -> vec3 { + let inside = inside_vehicle(camera.cam_pos.xyz) * near_player_vehicle(world); + return reflection * (1.0 - step(0.5, inside)); +} diff --git a/crates/mx/tests/openomsi/scene_enhanced_plus.wgsl b/crates/mx/tests/openomsi/scene_enhanced_plus.wgsl new file mode 100644 index 0000000..c640ca5 --- /dev/null +++ b/crates/mx/tests/openomsi/scene_enhanced_plus.wgsl @@ -0,0 +1,5783 @@ +fn srgb_encode(c: vec3) -> vec3 { + let x = max(c, vec3(0.0)); + return select(1.055 * pow(x, vec3(1.0 / 2.4)) - 0.055, x * 12.92, x <= vec3(0.0031308)); +} +fn srgb_decode(c: vec3) -> vec3 { + let x = max(c, vec3(0.0)); + return select(pow((x + 0.055) / 1.055, vec3(2.4)), x / 12.92, x <= vec3(0.04045)); +} + +struct Camera { + view_proj: mat4x4, + cam_pos: vec4, + world_origin: vec4, // world-space origin removed from render coordinates + sun_dir: vec4, // xyz direction to the sun, w intensity + ambient: vec4, // rgb ambient (envir light C) + fog: vec4, // rgb, density + sun_color: vec4, // rgb (envir light A), w night factor 0..1 (nightmap strength) + sky_color: vec4, // rgb secondary light from above (envir light B), w 1 = vanilla (as OMSI 2), 0 = Vanilla+ + light_grid: vec4, // x,y grid origin (render-origin relative), z cell size, w cells per side + sky: vec4, + cam_right: vec4, + cam_up: vec4, + clouds: vec4, + light_view_proj: mat4x4, + light_view_proj_far: mat4x4, + shadow: vec4, // x enabled, y texel size, z near cascade half range + post: vec4, // x enhanced, y time, zw sun ndc + inside_a: vec4, // player vehicle box: origin xyz, sin(heading) + inside_b: vec4, // cos(heading), half extents xyz + inside_c: vec4, // box centre offset xyz, w = 1 when there is a box, 2 with the eye in it + flags: vec4, // x detail texturing, y enhanced graphics, z never set (see fs_main's end), w close cascade half range + light_view_proj_close: mat4x4, + wind: vec4, // the player's vehicle's velocity (m/s, world): the airstream on its glass + // Enhanced: the lamps' shadow maps (the tiles under the far map; zero where nothing is + // drawn) and where the tiles lie: x a tile's side, y tiles to a row, z the far map's + // texture height, w the number of tiles (`LampAtlas::uniform`) + lamp_view_proj: array, 56>, + lamp_atlas: vec4, + // Windy trees: xy the weather's wind (m/s, world; 0 with the setting off), zw how far + // the air has carried the gusts since the start (m, modulo PATTERN_PERIOD) + tree_wind: vec4, + // an articulated bus's rear section (as inside_*): read by the snowfall only - a test of + // it here, inlined into every use of inside_vehicle, brought Apple's M4 shader compiler + // down (see 0.2.21's Metal note) + inside2_a: vec4, + inside2_b: vec4, + inside2_c: vec4, + // Enhanced: the field each light cookie layer covers (xy: the tangents of its half + // angles across and up; z: its first record in the light buffer), see enhanced.wgsl + // `cookie_light` + cookies: array, 8>, + // Enhanced: the lights of the player's saloon that have a shadow map (their places in the + // light buffer, 4 a vector, -1 for none): see `cabin_visibility` + cabin_lamps: array, 4>, + // x: the textures' mip bias (FSR 1: negative, see `CameraUniform::lod`) + lod: vec4, // x mip bias, y ground-prepass flag, z road sunlight glare, w air temperature (degC) + // the classic picture's headlight (`CameraUniform::spot`, see `classic_spot`) + spot: array, 4>, +}; + +// 1 when the point lies inside the player's vehicle (its [boundingbox], shrunk a little so +// that the outer skin, the glass and the roof stay outside): weather stays out of the cab. +// The side/front/back shrink was a bare 0.12 m, which left an interior fixture close to the +// wall (a window sill, the handbrake by the windscreen) just outside the box, wearing the +// up-facing wet/snow coat meant for the body panel beside it (see the `outside` weight +// below). A previous fix WIDENED this margin to 0.6 m, reasoning by analogy with the falling- +// particle exclusion box in `rain.rs` - but that box works the other way round (its margin +// is added, growing the excluded region outward, away from the body) from this one (whose +// margin is subtracted, shrinking the "inside" region inward, toward the body): widening it +// here shrank the cabin's own "inside" zone and threw the *whole* cabin outside it, coating +// the entire interior in snow instead of just the ledge. Narrowed to 0.03 m instead - just +// enough that the true outer skin and glass stay outside, without giving up real interior +// floor space near the wall. +// A normal of no length (a mesh saved with zero normals) is upright instead of NaN: +// normalize(0) is NaN on Vulkan and Metal and the pixel went black. +fn safe_normal(v: vec3) -> vec3 { + let d = dot(v, v); + if (d > 1e-20) { + return v * inverseSqrt(d); + } + return vec3(0.0, 0.0, 1.0); +} + +fn inside_vehicle(world: vec3) -> f32 { + if (camera.inside_c.w < 0.5) { + return 0.0; + } + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let x = d.x * ch - d.y * sh - camera.inside_c.x; + let y = d.x * sh + d.y * ch - camera.inside_c.y; + let z = d.z - camera.inside_c.z; + let h = camera.inside_b.yzw; + let in_x = abs(x) < h.x - 0.03; + let in_y = abs(y) < h.y - 0.03; + let in_z = z > -h.z - 0.6 && z < h.z - 0.03; + return select(0.0, 1.0, in_x && in_y && in_z); +} + +// 1 when the point belongs to the player's vehicle: its `[boundingbox]` grown a little, +// so that the skin and the glass the cab test (`inside_vehicle`) leaves out are in. +fn near_player_vehicle(world: vec3) -> f32 { + if (camera.inside_c.w < 0.5) { + return 0.0; + } + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let x = d.x * ch - d.y * sh - camera.inside_c.x; + let y = d.x * sh + d.y * ch - camera.inside_c.y; + let z = d.z - camera.inside_c.z; + let h = camera.inside_b.yzw + vec3(0.25); + return select(0.0, 1.0, abs(x) < h.x && abs(y) < h.y && abs(z) < h.z); +} + +// How much of the way from the camera to `world` lies outside the player's vehicle: there is +// no fog in the cab. From the driver's seat the whole saloon (seats 2 m away, the doors 5 m +// away) took the fog of that distance and in thick ground fog the interior went milky, the +// door panes nearly opaque - outside the bus there was nothing of the kind. The box is the +// one `inside_vehicle` uses; the part of the ray inside it is taken off the fogged distance. +fn fog_distance(world: vec3) -> f32 { + let full = distance(world, camera.cam_pos.xyz); + if (camera.inside_c.w < 0.5) { + return full; + } + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let to_local = fn_box_local(camera.cam_pos.xyz); + let p1 = fn_box_local(world); + let d = p1 - to_local; + let h = camera.inside_b.yzw; + // slab test of the segment against the box (x, y the plan, z height) + var t0 = 0.0; + var t1 = 1.0; + for (var k = 0; k < 3; k = k + 1) { + let o = to_local[k]; + let dk = d[k]; + let hk = h[k]; + if (abs(dk) < 1e-6) { + if (abs(o) > hk) { + return full; + } + } else { + let a = (-hk - o) / dk; + let b = (hk - o) / dk; + t0 = max(t0, min(a, b)); + t1 = min(t1, max(a, b)); + } + } + if (t1 <= t0) { + return full; + } + return max(full * (1.0 - (t1 - t0)), 0.0); +} + +// A point in the player's vehicle box frame (centred, x across, y along, z up). +fn fn_box_local(world: vec3) -> vec3 { + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + return vec3(d.x * ch - d.y * sh - camera.inside_c.x, d.x * sh + d.y * ch - camera.inside_c.y, d.z - camera.inside_c.z); +} + +fn own_vehicle_blocks(p: vec3, l: vec3) -> bool { + if (camera.inside_c.w < 1.5) { + return false; + } + let a = fn_box_local(l); + let d = fn_box_local(p) - a; + let h = camera.inside_b.yzw - vec3(0.15); + if (all(abs(a) < h)) { + return false; + } + var t0 = 0.0; + var t1 = 1.0; + for (var k = 0; k < 3; k = k + 1) { + let o = a[k]; + let dk = d[k]; + let hk = h[k]; + if (abs(dk) < 1e-6) { + if (abs(o) >= hk) { + return false; + } + } else { + let lo = (-hk - o) / dk; + let hi = (hk - o) / dk; + t0 = max(t0, min(lo, hi)); + t1 = min(t1, max(lo, hi)); + } + } + return t1 > t0; +} + +// 1 where the weather reaches the point. The cab test above reaches 0.6 m below the +// vehicle's box so that the floor stays dry, and that takes in the road under the bus as +// well: the snow on it vanished in a bus-shaped patch of bare asphalt (which read as the +// bus's shadow wiping the snow off). The ground - terrain, roads, painted ground, flagged +// by `terrain` or the instance's surface flag - is never inside a vehicle. +fn weather_outside(world: vec3, terrain: bool, surface: f32) -> f32 { + if (terrain || surface > 0.5) { + return 1.0; + } + return 1.0 - inside_vehicle(world); +} + +// As `weather_outside`, knowing the surface's normal: the bus's own outer skin is outside +// even where it lies inside the box. A side wall leans in towards the roof (and bulges over +// the wheel arches), so the box's side plane cuts through the panel: above the cut the paint +// took the cab's light and stayed dry, below it the sky's - the wall looked half glossy, +// half matt, along a sharp line. A face within 0.35 m of a side, the front, the back or the +// roof of the box and turned out through it is skin, not cabin. +fn weather_outside_n(world: vec3, n: vec3, terrain: bool, surface: f32) -> f32 { + if (terrain || surface > 0.5) { + return 1.0; + } + // a vehicle's part (lib.rs `Instance::roof`): under its roof it is dry, whichever + // vehicle it is - the one the camera is in, another player's, a timetable bus + // (what faces up only: taken for every face below the roof, the whole outer skin of + // every car and bus below the roof's edge was cab - lit by the dim cab light in the + // enhanced picture, dry in the rain - with a hard seam round the body 0.3 m under the + // roof where the sky's light began, #805) + if (surface < -500.0) { + // (the code carries the roof's snow in its ten thousands, see scene/upload.rs) + let code = -surface; + let roof = code - 10000.0 * floor(code / 10000.0) - 5000.0; + if (world.z < roof - 0.3 && n.z > 0.5) { + return 0.0; + } + } + if (inside_vehicle(world) < 0.5) { + return 1.0; + } + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let x = d.x * ch - d.y * sh - camera.inside_c.x; + let y = d.x * sh + d.y * ch - camera.inside_c.y; + let z = d.z - camera.inside_c.z; + let nx = n.x * ch - n.y * sh; + let ny = n.x * sh + n.y * ch; + let h = camera.inside_b.yzw; + let skin_x = h.x - abs(x) < 0.35 && nx * sign(x) > 0.5; + let skin_y = h.y - abs(y) < 0.35 && ny * sign(y) > 0.5; + let skin_z = h.z - z < 0.35 && n.z > 0.5; + return select(0.0, 1.0, skin_x || skin_y || skin_z); +} +@group(0) @binding(0) var camera: Camera; +// Whether this pipeline draws alpha-tested materials. +// Opaque pipelines set the discard overrides false: a fragment +// function that can discard turns the GPU's early depth test off - on Apple's GPUs the +// hidden surface removal as well - for everything it draws, and the heavy shading then +// ran for every covered layer of the city, not once per pixel. +override ALPHA_TEST: bool = true; +// Multisampled cutout pipelines can turn filtered alpha directly into sample coverage. +override ALPHA_TO_COVERAGE: bool = false; +override DETAILED_TREES: bool = false; +@group(0) @binding(5) var t_shadow: texture_depth_2d; +@group(0) @binding(6) var s_shadow: sampler_comparison; +@group(0) @binding(7) var t_shadow_far: texture_depth_2d; +@group(0) @binding(8) var t_ao: texture_2d; +@group(0) @binding(9) var s_ao: sampler; + +// Enhanced+: the traced lighting at a pixel (rt.wgsl, full size; camera.clouds.w 2): x the +// ambient occlusion, z the sun's visibility (< 0 where it was not traced), w 1 where the +// texel lies at this surface's depth (the pixel's own or a neighbour's; 0: the surface is +// not in the depth prepass - a pane, a blended layer - and the shadow map stands in). +fn rt_at(frag: vec2, world: vec3) -> vec4 { + if (camera.clouds.w < 1.5) { + return vec4(1.0, 0.0, -1.0, 0.0); + } + let size = vec2(textureDimensions(t_ao)); + let z = (camera.view_proj * vec4(world, 1.0)).w; + let tol = 0.03 + 0.01 * z; + let px = vec2(frag); + var best = vec4(1.0, 0.0, -1.0, 0.0); + var best_d = tol; + for (var k = 0; k < 5; k = k + 1) { + var o = vec2(0, 0); + switch k { + case 1: { o = vec2(1, 0); } + case 2: { o = vec2(-1, 0); } + case 3: { o = vec2(0, 1); } + case 4: { o = vec2(0, -1); } + default: {} + } + let s = textureLoad(t_ao, clamp(px + o, vec2(0), size - vec2(1)), 0); + let d = abs(s.g - z); + if (s.g > 0.0 && d < best_d) { + best_d = d; + best = vec4(s.r, s.g, s.b, 1.0); + } + if (k == 0 && d < tol * 0.3) { + break; + } + } + return best; +} + +// The ambient occlusion at a pixel of the full picture. It is worked out at half size, and +// a plain bilinear lookup blended the occlusion of the ground behind an edge with that of +// the object in front: every wheel, pole and kerb stood in a pale outline on the shaded +// ground under the bus. Of the four half-size texels around the pixel only those at the +// pixel's own depth count (a depth-aware upsample); none of them: the closest in depth. +// The light the surfaces round a point send back to it (irradiance, rgb), packed by +// ssao.wgsl `bounce_pack` in the AO texture's b and a. +fn bounce_unpack(t: vec4) -> vec3 { + let y = t.b; + let iu = floor(t.a / 32.0 + 0.001); + let iv = t.a - iu * 32.0; + let r = iu / 31.0 * 2.0 * y; + let b = iv / 31.0 * 2.0 * y; + let g = max((y - 0.2126 * r - 0.0722 * b) / 0.7152, 0.0); + return vec3(r, g, b); +} + +// The occlusion (x) and the bounced light (yzw) at a pixel, upsampled by depth as `ao_at`. +fn ao_gi_at(frag: vec2, world: vec3, traced: vec4) -> vec4 { + if (camera.clouds.w > 1.5) { + return vec4(select(traced.x, 1.0, traced.w < 0.5), 0.0, 0.0, 0.0); + } + let size = vec2(textureDimensions(t_ao)); + let z = (camera.view_proj * vec4(world, 1.0)).w; + let f = frag * 0.5 - vec2(0.5); + let base = vec2(floor(f)); + let fr = f - floor(f); + let tol = 0.04 + 0.015 * z; + var sum = 0.0; + var wsum = 0.0; + var best = vec4(1.0, 0.0, 0.0, 0.0); + var best_d = 1e9; + for (var j = 0; j < 2; j = j + 1) { + for (var i = 0; i < 2; i = i + 1) { + let c = clamp(base + vec2(i, j), vec2(0), size - vec2(1)); + let s = textureLoad(t_ao, c, 0); + let bw = select(1.0 - fr.x, fr.x, i == 1) * select(1.0 - fr.y, fr.y, j == 1); + let dz = abs(s.g - z); + let w = bw * (1.0 - smoothstep(0.0, tol, dz)) + 1e-4 * bw; + sum = sum + s.r * w; + wsum = wsum + w; + if (dz < best_d) { + best_d = dz; + best = s; + } + } + } + // no AO sample at this surface's depth: the surface is not in the depth prepass (a + // door or panel drawn in front of what the AO saw) - the AO behind it must not show + if (best_d > tol * 1.5) { + return vec4(1.0, 0.0, 0.0, 0.0); + } + // (the bounced light is smooth already - the blur pass averaged it - so the tap at this + // surface's depth is enough) + return vec4(select(best.r, sum / wsum, wsum > 0.02), bounce_unpack(best)); +} + +fn ao_traced_at(frag: vec2, world: vec3, traced: vec4) -> f32 { + if (camera.clouds.w > 1.5) { + return select(traced.x, 1.0, traced.w < 0.5); + } + return ao_upsampled(frag, world); +} + +fn bounce_at(frag: vec2, world: vec3) -> vec3 { + if (camera.clouds.w > 1.5) { + return vec3(0.0); + } + let size = vec2(textureDimensions(t_ao)); + let z = (camera.view_proj * vec4(world, 1.0)).w; + let base = vec2(floor(frag * 0.5 - vec2(0.5))); + var best = base; + var best_d = 1e9; + for (var j = 0; j < 2; j = j + 1) { + for (var i = 0; i < 2; i = i + 1) { + let c = clamp(base + vec2(i, j), vec2(0), size - vec2(1)); + let dz = abs(textureLoad(t_ao, c, 0).g - z); + if (dz < best_d) { + best_d = dz; + best = c; + } + } + } + if (best_d > (0.04 + 0.015 * z) * 1.5) { + return vec3(0.0); + } + return bounce_unpack(textureLoad(t_ao, best, 0)); +} + +fn ao_at(frag: vec2, world: vec3) -> f32 { + if (camera.clouds.w > 1.5) { + let t = rt_at(frag, world); + return select(t.x, 1.0, t.w < 0.5); + } + return ao_upsampled(frag, world); +} + +fn ao_upsampled(frag: vec2, world: vec3) -> f32 { + let size = vec2(textureDimensions(t_ao)); + let z = (camera.view_proj * vec4(world, 1.0)).w; + let f = frag * 0.5 - vec2(0.5); + let base = vec2(floor(f)); + let fr = f - floor(f); + let tol = 0.04 + 0.015 * z; + var sum = 0.0; + var wsum = 0.0; + var best = 1.0; + var best_d = 1e9; + for (var j = 0; j < 2; j = j + 1) { + for (var i = 0; i < 2; i = i + 1) { + let c = clamp(base + vec2(i, j), vec2(0), size - vec2(1)); + let s = textureLoad(t_ao, c, 0); + let bw = select(1.0 - fr.x, fr.x, i == 1) * select(1.0 - fr.y, fr.y, j == 1); + let dz = abs(s.g - z); + let w = bw * (1.0 - smoothstep(0.0, tol, dz)) + 1e-4 * bw; + sum = sum + s.r * w; + wsum = wsum + w; + if (dz < best_d) { + best_d = dz; + best = s.r; + } + } + } + // no AO sample at this surface's depth: the surface is not in the depth prepass (a + // door or panel drawn in front of what the AO saw) - the AO behind it must not show + if (best_d > tol * 1.5) { + return 1.0; + } + return select(best, sum / wsum, wsum > 0.02); +} +// the tile light maps (`.map.LM.bmp`) of the 5x5 tiles around the camera, north up, and where +// they lie: x, y the south-west corner (render-origin relative), z the side, w 1 when set +@group(0) @binding(18) var t_lmap: texture_2d; +@group(0) @binding(19) var lmap: vec4; + +// The tile light map's light at a world point (black outside the loaded square). +fn light_map_at(p: vec3) -> vec3 { + if (lmap.w < 0.5) { + return vec3(0.0); + } + let uv = vec2((p.x - lmap.x) / lmap.z, 1.0 - (p.y - lmap.y) / lmap.z); + let c = textureSampleLevel(t_lmap, s_ao, clamp(uv, vec2(0.0), vec2(1.0)), 0.0).rgb; + let inside = uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0; + return select(vec3(0.0), c, inside); +} + +// A material lit at night by the tile light map (`[LightMapMapping]`, the splines): the +// unlit flag carries 0.35. +fn light_map_mapped(m: vec4) -> bool { + return m.y > 0.3 && m.y < 0.45; +} +// (the model matrices as their columns, four vec4 each: some phone GPUs (Mali, Adreno) read an +// array of matrices from a storage buffer wrongly, and every mesh came out flat and far away) +@group(0) @binding(1) var models: array>; +// The affine row carries the draw order level and its octahedral geometric normal. +// Neither belongs to the transform used by shading, shadows or motion vectors. +fn model_matrix(e: u32) -> mat4x4 { + let k = e * 4u; + return mat4x4(vec4(models[k].xyz, 0.0), vec4(models[k + 1u].xyz, 0.0), vec4(models[k + 2u].xyz, 0.0), models[k + 3u]); +} +// x: alpha multiplier, y: visible (0/1), zw: uv offset +@group(0) @binding(2) var inst_params: array>; +// the frame's draw list: the per-draw entry of each drawn instance. Draws of the same mesh +// and material are batched, so the instance index points into this list, not at an entry. +@group(0) @binding(10) var draw_list: array; +struct PointLight { + pos: vec4, // xyz relative to the render origin, w radius (0: an enhanced-only light) + color: vec4, // rgb, w intensity + dir: vec4, // spot direction, w cosine of the outer cone (< -1.5: a point light) + extra: vec4, // enhanced path: cosine of the inner cone, core radius, beam gain, radius +}; +@group(0) @binding(3) var lights: array; +// per cell CELL_CAP light indices, 0xffffffff = empty +@group(0) @binding(4) var grid: array; +const CELL_CAP: u32 = 32u; +// The cutout of `[matl_alpha] 1`: Omsi.exe sets ALPHAREF 0x80 with ALPHAFUNC GREATER, so a +// texel of alpha 128 is thrown away. Painters' window layers (a bus's glass unwrapped on its +// own texture to draw on) mark the clear glass with exactly 128: cut below one half, those +// texels stayed and every window was the layer's black. +const ALPHA_REF: f32 = 128.5 / 255.0; + +struct MaterialParams { + color: vec4, + // x: alpha mode (0 opaque, 1 test, 2 blend), y: unlit flag, z: has transmap, w: transmap uses alpha + params: vec4, + // x: terrain material (uv in tile space), y: detail texture repeats per tile (0 = none), + // z: ground texture repeats per tile, w: has nightmap + extra: vec4, + // x: has lightmap, y: envmap factor, z: moisture, w: has [matl_envmap_mask] + params2: vec4, + // emissive colour (the o3d material's or a [matl_allcolor]'s) + emissive: vec4, + // specular colour and power of the D3D material (power in w; 0 = no highlight) + specular: vec4, + // x: [matl_bumpmap] factor, y: has a bump map, z/w: noZwrite/noZcheck + bump: vec4, + // the PBR set beside the diffuse texture: x normal map, y occlusion, z roughness, + // w metalness (1 = the map has it; see mx_tex2d[mx_mat.pbr_normal] / mx_tex2d[mx_mat.pbr_orm]) + pbr: vec4, + // x: one of the bus's own screens (the enhanced glow and FXAA leave it alone) + flags: vec4, + // rgb: the D3D material's ambient colour, which takes the ambient light (C) + ambient: vec4, + // Windy trees: x 1 for foliage that sways, y the height (mesh units) of its pivot - where + // the crown leaves the trunk, nothing below it moves - z the crown's top, w how much the + // tree gives to the wind (1 a broadleaf, less a conifer) + sway: vec4, + // Window wetness mask in mesh X/Z: origin, inverse size; zero disables it. + wipe_bounds: vec4, + // x: [matl_glow] strength (0 = the keyword is not there; the material is its own light - + // its `mx_tex2d[mx_mat.light]` is a greyscale mask of how much shines where, its colour is its own, see + // the enhanced pass), y an LED panel's share of the `Led glow` ([led_glow_effect], + // 1 without it), z/w free + glow: vec4, +}; +@group(1) @binding(2) var material: MaterialParams; +// (the material's textures and samplers by their places in the heap, see `materials_from_heap`) +struct MxMaterial { row: u32, diffuse: u32, sampler: u32, trans: u32, night: u32, light: u32, env: u32, envmask: u32, bump: u32, pbr_normal: u32, pbr_orm: u32, tile_sampler: u32 }; +var mx_mat: MxMaterial; + +// Paint/cut masks and night light maps cover one tile. Wrapping at its edge blends in +// the opposite edge of the SAME tile, opening grass seams even when adjacent masks +// agree. The diffuse/detail textures still repeat through mx_samplers[mx_mat.sampler]. +fn sample_transmap(uv: vec2) -> vec4 { + return sample_transmap_bias(uv, camera.lod.x); +} + +// (`bias`: FSR 1's mip bias for the picture, `camera.lod`; 0 for the shadow and rain maps, +// drawn at their own size) +fn sample_transmap_bias(uv: vec2, bias: f32) -> vec4 { + if (material.extra.x > 0.5 || material.wipe_bounds.z != 0.0) { + return textureSampleBias(mx_tex2d[mx_mat.trans], mx_samplers[mx_mat.tile_sampler], uv, bias); + } + return textureSampleBias(mx_tex2d[mx_mat.trans], mx_samplers[mx_mat.sampler], uv, bias); +} + +fn sample_nightmap(uv: vec2) -> vec4 { + if (material.extra.x > 0.5) { + return textureSampleBias(mx_tex2d[mx_mat.night], mx_samplers[mx_mat.tile_sampler], uv, camera.lod.x); + } + return textureSampleBias(mx_tex2d[mx_mat.night], mx_samplers[mx_mat.sampler], uv, camera.lod.x); +} + +// Some vehicle lamps use a clear diffuse placeholder and put the entire lit +// picture, including its silhouette, in the switched night texture. A transmap +// still owns coverage when the model explicitly supplies one. +fn night_coverage(alpha: f32, night_alpha: f32) -> f32 { + return select(alpha, night_alpha, + (u32(material.params2.w + 0.5) & 16u) != 0u && material.params.z < 0.5); +} + +// The reflection mask of a [matl_envmap] material: the alpha of its [matl_envmap_mask] +// texture when it has one, else the diffuse texture's alpha - which reads 1 for a texture +// without an alpha channel (a 24-bit bitmap, DXT1, a JPEG), so its factor alone decides. +fn has_env_mask() -> bool { + return (u32(material.params2.w + 0.5) & 1u) != 0u; +} + +// [matl_transmap] was given (its file there or not: see MaterialExtra::transmap_declared) +fn has_transmap_declared() -> bool { + return (u32(material.params2.w + 0.5) & 2u) != 0u; +} + +// [matl_texadress_border]: where the diffuse texture's coordinates leave [0, 1] (a roller +// blind's band scrolled away by [texcoordtransX/Y]) Direct3D reads the border colour, not +// the texture's edge (the sampler only clamps). Its rgb comes packed in flags.z. +fn diffuse_border(tex: vec4, uv: vec2) -> vec4 { + let p = u32(material.flags.z + 0.5); + let border = vec4( + f32((p >> 16u) & 0xffu) / 255.0, + f32((p >> 8u) & 0xffu) / 255.0, + f32(p & 0xffu) / 255.0, + material.flags.w, + ); + let outside = any(uv < vec2(0.0)) || any(uv > vec2(1.0)); + return select(tex, border, material.flags.y > 0.5 && material.flags.y < 1.5 && outside); +} + +// [matl_texadress_mirroronce]: Direct3D mirrors the coordinates once about 0 and clamps +// them beyond; the clamping sampler does the rest. +fn tex_address(uv: vec2) -> vec2 { + return select(uv, abs(uv), material.flags.y > 1.5); +} + +fn reflection_mask(uv: vec2, diffuse_a: f32) -> f32 { + let mask = textureSampleBias(mx_tex2d[mx_mat.envmask], mx_samplers[mx_mat.sampler], uv, camera.lod.x).a; + return select(diffuse_a, mask, has_env_mask()); +} + +// The D3DCOLOR Omsi.exe packs for its environment stage (0x7ff8ed): each channel the +// [matl_envmap] factor x 255 x its light (at most 1), truncated, and OR-ed together shifted +// into place without saturation - a factor over 1 spills into the neighbouring channel +// exactly as there (a factor of 10 at full light reads almost white). +fn omsi_texture_factor(factor: f32, light: vec3) -> vec3 { + let m = min(max(light, vec3(0.0)), vec3(1.0)) * max(factor, 0.0) * 255.0; + let r = u32(m.r); + let g = u32(m.g); + let b = u32(m.b); + let packed = (0xffu << 24u) | (r << 16u) | (g << 8u) | b; + return vec3(f32((packed >> 16u) & 0xffu), f32((packed >> 8u) & 0xffu), f32(packed & 0xffu)) / 255.0; +} + +// [matl_bumpmap]: Direct3D's bump-mapped environment stage moves the sphere-map lookup by +// a du/dv map times the factor. Every bump map in the stock and mod content is a grey +// height map, so the du/dv map has to be its slope; it is taken here as the forward +// differences of the height, a byte of height difference counting as a signed-byte step +// (1/127, hence the 2). The stock bodies' noise (factor 0.05-0.1) makes their reflections a +// little wavy, and the panel lines of the O530 Facelift's map (factor 1) break its +// reflection at every seam. +fn bump_offset(uv: vec2) -> vec2 { + let texel = 1.0 / vec2(textureDimensions(mx_tex2d[mx_mat.bump])); + let h = textureSampleBias(mx_tex2d[mx_mat.bump], mx_samplers[mx_mat.sampler], uv, camera.lod.x).a; + let hx = textureSampleBias(mx_tex2d[mx_mat.bump], mx_samplers[mx_mat.sampler], uv + vec2(texel.x, 0.0), camera.lod.x).a; + let hy = textureSampleBias(mx_tex2d[mx_mat.bump], mx_samplers[mx_mat.sampler], uv + vec2(0.0, texel.y), camera.lod.x).a; + return clamp(vec2(h - hx, h - hy) * 2.0, vec2(-1.0), vec2(1.0)) * material.bump.x; +} + +struct VsIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, + @builtin(instance_index) inst: u32, +}; +struct VsOut { + // invariant: the depth prepass and the main pass must compute the same depth to the + // last bit, the main pass tests against the depth the prepass left + @builtin(position) @invariant clip: vec4, + @location(0) world: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + @location(4) @interpolate(flat) params2: vec4, + // the D3D material's highlight, lit at the vertex as Omsi.exe's fixed function lights + // it: from the sun (light A) and from the light above (light B) + @location(5) spec_sun: vec3, + @location(6) spec_sky: vec3, + // where a [matl_envmap] reads its sphere map, made at the vertex (see `sphere_map_uv`) + @location(7) env_uv: vec2, + @location(8) wipe_uv: vec3, + // The classic headlight is lit at the vertices, as OMSI's fixed function light is. + @location(9) spot_diffuse: vec3, + @location(10) spot_ambient: vec3, + // the vertex as its mesh has it: a vehicle's snow lies on the vehicle, not on the + // world it drives through (road_snow.wgsl `vehicle_snow`) + @location(11) local: vec3, +}; +// What the fragment shaders take: VsOut without the invariant on the position. The +// invariant belongs to the vertex output; on a fragment input naga's GLSL writer turns it +// into `invariant gl_FragCoord`, which desktop GL drivers and GLES reject. +struct FsIn { + @builtin(position) clip: vec4, + @location(0) world: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + @location(4) @interpolate(flat) params2: vec4, + @location(5) spec_sun: vec3, + @location(6) spec_sky: vec3, + @location(7) env_uv: vec2, + @location(8) wipe_uv: vec3, + @location(9) spot_diffuse: vec3, + @location(10) spot_ambient: vec3, + @location(11) local: vec3, +}; + +// Direct3D's D3DTSS_TCI_SPHEREMAP, by which Omsi.exe's environment stage reads the sphere +// map of a [matl_envmap] (0x7ff670): at the vertex, from the reflection R in camera space +// (x right, y up, z ahead), u = Rx/m + 0.5 and v = Ry/m + 0.5 with m = 2|R - (0, 0, 1)| - +// as Windows draws it (wine's d3d9 test_generated_texcoords, measured there). What a pane +// facing the camera mirrors is the map's middle, at half the scale of the u = Rx/2 + 0.5 +// taken before (which showed the whole street of the picture across a bus's flank); the +// map's rim is the reflection running on away from the camera, at a grazing angle, where +// the picture swings round between two vertices - the seam the original shows there. +// `eye` is the camera's position, or its mirror image under the road for the player +// vehicle seen in a puddle; the camera's own axes lay the map out either way. +// (The headset: laid out by the bus's heading, level, not by each eye's view.) +fn sphere_map_uv(world: vec3, n: vec3, eye: vec3) -> vec2 { + let r = reflect(normalize(world - eye), n); + let vr_env = camera.cam_up.w > 0.5; + let right = select(camera.cam_right.xyz, vec3(cos(camera.cam_right.w), -sin(camera.cam_right.w), 0.0), vr_env); + let up = select(camera.cam_up.xyz, vec3(0.0, 0.0, 1.0), vr_env); + let rc = vec3(dot(r, right), dot(r, up), dot(r, cross(up, right))); + let m = 2.0 * length(rc - vec3(0.0, 0.0, 1.0)); + return rc.xy / max(m, 1e-6) + 0.5; +} + +// Direct3D's specular term at a vertex (Omsi.exe switches it on in FormActivate, 0x8254e0): +// Omsi.exe's sun (light 0, 0x7089f0: directional, specular = light A) and the light from +// straight above (light 1: specular = light B), each (N.H)^power with the local viewer's +// half vector, only where the light falls on the face, times the material's specular colour +// and clamped at 1 - then interpolated across the face. Computed per pixel instead, every +// small flat part (a gear selector, a switch, a dashboard screen) caught a sharp spot of the +// sun in its middle that the original, lighting only at the corners, never shows. +fn vertex_specular(wp: vec3, n: vec3) -> array, 2> { + var out = array, 2>(vec3(0.0), vec3(0.0)); + if (material.specular.w <= 0.0 || material.params.y >= 0.5) { + return out; + } + let v = normalize(camera.cam_pos.xyz - wp); + let p = material.specular.w; + let l = camera.sun_dir.xyz; + if (dot(n, l) > 0.0) { + out[0] = camera.sun_color.rgb * camera.sun_dir.w * pow(max(dot(n, normalize(v + l)), 0.0), p); + } + let up = vec3(0.0, 0.0, 1.0); + if (n.z > 0.0) { + out[1] = camera.sky_color.rgb * pow(max(dot(n, normalize(v + up)), 0.0), p); + } + let total = out[0] + out[1]; + let k = min(vec3(1.0), total) / max(total, vec3(1e-6)); + out[0] = min(vec3(1.0), out[0] * k * material.specular.rgb); + out[1] = min(vec3(1.0), out[1] * k * material.specular.rgb); + return out; +} + +// Windy trees: how far the wind moves a vertex of a tree's foliage (world, m). `local` is +// the vertex in the mesh, `m` its model matrix, whose origin is the tree's foot. +// +// The tree is bent, not shifted: nothing under its pivot (`material.sway.y`, where the crown +// leaves the trunk) moves, and above it the crown bends over as a cantilever does, by the +// square of the height above the pivot, sinking a little so that its branches keep their +// length. The crown moves as one heavy body - a tree is a lightly damped oscillator, and +// what it does is smooth: no part of the picture moves on its own (each corner of a card +// wobbling in its own phase made the crown jelly). +// +// What bends it is the drag of the air: it grows with the wind speed to the power 1.5 rather +// than 2, as a crown streamlines itself (Vogel's reconfiguration exponent), from a few +// millimetres at 1 m/s to some 3.5 % of the tree's height at 20 m/s, a storm. The gusts are +// a frozen pattern of faster and slower air carried along at the mean wind (Taylor): three +// smooth waves 54 .. 149 m long, a turbulence intensity of 0.3 as over a town, so that +// neighbouring trees bow together as a gust passes and the ones further on follow - and, +// being smooth, the gusts never stop the tree dead as the corners of a value noise did. +// Around that lean the tree swings at its own natural frequency (0.2 .. 1 Hz, lower the +// taller it is), its amplitude and phase wandering slowly as a resonance driven by +// turbulence does, and a little across the wind; the crown's top lags its middle a little. +// With no wind nothing moves. +fn tree_sway(local: vec3, m: mat4x4) -> vec3 { + let sw = material.sway; + let wind = camera.tree_wind.xy; + let speed = length(wind); + if (sw.x < 0.5 || speed < 0.05) { + return vec3(0.0); + } + let h = clamp((local.z - sw.y) / max(sw.z - sw.y, 1e-4), 0.0, 1.0); + if (h <= 0.0) { + return vec3(0.0); + } + let scale = length(m[2].xyz); + let crown = max((sw.z - sw.y) * scale, 0.1); + let height = max(sw.z * scale, crown); + let foot = (m * vec4(0.0, 0.0, 0.0, 1.0)).xyz; + let foot_map = world_pattern_xy(foot); + let t = camera.post.y; + // each tree its own phase + let seed = hash_cell(floor(foot_map * 2.0), 2000.0); + let phase = seed * 6.2831853; + // the gusts at the tree: whole waves per PATTERN_PERIOD (the map position and the + // drift arrive modulo it), 149, 93 and 54 m long - a gust lasts some seconds; their sum has a standard deviation of + // 0.51 (0.6, 0.35, 0.2 over sqrt 2), scaled to the turbulence intensity 0.3 + let gp = (foot_map - camera.tree_wind.zw) * (6.2831853 / PATTERN_PERIOD); + let waves = 0.6 * sin(dot(gp, vec2(6.0, 3.0)) + 1.3) + + 0.35 * sin(dot(gp, vec2(-4.0, 10.0)) + 4.1) + + 0.2 * sin(dot(gp, vec2(17.0, -7.0)) + 2.2); + let gust = max(1.0 + 0.59 * waves, 0.0); + let along = wind / speed; + let across = vec2(-along.y, along.x); + // the lean under the gusting wind, and the tree's swing about it + let give = 0.035 * height * sw.w; + let lean = give * pow(speed * gust / 20.0, 1.5); + // (in strong wind the swing is of the order of the mean lean itself) + let swing_size = 0.7 * give * pow(speed / 20.0, 1.5); + let f0 = clamp(1.6 / sqrt(height), 0.2, 1.0); + let w0 = 6.2831853 * f0 * t + phase + 0.8 * sin(0.17 * t + 9.0 * seed); + let envelope = 0.65 + 0.35 * sin(0.23 * t + 5.0 * seed); + let swing = swing_size * envelope; + // (the top lags the middle by a fraction of a cycle: the crown bends, not only leans) + let lag = 0.35 * h; + let move_xy = along * (lean + swing * sin(w0 - lag)) + across * (0.35 * swing * sin(0.93 * w0 + 1.7 - lag)); + var d = vec3(move_xy * h * h, 0.0); + // the crown's big boughs: lobes about the crown's size swaying at about twice the tree's + // frequency, each with its own slowly wandering phase, harder in a gust - neighbouring + // parts of the picture move nearly together, so the crown stirs rather than wobbles + let lm = (m * vec4(local, 0.0)).xyz; + let bp = dot(lm, vec3(0.45, 0.35, 0.3) * (4.0 / crown)) + phase; + let fb = clamp(2.2 * f0, 0.8, 2.0); + let wb = 6.2831853 * fb * t + bp + 0.6 * sin(0.31 * t + bp); + let bough = 0.25 * give * pow(speed * gust / 20.0, 1.5) * h; + d = d + vec3(along * sin(wb) + across * 0.5 * sin(1.17 * wb + 2.0), 0.25 * sin(0.9 * wb + 1.0)) * bough; + // the bent crown keeps its length: it sinks as it leans + let above = max((local.z - sw.y) * scale, 0.3); + d.z = d.z - 0.5 * dot(d.xy, d.xy) / above; + return d; +} + +// Where a scene vertex lands on the screen: the main pass's and the depth passes' vertex +// shaders (`vs_main`, `vs_depth`) both take it from here, so that their depths agree to the +// last bit (the main pass tests against the depth the prepass left). +fn scene_clip(e: u32, wp: vec4, nw: vec3) -> vec4 { + // Road surfaces (splines, the objects lying on them, a shadow blob) are pulled towards + // the eye along the line of sight - the picture does not move, only the depth - so that + // they win over the flush ground beside them. Code 0.9 keeps the surface shading without + // the pull; painted ground (0.75) stays put. + let surf = inst_params[e * 2u + 1u].w; + var cp = wp.xyz; + if (surf > 0.9) { + let to = wp.xyz - camera.cam_pos.xyz; + let d = length(to); + // The same share of the way to the eye at every vertex (0.3 %, a few millimetres of + // height seen from the cab): the pulled road is still the plane it was, so a spline + // laid a millimetre over another - the rails or markings over a road - stays over it + // however the two are cut into triangles. A fixed 2 cm more along each vertex's own + // line of sight bowed the road's long triangles over the short ones of what lies on + // it, by millimetres near the eye, and the rails went under the road there (#1196). + // (surface objects, 1.25, a little more than the splines under them) + // (a vehicle's shadow blob, 2: drawn without a depth test in the original, right + // over the road it lies on - with the road's own pull alone the two fought for + // every pixel and the road mostly won; a few centimetres more bring it through the + // road and still leave it behind the body and the wheels standing on it) + // The share stops growing at 5 cm. The pull is a depth, not a place - the picture + // does not move - but the pole of a traffic light that a mod's map tagged as a + // surface is pulled with the road under it, and a share still growing at distance + // (a third of a metre at 90 m) carried the pole through the signal head it stands + // beside. Capped, the pole stays behind what it stands by, and the depth a road + // needs over flush ground is a few millimetres at most (a floor raised 3 cm above + // the road is still seen - `surface_bias_keeps_raised_floors_visible_at_a_distance`). + // (a road's painted lines, 1.4, a little more again: a crossing object laid over + // the road covered the lines it overlaps, which in Omsi.exe lie a millimetre over + // the road and win the depth test against it - #1694) + let decal = surf > 1.1 && surf < 1.35; + let paint = surf > 1.35 && surf < 1.5; + let share = select(select(select(0.003, 0.004, decal), 0.0045, paint), 0.005, surf > 1.5); + let fixed = select(select(select(0.0, 0.01, decal), 0.015, paint), 0.05, surf > 1.5); + // The cap on the share is for upright faces, the poles. A flat surface keeps its + // share all the way: pulled by the same part of the way to the eye at every vertex + // the road is still one plane, however long its triangles, and a marking on it keeps + // its place. Capped at 5 cm the pull of a triangle from the eye to the horizon + // stopped growing with the distance and turned the road's plane into a bowl: at + // 40 m from a low eye the road came in front of the lines on it, and they were + // gone, and back as the bus came on (#3085). (Half a metre of it, at 170 m and + // beyond: millimetres of height from a driver's eye.) + let flat = abs(safe_normal(nw).z) > 0.5; + let pull = min(min(share * d, select(0.05, 0.5, flat)) + fixed, d * 0.3); + cp = wp.xyz - to / max(d, 1e-3) * pull; + } + // Omsi.exe draws a model mesh by mesh and subset by subset with LESSEQUAL into a 24-bit + // depth buffer: of two of its surfaces in one plane - a dashboard and the instruments + // printed on it - the later one is seen. Here their depths differed by rounding alone + // and every pixel was a coin toss. A slot lying on an earlier surface of its object + // (`draw_order_level`, 1 to 3; everything else 0) is brought nearer by two steps, each + // the same over a whole plane however it is cut into triangles (a step worked out per + // vertex from its own distance bends the surface): the reversed depth times 1 + 1e-5 a + // level, above the vertices' rounding; and 2e-5 a level over the plane's distance from + // the eye, against the tilt the rasterizer's snapping of each corner to a fraction of a + // pixel gives a triangle's depth, the more the flatter it is seen. Seen from above the + // plane that lifts it by 3e-5 a level times the distance: 0.9 mm at 10 m at level 3. + // (The plane's distance is at least 5 % of the vertex's own: the edge of a curved mesh, + // whose tangent plane runs through the eye, is not pulled metres forward.) + let clip = camera.view_proj * vec4(cp, 1.0); + let level_code = u32(round(models[e * 4u].w)); + var level = f32(level_code & 3u); + if (level <= 0.0) { + return clip; + } + if ((level_code & 4096u) != 0u) { + // Keep the depth step within half the measured gap. + let cap = f32((level_code >> 2u) & 1023u) * 1e-6; + let distance = length(cp - camera.cam_pos.xyz); + level = min(level, cap / max(3e-5 * distance, 1e-9)); + if (level <= 0.0) { + return clip; + } + } + // (the depth of the eye's own point: n f / (f - n), about the near plane) + let at_eye = (camera.view_proj * vec4(camera.cam_pos.xyz, 1.0)).z; + // Use geometric plane normals; lighting normals may be smoothed or authored independently. + let encoded = vec2(models[e * 4u + 1u].w, models[e * 4u + 2u].w); + var depth_n = nw; + if (all(abs(encoded) <= vec2(1.0))) { + var n = vec3(encoded, 1.0 - abs(encoded.x) - abs(encoded.y)); + let t = clamp(-n.z, 0.0, 1.0); + n.x += select(t, -t, n.x >= 0.0); + n.y += select(t, -t, n.y >= 0.0); + depth_n = n; + } + let plane = max(abs(dot(safe_normal(depth_n), cp - camera.cam_pos.xyz)), 0.05 * length(cp - camera.cam_pos.xyz)); + let slant = level * 2e-5 * at_eye * clip.w / plane; + return vec4(clip.x, clip.y, clip.z * (1.0 + level * 1e-5) + slant, clip.w); +} + +fn is_tree_card() -> bool { + return material.params.y > 0.1 && material.params.y < 0.2; +} + +fn detailed_trees() -> bool { + return DETAILED_TREES; +} + +fn tree_crown_normal(local: vec3, m: mat4x4, up: vec3) -> vec3 { + let pivot = select(0.28, material.sway.y, material.sway.x > 0.5); + let centre = mix(pivot, select(1.0, material.sway.z, material.sway.x > 0.5), 0.45); + let out = (m * vec4(local.x, local.y, local.z - centre, 0.0)).xyz; + let crown = smoothstep(pivot * 0.5, pivot + 0.1, local.z); + return safe_normal(mix(up, safe_normal(out), 0.65 * crown)); +} + +fn tree_card_fade(world: vec3) -> f32 { + if (!detailed_trees() || (!is_tree_card() && material.sway.x < 0.5)) { + return 1.0; + } + let c = cross(dpdx(world), dpdy(world)); + let v = (camera.cam_pos.xyz - world).xy; + if (dot(c, c) < 1e-20 || dot(v, v) < 1e-6) { + return 1.0; + } + let n = normalize(c); + let upright = smoothstep(0.6, 0.9, length(n.xy)); + let facing = abs(dot(normalize(n.xy + vec2(1e-6, 0.0)), normalize(v))); + return mix(1.0, smoothstep(0.3, 0.62, facing), upright); +} + +@vertex +fn vs_main(in: VsIn) -> VsOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0); + var out: VsOut; + out.clip = scene_clip(e, wp, (m * vec4(in.normal, 0.0)).xyz); + out.world = wp.xyz; + out.local = in.pos; + out.normal = safe_normal((m * vec4(in.normal, 0.0)).xyz); + if (detailed_trees() && (is_tree_card() || (material.sway.x > 0.5 && material.sway.z - material.sway.y > 2.5))) { + out.normal = tree_crown_normal(in.pos, m, out.normal); + } + let sp = vertex_specular(wp.xyz, out.normal); + out.spec_sun = sp[0]; + out.spec_sky = sp[1]; + // Ray blocking is disabled for exterior cameras; never light our own body or cabin. + // The vehicle surface code keeps roads and scenery in the same box illuminated. + out.spot_diffuse = vec3(0.0); + out.spot_ambient = vec3(0.0); + let own_vehicle = inst_params[e * 2u + 1u].w < -500.0 && near_player_vehicle(wp.xyz) > 0.5; + if (!own_vehicle) { + let spot = classic_spot(wp.xyz, out.normal); + out.spot_diffuse = spot[0]; + out.spot_ambient = spot[1]; + } + out.env_uv = sphere_map_uv(wp.xyz, out.normal, camera.cam_pos.xyz); + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + out.params2 = inst_params[e * 2u + 1u]; + let side_pane = material.wipe_bounds.z < 0.0; + let pane = select(in.pos.xz, in.pos.yz, side_pane); + out.wipe_uv = vec3((pane - material.wipe_bounds.xy) * abs(material.wipe_bounds.zw), select(in.pos.y, in.pos.x, side_pane)); + if (pr.y < 0.5) { + // invisible: collapse the triangle + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +// What the depth-only passes (the depth prepass, the multisampled prefill) take from a +// vertex: its place and what a cut-out or a transmap needs to decide its coverage. The +// highlights, the sphere map and the normal of `vs_main` are not worked out for them. +struct DepthOut { + @builtin(position) @invariant clip: vec4, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + // the instance's surface code (`inst_params` w, see `scene_clip`) + @location(4) surf: f32, + @location(5) world: vec3, +}; +struct DepthIn { + @builtin(position) clip: vec4, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + @location(4) surf: f32, + @location(5) world: vec3, +}; + +struct ShadowOut { + @builtin(position) @invariant clip: vec4, + @location(0) uv: vec2, + @location(1) @interpolate(flat) params: vec4, +}; +struct ShadowIn { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + @location(1) @interpolate(flat) params: vec4, +}; + +@vertex +fn vs_depth(in: VsIn) -> DepthOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0); + var out: DepthOut; + out.clip = scene_clip(e, wp, (m * vec4(in.normal, 0.0)).xyz); + out.world = wp.xyz; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + out.surf = inst_params[e * 2u + 1u].w; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +struct VehicleBox { a: vec4, b: vec4, c: vec4 }; +struct VehicleReflection { plane: vec4, parts: array }; +@group(2) @binding(0) var vehicle_reflection: VehicleReflection; + +@vertex +fn vs_puddle_vehicle(in: VsIn) -> VsOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + var out: VsOut; + out.world = (m * vec4(in.pos, 1.0)).xyz; + out.normal = safe_normal((m * vec4(in.normal, 0.0)).xyz); + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + out.params2 = inst_params[e * 2u + 1u]; + out.spec_sun = vec3(0.0); + out.spec_sky = vec3(0.0); + out.spot_diffuse = vec3(0.0); + out.spot_ambient = vec3(0.0); + let plane = vehicle_reflection.plane; + // the sphere map from the reflected eye fs_puddle_vehicle shades the vehicle from + out.env_uv = sphere_map_uv(out.world, out.normal, camera.cam_pos.xyz - 2.0 * plane.xyz * (dot(plane.xyz, camera.cam_pos.xyz) - plane.w)); + let reflected = out.world - 2.0 * plane.xyz * (dot(plane.xyz, out.world) - plane.w); + out.clip = camera.view_proj * vec4(reflected, 1.0); + if (out.params.y < 0.5) { out.clip = vec4(0.0, 0.0, 2.0, 1.0); } + return out; +} + +// Close an open legacy underbody with one depth-tested face in the same reflected +// view. Wheels and authored panels occlude it normally; no screen-space bands. +@vertex +fn vs_puddle_chassis(@builtin(vertex_index) i: u32, @builtin(instance_index) part: u32) -> @builtin(position) vec4 { + let corners = array, 6>(vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), + vec2(-1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, 1.0)); + let box = vehicle_reflection.parts[part]; + let local = corners[i] * max(box.b.yz - vec2(0.12, 0.18), vec2(0.0)) + box.c.xy; + let sh = box.a.w; + let ch = box.b.x; + let xy = box.a.xy + vec2(local.x * ch + local.y * sh, -local.x * sh + local.y * ch); + let plane = vehicle_reflection.plane; + let road_z = (plane.w - dot(plane.xy, xy)) / plane.z; + let z = max(road_z + 0.18, box.a.z + box.c.z - box.b.w + 0.04); + let world = vec3(xy, z); + let reflected = world - 2.0 * plane.xyz * (dot(plane.xyz, world) - plane.w); + return camera.view_proj * vec4(reflected, 1.0); +} + +// Shadow map passes: depth from the sun, alpha-tested materials cut out by their texture. +// A surface that casts - a spline standing clear of the ground, a bridge deck - casts from +// half a metre further away from the sun: what lies right under it (the embankment object +// under a railway, the ground a ramp touches down on) is no darker for it, while the ground +// metres below a deck gets its shadow. +fn shadow_caster_pos(e: u32, wp: vec4) -> vec4 { + if (abs(inst_params[e * 2u + 1u].w - 1.0) < 0.01) { + return vec4(wp.xyz - camera.sun_dir.xyz * 0.5, wp.w); + } + return wp; +} + +@vertex +fn vs_shadow(in: VsIn) -> ShadowOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = shadow_caster_pos(e, m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0)); + var out: ShadowOut; + out.clip = camera.light_view_proj * wp; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +@vertex +fn vs_shadow_close(in: VsIn) -> ShadowOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = shadow_caster_pos(e, m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0)); + var out: ShadowOut; + out.clip = camera.light_view_proj_close * wp; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +@vertex +fn vs_shadow_far(in: VsIn) -> ShadowOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = shadow_caster_pos(e, m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0)); + var out: ShadowOut; + out.clip = camera.light_view_proj_far * wp; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +// Enhanced: a lamp's shadow map (one of the tiles under the far map). The draw list names +// the tile above the entry's own bits (`LAMP_ENTRY_BITS` in lamp_slots.rs), and the tile's +// matrix looks down from a street lamp's head or along the road from a vehicle's headlamps. +const LAMP_ENTRY_BITS: u32 = 26u; + +@vertex +fn vs_shadow_lamp(in: VsIn) -> ShadowOut { + let raw = draw_list[in.inst]; + let e = raw & ((1u << LAMP_ENTRY_BITS) - 1u); + let k = raw >> LAMP_ENTRY_BITS; + let m = model_matrix(e); + let wp = m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0); + var out: ShadowOut; + out.clip = camera.lamp_view_proj[k] * wp; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +@fragment +fn fs_shadow(in: ShadowIn) { +} + +// Reflection rays need the window surface as well as the opaque interior behind it. +// This writes a private hit-depth texture after colour compositing; ordinary depth and +// AO still leave glass transparent. Reject absent/fully faded layers and texture holes. +@fragment +fn fs_puddle_glass_depth(in: FsIn) { + // From the cabin we see the street through our own pane. Treating that pane as + // an SSR hit terminates every ray at the window instead of the outside vehicle. + if (inside_vehicle(camera.cam_pos.xyz) * near_player_vehicle(in.world) > 0.5) { + discard; + } + var a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], tex_address(in.uv), camera.lod.x), in.uv).a; + if (material.params.z > 0.5) { + let tm = sample_transmap(tex_address(in.uv - in.params.zw)); + a = select(1.0, tm.a, material.params.w > 0.5); + } + if (a * material.color.a * in.params.x < 0.002) { + discard; + } +} + +// (the shadow and rain maps, drawn at their own size: their textures' mips as they are) +@fragment +fn fs_shadow_test(in: ShadowIn) { + cutout_coverage(in.uv, in.params, 0.0, 1.0); +} + +// the depth-only passes' (`vs_depth`) fragment shaders: plain, cut out, a transmap's +// opaque part +@fragment +fn fs_depth(in: DepthIn) { +} + +// (the picture's depth: its textures read with the colour pass's mip bias, `camera.lod` - +// a cut-out's edge the prepass took from a blurrier mip than the colour pass wrote depth +// where the colour then discarded, and the sky showed through) +@fragment +fn fs_depth_test(in: DepthIn) { + cutout_coverage(in.uv, in.params, camera.lod.x, tree_card_fade(in.world)); +} + +// (a transmap's opaque part, see `transmap_coverage`) +@fragment +fn fs_depth_transmap(in: DepthIn) { + transmap_coverage(in.uv, in.params, camera.lod.x); +} + +//MS @group(3) @binding(0) var t_pane_depth: texture_depth_multisampled_2d; + +//MS @fragment +//MS fn fs_depth_masked(in: DepthIn, @builtin(sample_index) sample: u32) { +//MS if (in.clip.z <= textureLoad(t_pane_depth, vec2(in.clip.xy), i32(sample))) { +//MS discard; +//MS } +//MS } + +// The multisampled prefill's cut-outs (foliage): their depth only where the colour pass +// is sure to cover every sample - the alpha-to-coverage of an alpha of 1 (`shade_enhanced`: +// the texture's alpha past the cutoff's smoothed edge, a plain material at full opacity, +// no pane, LED panel, transmap, ground or shadow blob). The edges, which alpha-to-coverage +// covers in part, are left to the colour pass: a sample laid here that the colour then +// left uncovered would hide what lies behind it (the sky showed through the houses). +@fragment +fn fs_depth_cover(in: DepthIn) { + let mode = material.params.x; + if (mode < 0.5 || mode > 1.5 || material.params.z > 0.5 || material.extra.x > 0.5 + || material.wipe_bounds.z != 0.0 || abs(material.emissive.w) > 1.5 + || material.color.a < 1.0 || in.params.x < 1.0 || in.surf > 1.5) { + discard; + } + let duv = tex_address(in.uv); + let a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv).a * tree_card_fade(in.world); + let aa = max(fwidth(a) * 0.5, 1.0 / 255.0); + if (a < ALPHA_REF + aa + 4.0 / 255.0) { + discard; + } +} + +// A cut-out's texel: kept where its alpha reaches the cutoff (`bias`: the mip bias its +// pass reads the textures with, the colour pass's for the picture's depth). +fn cutout_coverage(uv: vec2, params: vec4, bias: f32, fade: f32) { + var duv = tex_address(uv); + if (material.extra.x > 0.5) { + duv = uv * material.extra.z; + } + // Use the light-pass footprint for cutout coverage. Forcing mip 0 here aliases dense + // foliage and alpha layers into a checkerboard when the light projection moves by a + // texel; the mip-aware sample keeps the caster coverage coherent with its resolution. + // For a material promoted to the shadow pass from Blend, diffuse alpha is commonly a + // paint/gloss value rather than coverage (vehicle bodies use values such as 0.03). Only + // alpha-test materials use diffuse alpha as a cutout; blended bodies are solid unless a + // real transmap supplies coverage. + var a = select(diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, bias), duv).a, 1.0, material.params.x > 1.5 && material.params.z < 0.5); + if (material.params.z > 0.5) { + // (the transmap stays where it is: [texcoordtransX/Y] only moves the diffuse stage) + let tm = sample_transmap_bias(tex_address(uv - params.zw), bias); + a = select(1.0, tm.a, material.params.w > 0.5); + } + if (a * fade < ALPHA_REF) { + discard; + } +} + +// Roads with feathered alpha borders stay blended while their overlaps compose. +// Once the surface phases are complete, only fully covered diffuse pixels occlude +// later scenery. The transparent borders must not become invisible depth walls. +@fragment +fn fs_surface_depth(in: FsIn) -> @location(0) vec4 { + let a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], tex_address(in.uv), camera.lod.x), in.uv).a + * material.color.a * in.params.x; + if (a < 0.999) { + discard; + } + return vec4(0.0); +} + +// A vehicle body and its windows are often one mesh/material. OMSI represents that +// material as alpha-blended because the transmap contains the window opacity, but the +// alpha-tested body pixels still have to occlude vehicles behind them. The normal depth prepass +// deliberately skips all blended materials, so those pixels would otherwise have no depth +// until the colour pass (where blend order can expose the bus through the car). Keep only +// the effectively opaque part of a transmap in a separate depth-only pass; window pixels +// remain out of the prepass and are composited normally. +fn transmap_coverage(uv: vec2, params: vec4, bias: f32) { + if (material.params.z < 0.5) { + discard; + } + let tm = sample_transmap_bias(tex_address(uv - params.zw), bias); + let a = select(1.0, tm.a, material.params.w > 0.5) * params.x; + // Only what the colour pass will cover completely may hide what lies behind it: a + // texel that is merely more opaque than not (the dimmer and anti-aliased dots of a + // display's text layer, whose transmap is its script texture) wrote depth here, the + // display's backplate behind it was then rejected, and the half-transparent text was + // blended over the sky - holes in the display. + if (a < 0.99) { + discard; + } +} + +// 1 = lit by the sun, 0 = in shadow. Three cascades: the close one (the bus and what is +// next to it), the near one around the camera and the far one covering the rest of the +// visible street. + +// Depth bias of the sun shadow, in metres along the sun's ray. The maps' depth runs over +// the light box's 2199 m, and the comparison used to take off 0.0015 (near) and 0.004 (far) +// of that: 3.3 m and 8.8 m. Nothing closer to the ground than that along the ray cast a +// shadow - not a car (1.4 m), not a bus (3 m; only its roof's shadow at a low sun, +// which lay detached and offset from the bus) - and the grass and kerbs had none either. +// The receiver plane below takes care of what the big constant stood in for. +const SHADOW_DEPTH_RANGE: f32 = 2199.0; +const SHADOW_BIAS_NEAR: f32 = 0.06; +const SHADOW_BIAS_FAR: f32 = 0.3; +const SHADOW_BIAS_CLOSE: f32 = 0.025; + +// How the receiver's depth in the shadow map changes across the map (per unit of uv), from +// its normal: the PCF taps around the pixel compare against the surface's own depth at the +// tap instead of the centre's, so a surface at a slant to the sun does not shadow itself +// within the filter radius (acne), which a big constant bias used to hide. `lvp` is the +// cascade's light matrix (orthographic, so the map from the world is affine). +fn shadow_receiver_slope(lvp: mat4x4, n: vec3) -> vec2 { + let a = select(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), abs(n.x) > 0.9); + let t1 = normalize(cross(n, a)); + let t2 = cross(n, t1); + let p1 = (lvp * vec4(t1, 0.0)).xyz; + let p2 = (lvp * vec4(t2, 0.0)).xyz; + // (uv = 0.5 x + 0.5, 0.5 - 0.5 y) + let d1 = vec3(p1.x * 0.5, -p1.y * 0.5, p1.z); + let d2 = vec3(p2.x * 0.5, -p2.y * 0.5, p2.z); + let det = d1.x * d2.y - d2.x * d1.y; + if (abs(det) < 1e-12) { + return vec2(0.0); + } + let g = vec2(d1.z * d2.y - d2.z * d1.y, d1.x * d2.z - d2.x * d1.z) / det; + // a surface seen edge-on by the sun: keep the slope finite (it is in shadow of itself + // there anyway, by its normal) + return clamp(g, vec2(-2.0), vec2(2.0)); +} + +// The filter's half width in texels. A tent of 2 texels covers 4 x 4 texels, two gathers a +// side - four in all, fewer texture reads than the Poisson kernel's five (sixteen on an +// edge) - and spreads an edge about as the old kernel did in the near and close cascades +// (0.82 of a texel's standard deviation against 0.9 and 1.0; a fifth sharper in the far one). +const SHADOW_TENT: f32 = 2.0; +// Percentage-closer filtering with a tent of `SHADOW_TENT` texels, every texel of the map +// under it compared and weighted by the tent at its centre: four gathers of 2 x 2 texels, +// the whole 4 x 4 footprint read. The sparse Poisson kernel this replaces (16 bilinear taps +// 1.6 to 2.2 texels apart, and only its 5 outermost-and-middle taps when those agreed) +// sampled the map coarser than its texels: a lit gap between leaves, a few texels wide, came +// out as a copy of the kernel - an X of five magnified texels - and a feature lying between +// the taps vanished and reappeared as the receiver moved by a texel, which made the shadows +// shimmer. Read in full, the result is a continuous function of the receiver's position. +// `widen` (Enhanced: a veil of high cloud enlarging the sun) spreads the four gathers that +// many texels apart, a tent as much wider, without reading more. +// `uv`: the receiver in the cascade's own 0..1; `size`: the cascade's texels a side; +// `origin`: where its first texel lies in the texture; `slope`: its receiver plane (per uv). +// The shadow maps' size, texels a side, from the uniforms (`camera.shadow.y` is a texel): the +// near map an atlas of two cascades side by side, the far one taller by the lamps' tiles under +// it (`camera.lamp_atlas.z` is its texture's height). (Asked of the textures with +// textureDimensions in every inlined use of the sun's shadow, they brought Apple's M4 shader +// compiler down on every scene pipeline.) +fn shadow_map_size() -> f32 { + return 1.0 / max(camera.shadow.y, 1e-6); +} + +fn shadow_tent_place(uv: vec2, size: f32, widen: f32) -> vec4 { + let k = max(1.0, floor(widen + 0.5)); + // (texel i of the cascade has its centre at p = i; the first texel the tent reaches) + let p = uv * size - vec2(0.5); + let lo = floor(p - vec2(SHADOW_TENT * k)) + vec2(1.0); + return vec4(p, lo); +} + +// The tent's weights of a gather's four texels starting at `t0` (gather order: (0, 1), +// (1, 1), (1, 0), (0, 0) of the quad). +fn shadow_tent_weights(t0: vec2, p: vec2, r: f32) -> vec4 { + let w0 = max(vec2(0.0), vec2(1.0) - abs(t0 - p) / r); + let w1 = max(vec2(0.0), vec2(1.0) - abs(t0 + vec2(1.0) - p) / r); + return vec4(w0.x * w1.y, w1.x * w1.y, w1.x * w0.y, w0.x * w0.y); +} + +fn shadow_tent_near(uv: vec2, size: f32, origin: vec2, z: f32, slope: vec2, widen: f32, bias: f32) -> f32 { + let dims = vec2(2.0, 1.0) * shadow_map_size(); + let pl = shadow_tent_place(uv, size, widen); + let k = max(1.0, floor(widen + 0.5)); + let r = SHADOW_TENT * k; + var sum = 0.0; + var wsum = 0.0; + for (var q = 0; q < 4; q = q + 1) { + let t0 = pl.zw + vec2(f32(q & 1), f32(q >> 1u)) * 2.0 * k; + let a = (origin + t0 + vec2(1.0)) / dims; + let zr = z + dot(slope, (t0 + vec2(0.5) - pl.xy) / size) - bias; + let w = shadow_tent_weights(t0, pl.xy, r); + sum = sum + dot(textureGatherCompare(t_shadow, s_shadow, a, zr), w); + wsum = wsum + w.x + w.y + w.z + w.w; + } + return sum / max(wsum, 1e-6); +} + +fn shadow_tent_far(uv: vec2, size: f32, z: f32, slope: vec2, widen: f32, bias: f32) -> f32 { + let dims = vec2(shadow_map_size(), camera.lamp_atlas.z); + let pl = shadow_tent_place(uv, size, widen); + let k = max(1.0, floor(widen + 0.5)); + let r = SHADOW_TENT * k; + var sum = 0.0; + var wsum = 0.0; + for (var q = 0; q < 4; q = q + 1) { + let t0 = pl.zw + vec2(f32(q & 1), f32(q >> 1u)) * 2.0 * k; + let a = (t0 + vec2(1.0)) / dims; + let zr = z + dot(slope, (t0 + vec2(0.5) - pl.xy) / size) - bias; + let w = shadow_tent_weights(t0, pl.xy, r); + sum = sum + dot(textureGatherCompare(t_shadow_far, s_shadow, a, zr), w); + wsum = wsum + w.x + w.y + w.z + w.w; + } + return sum / max(wsum, 1e-6); +} + +// The near map is an atlas two cascades wide: the near cascade in its left half, the close +// one (`camera.light_view_proj_close`) from the top left of its right half, drawn no bigger +// than 2048 texels (`SHADOW_CLOSE_MAX` in lib.rs). `widen`: how much wider than the +// cascade's own the filter is (Enhanced: a veil of high cloud enlarging the sun). +fn shadow_pcf_near(uv: vec2, z: f32, slope: vec2, widen: f32) -> f32 { + let size = shadow_map_size(); + return shadow_tent_near(uv, size, vec2(0.0), z, slope, widen, SHADOW_BIAS_NEAR / SHADOW_DEPTH_RANGE); +} + +fn shadow_pcf_close(uv: vec2, z: f32, slope: vec2) -> f32 { + // (camera.post.w: the close map's size over the near map's) + let half = shadow_map_size(); + let size = half * select(1.0, camera.post.w, camera.post.w > 0.0); + return shadow_tent_near(uv, size, vec2(half, 0.0), z, slope, 1.0, SHADOW_BIAS_CLOSE / SHADOW_DEPTH_RANGE); +} + +fn shadow_push_close(n: vec3, ndl: f32) -> vec3 { + return n * (0.015 + 0.03 * (1.0 - ndl)); +} + +// The close cascade's value and weight at a point (weight 0 outside it): it fades into the +// near cascade between 60 and 90 % of its range from the camera. +fn shadow_close(world: vec3, n: vec3, ndl: f32, thin: bool) -> vec2 { + let range = camera.flags.w; + if (range <= 0.0) { + return vec2(1.0, 0.0); + } + let radial = distance(world, camera.cam_pos.xyz); + let w = 1.0 - smoothstep(range * 0.6, range * 0.9, radial); + if (w <= 0.001) { + return vec2(1.0, 0.0); + } + let lp = camera.light_view_proj_close * vec4(world + shadow_push_close(n, ndl), 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + if (edge >= 0.48 || lp.z < 0.0 || lp.z > 1.0) { + return vec2(1.0, 0.0); + } + let slope = select(shadow_receiver_slope(camera.light_view_proj_close, n), vec2(0.0), thin); + return vec2(shadow_pcf_close(uv, lp.z, slope), w); +} + +// The far map takes the top of its texture (its texels are the texture's first rows); the +// lamps' tiles lie under it (`LampAtlas` in lights.rs). +fn shadow_pcf_far(uv: vec2, z: f32, slope: vec2, widen: f32) -> f32 { + let size = shadow_map_size(); + return shadow_tent_far(uv, size, z, slope, widen, SHADOW_BIAS_FAR / SHADOW_DEPTH_RANGE); +} + +// The shadow lookup point: pushed off the surface along its normal by about a texel of the +// cascade (0.14 m near, 0.68 m far), more where the surface turns away from the sun. +fn shadow_push_near(n: vec3, ndl: f32) -> vec3 { + return n * (0.06 + 0.12 * (1.0 - ndl)); +} + +fn shadow_push_far(n: vec3, ndl: f32) -> vec3 { + return n * (0.3 + 0.6 * (1.0 - ndl)); +} + +// `thin`: an alpha-tested card (leaves, fences), whose normal says nothing about its plane +// (OMSI points a tree's normals up): no receiver plane, the lookup moves half a metre +// towards the sun instead, which keeps a crown from speckling itself. +fn sun_shadow(world_in: vec3, n: vec3, thin: bool) -> f32 { + if (camera.shadow.x < 0.5) { + return 1.0; + } + let world = world_in + select(vec3(0.0), camera.sun_dir.xyz * 0.5, thin); + let ndl = clamp(dot(n, camera.sun_dir.xyz), 0.0, 1.0); + let close = shadow_close(world, n, ndl, thin); + if (close.y >= 0.999) { + return close.x; + } + let near_lp = camera.light_view_proj * vec4(world + shadow_push_near(n, ndl), 1.0); + let near_uv = vec2(near_lp.x * 0.5 + 0.5, 0.5 - near_lp.y * 0.5); + let inside = max(abs(near_uv.x - 0.5), abs(near_uv.y - 0.5)); + if (inside < 0.48 && near_lp.z >= 0.0 && near_lp.z <= 1.0) { + let nv = shadow_pcf_near(near_uv, near_lp.z, select(shadow_receiver_slope(camera.light_view_proj, n), vec2(0.0), thin), 1.0); + return mix(nv, close.x, close.y); + } + let lp = camera.light_view_proj_far * vec4(world + shadow_push_far(n, ndl), 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || lp.z < 0.0 || lp.z > 1.0) { + return 1.0; + } + let sum = shadow_pcf_far(uv, lp.z, select(shadow_receiver_slope(camera.light_view_proj_far, n), vec2(0.0), thin), 1.0); + let edge = clamp((0.5 - max(abs(uv.x - 0.5), abs(uv.y - 0.5))) * 12.0, 0.0, 1.0); + return mix(1.0, sum, edge); +} + +// Sum of the point lights registered in the grid cell of `p`. A light is registered in +// every cell its range touches, so the point's own cell holds every light that reaches it; +// looking into the neighbouring cells as well counted a light up to four times, and how +// often depended on where the cell edges fell - lamp pools brightened and dimmed as the +// camera moved. +// `map_k`: how much of the map's lamps a surface takes (0 on a light-mapped road in the +// classic picture, whose lamps are in its light map); a vehicle's own lights (dir.x 1, see +// lib.rs `gpu_light`) always shine - the headlights lit no road at all in vanilla. +fn point_lights(p: vec3, n: vec3, map_k: f32) -> vec3 { + var sum = vec3(0.0); + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell <= 0.0 || side == 0u) { + return sum; + } + let f = (p.xy - camera.light_grid.xy) / cell; + let x = i32(floor(f.x)); + let y = i32(floor(f.y)); + if (x >= 0 && y >= 0 && x < i32(side) && y < i32(side)) { + let base = (u32(y) * side + u32(x)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let d = l.pos.xyz - p; + let dist = length(d); + if (dist >= l.pos.w) { + continue; + } + if (!(l.dir.w < -1.5 && l.dir.z < -0.5) && own_vehicle_blocks(p, l.pos.xyz)) { + continue; + } + if (l.dir.w >= -1.5 && l.extra.z != 0.0) { + // a Direct3D spot of the classic picture (lights.rs `push_classic_spot`): a + // vehicle's [spotlight] (its range negative) is the player's alone, lit by + // `classic_spot` at the vertices; another - a [spotlight_2], a cookie's + // cone - is lit so here, its ambient light with the diffuse + if (l.extra.z < 0.0) { + continue; + } + let s = d3d_spot(p, n, l.pos.xyz, l.dir, l.extra.x, l.extra.z, l.color.rgb * l.color.w); + sum = sum + s[0] + s[1]; + continue; + } + // full intensity within 1/8 of the range, then inverse-square, cut off at the range; + // the strength was set by eye while a street lamp was still counted about three + // times (see above), so it is three times what it was, to keep the lamp pools + let r0 = l.pos.w * 0.125; + let att = min(1.0, (r0 * r0) / max(dist * dist, 0.01)) * clamp(1.0 - dist / l.pos.w, 0.0, 1.0) * 3.75; + let ndl = max(dot(n, d / max(dist, 0.01)), 0.15); + var k = select(map_k, 1.0, l.dir.x > 0.5 && l.dir.w < -1.5); + if (l.dir.w >= -1.5) { + // a spot (a vehicle's [spotlight], as Direct3D lights with it): full inside + // the inner cone, fading to nothing at the outer one; nothing behind it + let c = dot(-d / max(dist, 0.01), l.dir.xyz); + k = smoothstep(l.dir.w, max(l.extra.x, l.dir.w + 1e-3), c); + } + sum = sum + l.color.rgb * l.color.w * att * ndl * k; + } + } + return sum; +} + +// [interiorlight]: the light of a vehicle's saloon lamps on a mesh that names them in its +// [illumination_interior], 1 = a lamp's full light on a seat under it. `code` is the +// instance's lamp code (lib.rs `Instance::interior_lamps`): the first of its lamp slots in +// `lights` times 64 plus how many; below 1 it is a plain brightness (a passenger standing in +// a lit bus). Each lamp is OMSI's Direct3D point light: attenuation +// 1 / (d² / core²) with `core` the lamp's [interiorlight] range, no cut-off short of 100 m, +// times N·L; the sum saturates, as Direct3D's vertex colour does. +fn interior_lamps(p: vec3, n: vec3, code: f32) -> vec3 { + if (code < 1.0) { + return vec3(1.0, 0.96, 0.84) * clamp(code, 0.0, 1.0); + } + let c = u32(code + 0.5); + // (LAMP_CODE_STRIDE: 64 - up to 63 lamps a mesh) + let first = c >> 6u; + let count = c & 63u; + var sum = vec3(0.0); + for (var i = 0u; i < count; i = i + 1u) { + let l = lights[first + i]; + let r = l.extra.w; + let d = l.pos.xyz - p; + let dist2 = max(dot(d, d), 1e-4); + if (l.color.w <= 0.0 || dist2 >= r * r) { + continue; + } + let core = max(l.extra.y, 0.01); + let att = core * core / dist2; + let ndl = max(dot(n, d * inverseSqrt(dist2)), 0.0); + sum = sum + l.color.rgb * l.color.w * att * ndl; + } + return min(sum, vec3(1.0)); +} + + +// A Direct3D spot light of the classic picture at `p` (normal `n`), as Omsi.exe sets its +// up for a vehicle's [spotlight] (0x708acc, see lights.rs `push_classic_spot`): `source` +// is the spotlight's own world position; attenuation 1 / (0.2 + d / R + 40 d² / R²) +// (R the declared range), the cone (`dir`: direction and the cosine of half the outer cone; +// `inner` the inner one's) with a falloff of 2, 0.3 x `color` as diffuse light (times N.L) +// and 0.1 x as ambient light, which lights the material's ambient colour whichever way the +// surface faces. [0] the diffuse light, [1] the ambient light. +fn d3d_spot(p: vec3, n: vec3, source: vec3, dir: vec4, inner: f32, range: f32, color: vec3) -> array, 2> { + let to_light = source - p; + let dl = max(length(to_light), 0.01); + let att = 1.0 / (0.2 + dl / range + 40.0 * dl * dl / (range * range)); + let rho = dot(-to_light / dl, dir.xyz); + let cone = pow(clamp((rho - dir.w) / (max(inner, dir.w + 1e-4) - dir.w), 0.0, 1.0), 2.0); + let lit = color * att * cone; + return array, 2>(lit * 0.3 * max(dot(n, to_light / dl), 0.0), lit * 0.1); +} + +// The classic picture's headlight at a vertex: Omsi.exe's one Direct3D spot light, the +// player's [spotlight] (`camera.spot`, see setup.rs `classic_spot`), lit at the vertices as +// its fixed function lights them. Across a road, whose vertices lie at its edges, the pool +// is spread as OMSI 2 spreads it: lit per pixel it was brightest on the crown of the road +// in front of the bus and gone far sooner. `vs_main` excludes the player's own vehicle. +// [0] is the vehicle-face origin for occlusion; [3] is the declared source for lighting. +// Nothing beyond 4 x its range, as Direct3D cuts it off. +fn classic_spot(p: vec3, n: vec3) -> array, 2> { + let s = camera.spot; + let none = array, 2>(vec3(0.0), vec3(0.0)); + if (s[0].w <= 0.0 || distance(s[3].xyz, p) >= 4.0 * s[0].w || own_vehicle_blocks(p, s[0].xyz)) { + return none; + } + return d3d_spot(p, n, s[3].xyz, s[1], s[2].w, s[0].w, s[2].rgb); +} +// Value noise in three octaves: the "fractal" detail (the `detail_textures` setting) laid +// over the ground and the road surfaces close by, so that a blurred texture keeps some grain. +// +// The lattice cell is hashed as an integer. The old `fract(sin(dot(q, …)) * 43758.5)` +// hash took the cell's map coordinate - two and a half million at Spandau's 892 km - into +// a sine: in 32-bit floats its argument is a multiple of 64 there, and what came out was +// not noise but a ramp that repeated along straight lines, so every road wore thin +// diagonal streaks at an exact spacing. Cells are wrapped at `PATTERN_PERIOD` (the pattern +// coordinate is taken modulo that on the CPU, see `world_pattern_xy`), which keeps the +// hash's input small and the pattern seamless across the wrap. +const PATTERN_PERIOD: f32 = 1000.0; + +fn hash_cell(c: vec2, cells: f32) -> f32 { + // the cell index modulo the lattice's cells per period, as an exact integer + let w = c - cells * floor(c / cells); + var v = vec2(w) * 1664525u + vec2(1013904223u); + // (a PCG-style mix: two rounds of multiply, cross-add and xor-shift) + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + return f32(v.x >> 8u) / 16777215.0; +} + +// `freq`: lattice cells per metre of `p` (a whole number of cells per `PATTERN_PERIOD`). +fn vnoise_f(p: vec2, freq: f32, offset: vec2) -> f32 { + let q = p * freq + offset; + let cells = round(PATTERN_PERIOD * freq); + let i = floor(q); + let f = q - i; + let u = f * f * (3.0 - 2.0 * f); + let a = hash_cell(i, cells); + let b = hash_cell(i + vec2(1.0, 0.0), cells); + let c = hash_cell(i + vec2(0.0, 1.0), cells); + let d = hash_cell(i + vec2(1.0, 1.0), cells); + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); +} + + +fn detail_noise(p: vec2, near: f32) -> f32 { + // Anti-alias: point-sampling a lattice this fine aliases wherever one pixel's + // footprint spans more than about one cell of it - looking down a street at a + // grazing angle, or just driving away, constantly changes that footprint, and the + // alias pattern with it, which reads as the "fractal" texture re-rendering itself as + // the view angle changes. `fwidth` gives the footprint in the same units as `p`; an + // octave fades to its own mean (0.5, the hash is uniform 0..1) once a pixel can no + // longer resolve it, which is what an infinitely dense filter of it would give anyway. + let w = max(fwidth(p).x, fwidth(p).y); + let seen = select(0.0, 1.0, near > 0.0); + let fade0 = (1.0 - smoothstep(0.3, 1.2, w * 2.9)) * seen; + let fade1 = (1.0 - smoothstep(0.3, 1.2, w * 0.73)) * seen; + let fade2 = (1.0 - smoothstep(0.3, 1.2, w * 0.19)) * seen; + var n0 = 0.5; + var n1 = 0.5; + var n2 = 0.5; + if (fade0 > 0.0) { + n0 = mix(0.5, vnoise_f(p, 2.9, vec2(0.0)), fade0); + } + if (fade1 > 0.0) { + n1 = mix(0.5, vnoise_f(p, 0.73, vec2(0.0)), fade1); + } + if (fade2 > 0.0) { + n2 = mix(0.5, vnoise_f(p, 0.19, vec2(0.0)), fade2); + } + return n0 * 0.5 + n1 * 0.3 + n2 * 0.2; +} + +fn world_pattern_xy(p: vec3) -> vec2 { + // Geometry is relative to the floating render origin for f32 precision. Procedural + // patterns are not: reconstruct their stable map-space coordinate so crossing the + // renderer's 100 m origin cell cannot re-seed the asphalt/ground pattern. The origin + // arrives modulo PATTERN_PERIOD (lib.rs), so this stays a small, exact number: the map + // coordinate itself (892 km at Spandau) has a 6 cm step in 32 bits, a fifth of the + // finest noise cell. + return p.xy + camera.world_origin.xy; +} + +// Whether every component is a finite number, tested on the bits: Metal's fast maths takes +// `x != x` and comparisons with a NaN as it likes (a NaN colour happened to come out as +// something on the Mac), Direct3D 12 keeps the NaN and draws it black. +fn all_finite(v: vec3) -> bool { + let e = bitcast>(v) & vec3(0x7f800000u); + return all(e != vec3(0x7f800000u)); +} + +fn finite_or(v: vec3, fallback: vec3) -> vec3 { + return select(fallback, v, all_finite(v)); +} + +// The side of a tracked pane's wetness mask (`window_wipers::SIZE`). A constant, not the +// texture's own size: with `textureDimensions(mx_tex2d[mx_mat.trans])` in these functions Apple's Metal +// compiler crashed on the scene shader (the pipelines failed and the renderer fell back to +// 1x MSAA without snowfall and lamp shadows). +const WIPE_MASK_SIZE: i32 = 128; + +fn window_wetness(in: FsIn) -> f32 { + if (material.wipe_bounds.z != 0.0) { + // The mask packs the pane depth into R/G (high and low byte) and the wetness into + // B (the pane's unwiped wetness) and A (the local wetness). A filtered sample mixes + // the depth bytes of neighbouring texels into a depth that belongs to neither, so + // the pane test flickered between A and B from texel to texel: a staircase along + // every texel row where the raked glass changes depth. Read the four texels + // unfiltered, test each by its own depth, and blend the results bilinearly. + let dims = vec2(WIPE_MASK_SIZE); + let inside = all(in.wipe_uv.xy >= vec2(0.0)) && all(in.wipe_uv.xy <= vec2(1.0)); + let p = in.wipe_uv.xy * vec2(dims) - 0.5; + let base = vec2(floor(p)); + let f = p - floor(p); + var wet = 0.0; + for (var k = 0; k < 4; k++) { + let o = vec2(k & 1, k >> 1); + let w = select(1.0 - f.x, f.x, o.x == 1) * select(1.0 - f.y, f.y, o.y == 1); + let texel = textureLoad(mx_tex2d[mx_mat.trans], clamp(base + o, vec2(0), dims - 1), 0); + let depth = dot(texel.rg, vec2(256.0, 1.0)) * (64.0 / 257.0) - 32.0; + let local = (texel.a * 255.0 - 8.0) * (2.0 / 247.0); + wet += w * select(texel.b, local, inside && abs(depth - in.wipe_uv.z) <= 0.1); + } + return wet; + } + return in.params.x; +} + +// The snow variant of a tracked pane (`wipe_bounds.w` < 0): the snow the mask holds while it +// snows, drawn instead of water drops (scene/08_rain_glass.wgsl `glass_snow_with`). The mask +// value is the cover: 0 clear glass, up to 1 a pane closed by snow, above 1 the bank a blade +// pushed to the end of its sweep, below 0 glass a blade has just cleared. +fn is_snow_pane() -> bool { + return material.wipe_bounds.z != 0.0 && material.wipe_bounds.w < 0.0; +} + +// Smooth value noise (0..1) from the cell hash: the corners' values blended with a +// smoothstep, so it has no seams at the cell edges. +fn snow_noise(p: vec2) -> f32 { + let i = floor(p); + let f = p - i; + let u = f * f * (3.0 - 2.0 * f); + let a = rain_hash(i).x; + let b = rain_hash(i + vec2(1.0, 0.0)).x; + let c = rain_hash(i + vec2(0.0, 1.0)).x; + let d = rain_hash(i + vec2(1.0, 1.0)).x; + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); +} + +// By day in a downpour some of the houses' windows are lit, as people switch the light on when +// it gets that dark (`camera.wind.w` - 1: the share, `Lighting::rain_lights`, 0 with the +// setting off): the night maps of a few rooms here and there, chosen by a cell of the +// object's own frame some four metres wide and three high (`local`: the same rooms of a +// house stay lit, and a bus driving by does not flicker as it crosses cells of the world), +// each fading in at its own point of the rain. What a night map shows: the night's own +// strength or, where such a room is lit, the full light. +fn rain_lit_windows(local: vec3) -> f32 { + let night = clamp(camera.sun_color.w, 0.0, 1.0); + let share = clamp(camera.wind.w - 1.0, 0.0, 1.0); + if (share <= 0.0) { + return night; + } + let cell = floor(vec3(local.xy / 4.0, local.z / 3.0)); + let h = rain_hash(cell.xy + vec2(cell.z * 17.3, cell.z * 5.1)); + // (some a third of the rooms at the heaviest rain) + let lit = smoothstep(h.x, h.x + 0.08, share * 0.38); + return max(night, lit * (0.75 + 0.25 * h.y)); +} +fn rain_hash(p: vec2) -> vec2 { + // Integer mixing keeps neighbouring cells independent without the precision loss and + // repeated sine evaluations of a floating-point hash. + let cell = bitcast>(vec2(floor(p))); + var a = cell.x * 0x9e3779b9u ^ cell.y * 0x85ebca6bu; + a = (a ^ (a >> 16u)) * 0x7feb352du; + a = (a ^ (a >> 15u)) * 0x846ca68bu; + a = a ^ (a >> 16u); + var b = a ^ 0x68bc21ebu; + b = (b ^ (b >> 16u)) * 0x7feb352du; + b = (b ^ (b >> 15u)) * 0x846ca68bu; + b = b ^ (b >> 16u); + return vec2(f32(a), f32(b)) * (1.0 / 4294967296.0); +} + +// Smooth noise for water-film refraction and residual wiper streaks (0..1). +fn rain_patches(q: vec2) -> vec2 { + let c = floor(q); + let f = q - c; + let w = f * f * (3.0 - 2.0 * f); + let a = rain_hash(c); + let b = rain_hash(c + vec2(1.0, 0.0)); + let d = rain_hash(c + vec2(0.0, 1.0)); + let e = rain_hash(c + vec2(1.0, 1.0)); + return mix(mix(a, b, w.x), mix(d, e, w.x), w.y); +} + +// A grid of its own for each layer of drops: turned by its own angle and shifted, so that +// no two layers line up and none runs along the glass's edges. +fn rain_turn(q: vec2, a: f32) -> vec2 { + let cs = vec2(cos(a), sin(a)); + return vec2(q.x * cs.x - q.y * cs.y, q.x * cs.y + q.y * cs.x); +} + +// What a drop shows in the classic picture: the sky from the weather's colours, the +// horizon in the fog's, the ground darker. +fn rain_env_vanilla(d: vec3) -> vec3 { + let zenith = camera.sky_color.rgb + camera.ambient.rgb * 0.5; + let horizon = max(camera.fog.rgb, camera.ambient.rgb); + let ground = camera.ambient.rgb * 0.4 + camera.sun_color.rgb * camera.sun_dir.w * 0.06; + let sky = mix(horizon, zenith, smoothstep(0.0, 0.5, d.z)); + let c = mix(ground, sky, smoothstep(-0.06, 0.04, d.z)); + return select(c, srgb_decode(c), camera.sky_color.w > 0.5); +} + +// --- The rain on a pane as all the pictures draw it (the enhanced film, enhanced/07_glass.wgsl +// `glass_film`, and the classic one, scene/09_vanilla.wgsl `glass_film_classic`): the drops laid +// out in the vehicle's own frame (`FsIn.local`), so they stay on the glass however the body +// rolls and pitches and on a door that swings open. The modellers' texture coordinates of a +// film are no measure of the glass: on the windscreen of the NL202 they run half as fast +// again one way as the other and at sixty degrees to each other, from triangle to triangle +// anew, and every drop drawn in them came out a slanting streak (the classic pictures' old +// `rain_glass` did, and was replaced by this). So a pane is laid flat by the axes of the +// vehicle (`pane_proj`). + +// The glass at a pixel: the position and the flat normal in the vehicle's frame, the +// normal on the rain's side in the world, the pixel's footprint on the glass (m, its longer +// side and the side of a square of its area), and the screen derivatives of both positions. +struct PaneBase { + l: vec3, + nl: vec3, + out: vec3, + px: f32, + px_area: f32, + dlx: vec3, + dly: vec3, + dwx: vec3, + dwy: vec3, + ok: bool, +}; + +fn pane_base(world: vec3, local: vec3, n: vec3, outside_in: bool) -> PaneBase { + var b: PaneBase; + b.l = local; + b.dlx = dpdx(local); + b.dly = dpdy(local); + b.dwx = dpdx(world); + b.dwy = dpdy(world); + // the film faces the eye unless the eye is in the bus behind it (the triangle's own + // normal: a film mesh's vertex normals are not to be relied on, many have none, and + // the drops' size followed their noise) + let eye = normalize(camera.cam_pos.xyz - world); + let gn = cross(b.dwx, b.dwy); + var out = select(safe_normal(n), gn / max(length(gn), 1e-20), dot(gn, gn) > 1e-24); + out = select(-out, out, dot(out, eye) >= 0.0); + out = select(out, -out, outside_in); + b.out = out; + b.px = max(max(length(b.dwx), length(b.dwy)), 1e-5); + b.px_area = max(sqrt(length(cross(b.dwx, b.dwy))), 1e-5); + let c = cross(b.dlx, b.dly); + let cl = length(c); + b.ok = cl > 1e-12; + b.nl = select(vec3(0.0, 1.0, 0.0), c / max(cl, 1e-20), b.ok); + return b; +} + +// A direction on the glass in the vehicle's frame, in the world (through the two positions' +// screen derivatives). +fn pane_to_world(b: PaneBase, t: vec3) -> vec3 { + let g = vec3(dot(b.dlx, b.dlx), dot(b.dlx, b.dly), dot(b.dly, b.dly)); + let det = g.x * g.z - g.y * g.y; + if (abs(det) < 1e-24) { + return vec3(0.0); + } + let r = vec2(dot(b.dlx, t), dot(b.dly, t)); + let a = (g.z * r.x - g.y * r.y) / det; + let c = (g.x * r.y - g.y * r.x) / det; + return a * b.dwx + c * b.dwy; +} + +// The pane laid flat along two of the vehicle's axes (`axis`: 0 across and up, the +// windscreen and the rear window; 1 along and up, the side windows; 2 the plan, a roof +// light): where the pixel is (m: x across, y down), how an offset there is taken back onto +// the glass (`m`: metres along `side_w` and `down_w`, the glass's own across and down in +// the world), and the projection's screen derivatives (for the wiper's ridge). +struct PaneProj { + q: vec2, + m: mat2x2, + side_w: vec3, + down_w: vec3, + dqx: vec2, + dqy: vec2, + steep: bool, +}; + +fn pane_proj(b: PaneBase, axis: i32) -> PaneProj { + var p: PaneProj; + var ea = vec3(1.0, 0.0, 0.0); + var eb = vec3(0.0, 0.0, -1.0); + var ec = vec3(0.0, 1.0, 0.0); + if (axis == 1) { + ea = vec3(0.0, 1.0, 0.0); + ec = vec3(1.0, 0.0, 0.0); + } else if (axis == 2) { + eb = vec3(0.0, 1.0, 0.0); + ec = vec3(0.0, 0.0, 1.0); + } + let nl = b.nl; + let nc = dot(nl, ec); + let ncs = select(nc, select(-1e-3, 1e-3, nc >= 0.0), abs(nc) < 1e-3); + p.q = vec2(dot(b.l, ea), dot(b.l, eb)); + p.dqx = vec2(dot(b.dlx, ea), dot(b.dlx, eb)); + p.dqy = vec2(dot(b.dly, ea), dot(b.dly, eb)); + // the glass under a step of the projection's two axes + let t1 = ea - ec * (dot(nl, ea) / ncs); + let t2 = eb - ec * (dot(nl, eb) / ncs); + // the glass's own down (the steepest way on it) and across, in the vehicle's frame + p.steep = axis != 2; + var dl = vec3(0.0, 0.0, -1.0) + nl * nl.z; + dl = select(normalize(t2), dl / max(length(dl), 1e-6), dot(dl, dl) > 0.02 && p.steep); + var sl = t1 - dl * dot(t1, dl); + sl = sl / max(length(sl), 1e-6); + p.m = mat2x2(vec2(dot(t1, sl), dot(t1, dl)), vec2(dot(t2, sl), dot(t2, dl))); + // the same two ways in the world, square to the normal on the rain's side + var sw = pane_to_world(b, sl); + sw = sw - b.out * dot(sw, b.out); + var dw = pane_to_world(b, dl); + dw = dw - b.out * dot(dw, b.out); + p.side_w = sw / max(length(sw), 1e-6); + dw = dw - p.side_w * dot(dw, p.side_w); + p.down_w = dw / max(length(dw), 1e-6); + return p; +} + +// The water on a pane at a pixel: the surface's normal (world, out of the water), how much +// of the pixel a drop or a bead covers and how far out on it the pixel lies (0 its middle, +// 1 its rim), the drop's radius in pixels, the pane's normal on the rain's side, the fine +// mist of droplets under a millimetre, and how much of the view through the pane the +// connected water scatters into a soft blur (`veil`). +struct GlassWater { + n: vec3, + cover: f32, + out: vec3, + mist: f32, + veil: f32, + rim: f32, + size_px: f32, +}; + +// One drop of radius `r` (m) at `d` (m on the glass, across / down): the slope of its dome +// (the normal's part along the glass), its cover of the pixel (`px`: the pixel's size on +// the glass) and how far out on it the pixel lies. A shallow cap, as water spreading on +// glass makes; a drop smaller than the pixel keeps its share of it, its slopes flattened +// to their average. +fn glass_dome(d: vec2, r: f32, px: f32) -> vec4 { + let rr = length(d) / max(r, 1e-6); + let aa = clamp(px / max(r, 1e-6), 0.02, 1.0); + let cover = 1.0 - smoothstep(1.0 - aa, 1.0 + aa, rr); + let seen = smoothstep(0.0, 0.8, r / px); + let cap = mix(0.15, 0.55, smoothstep(0.7, 2.5, r / px)); + let s = d / max(r, 1e-6) * cap * (0.6 + 0.4 * rr * rr); + return vec4(s, cover * seen, min(rr, 1.0)); +} + +// What covers the pixel, gathered over the layers: the cover, the slope, the rim and the +// drop's size in pixels of the drop on top. +struct DropAcc { + cover: f32, + slope: vec2, + rim: f32, + size_px: f32, + track: f32, + // the cover of the drops too small for the pixel to see one by one, as their average + // (taken into the mist, so that they read as an even haze, not as random specks) + avg: f32, +}; + +fn drop_take(a: ptr, d: vec4, r: f32, px: f32) { + if (d.z > (*a).cover) { + (*a).cover = d.z; + (*a).slope = d.xy; + (*a).rim = d.w; + (*a).size_px = r / px; + } +} + +// One layer of the drops that sit on the glass: a jittered grid of cells `cell` metres +// wide (of the projection), each holding a drop now and then (`occ` the share of cells +// that hold one). A drop lands, spreads to its size within a moment and sits; after its +// own while it is gone again, taken by a runner or merged into a neighbour, and the next +// lands somewhere else in the cell - all fading, nothing popping. +fn glass_bead(a: ptr, p: PaneProj, layer: f32, cell: f32, occ: f32, r0: f32, size: f32, t: f32, px: f32) { + // (a layer whose drops are smaller than the pixel, or cells no wider than it - a mirror's + // small picture, the glass seen from afar - is taken at its average cover: sampled one + // random cell a pixel, it drew white noise) + let fine = max(1.0 - smoothstep(0.7, 1.5, r0 * size / px), 1.0 - smoothstep(1.0, 2.5, cell / px)); + if (fine > 0.0) { + let rr = 1.6 * r0 * size / cell; + (*a).avg = (*a).avg + fine * occ * min(3.14159 * rr * rr, 1.0); + if (fine > 0.99) { + return; + } + } + let turn = 0.61 + layer * 1.37; + let g2 = rain_turn(p.q, turn) / cell + vec2(layer * 17.3, layer * 5.1); + let c = floor(g2); + let timing = rain_hash(c + vec2(3.7, 9.2 + layer)); + let life = (9.0 + layer * 4.0) * (1.0 + timing.y); + let cycle = t / life + timing.x; + let ph = fract(cycle); + let arrival = c + floor(cycle) * vec2(17.0, 43.0); + let h = rain_hash(arrival); + // (a share of cells rising with the wetness: a drop fades in over a small rise of it) + let shown = clamp((occ - h.x) * 20.0, 0.0, 1.0) * smoothstep(0.0, 0.03, ph) * (1.0 - smoothstep(0.9, 1.0, ph)) * (1.0 - fine); + if (shown <= 0.0) { + return; + } + // (`r0` the layer's smallest drop, the largest twice that: rain on glass sits as drops of + // half a millimetre to four across - drawn up to a share of the cell they made drops of a + // centimetre and more, few and far between) + let radius = r0 * (1.0 + h.y * h.y) * mix(0.6, 1.0, smoothstep(0.0, 0.2, ph)) * size; + // (anywhere in the cell the largest still fits in - on the glass it is never smaller + // than in the projection - and the same place whatever its size: the size follows the + // wetness, which changes across the glass) + let room = min(r0 * 3.0 / cell, 0.45); + let centre = c + vec2(room) + rain_hash(arrival + 9.1) * (1.0 - 2.0 * room); + let dq = rain_turn((g2 - centre) * cell, -turn); + if (length(dq) > radius * 1.3) { + return; + } + var d = p.m * dq; + // No drop is a circle: its rim wanders where the glass held it as it spread, and its + // weight draws it a little fuller below than above. + let h3 = rain_hash(arrival + 23.9); + let dl = max(length(d), 1e-7); + let u = d / dl; + let c2 = u.x * u.x - u.y * u.y; + let s2 = 2.0 * u.x * u.y; + let c3 = u.x * (4.0 * u.x * u.x - 3.0); + let s3 = u.y * (3.0 - 4.0 * u.y * u.y); + let p2 = h3 * 2.0 - 1.0; + let wave = (s2 * p2.x + c2 * p2.y) * 0.7 + 0.45 * (s3 * p2.y - c3 * p2.x); + d = d / (1.0 + (0.03 + 0.05 * h.y) * wave); + d.y = d.y * select(1.06, 0.94, d.y > 0.0); + let dome = glass_dome(d, radius, px); + drop_take(a, vec4(dome.xy, dome.z * shown, dome.w), radius, px); +} + +// A runner's sideways wander as it goes down (m): a smooth random path of its own. +fn glass_meander(s: f32, seed: vec2, amp: f32) -> f32 { + let w = rain_patches(vec2(s * 9.0 + seed.x, seed.y)); + return amp * ((w.x - 0.5) * 1.5 + (w.y - 0.5) * 0.5); +} + +// The runners in a lattice of lanes (`qr`: the projection turned so they run down +y, `mr` +// taking its offsets onto the glass): now and then a drop grown heavy breaks loose and +// slides a hand's breadth or two down, in fits and starts, wandering a little from side to +// side, and stops again. It sweeps a narrow clear track through the small drops, which +// fill in again as the rain falls on it; behind it lies a short wet trail that drains +// within a second, and a few beads it left. One chance a cell of 4.5 cm x 1.2 m; a pixel +// looks at its own cell and the one above, whose drop may have slid into it. +fn glass_runners(a: ptr, qr: vec2, mr: mat2x2, seed: f32, wet: f32, heavy: f32, blow: f32, size: f32, t: f32, px: f32) { + // (lanes of 4.5 cm and cells 1.2 m tall, few of them running at once: with lanes of 2 cm + // and cells of 0.8 m nearly every lane ran in a downpour, and their tracks cut the glass + // into wide clear stripes, #4153) + let lane_w = 0.045; + let seg_h = 1.2; + let lane = floor(qr.x / lane_w); + let seg0 = floor(qr.y / seg_h); + for (var k = 0; k < 2; k = k + 1) { + let seg = seg0 - f32(k); + let key = vec2(lane * 1.7 + seed * 101.0, seg * 2.3 + seed * 37.0); + let h1 = rain_hash(key + vec2(3.0, 11.0)); + if (h1.x >= wet * (0.15 + 0.15 * heavy + 0.1 * blow)) { + continue; + } + let h2 = rain_hash(key + vec2(8.1, 5.1)); + // (it gathers a while, runs, and its trail fills in with new rain) + // (a drop grown heavy on upright glass runs off at some ten to twenty centimetres a + // second, most of the way down the pane) + let sit = 0.6 + 2.4 * h2.y; + let v = (0.08 + 0.16 * h1.y * h1.y) * (1.0 + 0.8 * blow) * (1.0 + 0.4 * heavy); + let run_len = 0.12 + 0.4 * h2.x; + let run_t = run_len / v; + let refill = mix(3.0, 1.5, wet); + let period = sit + run_t + refill; + let cycle = t / period + h2.x; + let tau = fract(cycle) * period; + let h3 = rain_hash(key + vec2(1.3, 29.7) + floor(cycle) * vec2(13.0, 41.0)); + // stick and slip: v s - v P / 2 pi sin(2 pi s / P) halts once a pulse P + let pulse = 0.3 + 0.4 * h3.x; + let st = clamp(tau - sit, 0.0, run_t * 1.05); + let travel = min(v * st - v * pulse * 0.1591549 * sin(6.283185 * st / pulse), run_len); + let vis = smoothstep(0.0, 0.6, tau) * (1.0 - smoothstep(period - 1.0, period, tau)); + let y0 = (seg + 0.02 + 0.32 * h3.x) * seg_h; + let x0 = (lane + 0.3 + 0.4 * h3.y) * lane_w; + let wseed = h3 * 57.0; + let amp = 0.002 + 0.002 * h2.y; + if (abs(qr.x - x0) > lane_w * 0.5 + amp * 1.5 || qr.y < y0 - 0.01 || qr.y > y0 + run_len + 0.01) { + continue; + } + // (a downpour's runners are heavier; a drop gathers before it goes) + let rh = size * (0.0012 + 0.0008 * h1.y) * (1.0 + 0.3 * heavy) * mix(0.6, 1.0, smoothstep(0.0, sit, tau)); + var head_d = mr * vec2(qr.x - (x0 + glass_meander(travel, wseed, amp)), qr.y - (y0 + travel)); + // (drawn out a little behind, full in front) + head_d.y = head_d.y * select(0.8, 1.0, head_d.y > 0.0); + let head = glass_dome(head_d, rh, px); + // (once stopped it sits at the end of its run and is taken into the new rain) + let head_vis = vis * (1.0 - smoothstep(sit + run_t, sit + run_t + refill * 0.8, tau)); + drop_take(a, vec4(head.xy, head.z * head_vis, head.w), rh, px); + let along = qr.y - y0; + if (along > 0.0 && along < travel - rh * 0.5) { + let dxq = qr.x - (x0 + glass_meander(along, wseed, amp)); + let dx = (mr * vec2(dxq, 0.0)).x; + // how long ago the head passed here + let age = max(tau - sit - along / v, 0.0); + let hw = rh * 0.9; + let cleared = (1.0 - smoothstep(hw * 0.6, hw * 1.1, abs(dx))) * (1.0 - smoothstep(refill * 0.4, refill, age)) * vis; + (*a).track = max((*a).track, cleared); + // the thin wet trail it draws, draining within a second: a faint lens, no strip + let tw = rh * 0.45 * exp(-age * 2.0); + let trail = glass_dome(vec2(dx, 0.0), max(tw, 1e-5), px); + let trail_cover = trail.z * 0.35 * (1.0 - smoothstep(0.2, 1.0, age)) * vis; + drop_take(a, vec4(trail.xy * 0.4, trail_cover, trail.w), tw, px); + // ... and a few beads, left behind where the trail broke + let bc = floor(along / 0.009); + let bh = rain_hash(vec2(lane * 3.1 + bc, seg * 1.9 + 41.0 + seed * 7.0)); + if (bh.x < 0.3) { + let bcen = vec2((bh.y - 0.5) * hw * 0.8, ((bc + 0.5) * 0.009 - along) * (mr * vec2(0.0, 1.0)).y); + let br = 0.0004 + 0.0005 * bh.y; + let bead = glass_dome(vec2(dx, 0.0) - bcen, br, px); + let bead_cover = bead.z * smoothstep(0.4, 1.0, age) * (1.0 - smoothstep(refill * 0.5, refill, age)) * vis; + drop_take(a, vec4(bead.xy, bead_cover, bead.w), br, px); + } + } + } +} + +// The drops on one projection of the pane (`w` its share, see `glass_water`). +fn glass_drops(a: ptr, b: PaneBase, p: PaneProj, w: f32, wet: f32, heavy: f32, bank: f32, size: f32, world: vec3, t: f32) { + // --- the airstream: a drop's drag grows with the speed squared, and at some 40 km/h it + // matches its weight. Along the glass the air drives the water back; where it meets the + // glass head on (the windscreen) it parts, up and out. The runners go where weight and + // air take them together; the drops that sit hold on. + var flow = vec2(0.0, 1.0); + var blow = 0.0; + if (camera.wind.w > 0.5 && near_player_vehicle(world) > 0.5) { + let air = -camera.wind.xyz; + var aw = vec2(dot(air, p.side_w), dot(air, p.down_w)); + aw.y = aw.y - abs(dot(air, b.out)) * 0.6; + let v2 = dot(aw, aw); + blow = clamp(v2 / 130.0, 0.0, 3.0); + flow = flow + aw / max(sqrt(v2), 1e-4) * blow; + } + if (p.steep) { + // The runners' lanes are laid along the way the water runs, in sixteenths of a turn + // (turned freely, a degree moved every lane a metre off by its width). Between two + // such ways the two lattices cross-fade, so a change of speed fades the runners + // over instead of jumping them. (`flow` is on the glass; the lanes in the + // projection, whose down is the glass's down.) + let fstep = 0.3926991; + let fa = atan2(flow.x, flow.y) / fstep; + let f0 = floor(fa); + let fw = smoothstep(0.35, 0.65, fa - f0); + for (var k = 0; k < 2; k = k + 1) { + let wk = select(1.0 - fw, fw, k == 1) * w; + if (wk < 0.01) { + continue; + } + let ang = (f0 + f32(k)) * fstep; + let cs = vec2(cos(ang), sin(ang)); + let mr = p.m * mat2x2(vec2(cs.x, -cs.y), vec2(cs.y, cs.x)); + glass_runners(a, rain_turn(p.q, ang), mr, f0 + f32(k), wet * wk, heavy, blow, size, t, b.px_area); + } + } + // --- the drops that sit: four sizes, a great many small ones and fewer large ones (radius + // 1 to 2, 1.6 to 3.2, 2.4 to 4.8 and 3.4 to 6.8 mm: smaller ones, true to a drizzle's, + // were under a pixel from the driver's seat and drew the windscreen as an even grain), + // all fewer in the runners' fresh + // tracks and under the bank + let room = (1.0 - (*a).track) * (1.0 - bank) * w; + for (var layer = 0; layer < 4; layer = layer + 1) { + let fl = f32(layer); + var cell = 0.0068; + var r0 = 0.001; + var occ = 0.85 * smoothstep(0.02, 0.25, wet); + if (layer == 1) { + cell = 0.0108; + r0 = 0.0016; + occ = 0.75 * smoothstep(0.05, 0.4, wet); + } else if (layer == 2) { + cell = 0.016; + r0 = 0.0024; + occ = 0.6 * smoothstep(0.15, 0.6, wet); + } else if (layer == 3) { + cell = 0.023; + r0 = 0.0034; + occ = 0.4 * smoothstep(0.35, 0.9, wet); + } + glass_bead(a, p, fl, cell, occ * room, r0, size, t, b.px_area); + } +} + +// The rain on a pane at a pixel (see the head of this file). `water` is the pane's +// wetness (0..1; below 0 a blade has just wiped it, above 1 the bank a blade pushed), +// `t` the animation clock, `outside_in` true for the eye in the bus. +fn glass_water(world: vec3, local: vec3, n: vec3, water: f32, t: f32, outside_in: bool) -> GlassWater { + let b = pane_base(world, local, n, outside_in); + let wdx = dpdx(water); + let wdy = dpdy(water); + var g: GlassWater; + g.n = b.out; + g.out = b.out; + g.cover = 0.0; + g.mist = 0.0; + g.veil = 0.0; + g.rim = 0.0; + g.size_px = 0.0; + let wet = clamp(water, 0.0, 1.0); + let wiped = clamp(-water * 25.0, 0.0, 1.0); + let bank = clamp((water - 1.0) * 0.18, 0.0, 1.0); + if (!b.ok || (wet <= 0.01 && wiped <= 0.01 && bank <= 0.0)) { + return g; + } + // Which way the pane is laid flat: by the larger of its normal's parts across and along + // the vehicle, the two cross-faded over a band round 45 degrees (a windscreen's curved + // corner), each drop of either set coming or going whole; a pane facing up is a roof's. + let an = abs(b.nl); + let roof = an.z > max(an.x, an.y) * 2.0; + let w_front = select(smoothstep(-0.12, 0.12, an.y - an.x), 1.0, roof); + let main_axis = select(select(1, 0, w_front >= 0.5), 2, roof); + let p = pane_proj(b, main_axis); + // the wetness's gradient on the glass (from its screen derivatives) + let jd = p.dqx.x * p.dqy.y - p.dqx.y * p.dqy.x; + var grad = vec2(0.0); + if (abs(jd) > 1e-14) { + grad = vec2(wdx * p.dqy.y - wdy * p.dqx.y, wdy * p.dqx.x - wdx * p.dqy.x) / jd; + } + if (wiped > 0.01) { + // Just wiped: fine streaks along the blade's sweep (the age gradient follows it) + // bend the view for a moment, without bringing the drops back. + var along = vec2(0.0, 1.0); + if (length(grad) > 0.01) { + along = normalize(grad); + } + let across = vec2(-along.y, along.x); + let streak = rain_patches(vec2(dot(p.q, across) * 600.0, dot(p.q, along) * 4.0)); + g.cover = wiped * (0.012 + 0.018 * streak.x); + g.veil = wiped * 0.06; + g.size_px = 4.0; + g.n = normalize(b.out + (p.side_w * across.x + p.down_w * across.y) * (streak.y - 0.5) * wiped * 0.003); + return g; + } + let heavy = smoothstep(0.55, 1.0, wet); + // (a drizzle leaves beads, a downpour full drops; on an upright side pane, which the rain + // meets edge on and the airstream sweeps, they stay smaller than on a raked windscreen) + let size = mix(0.85, 1.1, smoothstep(0.1, 0.8, wet)) * mix(0.8, 1.0, smoothstep(0.0, 0.4, abs(b.out.z))); + var acc: DropAcc; + acc.cover = 0.0; + acc.slope = vec2(0.0); + acc.rim = 0.0; + acc.size_px = 0.0; + acc.track = 0.0; + acc.avg = 0.0; + // the bank a blade pushed: its ridge bends the view + if (bank > 0.0) { + acc.cover = bank; + acc.slope = clamp(-0.00005 * grad, vec2(-0.15), vec2(0.15)) * bank; + acc.size_px = 8.0; + } + let w_main = select(select(1.0 - w_front, w_front, main_axis == 0), 1.0, roof); + glass_drops(&acc, b, p, w_main, wet, heavy, bank, size, world, t); + var side_w = p.side_w; + var down_w = p.down_w; + if (w_main < 0.99) { + let p2 = pane_proj(b, 1 - main_axis); + glass_drops(&acc, b, p2, 1.0 - w_main, wet, heavy, bank, size, world, t); + } + // --- the mist: droplets of a millimetre and less, too many to draw one by one far off + var grain = 0.0; + { + let mg = rain_turn(p.q, 0.33) / 0.0024; + let mc = floor(mg); + let mh = rain_hash(mc + 71.0); + let mr = 0.1 + 0.16 * mh.y; + let at = mc + vec2(mr) + rain_hash(mc + 5.3) * (1.0 - 2.0 * mr); + grain = step(mh.x, wet * 0.3) * (1.0 - smoothstep(mr * 0.6, mr, length(mg - at))); + } + // (seen from further than a millimetre a pixel: their average) + let mist = mix(wet * 0.3 * 0.12, grain, smoothstep(0.0015, 0.0006, b.px)); + g.mist = clamp((mist + 0.6 * acc.avg) * (1.0 - acc.track), 0.0, 1.0); + // The connected water between the drops scatters some of the view into a soft haze + // (the veil, drawn from the picture's blurred levels), the same on every pane as wet. + // A runner's fresh track is a clear sheet of water, sharper than the rest. + let film = smoothstep(0.03, 0.4, wet) * (1.0 - 0.3 * acc.track); + // (by the air's temperature, `camera.lod.w`: on cold glass the water spreads into a film + // and a fine mist of droplets that scatter the view - near freezing the sleet's slush on + // top - while in a warm summer rain it beads up and runs off, the glass between the drops + // nearly clear) + let cold = 1.0 - smoothstep(2.0, 24.0, camera.lod.w); + // (light: a strong veil hid the drops behind a uniform fog) + g.veil = film * mix(0.12, 0.25, heavy) * mix(0.7, 1.2, cold); + g.cover = acc.cover; + g.rim = acc.rim; + g.size_px = acc.size_px; + let slope = acc.slope; + let nz = sqrt(max(1.0 - dot(slope, slope), 0.02)); + g.n = normalize(b.out * nz + side_w * slope.x + down_w * slope.y); + return g; +} + +// The picture behind the glass (`glass_mips.rs`, pre-exposed radiance) at `uv`, blurred to +// level `lod`: five reads round the point a texel of that level apart, so the small levels' +// texels do not show as blocks when they are spread over many pixels. +fn glass_blur(uv: vec2, lod: f32) -> vec3 { + let dims = vec2(textureDimensions(mx_tex2d[mx_mat.env])); + let o = exp2(lod) * 0.75 / dims; + let c = clamp(uv, vec2(0.001), vec2(0.999)); + var s = textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], c, lod).rgb * 2.0; + s = s + textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], clamp(c + vec2(o.x, o.y * 0.5), vec2(0.001), vec2(0.999)), lod).rgb; + s = s + textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], clamp(c + vec2(-o.x * 0.5, o.y), vec2(0.001), vec2(0.999)), lod).rgb; + s = s + textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], clamp(c + vec2(-o.x, -o.y * 0.5), vec2(0.001), vec2(0.999)), lod).rgb; + s = s + textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], clamp(c + vec2(o.x * 0.5, -o.y), vec2(0.001), vec2(0.999)), lod).rgb; + return s / 6.0; +} + +// The snow a wiped pane holds while it snows (see enhanced/07_glass.wgsl `glass_snow`): +// `defrost` how far the windscreen's defroster has cleared it (0..0.85), `fz` the height on +// the glass in the bus's frame (-1 its bottom, 1 its top), for the drift along the bottom. +fn glass_snow_with(in: FsIn, cover: f32, defrost: f32, fz: f32) -> vec4 { + if (cover <= 0.0) { + return vec4(1.0, 1.0, 1.0, 0.0); + } + // (laid out on the glass as the drops are, `pane_proj`: the film's own coordinates + // drew the crystals and the drifts out long on the windscreen) + let b = pane_base(in.world, in.local, in.normal, false); + let an = abs(b.nl); + let axis = select(select(1, 0, an.y >= an.x), 2, an.z > max(an.x, an.y) * 2.0); + let m = pane_proj(b, axis).q; + let t = camera.post.y; + let front = material.wipe_bounds.z > 0.0; + let heat = select(0.15, 0.45 + 0.55 * clamp(defrost / 0.85, 0.0, 1.0), front); + var flakes = 0.0; + var melt_water = 0.0; + for (var layer = 0; layer < 2; layer = layer + 1) { + let fl = f32(layer); + let cell = select(0.012, 0.022, layer == 1); + let p = m / cell + fl * 37.0; + let c = floor(p); + let tm = rain_hash(c + vec2(5.0, 1.0 + fl)); + let life = mix(40.0, 7.0, heat) * (0.6 + 0.8 * tm.y); + let cycle = t / life + tm.x; + let ph = fract(cycle); + let arrival = c + floor(cycle) * vec2(19.0, 47.0); + let h = rain_hash(arrival); + let h2 = rain_hash(arrival + vec2(91.0, 13.0)); + // (a crystal shows once the cover passes its own threshold: they come one by one) + let shown = clamp((cover * select(1.15, 0.85, layer == 1) - h2.y) * 12.0, 0.0, 1.0) * smoothstep(0.0, 0.02, ph); + // the second half of its while it melts: it rounds off, shrinks and goes clear + let melt = smoothstep(0.45, 0.95, ph); + let d = p - (c + 0.25 + 0.5 * h); + let dl = length(d); + let r = (0.16 + 0.2 * h2.x) * (1.0 - 0.5 * melt); + // six arms, the rim reaching out along them + let arm = pow(abs(cos(3.0 * atan2(d.y, d.x) + h.x * 6.283185)), 4.0); + let rr = r * (0.55 + 0.45 * mix(arm, 1.0, melt)); + let edge = 1.0 - smoothstep(rr * 0.7, rr, dl); + flakes = max(flakes, shown * edge * (0.6 + 0.4 * h.x) * (1.0 - melt)); + melt_water = max(melt_water, shown * edge * melt * (1.0 - smoothstep(0.92, 1.0, ph))); + } + // settled snow is never even: a smooth noise of a few centimetres and a finer one break + // up where the layer closes and give the bank and the drifts their ragged edges + let lumps = snow_noise(m / 0.045) * 0.65 + snow_noise(m / 0.012 + 7.0) * 0.35; + var drift = 0.0; + if (front) { + // (by the height in the bus's own frame, not by the wiper mask's `wipe_uv`: a + // windscreen's film is several slots - each wiper's field and the glass round them - + // each with its own mask and its own 0 .. 1, and a bank laid along their edges drew + // seams down the middle of the windscreen and round the wipers' arcs) + if (camera.inside_c.w > 0.5) { + let low = 1.0 - (fz * 0.5 + 0.5); + drift = smoothstep(0.5, 0.75, low + 0.12 * (lumps - 0.5)) * smoothstep(0.1, 0.6, cover); + } + } + let c = cover * (0.7 + 0.6 * lumps) * (1.0 - 0.3 * heat) + drift * 0.9; + let sheet = smoothstep(0.5, 1.2, c) * 0.75 + smoothstep(1.0, 1.7, c) * 0.22; + let white = mix(vec3(0.9, 0.92, 0.96), vec3(0.97, 0.98, 1.0), smoothstep(1.0, 1.8, c)); + let solid = max(flakes * 0.92, sheet); + // (the melt water: a faint clear bead, the street a shade darker through it) + let wet = melt_water * 0.16 * (1.0 - solid); + let alpha = clamp(solid + wet, 0.0, 0.97); + let col = (white * solid + vec3(0.5, 0.55, 0.6) * wet) / max(solid + wet, 1e-4); + return vec4(col, alpha); +} + +// The rain on a pane that has no film of its own to carry it (`glass_film`): the windows of +// the traffic's cars and buses, seen from the street. OMSI gives only some buses a rain film, +// and only the player's own wets it, so every other window stayed dry and clear in a downpour. +// The same drops and runners (`glass_water`), as wet as the roads (`camera.shadow.w`); none +// on the player's own bus, whose films carry its rain. +fn pane_rain(world: vec3, local: vec3, n: vec3) -> GlassWater { + let wet = clamp(camera.shadow.w * 1.3, 0.0, 1.0); + let own = near_player_vehicle(world) > 0.5; + let far = distance(world, camera.cam_pos.xyz) > 80.0; + let w = select(wet, 0.0, own || far); + return glass_water(world, local, n, w, camera.post.y, false); +} + +// The pane's colour `rgb` and cover `a` under that rain (`vn` towards the eye): the drops, +// small lenses darker than the glass round them with the sky mirrored on their domes +// (`refl`, what the dome mirrors), and between them the wet film, a little milky +// (`haze`, the daylight it scatters) and less see-through. +fn pane_rain_compose(g: GlassWater, rgb: vec3, a: f32, vn: vec3, refl: vec3, haze: vec3) -> vec4 { + let cosv = clamp(abs(dot(g.n, vn)), 0.0, 1.0); + let f = 0.02 + 0.98 * pow(1.0 - cosv, 5.0); + let drop = mix(rgb * 0.7, refl, clamp(f * 3.0, 0.15, 0.8)); + var c = mix(rgb, drop, g.cover * 0.85); + let film = clamp(g.veil * 0.35 + g.mist * 0.2, 0.0, 0.5); + c = mix(c, haze, film); + let a2 = clamp(a + (1.0 - a) * (g.cover * 0.5 + film), a, 1.0); + return vec4(c, a2); +} + +@fragment +fn fs_main(in: FsIn) -> @location(0) vec4 { + var unused = 0.0; + return shade_vanilla(in, &unused, camera.cam_pos.xyz); +} + +// Shared with Enhanced and the wheel splash mask: pools spread as the road soaks. +fn road_puddle_coverage(world: vec3, normal: vec3, wet: f32) -> f32 { + let xy = world_pattern_xy(world); + let pn = vnoise_f(xy, 0.35, vec2(17.3, -9.1)) * 0.6 + + vnoise_f(xy, 1.6, vec2(-4.0, 8.0)) * 0.3 + + vnoise_f(xy, 5.0, vec2(2.7, 11.3)) * 0.1; + // The pools spread from the lowest spots as the road soaks, but they stay pools: a road + // wet through has standing water on about a fifth of it (PUDDLE_SPREAD in enhanced.wgsl, + // the same in `omsi-app/src/puddles.rs`) and wet asphalt between. + let threshold = 1.0 - wet * PUDDLE_SPREAD; + return smoothstep(threshold - 0.02, threshold + 0.02, pn) * smoothstep(0.75, 0.95, normal.z); +} + +@fragment +fn fs_vanilla_reflections(in: FsIn) -> EnhancedOut { + var weight = 0.0; + let c = shade_vanilla(in, &weight, camera.cam_pos.xyz); + let coverage = select(c.a, 0.0, in.params2.w > 1.5); + var out: EnhancedOut; + out.color = c; + out.mask = vec4(0.0, weight * 0.49, weight, coverage); + return out; +} + +fn shade_vanilla(in: FsIn, puddle_weight: ptr, eye: vec3) -> vec4 { + // (the pane's water, read once for the uses below) + let film_water = window_wetness(in); + if (material.emissive.w > 1.5) { + // a pane's film of water: drops, not the sliding texture (`glass_film_classic`) + return glass_film_classic(in, film_water); + } + var duv = tex_address(in.uv); + if (material.extra.x > 0.5) { + // terrain: uv is tile space; the ground texture repeats extra.z times per tile + duv = in.uv * material.extra.z; + } + var tex = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv); + if (is_snow_pane()) { + // (as the enhanced picture lays it, `glass_snow_with`: no cabin air here, so no + // defroster, and the height on the glass by the bus's level frame) + let fz = clamp((in.world.z - camera.inside_a.z - camera.inside_c.z) / max(camera.inside_b.w, 0.1), -1.0, 1.0); + tex = glass_snow_with(in, film_water, 0.0, fz); + } + // The texture coordinates without the [texcoordtransX/Y] offset: in Omsi.exe's + // fixed-function pipeline the texture transform is the diffuse stage's alone, the + // transmap, night map and light map stay in place under a scrolling roller blind. + let buv = tex_address(in.uv - in.params.zw); + if (material.extra.x > 0.5 && material.extra.y > 0.0) { + // the ground texture's detail texture, repeated finer than the texture itself and + // modulated over it as the original's terrain pass does. The stock detail maps are + // bright (noise_low averages 242, gras_det 179), so they are meant to be multiplied + // in plainly: doubling like a grey-centred D3D detail map blows the ground out. + let det = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], in.uv * material.extra.y, camera.lod.x); + tex = vec4(clamp(tex.rgb * det.rgb, vec3(0.0), vec3(1.0)), tex.a); + } + if (material.params.z > 0.5) { + // [matl_transmap]: alpha comes from a separate map, its alpha channel (a map without one + // is opaque, as D3D samples it: the WH UK AI cars' paint layer has a black 24-bit + // `transmap_null.tga`, read as luminance the paint was invisible); + // for terrain the map is the per-tile surface mask in tile space + let tm = sample_transmap(buv); + tex.a = select(1.0, tm.a, material.params.w > 0.5); + if (material.extra.x > 0.5 && material.params.x > 1.5) { + // A painted ground layer. The brush mask is coarse (0.6-3 m per texel) and + // binary; the loader smooths it into a soft ramp around a smooth curve + // (`smooth_paint_mask` in scene.rs). Sharpen only that coverage ramp: + // diffuse/detail mip colours change with viewing angle, and including + // their luminance made covered ground fade into lower layers at a slant. + tex.a = smoothstep(0.32, 0.68, tex.a); + } + } + // One night-map read supplies both coverage and lighting. Keep the tile map + // in its north-up UVs; vehicle maps use the unscrolled material UVs. + var night_sample = vec4(0.0); + if (material.extra.w > 0.5) { + let nuv = select(buv, vec2(in.uv.x, 1.0 - in.uv.y), material.extra.x > 0.5); + night_sample = sample_nightmap(nuv); + } + tex.a = night_coverage(tex.a, night_sample.a) * tree_card_fade(in.world); + let mode = material.params.x; + // Mip-filtered alpha is the fraction of the pixel covered by leaves or fence wires. + // Tighten the transition around the cutout edge before MSAA turns it into sample + // coverage. The depth prepass leaves these draws out so its binary cutoff cannot hide + // the scene behind samples that the colour pass leaves open. + if (ALPHA_TEST && mode > 0.5 && mode < 1.5) { + if (ALPHA_TO_COVERAGE) { + let aa = max(fwidth(tex.a) * 0.5, 1.0 / 255.0); + // (not `ALPHA_REF - aa`: a layer whose clear glass is alpha 128 kept a third of + // its samples there, a moire of the layer's paint over every window) + if (tex.a < ALPHA_REF) { + discard; + } + tex.a = smoothstep(ALPHA_REF - aa, ALPHA_REF + aa, tex.a); + } else if (tex.a < ALPHA_REF) { + discard; + } + } + // (a blended slot that keeps Omsi.exe's alpha test, `MaterialExtra::alpha_cut`: a + // livery's clear glass is cut away, its tinted glass blended) + tex.a = select(tex.a, 0.0, mode > 2.5 && tex.a < ALPHA_REF); + let n = safe_normal(in.normal); + let ndl = max(dot(n, camera.sun_dir.xyz), 0.0); + // three lights like the original: direct sun (A), light from above (B), ambient (C) + let from_above = 0.5 + 0.5 * n.z; + let shadow = sun_shadow(in.world, n, mode > 0.5 && mode < 1.5); + // screen-space ambient occlusion darkens the indirect light (sky and ambient) in + // corners, under the bus, between the seats - not the sun, which the shadow map handles + var ao = 1.0; + // (not on a blended surface: the AO is the opaque depth's, and a translucent door + // showed the shade of what stood behind it) + if (camera.clouds.w > 0.5 && mode < 1.5) { + ao = ao_at(in.clip.xy, in.world); + } + var diffuse = camera.sun_color.rgb * camera.sun_dir.w * ndl * shadow + (camera.sky_color.rgb * from_above * (0.6 + 0.4 * shadow) + camera.ambient.xyz) * ao; + var albedo = tex.rgb; + if (camera.flags.x > 0.5 && (material.extra.x > 0.5 || in.params2.w > 0.5)) { + // detail texturing (setting): procedural grain on the ground and the roads, fading out with distance + let dist0 = distance(in.world, camera.cam_pos.xyz); + let k = clamp(1.0 - (dist0 - 25.0) / 120.0, 0.0, 1.0); + let nz = detail_noise(world_pattern_xy(in.world), k); + albedo = albedo * (1.0 + (nz - 0.5) * 0.42 * k); + } + // ([nomaplighting]: params.y 0.25 - not lit by the map's lamps) + // (a light-mapped road or plate takes the map's lamps only in Vanilla+: as OMSI 2 shows + // it, the vanilla picture lights it from the tile light map alone) + let lm_only = light_map_mapped(material.params) && camera.sky_color.w > 0.5; + // (and a [tree]'s leaf cards, params.y 0.15: OMSI 2 leaves a tree dark even right under + // a street lamp, where the lamp's 40 m core lit the crown up yellow-green) + let tree_unlamped = camera.sky_color.w > 0.5 && material.params.y > 0.1 && material.params.y < 0.2; + let map_lamps = select(1.0, 0.0, (material.params.y > 0.2 && material.params.y < 0.3) || lm_only || tree_unlamped); + let lamp_light = point_lights(in.world, n, map_lamps); + // The headlight is lit at the vertices: see `classic_spot`. + var light = diffuse + lamp_light + in.spot_diffuse + in.spot_ambient; + // D3D lights the material's diffuse colour with the sun, the light from above and the + // lamps, and its ambient colour with the ambient light (C) and the headlight's ambient + // light. Omsi.exe makes every o3d slot's ambient white (0x7c62f8), so a white sign + // texture on a green material shows white in the shade, not green. + let ambient_light = camera.ambient.xyz * ao + in.spot_ambient; + let mat_light = material.color.rgb * (light - ambient_light) + material.ambient.rgb * ambient_light; + let light_mapped = material.params2.x > 0.5 && material.extra.x < 0.5; + // The low-range Vanilla+ target has no exposure/tonemapping. Saturate the + // diffuse light before modulating the texture, as the classic path does: + // overlapping lamps must not clip a coloured texture into a white patch. + // The light is OMSI's - the envir.cfg's sun, sky and ambient and its lamps - and those + // numbers are what Direct3D multiplies into the gamma-encoded texture: it is laid on the + // encoded texture here too, as in the classic picture below. Multiplied in linear light, + // a light L showed as L^(1/2.2): the night's 0.06 as 0.28, every night, dusk and shade + // in Vanilla+ several times as bright as in OMSI 2 (#300, #1612). + var lit = srgb_decode(srgb_encode(albedo) * clamp(mat_light, vec3(0.0), vec3(1.0))); + // The vanilla picture: Omsi.exe's texture stages multiply the gamma-encoded texture by + // the vertex light (clamped at 1); here the texture is sampled linear and the target + // encodes again, so multiplied here a light L showed as L^(1/2.2) - a night at 0.06 + // looked like 0.28, a late dusk (#300). So the product is made on the encoded texture + // and decoded again, with the light map laid on encoded as well. (Through the sRGB curve + // itself: taken as a power of 2.2, t v^2.2, the curve's linear foot below 0.0031 put a + // night wall at a quarter of OMSI 2's - a texture of 0.66 under a light of 0.05 came out + // at 2 of 255 instead of 8.) + let classic = camera.sky_color.w > 0.5; + // (the terrain's night map is its tile light map: light, not a glow - see below) + let terrain_map = material.params.y < 0.5 + && material.extra.x > 0.5 + && material.extra.w > 0.5 + && material.extra.w < 1.5; + let terrain_night = classic && terrain_map; + if (classic && material.params.y < 0.5) { + var v = clamp(material.emissive.rgb + mat_light + material.color.rgb * interior_lamps(in.world, n, in.params2.z), vec3(0.0), vec3(1.0)); + if (light_mapped) { + let lm = srgb_encode(textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], buv, camera.lod.x).rgb) * clamp(in.params2.x, 0.0, 1.0); + v = v + lm * (vec3(1.0) - v); + } + if (terrain_night) { + // the terrain's tile light map lights the ground as the lamps' own light: added + // to the vertex light before the texture is multiplied in. Laid over the lit + // ground instead, as a night map glows, its faint fringe (0.01, linear) put + // one beige veil over cobbles and grass alike, a whole car park the colour of + // sand where OMSI 2 shows it dark grey. + let nm = srgb_encode(night_sample.rgb); + v = min(v + nm * camera.sun_color.w * clamp(in.params2.y, 0.0, 1.0), vec3(1.0)); + } + if (lm_only) { + // a road, a plate or a [LightMapMapping] object: the same tile light map, the + // same way as the ground beside it (Omsi.exe lights both from it alone - its + // `[maplight]`s only bake the map, 0x7903e0). Added after the texture in linear + // light instead, the pools that lay bright on the verges hardly showed on the + // asphalt between them: the street lamps lit everything but the road (#847). + let lm = srgb_encode(light_map_at(in.world)); + v = min(v + lm * camera.sun_color.w, vec3(1.0)); + } + lit = srgb_decode(srgb_encode(albedo) * v); + } else if (light_mapped) { + // [matl_lightmap], as Omsi.exe's texture stages have it (0x7fe4d3..0x7fe604): the + // light map is laid onto the vertex light with D3DTOP_ADDSMOOTH (light + map x (1 - + // light)) before the texture is multiplied in - a lit saloon glows at night and + // hardly shows in daylight. The vertex light is D3D's: the material's emissive and + // its colour times every light - the saloon lamps (`[interiorlight]`, D3D lights + // too, 0x5fa8f0) among them - clamped at 1. (Added once more after the map, the + // saloon lamps lit a cabin twice over, flat white where the map was full; and the + // material's colour took the map down with it.) + let lm = srgb_encode(textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], buv, camera.lod.x).rgb) * clamp(in.params2.x, 0.0, 1.0); + let v = clamp(material.emissive.rgb + mat_light + material.color.rgb * interior_lamps(in.world, n, in.params2.z), vec3(0.0), vec3(1.0)); + lit = srgb_decode(srgb_encode(albedo) * (v + lm * (vec3(1.0) - v))); + } + // the D3D material's own highlight (specular colour and power of the o3d file or a + // [matl_allcolor]), lit at the vertices (see `vertex_specular`) and added after the + // texture as D3D's specular is; the sun's not in its shadow + let specular = in.spec_sun * shadow + in.spec_sky; + if (classic) { + // D3D adds its vertex specular after the encoded texture stages. Adding + // it in linear light encoded it again at the target and washed out dusk. + lit = srgb_decode(min(srgb_encode(lit) + specular, vec3(1.0))); + } else { + lit = lit + specular; + } + if (material.params.y > 0.5) { + lit = tex.rgb * material.color.rgb; + } + if ((!light_mapped && !classic) || material.params.y > 0.5) { + lit = lit + tex.rgb * material.emissive.rgb; + } + // [interiorlight]: the saloon lamps on the meshes and passengers they illuminate (in + // a light-mapped material's vertex light already, above) + if (!light_mapped && !classic) { + lit = lit + tex.rgb * interior_lamps(in.world, n, in.params2.z); + } + // (Vanilla+: the map's lamps light the ground, as they light the roads) + if (material.extra.w > 0.5 && !terrain_map) { + // [matl_nightmap]: self-illumination that fades in with the night + // terrain: the tile light map in tile space (north at the top row) + // a [matl_item] night map is switched by its variable (warning lamps, displays): + // it glows whenever that is on, by day as well; the others fade in with the night + let night = select(rain_lit_windows(in.local), 1.0, material.extra.w > 1.5); + lit = lit + night_sample.rgb * night * select(clamp(in.params2.y, 0.0, 1.0), 1.0, material.extra.w > 1.5); + } + if (material.params2.y > 0.0) { + // [matl_envmap]: sphere map reflection, masked by the diffuse alpha like the original + let vdir = normalize(in.world - eye); + var env_uv = in.env_uv; + if (material.bump.y > 0.5) { + env_uv = env_uv + bump_offset(duv); + } + let env = textureSample(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], env_uv); + let diffuse_a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv).a; + if (material.params.x < 1.5) { + // rain: a painted body goes darker and glossier when it is wet, so the bus + // stands out against a grey street instead of fading into it + let env_night = select(1.0 - 0.85 * clamp(camera.sun_color.w, 0.0, 1.0), 1.0, camera.sky_color.w > 0.5); + let env_light = clamp(camera.sun_color.r * camera.sun_dir.w + camera.sky_color.r + camera.ambient.r, 0.05, 1.0) * env_night; + let wet = camera.shadow.w * weather_outside_n(in.world, n, false, in.params2.w); + lit = lit * (1.0 - 0.30 * wet); + // the water film mirrors the (overcast) sky a little, mostly at grazing + // angles; kept faint - a strong rim read as a white outline round the bus + let facing = clamp(abs(dot(vdir, n)), 0.0, 1.0); + let sheen = wet * min(material.params2.y, 1.0) * (0.05 + 0.22 * pow(1.0 - facing, 5.0)); + lit = mix(lit, camera.sky_color.rgb * env_light, sheen); + } + // Omsi.exe's environment stage (0x7fd6c4 at 0x7ff626, fixed function), for paint + // and glass alike: the sphere map's colour as it is, over what the stages before + // made of the lit texture - D3DTOP_LERP by the texture factor when the material has + // neither a [matl_transmap] nor a [matl_envmap_mask], D3DTOP_BLENDCURRENTALPHA when + // it has one - and the alpha left as the stages before made it (ALPHAARG1 CURRENT, + // SELECTARG1, 0x7ff98a): a clear pane shows its reflection as faintly as it shows + // itself. (A glass path of our own - a quarter reflection at least, a Fresnel rim + // and the pane made opaque where it reflected - mirrored the street in every + // window far more than the original does.) The factor is [matl_envmap]'s times + // the ambient light plus `g` (the light the vehicle stands in: the lamps of the + // tile's light map and the sky), each at most 1, packed into a D3DCOLOR without + // saturation (0x7ff8ed: a factor over 1 spills its bits into the next channel, as + // there). The alpha it blends by is the mask's, or the diffuse texture's times `g` + // (0x7feacc, 0x7ff092) - never the diffuse alpha of a material without one of + // them: taken as a reflection mask, a body whose texture carries an alpha channel + // for other purposes was mirrored (dark) where that alpha was high. + // `g` (0x861ca0, set per vehicle at 0x7d8735): the mean of the light the tile's + // light map throws on it plus the day's light A (weather +0xac = the mean of + // lightcolor A, 0x75333f - by it the stars fade), at most 1 + let g = clamp(dot(lamp_light, vec3(1.0 / 3.0)) + dot(camera.sun_color.rgb, vec3(1.0 / 3.0)), 0.0, 1.0); + var kk = vec3(0.0); + if (has_transmap_declared() || has_env_mask()) { + let a = select(diffuse_a, textureSampleBias(mx_tex2d[mx_mat.envmask], mx_samplers[mx_mat.sampler], duv, camera.lod.x).a, has_env_mask()); + kk = vec3(a * g); + } else { + kk = omsi_texture_factor(material.params2.y, camera.ambient.rgb + vec3(g)); + } + // The lerp is made on the encoded values, as the stage makes it, like the texture x + // light product above: made on linear ones it showed the reflection about twice as + // bright over a dark surface - since the nights got dark (#300) the instrument glass + // of the MAN NL/NG (Fenster.tga, factor 0.5, the sky at the sphere map's bottom) lay + // milky white over the unlit gauges. (Vanilla+ as well: its linear lerp laid the + // sphere map as a grey sheen over every dark window band and chassis, #780.) + // The sphere map's colour as it is, as the stage takes it: the night already weakens + // the reflection through the factor (`kk`, the ambient light and `g`). Darkened once + // more by that light, as a photograph lit by the night, the reflection went twice + // and the paint and the windows lost their shine at dusk and by night, which they + // keep in OMSI (#2284). + lit = srgb_decode(mix(srgb_encode(lit), srgb_encode(env.rgb), kk * camera.cam_pos.w)); + } + // wet road: a surface whose texture carries [moisture] darkens under rain and starts + // to mirror the sky, strongest where you look along it (the Fresnel sheen that makes a + // wet street read as wet) + let outside = weather_outside_n(in.world, n, material.extra.x > 0.5, in.params2.w); + let wet = camera.shadow.w * material.params2.z * outside * (1.0 - clamp(camera.ambient.w, 0.0, 1.0)); + if (wet > 0.0) { + let vdir = normalize(in.world - eye); + let facing = clamp(-dot(vdir, n), 0.0, 1.0); + let fresnel = pow(1.0 - facing, 4.0); + let puddle = road_puddle_coverage(in.world, n, wet); + let water = 0.02 + 0.98 * pow(1.0 - facing, 5.0); + let weight = clamp(mix(fresnel * wet * 0.85, water * wet, puddle), 0.0, 0.9); + let sheen = camera.sky_color.rgb * 0.5 + camera.sun_color.rgb * camera.sun_dir.w * 0.35; + if (classic) { + // Vanilla blends encoded weather colours, but asphalt darkening + // must stay in linear light to avoid turning the road black. + lit = srgb_decode(mix(srgb_encode(lit * mix(1.0, 0.75, wet)), sheen, weight)); + } else { + lit = mix(lit * mix(1.0, 0.55, wet), sheen, weight); + } + *puddle_weight = weight * puddle; + } + // snow: the ground, the roads and every upward-facing surface whiten under it + // (not on a shadow blob: whitened, it lit the snow under the bus instead of shading it) + // (not in vanilla: OMSI 2 shows snow only through the season's WinterSnow textures) + // (nor on a texture that is the season's snow picture: the map's own WinterSnow + // textures show the snow as OMSI 2 does, and whitened over, the snowy grass and the + // grey road went one flat white, the lane markings left standing in it, #879) + let snow_ok = outside * select(1.0, 0.0, in.params2.w > 1.5 || camera.sky_color.w > 0.5 || material.ambient.w > 0.5); + // a carriageway (a [moisture] texture that is not the terrain) under snow that builds + // up: its own cover, the ruts of the lanes and the tyres' tracks (road_snow.wgsl) + let carriageway = material.extra.x < 0.5 && material.params2.z > 0.0 && road_snow_dynamic(); + var rs = vec3(0.0); + if (carriageway && snow_ok > 0.0) { + rs = road_snow(in.world); + } + // a vehicle's part: the snow its own roof has gathered, where that is kept (another + // player's bus keeps the weather's) + let vehicle = vehicle_snow_kept(in.params2.w); + var on_vehicle = 0.0; + if (vehicle && snow_ok > 0.0) { + on_vehicle = vehicle_snow(in.params2.w, in.local); + } + let snow = select(select(camera.ambient.w, rs.x, carriageway), on_vehicle, vehicle) * snow_ok; + if (snow > 0.0 || rs.y > 0.0) { + let up = clamp(n.z, 0.0, 1.0); + let ground = select(0.0, 1.0, material.extra.x > 0.5 || material.params2.z > 0.0); + // (a road kept clear - "snow on road" off - stays asphalt, #1362; built-up snow + // brings its own cover) + let cleared = select(1.0, 0.0, !carriageway && camera.post.z > 0.5 && material.extra.x < 0.5 && material.params2.z > 0.0); + // only surfaces that really face up get a cover; a soft threshold keeps the snow + // off the sides and off the grazing rims that showed as a white outline + let cover = cleared * snow * clamp(max(ground, smoothstep(0.78, 0.95, up) * 0.8), 0.0, 1.0); + let light = camera.sun_color.rgb * camera.sun_dir.w * ndl * shadow * 0.6 + camera.sky_color.rgb * 0.7 + camera.ambient.xyz; + let white = vec3(0.92, 0.94, 0.98) * light * ao; + // (a vehicle's gathered snow lies thick enough to hide the paint: the ground's + // dusting lets the texture show through) + lit = mix(lit, white, min(cover * select(0.55 + 0.35 * tex.a, 1.2, vehicle), 1.0)); + // the slush in the ruts and the tracks: wet, grey, darker than the snow beside it + lit = mix(lit, lit * 0.6 + white * 0.12, rs.y * snow_ok); + } + let dist = distance(in.world, camera.cam_pos.xyz); + let f = 1.0 - exp(-fog_distance(in.world) * camera.fog.w); + *puddle_weight *= 1.0 - clamp(f, 0.0, 1.0); + var rgb = mix(lit, camera.fog.xyz, clamp(f, 0.0, 1.0)); + if (classic) { + // D3D's fixed-function fog blends the encoded vertex fog colour too. + // Treating that colour as linear raised a mid-grey fog from 128 to 188. + rgb = srgb_decode(mix(srgb_encode(lit), camera.fog.xyz, clamp(f, 0.0, 1.0))); + } + if (camera.flags.z > 0.0) { + // Never taken: flags.z (the old enhanced look's aerial perspective) is always 0 + // now - the enhanced path has its own fragment shader (enhanced.wgsl). The branch + // stays because Metal's fast-math contracts the fog mix above differently without + // it, and the vanilla picture is to stay what it was to the last code value. + let vdir = normalize(in.world - camera.cam_pos.xyz); + let towards_sun = clamp(dot(vdir, camera.sun_dir.xyz), 0.0, 1.0); + let k = (1.0 - exp(-dist * 0.00045)) * camera.flags.z * (0.55 + 0.45 * clamp(camera.sun_dir.w, 0.0, 1.0)); + let scatter = mix(camera.sky_color.rgb * 1.4 + camera.ambient.rgb * 0.5, camera.sun_color.rgb * camera.sun_dir.w + camera.sky_color.rgb, towards_sun * towards_sun); + rgb = mix(rgb, scatter, clamp(k * 0.6, 0.0, 0.5)); + } + // (a NaN anywhere above - a zero-length vector normalised, 0 x infinity - was a black + // patch on Windows, e.g. an EN92's headlights while off, and invisible on the Mac) + rgb = finite_or(rgb, finite_or(albedo * material.color.rgb * diffuse, albedo)); + var a = tex.a * material.color.a; + if (mode < 0.5) { + a = 1.0; + } + if (!is_snow_pane()) { + a = a * clamp(film_water, 0.0, 1.0); + } + if (mode > 1.5 && min(material.emissive.r, min(material.emissive.g, material.emissive.b)) > 0.99 && material.emissive.w < 1.5) { + a = encoded_blend_alpha(rgb, a, light); + } + if (material.emissive.w > 0.5 && material.emissive.w < 1.5) { + // a pane in the rain without a film of its own (`pane_rain`): the traffic's windows + let g = pane_rain(in.world, in.local, in.normal); + if (g.cover > 0.001 || g.veil > 0.001 || g.mist > 0.001) { + let vn = normalize(camera.cam_pos.xyz - in.world); + let o = pane_rain_compose(g, rgb, a, vn, rain_env_vanilla(reflect(-vn, g.n)), rain_env_vanilla(vec3(0.0, 0.0, 0.5)) * 0.9); + rgb = o.rgb; + a = o.a; + } + } + return vec4(rgb, a); +} + +// What lies under a self-lit layer, for `encoded_blend_alpha`: a surface of this encoded +// brightness lit by the light at the layer (the road's asphalt under the KVB Citaro's +// light cone is 0.44 - 0.49 encoded). +const BLEND_GROUND_ENCODED: f32 = 0.45; + +// A self-lit blended layer (emissive white: a light cone laid on the road, a glow) as +// Omsi.exe blends it: Direct3D 9 mixes the gamma-encoded colours, the sRGB target here mixes +// linear ones, and a faint layer came out far brighter - the KVB Citaro's `lichtkegel.o3d` +// (alpha 0.14 on average) a flat beige sheet over the road where OMSI 2 shows a soft pool, +// 120 of 255 against its 85. The target cannot be read, so what is under the layer is taken +// to be ground lit by the light here (`light`, the vertex light the layer would have): +// the alpha is the one that gives Omsi.exe's encoded mix over it, never more than the +// layer's own. +fn encoded_blend_alpha(rgb: vec3, a: f32, light: vec3) -> f32 { + let w = vec3(0.2126, 0.7152, 0.0722); + let s = max(rgb, vec3(0.0)); + if (a <= 0.0) { + return a; + } + let d_enc = clamp(light, vec3(0.0), vec3(1.0)) * BLEND_GROUND_ENCODED; + let d = dot(srgb_decode(d_enc), w); + let over = dot(srgb_decode(srgb_encode(s) * a + d_enc * (1.0 - a)), w); + let span = dot(s, w) - d; + if (span < 1e-4) { + return a; + } + return clamp((over - d) / span, 0.0, a); +} + +// The rain film on a pane in the classic pictures: the drops, the runners and the blur of the +// wet glass as the enhanced picture draws them (`glass_water`, enhanced/07_glass.wgsl +// `glass_film`), lit by the classic picture's own sky (`rain_env_vanilla`). Without the +// cabin's air there is no condensation behind them. +fn glass_film_classic(in: FsIn, water: f32) -> vec4 { + let v = camera.cam_pos.xyz - in.world; + let dist = length(v); + let vn = v / max(dist, 1e-4); + let in_cab = inside_vehicle(camera.cam_pos.xyz) * near_player_vehicle(in.world) > 0.5; + let g = glass_water(in.world, in.local, in.normal, water, camera.post.y, in_cab); + if (g.cover <= 0.001 && g.mist <= 0.001 && g.veil <= 0.001) { + return vec4(0.0); + } + let has_picture = camera.flags.z < -0.5; + let dims = vec2(textureDimensions(mx_tex2d[mx_mat.env])); + let uv0 = in.clip.xy / dims; + let mist_col = rain_env_vanilla(vec3(0.0, 0.0, 0.5)) * 0.9; + // the view through the wet glass between the drops, softened by the film of water + let veil_lod = log2(max(dims.y * mix(0.002, 0.006, clamp(g.veil / 0.3, 0.0, 1.0)), 1.0)); + var behind = mist_col; + if (has_picture) { + behind = finite_or(glass_blur(uv0, veil_lod), mist_col); + } + // a drop: a small lens, the street small and upside down in it, darker at its rim + var drop_col = behind; + var a_drop = 0.0; + if (g.cover > 0.001) { + // (bent by the dome, the way out of the drop is looked up where it meets the street a + // few metres on - not a fixed share of the screen aside, which from the driver's seat + // landed on the dark dashboard and the pillars and drew every drop as a black speck: + // the classic pictures keep no depth to tell those from the street) + let tilt = g.n - g.out * dot(g.n, g.out); + let thr = normalize(-vn - tilt * 0.9); + var seen = behind; + let cp = camera.view_proj * vec4(in.world + thr * 6.0, 1.0); + if (has_picture && cp.w > 0.05) { + let ndc = cp.xy / cp.w; + let uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + let inside = smoothstep(0.0, 0.06, min(min(uv.x, 1.0 - uv.x), min(uv.y, 1.0 - uv.y))); + let far = finite_or(glass_blur(clamp(uv, vec2(0.001), vec2(0.999)), 0.8 + 1.5 * g.mist), behind); + seen = mix(behind, far, inside); + } + let rim = smoothstep(0.55, 1.0, g.rim); + let facing = dot(g.out, vn) > 0.0; + let cosv = clamp(abs(dot(g.n, vn)), 0.0, 1.0); + let f = select(0.02, 0.02 + 0.98 * pow(1.0 - cosv, 5.0), facing); + var c = seen * (1.0 - 0.45 * rim) * (1.0 - f) + rain_env_vanilla(reflect(-vn, g.n)) * f; + if (facing) { + let r = reflect(-vn, g.n); + c = c + camera.sun_color.rgb * camera.sun_dir.w * pow(max(dot(r, camera.sun_dir.xyz), 0.0), 900.0) * f * 60.0; + } + let detail = smoothstep(0.5, 1.6, g.size_px); + drop_col = mix(behind * 0.93, c, detail); + a_drop = g.cover * mix(select(0.15, 0.5, has_picture), 0.95, detail) * (1.0 - smoothstep(5.0, 15.0, dist)); + } + let a_mist = g.mist * 0.5; + var a_veil = 0.0; + if (g.veil > 0.001 && has_picture) { + a_veil = g.veil * (1.0 - smoothstep(25.0, 60.0, dist)); + } + let a_under = a_veil + a_mist * (1.0 - a_veil); + let under = (behind * a_veil + mix(mist_col, behind, 0.9) * a_mist * (1.0 - a_veil)) / max(a_under, 1e-4); + let a = a_drop + a_under * (1.0 - a_drop); + if (a <= 1e-4) { + return vec4(0.0); + } + let col = (drop_col * a_drop + under * a_under * (1.0 - a_drop)) / a; + return vec4(min(col, vec3(1.5)), a); +} + +// Snow on the carriageways: how far it has built up, the ruts the traffic keeps in it and +// the fresh tracks the tyres press into it (see `Renderer::set_snow_track_rect`). +// +// The field is a square of `place.z` metres that wraps around the world (a torus): texel +// (i, j) holds the world's point (x, y) where floor(x / texel) and floor(y / texel) are i and +// j modulo its size, so the app only rewrites the tiles the camera moves into. It is kept +// tile after tile (`TRACK_TILE` texels a side), each row after row, a texel an RGBA8 word: +// r: the ruts of the lanes' wheel tracks (0..1) +// g: a tyre has pressed the snow here (how much of the texel it covered) +// b, a: how much snow had fallen when a tyre last ran here (16 bits, see `state.y`; for +// a rut no tyre has run in yet, a moment as long ago as its lane's traffic makes +// likely): the track and the rut fill as more falls + +struct SnowTrack { + // xy: the render origin modulo the field's side (m), z: the side (m), w: 1 while the + // field holds the area around the camera + place: vec4, + // x: how far the snow covers the roads (0..1; below 0 the weather's "snow on road" + // decides, as before), y: the snow fallen so far (thousandths of a full cover, modulo + // 65536), z: how deep the lanes' ruts show (0..1), w: how far it thaws to slush (0..1; + // Enhanced alone, 0 on the other paths) + state: vec4, +}; + +@group(0) @binding(20) var snow_track_px: array; +@group(0) @binding(21) var snow_track: SnowTrack; + +const TRACK_TEXELS: i32 = 2048; +const TRACK_TILE: i32 = 256; + +// One texel's rut and fresh track, each filled by the snow fallen since a tyre last ran +// over it. +fn snow_track_texel(p: vec2) -> vec2 { + let q = ((p % TRACK_TEXELS) + TRACK_TEXELS) % TRACK_TEXELS; + let tile = (q.y / TRACK_TILE) * (TRACK_TEXELS / TRACK_TILE) + q.x / TRACK_TILE; + let i = (tile * TRACK_TILE + q.y % TRACK_TILE) * TRACK_TILE + q.x % TRACK_TILE; + let t = unpack4x8unorm(snow_track_px[i]); + let then = round(t.b * 255.0) * 256.0 + round(t.a * 255.0); + let since = (snow_track.state.y - then + 65536.0) % 65536.0; + // (a track begins to blur after 8 % of a cover has fallen on it and is gone at 28 %; a + // rut, worn deeper by the traffic, begins to fill at 15 % and is gone at 52 % - in a + // heavy snowfall (Starker Schneefall) one or two minutes, and four or seven, without a + // car: a driver who waits that long at a stop sees it happen) + let fresh = t.g * (1.0 - smoothstep(80.0, 280.0, since)); + let rut = t.r * (1.0 - smoothstep(150.0, 520.0, since)); + return vec2(rut, fresh); +} + +// The rut (x) and the fresh track (y) at a point of the render frame, blended between the +// four texels around it (each decoded first: the fill time does not blend). +// +// Faded out from 75 m off and not read beyond 90: the tiles the field takes as the camera +// moves lie 96 m off and more, and hold what they held before until their ruts are drawn +// a few frames later (see `SnowTracks::update`) - and a rut that far is a pixel or two. +fn snow_track_at(world: vec2) -> vec2 { + let fade = 1.0 - smoothstep(75.0, 90.0, distance(world, camera.cam_pos.xy)); + if (snow_track.place.w < 0.5 || fade <= 0.0) { + return vec2(0.0); + } + let q = (world + snow_track.place.xy) * (f32(TRACK_TEXELS) / snow_track.place.z) - 0.5; + let b = floor(q); + let f = q - b; + let i = vec2(b); + let a00 = snow_track_texel(i); + let a10 = snow_track_texel(i + vec2(1, 0)); + let a01 = snow_track_texel(i + vec2(0, 1)); + let a11 = snow_track_texel(i + vec2(1, 1)); + return mix(mix(a00, a10, f.x), mix(a01, a11, f.x), f.y) * fade; +} + +// Whether a part's surface code carries its roof's own snow (`vehicle_snow`) rather than +// leaving it to the weather's (a roof the roads' snow does not keep: another player's bus). +fn vehicle_snow_kept(code: f32) -> bool { + return code < -10000.0 && road_snow_dynamic(); +} + +// The snow on a vehicle's part (`code`: its instance's surface code, whose ten thousands +// carry how much snow its roof has gathered, 1..41 for 0..1, see upload.rs `roof_code`), +// at `local`, the point in the part's own mesh: patches at first, a closed layer as it +// goes on, laid out on the vehicle so that they ride with it. +fn vehicle_snow(code: f32, local: vec3) -> f32 { + let amount = (floor(-code / 10000.0) - 1.0) / 40.0; + let level = amount * 1.3 - 0.12; + // (bare, or closed over whatever the patches: no noise to sample) + if (amount <= 0.0) { + return 0.0; + } + if (level >= 1.08) { + return 1.0; + } + let p = local.xy; + let p2 = vec2(p.x * 0.8 - p.y * 0.6, p.x * 0.6 + p.y * 0.8); + let patches = vnoise_f(p, 0.9, vec2(4.3, 1.9)) * 0.65 + vnoise_f(p2, 3.1, vec2(8.1, 6.7)) * 0.35; + return smoothstep(patches - 0.3, patches + 0.08, level); +} + +// Whether the roads' snow is the built-up kind (`state.x` at or above 0) rather than the +// weather's on/off "snow on road". +fn road_snow_dynamic() -> bool { + return snow_track.state.x >= 0.0; +} + +// The snow on a carriageway at `world` (render frame): x the cover (0..1), y the slush in +// the ruts (0..1: the wheels keep it wet and grey), z a fresh tyre track (0..1). +fn road_snow(world: vec3) -> vec3 { + let base = clamp(snow_track.state.x, 0.0, 1.0); + if (base <= 0.0) { + return vec3(0.0); + } + // the map's own coordinates (modulo the pattern's period): the patches stay put + let m = world.xy + camera.world_origin.xy; + // It does not settle evenly: first a dusting in patches a stride or two across and in + // the grain of the asphalt, which close up as it goes on falling. + // (three octaves, the finer ones turned against the coarse: a single lattice's cells + // showed as square blots where the cover's edge ran through them) + // (once the cover has closed - its level over the patches' highest - every pixel of the + // road paid for three octaves of noise that changed nothing) + let m2 = vec2(m.x * 0.8 - m.y * 0.6, m.x * 0.6 + m.y * 0.8); + let level = base * 1.35 - 0.15; + var cover = 1.0; + if (level < 1.1) { + let m3 = vec2(m.x * 0.28 + m.y * 0.96, m.y * 0.28 - m.x * 0.96); + let patches = vnoise_f(m, 0.45, vec2(3.1, 7.7)) * 0.55 + vnoise_f(m2, 1.3, vec2(11.3, 2.9)) * 0.3 + vnoise_f(m3, 3.7, vec2(5.9, 13.1)) * 0.15; + cover = smoothstep(patches - 0.35, patches + 0.1, level); + } + let tracks = snow_track_at(world.xy); + // The ruts: the wheels of the traffic keep two strips of each lane down to slush, the + // more of it the more snow there is to churn; with a mere dusting they show the asphalt. + let rut = tracks.x * snow_track.state.z; + let slush = rut * smoothstep(0.15, 0.7, base); + cover = cover * (1.0 - rut * 0.85); + // A fresh track: the tread pressed the snow flat and grey. Its edge sharpened from the + // texels' blend (a soft ramp over a whole texel read as a blur), and the pressed snow + // grainy - the tread's blocks, as fine as the eye can still tell apart. + let edge = smoothstep(0.2, 0.75, tracks.y); + var track = 0.0; + if (edge > 0.0) { + track = edge * (0.75 + 0.25 * vnoise_f(m2, 14.0, vec2(1.7, 9.3))); + } + cover = cover * (1.0 - track * 0.6); + var wet = max(slush, track * 0.5 * base); + // Thawing (rain on it, or a wet road, while no fresh snow falls): what is left goes grey + // and soaked, and it breaks up - the thin patches first, in the grain of a smooth noise + // a few strides across - into slush over the wet asphalt. + let thaw = clamp(snow_track.state.w, 0.0, 1.0); + if (thaw > 0.0 && cover > 0.0) { + let n = vnoise_f(m, 1.1, vec2(6.1, 2.3)) * 0.6 + vnoise_f(m2, 4.3, vec2(9.7, 4.1)) * 0.4; + let bare = smoothstep(n - 0.06, n + 0.06, thaw * 0.6 - 0.08 + 0.3 * (1.0 - base)); + let left = cover * (1.0 - bare); + wet = max(wet, (cover - left) * 0.7 + left * thaw * 0.8); + cover = left * (1.0 - 0.55 * thaw); + } + return vec3(cover, wet, track); +} + +// Enhanced graphics: what the enhanced main pass, the sky and the coronas share - the +// light of the physically based sky (see atmosphere.rs), in its units (1 = 10 000 lux), +// and the air between the camera and what it sees. The scene is drawn pre-exposed: +// radiance times `enh.exposure.x`, so that the half-float target keeps its precision by +// night as well as by day. +struct Enhanced { + // x pre-exposure, y the level unlit things are drawn at, z a lit window's radiance + // (pre-exposed), w how bright a light's corona is drawn + exposure: vec4, + // rgb irradiance of the sun after the clouds, w its angular radius (rad) + sun: vec4, + // irradiance from the sky and the ground: order-2 spherical harmonics, rgb + sh: array, 9>, + // rgb radiance of the ground, w the sky table's scale + ground: vec4, + // x weather fog extinction (1/m) at its base, y its height falloff (1/m), z the base + // height (render-origin relative), w clear-air extinction (1/m) at the ground + fog: vec4, + // rgb fog radiance from the light around it (the sun's part is added by angle), + // w the table scale the reflection probe was drawn with + fog_color: vec4, + // x wet roads, y snow cover, z rain, w cloud cover in front of the sun + weather: vec4, + // x mip levels of the probe, y illuminance of a light's core (maplight colour 1), + // z cabin light illuminance, w how much of the sun the clouds let through + lights: vec4, + // rgb the sun disc's irradiance before the clouds, w frame time (s) + sun_disc: vec4, + // x which term the main pass shows alone (OMSI_DEBUG_ENHANCED, 0 = the picture), + // y the puddles' F0, z the envmap photo's strength, w the tone curve's contrast + debug: vec4, + // xyz where the sky cube is drawn from, relative to the camera + eye: vec4, + // x how bright an LED panel's dots burn (0 = off), y whether the LED panels' `\S:n` + // masks keep their mip chain (0: at full resolution, the dots stay visible when small), z 1 + // when lights glare and glow in the night air (the settings' `light_glow`) + led: vec4, + // xyz towards the moon, w its angular radius (rad) + moon: vec4, + // rgb the moon disc's irradiance before the clouds, w how much of the starry sky shows + moon_disc: vec4, + // rgb the sun's irradiance at 1400, 2100 and 2800 m (the cumulus layer) and 7000 m + // (the high thin layer), through the atmosphere from up there + cloud_sun: array, 4>, + // rgb the moonlight on a surface facing the moon (after the clouds), w 1 while the + // shadow maps are the moon's + moon_light: vec4, + // the condensation on the player's bus's panes (optical depths): windscreen, sides, + // rear, and how far the defroster has cleared the windscreen (0..1; omsi-app + // condensation.rs) + condensation: vec4, + // x the cumulus layer's base, y its top (m over the ground), z the altocumulus cover, + // w the storm's activity + layers: vec4, + // the lightning of this frame: x the light it throws on a surface facing it (1 = 10 000 + // lux), yz towards it (horizontal unit vector), w its elevation (rad) + flash: vec4, + // xyz towards the flash (unit vector), w how bright its channel is + flash2: vec4, + // x a number the channel's shape is drawn from + flash3: vec4, + // the clouds' shadow field (cloud_field.rs): xy its middle in cloud space, z one over its + // width, w 1 when there is one + cloud_f1: vec4, + // xy what takes a world point to cloud space, z the height of the plane it is taken on, + // w the share of the sun the main pass has taken off already for the clouds over the camera + cloud_f2: vec4, + // the player's bus's pitch and roll: sin, cos of each (its panes' condensation sits on + // the glass on a slope, `pane_local`) + pane_tilt: vec4, + // Slots of the weather overhaul, one owner each (zero until it fills them): + // the volumetric clouds, the volumetric fog, the precipitation, the bus's panes, the + // surfaces' PBR and the ray tracing, and two spare. + clouds_ext: vec4, + clouds_ext2: vec4, + vol_fog: vec4, + vol_fog2: vec4, + precip_ext: vec4, + glass_ext: vec4, + // (pbr_ext: x the share of the sun's light that still comes as a beam - the rest the + // clouds scatter, `sun_scattered` - y 1 when x is set) + pbr_ext: vec4, + rt_ext: vec4, +}; +@group(0) @binding(11) var enh: Enhanced; +@group(0) @binding(13) var s_lin: sampler; +@group(0) @binding(14) var t_sky_lut: texture_2d; + +const PI: f32 = 3.14159265; + +// Irradiance from the sky and the ground on a surface facing n. +fn sh_irradiance(n: vec3) -> vec3 { + let c = enh.sh; + let e = c[0].rgb * 0.282095 + + c[1].rgb * (0.488603 * n.y) + c[2].rgb * (0.488603 * n.z) + c[3].rgb * (0.488603 * n.x) + + c[4].rgb * (1.092548 * n.x * n.y) + c[5].rgb * (1.092548 * n.y * n.z) + + c[6].rgb * (0.315392 * (3.0 * n.z * n.z - 1.0)) + c[7].rgb * (1.092548 * n.x * n.z) + + c[8].rgb * (0.546274 * (n.x * n.x - n.y * n.y)); + return max(e, vec3(0.0)); +} + +// The lightning's light on a surface facing n: half of it from the cloud overhead and +// round it (a hemisphere), half along the way to the flash itself. +fn flash_irradiance(n: vec3) -> vec3 { + if (enh.flash.x <= 0.0) { + return vec3(0.0); + } + return vec3(0.80, 0.90, 1.0) * enh.flash.x * (0.5 * (0.5 + 0.5 * n.z) + 0.5 * max(dot(n, enh.flash2.xyz), 0.0)); +} + +// Sky radiance towards d (unscaled: times enh.ground.w is the radiance). The table runs +// over the azimuth from the sun (0..π) and the elevation (denser at the horizon). +// The sky table's texture: the table (32 x 48) in its corner and the clouds' shadow field +// (192 x 192) beside it, one texel clear (cloud_field.rs `SKY_TEX_W`, `FIELD_X0`). +const SKY_TEX: vec2 = vec2(225.0, 192.0); +const SKY_TABLE: vec2 = vec2(32.0, 48.0); +const FIELD_ORIGIN: f32 = 33.0; +const FIELD_N: f32 = 192.0; + +fn sky_table_raw(d: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let ls = length(s.xy); + let ld = length(d.xy); + var az = 0.0; + if (ls > 1e-4 && ld > 1e-4) { + az = acos(clamp(dot(s.xy / ls, d.xy / ld), -1.0, 1.0)); + } + let el = asin(clamp(d.z, -1.0, 1.0)); + let v = 0.5 + 0.5 * sign(el) * sqrt(min(abs(el) / 1.5707963, 1.0)); + // (kept a half texel inside the table: its neighbours in the texture are not the sky) + let tx = clamp(vec2(az / PI, v) * SKY_TABLE, vec2(0.5), SKY_TABLE - vec2(0.5)); + return textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).rgb; +} + +// The share of the sun that reaches the point p through the clouds, as against what the main +// pass's sun (`enh.sun`) already has for the camera's own place: the cumulus layer's shadow +// field read where the sun's way through p meets the layer's middle. 1 where there is no +// field, beyond its edge and where the sun is low (the camera's own factor stands there). +fn cloud_shadow_ratio(p: vec3) -> f32 { + let s = camera.sun_dir.xyz; + if (enh.cloud_f1.w < 0.5 || s.z < 0.06) { + return 1.0; + } + let cs = p.xy + s.xy / s.z * (enh.cloud_f2.z - p.z) + enh.cloud_f2.xy; + let uv = (cs - enh.cloud_f1.xy) * enh.cloud_f1.z + vec2(0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + let w = 1.0 - smoothstep(0.36, 0.48, edge); + if (w <= 0.0) { + return 1.0; + } + let tx = vec2(FIELD_ORIGIN, 0.0) + clamp(uv * FIELD_N, vec2(0.5), vec2(FIELD_N - 0.5)); + let f = textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).r; + let ratio = min(f / max(enh.cloud_f2.w, 0.02), 6.0); + return mix(1.0, ratio, w); +} + +fn sky_table(d: vec3) -> vec3 { + return sky_table_raw(d) * enh.ground.w; +} + +// Henyey-Greenstein phase function. +fn hg_phase(c: f32, g: f32) -> f32 { + let g2 = g * g; + return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * c, 1e-4), 1.5)); +} + +// Optical depth of an exponentially thinning layer (extinction sigma at height 0, falling +// off with k per metre) along a straight path of length dist from height h0 to h1. +fn layer_depth(sigma: f32, k: f32, h0: f32, h1: f32, dist: f32) -> f32 { + if (sigma <= 0.0) { + return 0.0; + } + let a = max(h0, 0.0); + let b = max(h1, 0.0); + let dh = b - a; + if (abs(k * dh) < 1e-3) { + return sigma * dist * exp(-k * 0.5 * (a + b)); + } + return sigma * dist * (exp(-k * a) - exp(-k * b)) / (k * dh); +} + +// The air between the camera and a point dist metres away in direction dir (from the +// camera), at heights h0 (camera) and h1 (point) above the fog's base: rgb the light it +// scatters towards the camera (radiance), a what it lets through of the point. +fn air(dir: vec3, dist: f32, h0: f32, h1: f32) -> vec4 { + return air_of(dir, dist, h0, h1, 1.0); +} + +// The same with the clear air's share scaled (0 for the sky, whose table holds it already). +fn air_of(dir: vec3, dist: f32, h0: f32, h1: f32, clear: f32) -> vec4 { + let tau_fog = layer_depth(enh.fog.x, enh.fog.y, h0, h1, dist); + let tau_air = layer_depth(enh.fog.w * clear, 1.0 / 1500.0, h0, h1, dist); + let tau = tau_fog + tau_air; + let t = exp(-tau); + if (tau < 1e-5) { + return vec4(0.0, 0.0, 0.0, 1.0); + } + // clear air takes on the sky's own colour at the horizon in this direction (which + // already holds the glow round the sun); a weather fog glows with the light around it + // and brighter towards the sun + let horizon = sky_table(normalize(vec3(dir.x, dir.y, max(dir.z, 0.0) * 0.3 + 0.03))); + let fog_in = enh.fog_color.rgb + enh.sun.rgb * hg_phase(dot(dir, camera.sun_dir.xyz), 0.55) * 0.9; + let inscatter = mix(horizon, fog_in, tau_fog / tau); + return vec4(inscatter * (1.0 - t), t); +} + +// The water normal shared by shading and scene reflections. The integer hash and the +// 1000 m period match shader.wgsl, keeping the rings fixed through floating-origin moves. +fn puddle_hash(c: vec2) -> f32 { + let cells = 8000.0; + let w = c - cells * floor(c / cells); + var v = vec2(w) * 1664525u + vec2(1013904223u); + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + return f32(v.x >> 8u) / 16777215.0; +} + +// The rings the rain makes on standing water (Enhanced): xy the water's slope (a horizontal +// offset to its normal), z how much it is stirred (0..1, for its roughness as well). +// +// A falling drop sends out a short train of capillary waves: two or three rings close +// together, running out at a few decimetres a second and dying away within a hand's +// breadth. Three lattices of cells of 18 to 27 cm, turned against each other so that no grid +// shows, each take a drop now and then - the harder it rains the more often, and in more +// of them - every drop at a new place in its cell. A ring is a wave packet on its circle +// (a cosine under a Gaussian), its slope worked out exactly, and it stays inside its cell +// (no ring is cut off at a cell's edge). +fn puddle_ripple(pattern_xy: vec2, time: f32, rain: f32, coverage: f32) -> vec3 { + if (rain <= 0.001 || coverage <= 0.0) { + return vec3(0.0); + } + var slope = vec2(0.0); + var stir = 0.0; + let rate = 0.7 + 1.6 * rain; + let amp = min(1.0, 0.45 + rain) * coverage; + for (var i = 0; i < 3; i = i + 1) { + let fi = f32(i); + let size = 0.18 + 0.045 * fi; + let cs = vec2(cos(fi * 1.93), sin(fi * 1.93)); + let turned = vec2(pattern_xy.x * cs.x - pattern_xy.y * cs.y, pattern_xy.x * cs.y + pattern_xy.y * cs.x); + let q = turned / size + vec2(fi * 17.0, fi * 5.0); + let cell = floor(q); + let seed = puddle_hash(cell + vec2(fi * 311.0, 0.0)); + let tt = time * rate * (0.8 + 0.4 * seed) + seed * 7.0; + let n = floor(tt); + let age = tt - n; + let h = puddle_hash(cell + vec2(n - 97.0 * floor(n / 97.0) + 401.0, fi * 13.0 + 7.0)); + let hit = step(fract(h * 31.7), 0.3 + 0.65 * rain); + let centre = vec2(0.3) + 0.4 * vec2(h, fract(h * 13.7)); + let local = fract(q) - centre; + let r = length(local); + let radius = 0.05 + 0.24 * sqrt(age); + let d = r - radius; + let w = 0.045; + let k = 6.2831853 / 0.07; + let env = exp(-(d * d) / (w * w)); + let a = (1.0 - age) * (1.0 - age) * hit; + // the height is a * env * cos(k d): its slope along the radius + let dh = a * env * (-2.0 * d / (w * w) * cos(k * d) - k * sin(k * d)); + slope = slope - local / max(r, 1e-4) * dh / k; + stir = stir + a * env; + } + return vec3(slope * 0.03 * amp, clamp(stir * amp, 0.0, 1.0)); +} + +// The rings as a picture whose pixel covers `fp` metres of the water sees them: their +// slopes are a few centimetres long, and a pixel (or a puddle ray standing for several) +// wider than half of that lands on a ring's crest one frame and its trough the next - the +// water's picture trembled and broke into blocks. Faded out there, the rings leave their +// stir (the roughness) and the reflection keeps still. +fn puddle_ripple_seen(pattern_xy: vec2, time: f32, rain: f32, coverage: f32, fp: f32) -> vec3 { + let fade = 1.0 - smoothstep(0.012, 0.035, fp); + let r = puddle_ripple(pattern_xy, time, rain, coverage); + return vec3(r.xy * fade, r.z); +} + +// The classic rings (Vanilla+'s puddle reflections): one lattice of 12.5 cm cells. +fn puddle_ripple_classic(pattern_xy: vec2, time: f32, rain: f32, coverage: f32) -> vec3 { + let cell = floor(pattern_xy * 8.0); + let seed = puddle_hash(cell); + let phase = fract(time * (0.8 + seed * 0.9) + seed * 13.0); + let local = fract(pattern_xy * 8.0) - vec2(0.5); + let ring = abs(length(local) - phase * 0.4); + let hit = step(1.0 - clamp(0.25 + 0.6 * rain, 0.0, 0.9), fract(seed * 31.7)); + let strength = (1.0 - smoothstep(0.0, 0.06, ring)) * (1.0 - phase) * rain * coverage * hit; + // Shallow rain rings disturb the image gently; steep normals break neighbouring + // reflection rays apart and make otherwise still puddles look like rough waves. + let bump = normalize(local + vec2(1e-5, 0.0)) * strength * 0.018; + return vec3(bump, strength); +} + +// `beam_shadow.wgsl` for the shaders without the lamp shadow tiles: nothing stands in a beam. +fn beam_tile(li: u32, l: PointLight) -> u32 { + return 0xffffffffu; +} + +fn beam_reaches(k: u32, x: vec3) -> f32 { + return 1.0; +} + +// Enhanced graphics: the lamps as the scene and the sky share them - a headlamp's beam +// and the light the weather's fog scatters from the lamps towards the camera (needs the +// point lights, their grid and `camera.light_grid`). + +// A headlamp's intensity towards `t` (from the lamp) by the angles of a road lamp, not +// around its axis: wide across, brightest just under the lamp's horizon where it reaches +// far down the road, weak straight down, and with a low beam a sharp cut-off above it. +// `dir` is the lamp's axis in its vehicle's floor: its rise tilts the horizon with the +// vehicle, up a ramp and down (#1897). +fn headlamp(t: vec3, dir: vec3, low: bool) -> f32 { + let fwd = normalize(dir.xy + vec2(1e-6, 0.0)); + let ahead = dot(t.xy, fwd); + if (ahead <= 0.0) { + return 0.0; + } + let across = abs(t.x * fwd.y - t.y * fwd.x) / ahead; + let wide = 0.12 * smoothstep(1.0, 0.45, across) + 0.88 * exp(-across * across / 0.06); + let rise = t.z / max(length(t.xy), 1e-3); + let tilt = dir.z / max(length(dir.xy), 1e-3); + // (the tangent of the angle under that horizon) + let drop = (tilt - rise) / max(1.0 + rise * tilt, 1e-3); + // full out to where the road is 0.06 under the lamp's horizon, then less as the cube of + // the drop and a little more: the road is lit evenly from the bumper on, a little + // brighter as far as the beam reaches, and not as one hot pool where its axis lands + var up = min(1.0, pow(0.06 / max(abs(drop), 1e-4), 3.4)); + if (low) { + up = up * smoothstep(-0.012, 0.025, drop); + return wide * up; + } + // a full beam reaches far: a narrow, bright core along the lamp's horizon + let hot = exp(-across * across / 0.012 - drop * drop / 0.0004); + return wide * up + 6.0 * hot; +} + +// The lamps' light the weather's fog scatters towards the camera (radiance, not +// pre-exposed): single scattering along the view ray from `start` to `len` metres in +// direction `d` - the glow round a street lamp in the mist, its cone under it, a bus's +// beams reaching ahead into the fog or the falling snow. The droplets scatter strongly +// forward (fog and cloud droplets of some ten micrometres: g about 0.8), so the glow is +// brightest looking towards a lamp and a cone shows faintly from the side. +// +// Each lamp is taken once, over the whole stretch of the ray within its reach, in the grid +// cell the ray's point nearest to it lies in (the ray's cells are walked through; every +// cell lists the lamps reaching into it). Along a straight ray past a point source, with +// t - t0 = h tan(phi) (h the ray's distance from the lamp, t0 where it passes nearest), +// the inverse square cancels against the path element: dt / r^2 = dphi / h, and what is +// left is the phase function over the angle, cos(theta) = -sin(phi) - a smooth integral +// taken with five Gauss-Legendre nodes, at each of which a spot's or a headlamp's beam is +// asked how much it sends that way. The fog's extinction dims the light on its way from +// the lamp and to the camera (taken at the nearest point). A beam's light, which reaches +// only part of the way, is summed along the ray instead, its steps staggered by `jitter`. +// The droplets' phase function: a strong forward peak and the back-scattered light a +// fog's lidar ratio of some 18 sr asks for (0.055 per steradian straight back) - a single +// Henyey-Greenstein lobe of g 0.8 gave a tenth of it, and a bus's own headlights lit no +// wall of fog in front of the driver. Two lobes, 0.9 of g 0.85 and 0.1 of g -0.5. +fn fog_phase(c: f32) -> f32 { + return 0.9 * hg_phase(c, 0.85) + 0.1 * hg_phase(c, -0.5); +} +const AIRLIGHT_CELLS: u32 = 16u; + +// The clear night air's own haze, which lights a lamp's halo and a headlamp's beam as the fog's +// droplets do, only fainter: the lowest hundred metres of a city's air hold its dust, exhaust +// and humidity at several times the column's average aerosol extinction (`enh.fog.w`), 1-3e-4 +// per metre (a visibility of 15-40 km). A lamp then has a soft glow round it and a low beam +// a faint cone, as in any night photograph, instead of a lit disc on a black ground. +const GROUND_HAZE_GAIN: f32 = 8.0; + +// `droplets`: how much of the weather's extinction scatters like fog (see `FogLampUniform`). +fn lamp_airlight(c: vec3, d: vec3, start: f32, len: f32, jitter: f32, droplets: f32) -> vec3 { + var sum = vec3(0.0); + let sigma0 = enh.fog.x * droplets + enh.fog.w * GROUND_HAZE_GAIN * enh.led.z; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (sigma0 < 4e-5 || cell <= 0.0 || side == 0u || len <= start) { + return sum; + } + // (past a few optical depths nothing comes back) + let end = min(len, start + 4.0 / sigma0); + let gx = array(-0.9061798, -0.5384693, 0.0, 0.5384693, 0.9061798); + let gw = array(0.2369269, 0.4786287, 0.5688889, 0.4786287, 0.2369269); + // the walk through the grid's cells along the ray's plan + let o = (c.xy - camera.light_grid.xy) / cell; + let dd = d.xy / cell; + var ix = i32(floor(o.x + dd.x * start)); + var iy = i32(floor(o.y + dd.y * start)); + let sx = select(-1, 1, dd.x >= 0.0); + let sy = select(-1, 1, dd.y >= 0.0); + let inv_x = select(1e9, 1.0 / abs(dd.x), abs(dd.x) > 1e-7); + let inv_y = select(1e9, 1.0 / abs(dd.y), abs(dd.y) > 1e-7); + var tx = select((f32(ix) - o.x) / dd.x, (f32(ix + 1) - o.x) / dd.x, dd.x >= 0.0); + var ty = select((f32(iy) - o.y) / dd.y, (f32(iy + 1) - o.y) / dd.y, dd.y >= 0.0); + if (abs(dd.x) <= 1e-7) { tx = 1e9; } + if (abs(dd.y) <= 1e-7) { ty = 1e9; } + var t = start; + for (var k = 0u; k < AIRLIGHT_CELLS; k = k + 1u) { + if (t >= end) { + break; + } + let t_out = min(min(tx, ty), end); + if (ix >= 0 && iy >= 0 && ix < i32(side) && iy < i32(side)) { + let base = (u32(iy) * side + u32(ix)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let to_l = l.pos.xyz - c; + let t0 = dot(to_l, d); + // the ray's point nearest to the lamp: taken in this cell only + let tc = clamp(t0, start, end); + if (tc < t || tc > t_out) { + continue; + } + let range = l.extra.w; + let h = length(to_l - d * t0); + if (h >= range) { + continue; + } + // A beam (a headlamp, a spot) is lit in the weather's fog only: its cone is a sliver of + // sixteen jittered steps at half size, which the fog's density hides and the clear + // air's haze shows as shimmer and soap. The lamps' halo alone has the ground haze. + let beam_lamp = l.extra.z != 0.0 || l.dir.w > -1.5; + let fog_sigma = enh.fog.x * droplets; + if (beam_lamp && enh.fog.x < 2e-4) { + continue; + } + let s0 = select(sigma0, fog_sigma, beam_lamp); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + // (inside its core a lamp is as bright as at the core's edge) + let hh = max(h, select(core * 0.7, 0.4, l.extra.z != 0.0)); + let w = sqrt(range * range - h * h); + let ta = max(start, t0 - w); + let tb = min(end, t0 + w); + if (tb <= ta) { + continue; + } + var acc = 0.0; + var half = 0.0; + if (l.extra.z != 0.0 || l.dir.w > -1.5) { + // a beam (a headlamp, a spot): lit only where its cone or cut-off lets + // it - a sliver of the angles the lamp is seen under, which the five + // nodes missed. Sixteen even steps over that angle instead (dphi = + // h dt / r^2: the inverse square is in the step). (Sixteen even steps + // along the way put the few next to the lamp, where nearly all of its + // light is, a metre or more apart: the pixels' staggered steps came + // out as a coarse checker in the fog round every headlamp.) + let pa = atan((ta - t0) / hh); + let dphi = (atan((tb - t0) / hh) - pa) / 16.0; + let tile_k = beam_tile(li, l); + for (var q = 0u; q < 16u; q = q + 1u) { + let tq = t0 + hh * tan(pa + (f32(q) + jitter) * dphi); + let to = l.pos.xyz - (c + d * tq); + let ld = to * inverseSqrt(max(dot(to, to), 1e-6)); + var beam = 0.0; + if (l.extra.z != 0.0) { + beam = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0); + } else { + beam = smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } + // (the map is looked at only where the beam shines at all, and only for + // the few lamps that have a tile: no shadows, no tile, no tap) + var reach = 1.0; + if (beam > 0.002 && tile_k < 44u) { + reach = beam_reaches(tile_k, c + d * tq); + } + acc = acc + beam * reach * fog_phase(dot(ld, d)) * dphi; + } + half = 1.0; + } else { + let pa = atan((ta - t0) / hh); + let pb = atan((tb - t0) / hh); + half = 0.5 * (pb - pa); + let mid = 0.5 * (pa + pb); + let tile_p = beam_tile(li, l); + for (var q = 0u; q < 5u; q = q + 1u) { + let phi = mid + half * gx[q]; + let tq = t0 + hh * tan(phi); + let ld = normalize(l.pos.xyz - (c + d * tq)); + var beam = 1.0; + if (l.dir.z < -0.5) { + // (a lamp in a housing: see `lamp_light`) + beam = 0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z); + } + // (a lamp with a shadow map: what stands between it and the air + // keeps its light out of that air, as the headlamps' beams) + var reach = 1.0; + if (beam > 0.002 && tile_p < 44u) { + reach = beam_reaches(tile_p, c + d * tq); + } + acc = acc + gw[q] * beam * reach * fog_phase(-sin(phi)); + } + } + // a lamp's irradiance is core^2 / r^2 of its colour's (a headlamp's 1 / r^2) + let strength = select(core * core, 1.0, l.extra.z != 0.0); + let xc = c + d * tc; + let sigma = s0 * exp(-enh.fog.y * max(xc.z - enh.fog.z, 0.0)); + let dl = distance(xc, l.pos.xyz); + let atten = exp(-layer_depth(s0, enh.fog.y, c.z - enh.fog.z, xc.z - enh.fog.z, tc - start) - sigma * dl); + sum = sum + l.color.rgb * (l.color.w * strength * acc * half / hh * sigma * atten); + } + } + t = t_out; + if (tx < ty) { + tx = tx + inv_x; + ix = ix + sx; + } else { + ty = ty + inv_y; + iy = iy + sy; + } + } + return sum * enh.lights.y; +} + +// Enhanced: the light a raindrop or a snowflake sends towards the eye - what it scatters of +// the sky's light, the sun's and the lamps' round it, the drop's strongly forward (a +// streak flashes against a lamp seen through the rain, and is next to invisible in the +// dark between the lamps), the flake's nearly every way. (Drawn at the display's level +// whatever the light, the flakes of a snowfall at night shone white in the dark, far from +// any lamp.) +fn precip_light(x: vec3, to_eye: vec3, snow: bool) -> vec3 { + // the sky's and the ground's light round it, and the sun's on a small sphere + var e = enh.fog_color.rgb * (PI / 0.9) + enh.sun.rgb * 0.25; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell > 0.0 && side > 0u) { + let f = (x.xy - camera.light_grid.xy) / cell; + let gx = i32(floor(f.x)); + let gy = i32(floor(f.y)); + if (gx >= 0 && gy >= 0 && gx < i32(side) && gy < i32(side)) { + let base = (u32(gy) * side + u32(gx)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let dl = l.pos.xyz - x; + let dist2 = dot(dl, dl); + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let ld = dl * inverseSqrt(max(dist2, 1e-6)); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var k = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + if (l.extra.z != 0.0) { + k = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + k = k * smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } else if (l.dir.z < -0.5) { + k = k * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + // (the scattering towards the eye relative to an even one: a drop's light + // goes on forwards, a flake's every way. The angle is the one between the + // light's way from the lamp, -ld, and on to the eye: taken against -to_eye + // it put the forward peak behind the drop, and the drops in a bus's own + // beams, seen from behind the lamps, shone a hundred times too bright as + // white streaks down the road ahead) + let c = dot(-ld, to_eye); + let lobe = select(fog_phase(c), 0.7 * hg_phase(c, 0.3) + 0.3 / (4.0 * PI), snow) * 4.0 * PI; + e = e + l.color.rgb * l.color.w * enh.lights.y * k * lobe; + } + } + } + return e / PI; +} + + +// Enhanced graphics: the main pass's own lighting model, the usual metal/roughness one: +// GGX (Trowbridge-Reitz) microfacets with height-correlated Smith visibility and Schlick's +// Fresnel (F0 4 % for a dielectric, its colour for a metal), their multiple scattering given +// back (Fdez-Aguera), and Lambert diffuse with the share the specular part leaves it, so that +// nothing sends out more light than falls on it. Lit by the sun (soft shadows whose penumbra +// grows with the distance to the blocker; what the clouds scatter of it as a shadowless light +// of the sky's kind), the sky and the ground (spherical harmonics, occluded by the SSAO or +// the traced occlusion), a reflection probe of the sky for the reflections (the split sum +// with Karis' analytic DFG, occluded by the AO as Lagarde has it and by the horizon of a +// normal map), point and spot lights falling off with the square of the distance, and the +// air in between. Roughness is widened by the normal's spread across the pixel (specular +// antialiasing) and held off zero for the sun's disc. OMSI's material data +// decides the surface: [matl_envmap] factor x mask is how much it reflects and how smooth +// it is, the o3d specular power how rough a surface without one is, [matl_bumpmap] bends +// the normal. Everything is drawn pre-exposed into the high-range target. + +// Only painted terrain may skip empty brush-mask pixels. +override TERRAIN_PAINT: bool = false; + +@group(0) @binding(12) var t_probe: texture_cube; + +fn d_ggx(nh: f32, a: f32) -> f32 { + let a2 = a * a; + let d = nh * nh * (a2 - 1.0) + 1.0; + return a2 / (PI * d * d); +} + +// The microfacets of a film of water over a road: the slopes of a water surface are +// Gaussian (Cox and Munk 1954), the Beckmann distribution. Its tail falls off as +// exp(-tan^2 / a^2), where GGX's falls as a^2 / tan^4: under GGX a headlamp - a hundred +// thousand candela towards the road - kept a highlight brighter than the lit road some ten +// degrees off its mirror direction, and its reflection ran as one white line from the lamp +// down to the camera. +fn d_beckmann(nh: f32, a: f32) -> f32 { + let c2 = max(nh * nh, 1e-4); + let a2 = a * a; + return exp(-(1.0 - c2) / (c2 * a2)) / (PI * a2 * c2 * c2); +} + +// Height-correlated Smith visibility (G / (4 n.l n.v)). +fn v_smith(nv: f32, nl: f32, a: f32) -> f32 { + let a2 = a * a; + let gv = nl * sqrt(nv * nv * (1.0 - a2) + a2); + let gl = nv * sqrt(nl * nl * (1.0 - a2) + a2); + return 0.5 / max(gv + gl, 1e-5); +} + +// A diffuse surface's albedo under a film of water (n = 1.33; Lekner and Dorf 1988): the +// film lets in 1 - 0.066 of diffuse light, and of what the surface scatters back up only +// 1 - 0.472 leaves through the film's top, the rest returns to the surface. +fn wet_albedo(a: vec3) -> vec3 { + return 0.934 * a * 0.528 / (vec3(1.0) - 0.472 * a); +} + +fn f_schlick(f0: vec3, c: f32) -> vec3 { + let f = pow(1.0 - clamp(c, 0.0, 1.0), 5.0); + return f0 + (vec3(1.0) - f0) * f; +} + +// The split-sum's integral of the GGX lobe over the hemisphere for a white and a black F0 +// (Karis' analytic fit of the DFG table): the reflectance is f0 * x + y. +fn dfg_ab(rough: f32, nv: f32) -> vec2 { + let c0 = vec4(-1.0, -0.0275, -0.572, 0.022); + let c1 = vec4(1.0, 0.0425, 1.04, -0.04); + let r = c0 * rough + c1; + let a004 = min(r.x * r.x, pow(2.0, -9.28 * nv)) * r.x + r.y; + return vec2(-1.04, 1.04) * a004 + r.zw; +} + +// The split-sum environment term, single scattering only. +fn env_brdf(f0: vec3, rough: f32, nv: f32) -> vec3 { + let ab = dfg_ab(rough, nv); + return f0 * ab.x + vec3(ab.y); +} + +// What a surface reflects specularly towards the eye of light from every direction, with the +// light its microfacets pass on to each other before it leaves (Fdez-Aguera 2019, after +// Kulla and Conty): rgb that reflectance (the probe's weight; one minus it is what is left +// for the diffuse part, so the two never add up to more than came in), w the factor by which +// the single-scattering lobe of a direct light falls short of it. Without the multiple +// scattering a rough metal lost up to half its light and went dark grey. +fn spec_ms(f0: vec3, rough: f32, nv: f32) -> vec4 { + let ab = dfg_ab(rough, nv); + let ess = clamp(ab.x + ab.y, 0.05, 1.0); + let fss = f0 * ab.x + vec3(ab.y); + let ems = 1.0 - ess; + let favg = f0 + (vec3(1.0) - f0) / 21.0; + let fms = fss * favg / (vec3(1.0) - ems * favg); + let comp = 1.0 + dot(f0, vec3(0.2126, 0.7152, 0.0722)) * (1.0 / ess - 1.0); + return vec4(min(fss + fms * ems, vec3(1.0)), comp); +} + +// Specular antialiasing (Tokuyoshi and Kaplanyan 2019): the spread of the normal across the +// pixel widens the lobe, so that a mirror-smooth finish on a curved, faceted or normal-mapped +// surface does not sparkle and crawl where it is smaller than a pixel. Returns the +// perceptual roughness. +fn rough_aa(rough: f32, n: vec3) -> f32 { + let dx = dpdx(n); + let dy = dpdy(n); + let variance = 0.25 * (dot(dx, dx) + dot(dy, dy)); + let kernel = min(2.0 * variance, 0.18); + let a = rough * rough; + return sqrt(sqrt(clamp(a * a + kernel, 0.0, 1.0))); +} + +// Horizon occlusion (Jimenez et al. 2016): a normal map can turn a reflection below the +// surface the geometry really has; that part of the lobe sees the surface itself, not the sky. +fn horizon_occlusion(r: vec3, geo_n: vec3) -> f32 { + let h = clamp(1.0 + 1.3 * dot(r, geo_n), 0.0, 1.0); + return h * h; +} + +// The sun's light through the clouds that is no longer a beam (`enh.pbr_ext.x` the beam's +// share, lighting/enhanced.rs `sun_directness`): what a veil or a thin deck scatters round the +// sun lies on the street as a bright dome overhead with a glow towards the sun, casting no +// shadow. It is the flux the beam would have brought to the ground (its share on a horizontal +// surface), spread so: a cloudy day's light is flat, not a weaker sun with sharp shadows. +fn sun_scattered(n: vec3, e: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let dome = 0.5 + 0.5 * n.z; + let lobe = (1.0 + dot(n, s)) / (1.0 + max(s.z, 0.0)); + return e * max(s.z, 0.0) * mix(dome, lobe, 0.4); +} + +// The beam's share of the sun's light (1 under a clear sky; 0 while the pass has not set it). +fn sun_beam_share() -> f32 { + return select(1.0, clamp(enh.pbr_ext.x, 0.0, 1.0), enh.pbr_ext.y > 0.5); +} + +// Ambient occlusion that lets bright surfaces bounce some light back into their own +// corners (Jimenez' multi-bounce fit), so white walls do not get grey creases. +fn ao_bounce(ao: f32, albedo: vec3) -> vec3 { + let a = 2.0404 * albedo - vec3(0.3324); + let b = -4.7951 * albedo + vec3(0.6417); + let c = 2.7552 * albedo + vec3(0.6903); + return max(vec3(ao), ((a * ao + b) * ao + c) * ao); +} + +// World direction to the probe's cube coordinates (and back: the swap is its own inverse). +fn to_cube(d: vec3) -> vec3 { + return vec3(d.x, d.z, d.y); +} + +// What a raindrop on a pane shows (`glass_film`): the sky probe that way, blurred a little +// by the drop's small lens, and low down the street's light in place of the probe's +// horizon (see the reflections in `shade_enhanced`). +fn rain_env_enhanced(d: vec3, lod: f32) -> vec3 { + let e = textureSampleLevel(t_probe, s_lin, to_cube(d), lod).rgb * enh.fog_color.w; + let surround = enh.fog_color.rgb * (0.25 / 0.9); + return mix(surround, e, smoothstep(-0.05, 0.35, d.z)); +} + +// A fixed, deterministic PCF kernel (shader.wgsl's `shadow_tent`). The old PCSS blocker +// search was unstable for alpha-tested foliage: a few leaves entering or leaving its +// 12-sample search changed the penumbra radius, producing checkerboard patches and +// camera-driven strips. The filter is fixed in shadow-map space, so the only thing that +// can change is the actual caster. `thin`: foliage, whose normals OMSI points up for even +// lighting - no receiver plane can be taken from them, a leaf compares at its own depth. +fn sun_shadow_soft(world_in: vec3, n: vec3, thin: bool) -> f32 { + if (camera.shadow.x < 0.5) { + return 1.0; + } + // (half a metre towards the sun for a leaf, as in `sun_shadow`) + let world = world_in + select(vec3(0.0), camera.sun_dir.xyz * 0.5, thin); + let ndl = clamp(dot(n, camera.sun_dir.xyz), 0.0, 1.0); + // (a veil of high cloud spreads the sun into an aureole a few degrees wide: the light + // comes from a larger source, and the shadow's edge widens with it) + // (the tent's four gathers step apart for it: see `shader.wgsl`'s `shadow_tent_near`) + let widen = 1.0 + 3.0 * enh.cloud_sun[1].w; + let close = shadow_close(world, n, ndl, thin); + if (close.y >= 0.999) { + return close.x; + } + let near_lp = camera.light_view_proj * vec4(world + shadow_push_near(n, ndl), 1.0); + let near_uv = vec2(near_lp.x * 0.5 + 0.5, 0.5 - near_lp.y * 0.5); + let near_edge = max(abs(near_uv.x - 0.5), abs(near_uv.y - 0.5)); + let near_valid = near_edge < 0.48 && near_lp.z >= 0.0 && near_lp.z <= 1.0; + var near_slope = shadow_receiver_slope(camera.light_view_proj, n); + var far_slope = shadow_receiver_slope(camera.light_view_proj_far, n); + if (thin) { + near_slope = vec2(0.0); + far_slope = vec2(0.0); + } + // Blend cascades by radial distance, not by the near map's projected square. The + // projected-edge test made the blend factor change when the camera moved sideways or + // turned, even for a stationary receiver; that reads as a full shadow shimmer at the + // cascade boundary. The light boxes still validate coverage above, while this gives + // the overlap a camera-centred, continuous transition. + let radial = distance(world, camera.cam_pos.xyz); + let near_weight = select( + 0.0, + 1.0 - smoothstep(camera.shadow.z * 0.62, camera.shadow.z * 0.92, radial), + near_valid, + ); + // Each cascade is filtered only where it counts: sampling both everywhere (32 compares + // a pixel) halved the enhanced picture's frame rate against shadows off. + var near_value = 1.0; + if (near_weight > 0.001) { + near_value = shadow_pcf_near(near_uv, near_lp.z, near_slope, widen); + } + near_value = mix(near_value, close.x, close.y); + if (near_weight >= 0.999) { + return near_value; + } + let flp = camera.light_view_proj_far * vec4(world + shadow_push_far(n, ndl), 1.0); + let fuv = vec2(flp.x * 0.5 + 0.5, 0.5 - flp.y * 0.5); + let far_valid = fuv.x >= 0.0 && fuv.x <= 1.0 && fuv.y >= 0.0 && fuv.y <= 1.0 && flp.z >= 0.0 && flp.z <= 1.0; + var far_safe = 1.0; + if (far_valid) { + let far_value = shadow_pcf_far(fuv, flp.z, far_slope, widen); + let far_edge = max(abs(fuv.x - 0.5), abs(fuv.y - 0.5)); + far_safe = mix(1.0, far_value, clamp((0.5 - far_edge) * 12.0, 0.0, 1.0)); + } + return mix(far_safe, near_value, near_weight); +} + +// Enhanced+: the solid casters' shadow where no traced one is there for a surface. The close +// and near maps hold only the cut-out casters then (`shadow_plan`), and such a surface - a +// pane, the edge of a step or a handrail thinner than a pixel of the depth prepass - lay in +// the sun under a roof: bright specks and stair-stepped lines along the edges, flickering +// as the camera moved and the traced texel was found or not. The far map keeps them all. +fn sun_shadow_far(world: vec3, n: vec3) -> f32 { + if (camera.shadow.x < 0.5) { + return 1.0; + } + let ndl = clamp(dot(n, camera.sun_dir.xyz), 0.0, 1.0); + let flp = camera.light_view_proj_far * vec4(world + shadow_push_far(n, ndl), 1.0); + let fuv = vec2(flp.x * 0.5 + 0.5, 0.5 - flp.y * 0.5); + if (fuv.x < 0.0 || fuv.x > 1.0 || fuv.y < 0.0 || fuv.y > 1.0 || flp.z < 0.0 || flp.z > 1.0) { + return 1.0; + } + return shadow_pcf_far(fuv, flp.z, shadow_receiver_slope(camera.light_view_proj_far, n), 1.0); +} + +// The sun's shadow at a point by one compare in the finest cascade that holds it (the close +// one, else the near one; lit beyond): for glass (see fs_enhanced). +fn sun_shadow_hard(world: vec3, n: vec3) -> f32 { + if (camera.shadow.x < 0.5) { + return 1.0; + } + let ndl = clamp(dot(n, camera.sun_dir.xyz), 0.0, 1.0); + let range = camera.flags.w; + if (range > 0.0 && distance(world, camera.cam_pos.xyz) < range * 0.75) { + let lp = camera.light_view_proj_close * vec4(world + shadow_push_close(n, ndl), 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (max(abs(uv.x - 0.5), abs(uv.y - 0.5)) < 0.48 && lp.z >= 0.0 && lp.z <= 1.0) { + let scale = select(1.0, camera.post.w, camera.post.w > 0.0); + let a = vec2(uv.x * 0.5 * scale + 0.5, uv.y * scale); + return textureSampleCompareLevel(t_shadow, s_shadow, a, lp.z - SHADOW_BIAS_CLOSE / SHADOW_DEPTH_RANGE); + } + } + let lp = camera.light_view_proj * vec4(world + shadow_push_near(n, ndl), 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (max(abs(uv.x - 0.5), abs(uv.y - 0.5)) < 0.48 && lp.z >= 0.0 && lp.z <= 1.0) { + return textureSampleCompareLevel(t_shadow, s_shadow, vec2(uv.x * 0.5, uv.y), lp.z - SHADOW_BIAS_NEAR / SHADOW_DEPTH_RANGE); + } + return 1.0; +} + +// What a surface reflects and scatters: diffuse albedo, specular colour at normal +// incidence, perceptual roughness. +struct Surface { + albedo: vec3, + f0: vec3, + rough: f32, + // what the specular reflection leaves the diffuse part (`spec_ms`), and the factor + // that gives the specular lobe back the light of its multiple scattering + kd: vec3, + comp: f32, +}; + +// How much of lamp `li` reaches the point (1 for a lamp without a shadow map): its map is +// one of the tiles under the far shadow map (lib.rs `LampShadow`), which the light's record +// names (`light_marks`): looking down from a street lamp's head, or along the road from a +// vehicle's headlamps; a few taps of it soften the edge, as the lamp's glowing bowl does. +// (the player's headlamps - marked so - share one map from between them along the road, +// `passes::headlamp_shadow`; it is read once for the pair, `own_shadow`) +var own_shadow: f32; +fn lamp_shadow_at(li: u32, p: vec3, n: vec3, thin: bool) -> f32 { + let marks = light_marks(lights[li]); + let own = marks.x > 0.5; + if (marks.z < 0.5) { + return 1.0; + } + var k = u32(marks.z - 0.5); + if (own && own_shadow >= 0.0) { + return own_shadow; + } + let to_lamp = p - lights[li].pos.xyz; + // a lamp that shines every way has a block of six tiles, one a direction (+x -x +y -y +z -z, + // lib.rs `CUBE_SLOTS`): the one the lit point lies in + if (k >= 44u) { + let a = abs(to_lamp); + var face = select(5u, 4u, to_lamp.z > 0.0); + if (a.x >= a.y && a.x >= a.z) { + face = select(1u, 0u, to_lamp.x > 0.0); + } else if (a.y >= a.z) { + face = select(3u, 2u, to_lamp.y > 0.0); + } + k = k + face; + } + let d = length(to_lamp); + // (off the surface by a texel or so of the map there; a leaf card towards the lamp) + let off = select(n * (0.03 + 0.012 * d), normalize(lights[li].pos.xyz - p) * 0.3, thin); + let q = camera.lamp_view_proj[k] * vec4(p + off, 1.0); + if (q.w <= 0.0) { + return 1.0; + } + let ndc = q.xyz / q.w; + if (abs(ndc.x) >= 1.0 || abs(ndc.y) >= 1.0 || ndc.z >= 1.0 || ndc.z <= 0.0) { + return 1.0; + } + + let tuv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + // (the far map's texture: its width, its height with the tiles under it; the tile's + // texels in the atlas's terms, kept a texel off its edges) + let dims = vec2(1.0 / camera.shadow.y, camera.lamp_atlas.z); + let tile = camera.lamp_atlas.x; + let cols = camera.lamp_atlas.y; + let tx = clamp(tuv * tile, vec2(1.5), vec2(tile - 1.5)); + let base = vec2(f32(k % u32(cols)) * tile, dims.x + f32(k / u32(cols)) * tile) + tx; + // (nine taps; a saloon's lamp - tiles 28 on - four: its tile's texels are three centimetres + // and every pixel of a saloon takes a handful of lamps) + // (two loops of fixed bounds: one bounded by the tile's kind was not unrolled) + let saloon = k >= 28u && k < 44u; + let zr = ndc.z - 0.00002; + var sum = 0.0; + var taps = 9.0; + if (saloon) { + for (var y = 0; y <= 1; y = y + 1) { + for (var x = 0; x <= 1; x = x + 1) { + let a = (base + (vec2(f32(x), f32(y)) - vec2(0.5)) * 1.25) / dims; + sum = sum + textureSampleCompareLevel(t_shadow_far, s_shadow, a, zr); + } + } + taps = 4.0; + } else { + for (var y = -1; y <= 1; y = y + 1) { + for (var x = -1; x <= 1; x = x + 1) { + let a = (base + vec2(f32(x), f32(y)) * 1.25) / dims; + sum = sum + textureSampleCompareLevel(t_shadow_far, s_shadow, a, zr); + } + } + } + let lit = sum / taps; + if (own) { + own_shadow = lit; + } + return lit; +} + +const CABIN_FILL: f32 = 0.2; + +// How much of the player's saloon lamps' light reaches a point past what stands in it, 1 where +// nothing does: each lamp that has a shadow map (`camera.cabin_lamps`: the first sixteen, by +// their records in the light buffer, -1 for none) weighs by what it would give the point +// unshadowed. The saloon's meshes are lit by the sets of lamps their models name and by light +// maps made for the lamps; this is what lets a handrail or a seat shade what it stands over +// in both. +fn cabin_visibility(p: vec3, n: vec3) -> f32 { + var open_light = 0.0; + var seen_light = 0.0; + for (var i = 0u; i < 16u; i = i + 1u) { + let at = camera.cabin_lamps[i / 4u][i % 4u]; + if (at < 0.0) { + break; + } + let li = u32(at); + let l = lights[li]; + let d = l.pos.xyz - p; + let dist2 = max(dot(d, d), 1e-4); + let ndl = dot(n, d * inverseSqrt(dist2)); + if (ndl <= 0.0 || l.color.w <= 0.0) { + continue; + } + let core = max(l.extra.y, 0.01); + let share = (l.color.r + l.color.g + l.color.b) * l.color.w * core * core / dist2 * ndl; + open_light = open_light + share; + seen_light = seen_light + share * lamp_shadow_at(li, p, n, false); + } + // (the light a closed room's lining sends back where the lamps do not reach: a saloon's + // walls, ceiling and seats, a third reflecting, lit by the lamps again and again - about + // a fifth of what the lit parts have) + let direct = clamp(seen_light / max(open_light, 1e-6), 0.0, 1.0); + return select(1.0, mix(CABIN_FILL, 1.0, direct), open_light > 1e-4); +} + +// A light cookie layer's texels a side (lib.rs `cookies::COOKIE_SIZE`). +const COOKIE_SIZE: u32 = 32u; + +// The enhanced path's marks on a light (lib.rs `prepare_lights`, carried in `pos.w` below +// zero, in steps of 32 for its tile and the low bits below): x 1 for one of the player's +// headlamps, y 1 + the layer of its beam's picture (0: none), z 1 + its shadow map's tile +// (0: none, see `LAMP_MARK`). +fn light_marks(l: PointLight) -> vec3 { + let m = max(-l.pos.w, 0.0); + let tile = floor(m / 32.0); + let rest = m - tile * 32.0; + let own = select(0.0, 1.0, rest > 15.5); + return vec3(own, rest - own * 16.0, tile); +} + +// A light cookie's texel (x, y) of the layer whose records start at `base`. +fn cookie_texel(base: u32, x: u32, y: u32) -> vec3 { + let i = min(y, COOKIE_SIZE - 1u) * COOKIE_SIZE + min(x, COOKIE_SIZE - 1u); + let rec = lights[base + i / 4u]; + let k = i % 4u; + return select(select(rec.pos.xyz, rec.color.xyz, k == 1u), select(rec.dir.xyz, rec.extra.xyz, k == 3u), k >= 2u); +} + +// What a lamp with a picture of its beam (`[spotlight_cookie]`) sends towards `t` (unit, +// from the lamp): the picture's light there, as the beam would show on a wall square to +// the lamp - the picture's right towards the lamp's right as seen from behind it, its top +// up - and nothing outside the field it covers (`camera.cookies`: x, y its half angles' +// tangents, z where its layer starts in the light buffer, four linear texels a record), +// filtered between its four nearest texels. +fn cookie_light(t: vec3, l: PointLight) -> vec3 { + let f = l.dir.xyz; + let ahead = dot(t, f); + let rc = cross(f, vec3(0.0, 0.0, 1.0)); + let r = select(vec3(1.0, 0.0, 0.0), normalize(rc), dot(rc, rc) > 1e-8); + let layer = camera.cookies[min(u32(light_marks(l).y - 0.5), 7u)]; + let q = vec2(dot(t, r), dot(t, cross(r, f))) / (max(ahead, 1e-3) * max(layer.xy, vec2(1e-3))); + let st = clamp(vec2(q.x * 0.5 + 0.5, 0.5 - q.y * 0.5) * f32(COOKIE_SIZE) - vec2(0.5), vec2(0.0), vec2(f32(COOKIE_SIZE) - 1.0)); + let c0 = vec2(st); + let w = st - floor(st); + let base = u32(layer.z); + let top = mix(cookie_texel(base, c0.x, c0.y), cookie_texel(base, c0.x + 1u, c0.y), w.x); + let bottom = mix(cookie_texel(base, c0.x, c0.y + 1u), cookie_texel(base, c0.x + 1u, c0.y + 1u), w.x); + return select(vec3(0.0), mix(top, bottom, w.y), ahead > 1e-3 && all(abs(q) < vec2(1.0))); +} + +// The radiance of the street round the point as the lamps light it (`lamp_light` leaves it +// here): what a reflection pointing at the street and the walls beside it sees at night. +var lamp_ground: vec3; + +// The point and spot lights of the pixel's grid cell: diffuse and specular. +// `thin`: foliage, lit from whichever side the lamp is on (see the sun below). +// `film`: a wet road's film of water - x how much of the surface it is (0: none), y how +// rough it is, z the share of it that mirrors - with which the lamps are reflected as the +// sky is (`refl_rough`, `wet_share` in fs_enhanced), not by the dry surface's own lobe. +fn lamp_light(p: vec3, n: vec3, v: vec3, sf: Surface, thin: bool, shadows: bool, film: vec3, back: bool) -> vec3 { + var sum = vec3(0.0); + lamp_ground = vec3(0.0); + own_shadow = -1.0; + // the lamps' light on the ground round the point (a horizontal surface's, unshadowed: + // the ground the point looks down at is wider than its own shadow) + var ground_e = vec3(0.0); + + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell <= 0.0 || side == 0u) { + return sum; + } + let f = (p.xy - camera.light_grid.xy) / cell; + let x = i32(floor(f.x)); + let y = i32(floor(f.y)); + if (x < 0 || y < 0 || x >= i32(side) || y >= i32(side)) { + return sum; + } + let a = max(sf.rough * sf.rough, 0.02); + let a_film = max(film.y * film.y, 0.02); + let nv = max(dot(n, v), 1e-4); + let facing = select(1.0, 0.0, back); + let base = (u32(y) * side + u32(x)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let d = l.pos.xyz - p; + let dist2 = dot(d, d); + // (pos.w is 0 on a spot light, which the vanilla shader is to pass by) + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let dist = sqrt(dist2); + let ld = d / max(dist, 1e-3); + // inverse-square beyond the core with a soft knee at it, not flat within it; windowed to zero at + // the range so the grid cut-off does not show + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var e = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + // (a lamp's picture of its beam: its colour that way, see `cookie_light`) + var tint = vec3(1.0); + if (l.extra.z != 0.0) { + e = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + let cd = dot(-ld, l.dir.xyz); + if (light_marks(l).y > 0.5) { + tint = cookie_light(-ld, l); + e = e * step(1e-4, max(tint.r, max(tint.g, tint.b))); + } else { + e = e * smoothstep(l.dir.w, l.extra.x, cd); + } + } else if (l.dir.z < -0.5) { + // a lamp in a housing (a street lamp's head, a platform's light): its reflector + // sends the light down and out, its housing keeps it from the sky - a few per + // cent above its horizon, what the bowl and the pole scatter (the upward light + // ratio of road lighting, EN 13201 / CIE 115). Shining evenly every way, every + // lamp lit the crowns of the trees and the upper floors over it as brightly + // as the street. + e = e * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + if (e <= 0.0 || (!(l.extra.z == 0.0 && l.dir.w < -1.5 && l.dir.z < -0.5) && own_vehicle_blocks(p, l.pos.xyz))) { + continue; + } + var irr = l.color.rgb * tint * l.color.w * enh.lights.y * e; + let nl = dot(n, ld); + ground_e = ground_e + irr * max(ld.z, 0.0); + // Ground bounce is unshadowed. A lamp behind an ordinary surface contributes + // no direct light, so it must not sample its shadow map before being rejected. + if (!thin && nl <= 0.0) { + continue; + } + // the lamps' own shadow maps (the few lighting the view most, see `lamp_shadow_at`) + if (shadows) { + irr = irr * lamp_shadow_at(li, p, n, thin); + } + if (thin) { + // a headlamp skims the grass: it lights the tips, not a crown's every side + let wrap = select(0.45 + 0.25 * nl, 0.15 + 0.6 * max(nl, 0.0), l.extra.z != 0.0); + sum = sum + irr * wrap * sf.albedo / PI; + continue; + } + let h = normalize(ld + v); + let nh = max(dot(n, h), 0.0); + let fr = f_schlick(sf.f0, dot(v, h)); + var spec = d_ggx(nh, a) * v_smith(nv, nl, a) * fr; + if (film.x > 0.0) { + spec = mix(spec, d_beckmann(nh, a_film) * v_smith(nv, nl, a_film) * fr * film.z, film.x); + } + spec = spec * facing * sf.comp; + sum = sum + irr * nl * (sf.albedo / PI * sf.kd + spec); + } + // What the lit ground throws back up: a diffuse reflector of the street's albedo (asphalt + // and paving about 0.18, under water darker, fresh snow 0.75), seen by a surface over the + // lower half of its view, (1 - n.z) / 2 of it - a wall half, the underside of a shelter's + // roof all, the ground itself nothing. Without it the lamps lit only what faces them, and + // a facade or a bus's flank beside a lit street stood black. + let snow = clamp(enh.weather.y, 0.0, 1.0); + let rho = mix(0.18, 0.75, snow) * mix(1.0, 0.6, clamp(enh.weather.x, 0.0, 1.0) * (1.0 - snow)); + let seen = select((1.0 - clamp(n.z, -1.0, 1.0)) * 0.5, 0.5, thin); + sum = sum + ground_e * rho * seen * sf.albedo / PI; + lamp_ground = ground_e * rho / PI; + return sum; +} + +// The relief a rough surface has under its microfacets - asphalt's grit and chippings, a +// paving stone's dressing, a cobble's dome (slopes of a quarter and more, at millimetres to +// centimetres) - shadows and masks itself (Smith's function for that slope spread, +// height-correlated) towards a light and an eye low over it. GGX's own roughness is the +// grain under that; on its own it let a low sun's grazing glint off every rough road and +// wall shine white towards the camera, where a real road keeps it dull. The spread grows +// with the rougher surface, and with the patch the pixel covers: farther off, the road's +// waves and ruts are under the pixel too. A smooth surface is left as it is. +fn relief_masking(nl: f32, nv: f32, rough: f32, footprint: f32) -> f32 { + let s2 = 0.0625 * smoothstep(0.45, 0.85, rough) + 0.02 * smoothstep(0.01, 0.12, footprint) * smoothstep(0.45, 0.7, rough); + if (s2 <= 0.0) { + return 1.0; + } + // (Smith's Lambda for a slope variance s2: (sqrt(1 + s2 tan^2) - 1) / 2) + let ml = clamp(nl, 1e-3, 1.0); + let mv = clamp(nv, 1e-3, 1.0); + let ll = 0.5 * (sqrt(1.0 + s2 * (1.0 - ml * ml) / (ml * ml)) - 1.0); + let lv = 0.5 * (sqrt(1.0 + s2 * (1.0 - mv * mv) / (mv * mv)) - 1.0); + return 1.0 / (1.0 + ll + lv); +} + +// The light inside a cab relative to the average light outside: a bus's big windows let in +// most of the sky, and the dashboard lies right under the windscreen. +const CAB_AMBIENT: f32 = 1.15; + +// How far the puddle threshold drops with the wetness: see the puddle mask in `shade_enhanced`. +const PUDDLE_SPREAD: f32 = 0.37; + +/// The mip level a pixel's footprint asks for, in levels of the texture whose size is +/// `texels` (the usual `log2` of the larger derivative, held at 0 and up). An LED panel is +/// sampled with this, held at `enh.led.y` (`Lighting::led_mips`): 0 point-samples it, which +/// is the sharpest and shimmers worst - a regular dot grid is the worst case for a point +/// sample - and every level the chain is allowed to take is a 2x2 average that a point +/// sample of the level below does not have. (The derivatives have to be taken in uniform +/// control flow: the panels are per draw, so a call inside the material's branch is not.) +fn led_lod(uv: vec2, texels: vec2) -> f32 { + let dx = dpdx(uv) * texels; + let dy = dpdy(uv) * texels; + return max(0.5 * log2(max(dot(dx, dx), dot(dy, dy))), 0.0); +} + +// A tangent-space normal `tn` (a PBR normal map's) turned into the world about the +// surface normal `n`, with the tangent frame taken from how the position and the uv change +// across the pixel (no tangents in OMSI's meshes). `tn.y` down the texture, as Direct3D's +// normal maps have it. +fn perturb_normal(n: vec3, p: vec3, uv: vec2, tn: vec3) -> vec3 { + let dp1 = dpdx(p); + let dp2 = dpdy(p); + let duv1 = dpdx(uv); + let duv2 = dpdy(uv); + let dp2perp = cross(dp2, n); + let dp1perp = cross(n, dp1); + let t = dp2perp * duv1.x + dp1perp * duv2.x; + let b = dp2perp * duv1.y + dp1perp * duv2.y; + let m = max(dot(t, t), dot(b, b)); + if (m < 1e-20) { + return n; + } + let k = inverseSqrt(m); + return safe_normal(t * k * tn.x + b * k * tn.y + n * max(tn.z, 0.05)); +} + +// The enhanced pass's two targets: the picture, and the screen mask (r: 1 on the bus's own +// screens, carried by the coverage of what is drawn over them; g: 1 on an LED panel's own +// dots, 0.25 on other screens, see MASK_FORMAT; b is wet puddles' reflected-light weight). +struct EnhancedOut { + @location(0) color: vec4, + @location(1) mask: vec4, + @location(2) gbuf: vec4, + @location(3) aux: vec4, +}; + +// Enhanced+ (the window's picture, camera.clouds.w 2): the surface the traced reflections +// start from - its normal and how much of the reflection lands on the screen (w), its +// distance from the eye and its roughness, all times that weight (see GBUF_FORMAT). The +// probe's reflection is left out of the colour there: the traced one is added in its place. +var rt_gbuf: vec4; +var rt_aux: vec4; + +fn enhanced_surface(in: FsIn) -> EnhancedOut { + rt_gbuf = vec4(0.0); + rt_aux = vec4(0.0); + var puddle_weight = vec2(0.0); + let c = shade_enhanced(in, &puddle_weight, false, camera.cam_pos.xyz); + let screen = material.flags.x > 0.5; + // an LED panel's dots stay in the glow's source (`post.wgsl`), the other screens' + // letters stay out of it + let led = select(0.0, 1.0, material.emissive.w < -1.5); + var out: EnhancedOut; + out.color = c; + // Non-LED screens carry g = r / 4. The ratio survives a clear pane's coverage + // blending, so a faded screen marker cannot be mistaken for condensation. + // Water keeps its occluded sky weight in g and reflection weight in b. + // A vehicle's shadow is light blocked from the road, not a new dry surface. Its + // colour still blends normally, but it must preserve the road's reflection mask. + // A transparent screen layer must leave the masks underneath intact. Otherwise + // unused LED colour layers make the whole panel's background bloom as lit dots. + let coverage = select(c.a, 0.0, in.params2.w > 1.5); + // (r under 0.5: how much light the player's bus's misted glass scatters there, for the + // tone mapping's blur - post.wgsl `misted`. The mask is blended by the coverage, so the + // share is divided by it to land as MIST_MASK x the share over what lies behind; + // a misted pane's coverage is at least half its share, see `shade_enhanced`) + let mist = select(0.0, glass_fog * MIST_MASK / max(coverage, 1e-3), glass_fog > 0.001); + let screen_code = select(0.25, 1.0, led > 0.5); + out.mask = vec4(select(min(mist, 0.49), 1.0, screen), select(max(led, puddle_weight.y * 0.49), screen_code, screen), puddle_weight.x, coverage); + out.gbuf = rt_gbuf; + out.aux = rt_aux; + return out; +} + +@fragment +fn fs_enhanced(in: FsIn) -> EnhancedOut { + return enhanced_surface(in); +} + +// A headset uses mapped shadows, not screen-space ray reflections. Its colour +// pass needs only colour and the screen mask, even on an Enhanced+ renderer. +struct EnhancedColorOut { + @location(0) color: vec4, + @location(1) mask: vec4, +}; + +@fragment +fn fs_enhanced_color(in: FsIn) -> EnhancedColorOut { + let surface = enhanced_surface(in); + return EnhancedColorOut(surface.color, surface.mask); +} + +// A self-lit picture (a display, a light-mapped surface lit fully) at its own colour after +// the tone curve (post.wgsl `natural_tone`): it bleaches what is brighter than its knee - +// a display's yellow-green text came out olive - and gives the middle tones the contrast +// of `enh.debug.w` about mid grey. So the colour is kept under the knee and the contrast +// undone in advance (with the small black offset the text has always been drawn with). +// A display's own brightness for the light round it: as a bus's screens dim at night, to +// 15 % of the day's, and never lifted over their own colour by the dark-adapted metering. +fn display_dim(lift: f32) -> f32 { + let night = clamp(camera.sun_color.w, 0.0, 1.0); + return mix(lift, min(lift, 1.0) * 0.15, night); +} + +fn display_level(t: vec3) -> vec3 { + let peak = max(t.r, max(t.g, t.b)); + let tk = t * min(1.0, 0.64 / max(peak, 1e-3)); + let c = max(enh.debug.w, 1.0); + let x = 0.18 * pow(tk / 0.18 + vec3(1e-7), vec3(1.0 / c)); + return x + 0.04 * smoothstep(vec3(0.0), vec3(0.08), x); +} + +// [matl_glow] (see MaterialExtra::glow): the material is its own light. `buv` is where its +// mask is read (the light map's own coordinate, the slot it rides in) and `col` the colour +// the light is drawn in - the material's own, so a destination panel keeps the colour its +// display draws. The mask is a greyscale picture of how much shines where (white full, black +// none). The strength is the mod's own (the .cfg value x0.25, on the scale of the LED +// panels' `Led glow`) and is held against the metering as an LED panel's dots are; the +// glare round it comes from how bright it is, as every light's does (post.wgsl). +fn matl_glow_light(buv: vec2, col: vec3) -> vec3 { + let gm = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], buv, camera.lod.x); + return col * dot(gm.rgb, vec3(0.299, 0.587, 0.114)) * material.glow.x * max(enh.exposure.z * 2.0, 0.8); +} + +// How much of the light crossing the player's bus's pane its condensation scatters (0..1, +// 07_glass.wgsl `glass_condensation`), for the screen mask. +var glass_fog: f32; +// The screen mask's r for a pane scattering all the light (post.wgsl `MIST_MASK`). +const MIST_MASK: f32 = 0.24; +// Heading, pitch and roll: with the heading alone the film slid along the glass on a hill (#3958). +fn pane_local(world: vec3) -> vec3 { + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let v = vec3(d.x * ch - d.y * sh, d.x * sh + d.y * ch, d.z); + let t = enh.pane_tilt; + let p = vec3(v.x, v.y * t.y + v.z * t.x, v.z * t.y - v.y * t.x); + let b = vec3(p.x * t.w - p.z * t.z, p.y, p.z * t.w + p.x * t.z); + return b - camera.inside_c.xyz; +} + +fn shade_enhanced(in: FsIn, puddle_weight: ptr>, capture: bool, eye: vec3) -> vec4 { + // (the pane's water, read once for the uses below) + let film_water = window_wetness(in); + if (material.emissive.w > 1.5) { + // a pane's film of water: drops laid out on the glass, each a lens that mirrors the + // sky probe and shows the street upside down through itself, and the haze of the wet + // glass between them (07_glass.wgsl `glass_film`) + return glass_film(in, film_water); + } + // --- the surface's texture and alpha, exactly as the vanilla pass reads them + let terrain = material.extra.x > 0.5; + var duv = tex_address(in.uv); + if (terrain) { + duv = in.uv * material.extra.z; + } + // (without the [texcoordtransX/Y] offset: the transmap, night map and light map stay + // in place, see fs_main) + let buv = tex_address(in.uv - in.params.zw); + let msk_lod = led_lod(buv, vec2(textureDimensions(mx_tex2d[mx_mat.trans]))); + // Empty paint also needs no tiled diffuse or detail samples. Its brush mask + // replaces diffuse alpha, so coverage can be checked before those reads. + if (TERRAIN_PAINT && material.params.x > 1.5 && material.params.z > 0.5 + && material.params.w > 0.5 && enh.debug.x <= 0.5 && material.ambient.w <= 1.5) { + var coverage = sample_transmap(buv).a; + if (material.emissive.w < -1.5 && enh.led.y < msk_lod) { + coverage = textureSampleLevel(mx_tex2d[mx_mat.trans], mx_samplers[mx_mat.sampler], buv, enh.led.y).a; + } + coverage = smoothstep(0.32, 0.68, coverage); + if (coverage * material.color.a * in.params.x == 0.0) { + discard; + } + } + // An LED panel is sampled at the level its screen footprint asks for, held at + // `enh.led.y` (`Led mip strength`): its dots keep their gaps much further out than the + // full chain allows, and the shimmer is a fraction of a full-resolution sample's. The + // levels are worked out here and not inside the branch: derivatives are undefined in + // non-uniform control flow, and which of the two samples runs is per draw. When the + // setting does not bite, the plain (anisotropic) sample of the hardware is the better + // one and stays. + let pic_lod = led_lod(duv, vec2(textureDimensions(mx_tex2d[mx_mat.diffuse]))); + let led_pic = material.emissive.w < -1.5 && enh.led.y < pic_lod; + // The painted ground's albedo comes from the picture `fs_ground` laid (the base's and its + // layers', the frame's `camera.lod.y`): the terrain's base is lit once for all of them. + // (A condition of the draw alone, so the texture reads below stay in uniform control flow; + // `Renderer::plan_ground` has seen to it that every draw this holds for is in that picture.) + let from_ground = camera.lod.y > 0.5 && terrain && !TERRAIN_PAINT && !capture && material.params.x < 0.5 && material.params.z < 0.5; + var tex = vec4(1.0); + if (from_ground) { + tex = vec4(textureLoad(t_ao, vec2(in.clip.xy), 0).rgb, 1.0); + } else { + tex = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv); + if (is_snow_pane()) { + tex = glass_snow(in, film_water); + } + if (led_pic) { + tex = diffuse_border(textureSampleLevel(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, enh.led.y), duv); + } + } + let diffuse_a = tex.a; + if (terrain && !from_ground && material.extra.y > 0.0) { + let det = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], in.uv * material.extra.y, camera.lod.x); + tex = vec4(clamp(tex.rgb * det.rgb, vec3(0.0), vec3(1.0)), tex.a); + } + if (material.params.z > 0.5) { + // (an LED panel's `\S:n` mask is taken the same way: the dots stay dots when the + // panel is small, without the full-resolution shimmer) + var tm = sample_transmap(buv); + if (material.emissive.w < -1.5 && enh.led.y < msk_lod) { + tm = textureSampleLevel(mx_tex2d[mx_mat.trans], mx_samplers[mx_mat.sampler], buv, enh.led.y); + } + tex.a = select(1.0, tm.a, material.params.w > 0.5); + if (terrain && material.params.x > 1.5) { + // Coverage belongs to the brush mask, not the angle-dependent diffuse mip. + tex.a = smoothstep(0.32, 0.68, tex.a); + } + } + // One night-map read supplies both coverage and lighting. Keep the tile map + // in its north-up UVs; vehicle maps use the unscrolled material UVs. + var night_sample = vec4(0.0); + if (material.extra.w > 0.5) { + let nuv = select(buv, vec2(in.uv.x, 1.0 - in.uv.y), terrain); + night_sample = sample_nightmap(nuv); + } + tex.a = night_coverage(tex.a, night_sample.a) * tree_card_fade(in.world); + let mode = material.params.x; + // Keep the filtered fractional coverage, but tighten its transition around the cutout + // edge before MSAA turns it into sample coverage. The MSAA depth prepass skips these + // draws so uncovered samples keep the depth and colour of the scene behind them. + if ((ALPHA_TEST || capture) && mode > 0.5 && mode < 1.5) { + if (ALPHA_TO_COVERAGE) { + let aa = max(fwidth(tex.a) * 0.5, 1.0 / 255.0); + // (not `ALPHA_REF - aa`: a layer whose clear glass is alpha 128 kept a third of + // its samples there, a moire of the layer's paint over every window) + if (tex.a < ALPHA_REF) { + discard; + } + tex.a = smoothstep(ALPHA_REF - aa, ALPHA_REF + aa, tex.a); + } else if (tex.a < ALPHA_REF) { + discard; + } + } + // (a blended slot that keeps Omsi.exe's alpha test, `MaterialExtra::alpha_cut`: a + // livery's clear glass is cut away, its tinted glass blended) + tex.a = select(tex.a, 0.0, mode > 2.5 && tex.a < ALPHA_REF); + var alpha = tex.a * material.color.a; + if (mode < 0.5) { + alpha = 1.0; + } + if (!is_snow_pane()) { + alpha = alpha * clamp(film_water, 0.0, 1.0); + } + // Sparse brush masks still cover the whole tile mesh. Empty pixels contribute + // neither colour nor reflection coverage, so avoid lighting them. Keep fractional + // edges, debug views, and water (whose Fresnel can raise zero alpha) unchanged. + if (TERRAIN_PAINT && alpha == 0.0 && enh.debug.x <= 0.5 && material.ambient.w <= 1.5) { + discard; + } + let pre = enh.exposure.x; + let to_cam = eye - in.world; + let dist = length(to_cam); + let v = to_cam / max(dist, 1e-4); + let h_cam = camera.cam_pos.z - enh.fog.z; + let h_pt = in.world.z - enh.fog.z; + // (no fog inside the cab: only the part of the way outside the bus is misty) + // (the lamps' light in the fog is added over the whole picture afterwards: fog_lamps.wgsl) + let aer = air(-v, fog_distance(in.world), h_cam, h_pt); + if (in.params2.w > 1.5) { + // A vehicle's shadow blob is no surface: it is the sky light the body keeps off the + // road, a layer that only darkens what lies under it (as OMSI blends it). Shaded as + // a black surface it took the sky, the wet road's sheen and the lamps on top and + // hardly darkened anything. The air in front of it stays (the road's own fog, under + // the blob, is darkened with it as in the original). + return vec4(aer.rgb * pre, alpha * aer.a); + } + if (material.params.y > 0.5) { + // unlit (mirror glass, script and text textures): shown at their own brightness, + // under the tone curve's knee (`display_level`), and `exposure.y` undoes the + // metering (see ExposureLog in lib.rs) + let t = tex.rgb * material.color.rgb; + // A mirror (params.y 0.9) is no display: its picture is the street drawn a moment + // ago, dark at night. Brightened like a display by the metering (up to 1.6 in the + // dark) it showed a street far brighter than the one through the windscreen. + let lift = select(display_dim(enh.exposure.y), min(enh.exposure.y, 1.0), material.params.y < 0.95); + // (no [matl_glow] here: an unlit slot is drawn at its own brightness already, and + // reading the light map's slot in this branch failed Metal's shader compiler) + let c = display_level(t) * lift; + return vec4(c * aer.a + aer.rgb * pre, alpha); + } + let outside = weather_outside_n(in.world, safe_normal(in.normal), terrain, in.params2.w); + // the normal as the content gives it: never turned towards the viewer (Direct3D does + // not either, and OMSI's foliage points every leaf's normal up so the whole crown is lit + // evenly - turned round, the crown went dark above the horizon line) + var n = safe_normal(in.normal); + // the map's water (`MaterialExtra::water`): small waves running over it ripple its + // normal - fading with the distance, where they would only flicker - so that what it + // mirrors breaks up as on a lake instead of standing in it as in a pane of glass (#841) + let is_water = material.ambient.w > 1.5; + if (is_water) { + n = normalize(n + vec3(water_ripple(world_pattern_xy(in.world), camera.post.y) * clamp(1.0 - dist / 250.0, 0.2, 1.0), 0.0)); + } + // Leaves and fences transmit light. A terrain road-cut mask only removes ground: + // its remaining pixels must shade like the uncut ground on terrain-mapped splines. + // (people's cut-out hair and clothes are bodies: material flag 8) + let thin = !terrain && mode > 0.5 && mode < 1.5 && (u32(material.params2.w + 0.5) & 8u) == 0u; + let has_env = material.params2.y > 0.0; + // A blended transmap body is a masked paint surface, not glass. Traffic cars often + // use this material layout for their body; depth-disabled blends remain glass. + // Window assets are not consistent about carrying an envmap. The reliable signal + // is an explicitly named window, or a depth-disabled blended layer with env/transmap + // data that identifies a pane rather than a dirt/text overlay. This keeps bus + // panes on the reflection/transmission path after the material-depth repair. + // Painted terrain also blends a transmap without writing depth. It is never glass: + // Fresnel opacity on its empty mask pixels darkens every lower layer at grazing angles. + // A script's screen is never a pane, though it is laid out as one - blended, not writing + // depth, its letters a `\S:n` transparency map: the EMT Citaro's Krueger matrix + // (Mallorca) was taken for glass, which gives no light of its own, and its letters stayed + // grey at night while its light map lit them in Vanilla+ (#2927). + let glass = !terrain && mode > 1.5 && (material.bump.z > 0.5 || material.emissive.w > 0.5) && + (has_env || material.params.z > 0.5 || material.emissive.w > 0.5) && material.flags.x < 0.5; + // An envmap on opaque vehicle paint is legacy material data, not a request to make + // the whole body behave like glass. Keep the diffuse/sun response, but use the + // ordinary rough dielectric path for the body. + // Foliage and other alpha-tested assets are diffuse silhouettes, not polished surfaces. + // Letting the generic probe term reflect them creates white sparkles at grazing angles; + // the photographed envmap is reserved for materials that explicitly request it. + // (opaque materials reflect as well - chrome handrails, bumpers and wheel trims are + // opaque with a sphere map, and left out they showed no reflection at all in the + // enhanced picture, #266 - but through the clear-coat path below: metal only where a + // mask of its own says so) + // (not the water: its sphere map is OMSI's stand-in for the sky it mirrors, which the + // probe holds itself - drawn as paint's photo, it lay on the water as green specks) + // (a body painted through a [matl_transmap] too - most mod buses' and cars' paint, + // the W123's: its alpha is the transmap's, the envmap's mask the texture's own, as in + // the vanilla picture; left out, their paint showed no reflection at all while their + // windows did) + let reflective_env = has_env && !thin && !is_water; + // see-through glass is seen from either side: from inside the bus its normal points + // away (the vanilla pass takes the angle either way round too); taken as it is, the + // grazing Fresnel turned the whole windscreen into a milky mirror + var geo_n = n; + if (glass && dot(n, v) < 0.0) { + n = -n; + geo_n = n; + } + var face_n = n; + var face_v = 0.0; + var face_w = 1.0; + if (reflective_env && !glass && !terrain) { + let c = cross(dpdx(in.world), dpdy(in.world)); + if (dot(c, c) > 1e-14) { + let face = normalize(c) * select(-1.0, 1.0, dot(c, v) >= 0.0); + face_n = face; + face_v = dot(face, v); + face_w = smoothstep(0.5, 0.9, dot(n, face)); + } + } + if (reflective_env && material.bump.y > 0.5) { + // [matl_bumpmap]: the height map's slope bends the normal (tangent frame from the + // screen-space derivatives of position and texture coordinate) + let slope = bump_offset(duv); + let dp1 = dpdx(in.world); + let dp2 = dpdy(in.world); + let du1 = dpdx(duv); + let du2 = dpdy(duv); + let dp2p = cross(dp2, n); + let dp1p = cross(n, dp1); + let t = dp2p * du1.x + dp1p * du2.x; + let b = dp2p * du1.y + dp1p * du2.y; + let inv = inverseSqrt(max(max(dot(t, t), dot(b, b)), 1e-12)); + n = normalize(n - (t * inv * slope.x + b * inv * slope.y) * 0.6); + } + var albedo = select(tex.rgb * material.color.rgb, tex.rgb, from_ground); + // OMSI materials have separate diffuse and ambient colours. Some interiors have + // black diffuse but white ambient: using diffuse for both made them pitch black. + // Keep the direct response, and weather both colours with the same surface effects. + // A slot without a texture (ambient.w -1) takes its diffuse colour for both: Omsi.exe's + // white ambient of every o3d slot under a strong sky turned a coloured model white (#1737). + var ambient_albedo = select(tex.rgb * material.ambient.rgb, albedo, material.ambient.w < -0.5 || from_ground); + var detail_factor = 1.0; + if (camera.flags.x > 0.5 && (terrain || in.params2.w > 0.5)) { + let k = clamp(1.0 - (dist - 25.0) / 120.0, 0.0, 1.0); + let pattern_xy = world_pattern_xy(in.world); + detail_factor = 1.0 + (detail_noise(pattern_xy, k) - 0.5) * 0.42 * k; + albedo = albedo * detail_factor; + ambient_albedo = ambient_albedo * detail_factor; + } + // --- the material in physical terms + var refl = 0.0; + if (reflective_env) { + // (with a mask of its own or a [matl_transmap] the share is the mask's alone, as + // Omsi.exe's stage takes it - the factor counts only where there is none) + let by_mask = material.params.z > 0.5 || (u32(material.params2.w + 0.5) & 1u) != 0u; + refl = clamp(select(min(material.params2.y, 1.0), 1.0, by_mask) * reflection_mask(duv, diffuse_a), 0.0, 1.0); + } + var metal = 0.0; + var f0 = vec3(0.04); + var rough = 0.8; + let probe_only = camera.clouds.w < 1.5; + if (terrain) { + rough = 0.92; + f0 = vec3(0.03); + } else if (glass) { + // OMSI's window materials are deliberately very transparent. Raise the base + // dielectric reflection slightly so the outside scene remains readable through + // the pane instead of leaving a flat pale surface at normal incidence. + rough = 0.04; + // the pane's [matl_envmap] factor says how much it mirrors (its alpha is its + // transparency, never a mask): from glass's own 4 % up to 12 % for a factor of 1 + // (0.4 on the Scania's panes). Up to 26 % as before, every window of every bus + // was a mirror - far more than the original's panes reflect (issue #176). + // ... measured against the vanilla picture: Omsi.exe lays the sphere map over the + // pane by its factor and the pane shows that as faintly as it shows itself - the + // share it mirrors is the pane's alpha times the factor (0.25 .. 0.5 on the stock + // windows), at every angle, with no Fresnel term. Taken as the reflectance + // averaged over the angles (Schlick's mean, f0 + (1 - f0) / 21, as for the paint), + // the pane mirrors as much as there and rises towards grazing as glass does; 4 to + // 12 % at the normal, and three quarters of that, left the windows showing the + // saloon where the vanilla picture shows the street. + let share = clamp(alpha * min(material.params2.y, 1.0), 0.0, 1.0) * camera.cam_pos.w; + f0 = vec3(select(clamp((share - 1.0 / 21.0) * 21.0 / 20.0, 0.04, 0.9), 0.04, probe_only)); + } else if (reflective_env) { + // Paint reflects its few per cent through a smooth clear coat; much more than a few + // per cent is polished metal - but only where the model says so with a mask of its + // own ([matl_envmap_mask]). Nearly every car body carries `[matl_envmap] … 1` with + // no mask, which OMSI takes as "reflect the sphere map fully" and not as chrome: + // read as metalness it made a Golf's bonnet a mirror, in which the envmap photo's + // trees stood as contour lines across the paint at close range. + // + // The paint itself is a clear coat: a lacquer of refractive index 1.5 (4 % at normal + // incidence, Fresnel's 100 % at grazing) polished smooth, which mirrors the street + // as sharply as the windows do. How much of the sphere map OMSI lays over a + // material says how glossy it is: the stock bodies carry 1 or 10, the cabin's + // panels, frames and plastic trim 0.05 .. 0.2 - satin, a blurred sheen; the mask + // (the texture's alpha) says where. (Roughness + // 0.22 for every body, against the photo's contour lines on a car's bonnet, left + // the paint matte beside its sharp windows.) + let masked = (u32(material.params2.w + 0.5) & 1u) != 0u; + let metal_ok = (u32(material.params2.w + 0.5) & 4u) != 0u; + metal = select(0.0, smoothstep(0.3, 0.85, refl), masked || metal_ok); + // The coat is as smooth as lets it mirror, averaged over the angles, the share + // Omsi.exe lays over it: a polished 4 % coat mirrors 8.7 % on average (Fresnel's + // rise at grazing), a rough one less (2.5 % at 0.8, its grazing light scattered and + // shadowed by its own roughness). So a share of 8.7 % and more is smooth lacquer, the + // stock bodies' few per cent - the MAN NL's 15 of 255 - a satin one (taken as rough + // up to a share of a half they came out matte, #2067; smooth from 4 %, a body meant + // to mirror barely shone like glass against the light, #2474), and where the mask + // says nothing reflects - a tyre or a seal - the rough rubber or plastic it is. + // Between those and chrome, the share says how much the paint mirrors, not how + // sharply: Omsi.exe lays a soft sphere map over it, a blurred sheen of the sky. Taken + // as polished glass from 8.7 % on (0.2.42), the many mod bodies whose texture alpha + // holds a tenth to a half mirrored the grey sky like chrome - silver buses and AI + // cars that glowed (#2563, #2301). Only a share near the whole is a sharp mirror. + let coat_rough = max(clamp(0.06 + (0.087 - refl) * 11.9, 0.06, 0.8), mix(0.3, 0.06, smoothstep(0.5, 0.95, refl))); + // Where the model says how much it mirrors - a [matl_envmap_mask], or the texture's + // alpha under a [matl_transmap] (most mod bodies) - Omsi.exe lays the sphere map + // over the paint by that share at every angle (shader.wgsl's environment stage): + // OMSI has no Fresnel term, so the share is the reflectance averaged over the angles + // the surface is seen at. A Fresnel reflectance with that average (Schlick's, whose + // hemispherical mean is f0 + (1 - f0) / 21) mirrors as much as the vanilla picture + // and rises towards grazing as a real coat does. (A plain 4 % coat left those + // bodies far fainter than in the vanilla picture.) A body with neither keeps the + // lacquer's 4 %: there Omsi.exe's lerp by the factor alone made every Golf a mirror. + let authored = masked || material.params.z > 0.5; + let coat = select(0.04, clamp((refl - 1.0 / 21.0) * 21.0 / 20.0, 0.04, 0.95), authored); + f0 = mix(vec3(coat), mix(albedo, vec3(1.0), 0.4) * refl, metal); + rough = mix(coat_rough, 0.14, metal); + } else if (!thin && material.specular.w > 0.0 && dot(material.specular.rgb, vec3(1.0)) > 0.05) { + // the o3d material's Blinn-Phong power as GGX roughness + rough = clamp(sqrt(sqrt(2.0 / (material.specular.w + 2.0))), 0.4, 0.9); + } else if (thin) { + rough = 0.7; + } + if (is_water) { + // water: a dielectric of 2 % at normal incidence, nearly a mirror where it is seen + // flat, smooth but for its waves + f0 = vec3(0.02); + rough = 0.06; + metal = 0.0; + } + // --- a PBR set beside the diffuse texture (`foo_n.png`, `foo_r` / `_m` / `_ao` or + // `foo_orm`: see omsi_texture::pbr): the normal map bends the normal, the packed map + // gives the occlusion, roughness and metalness in place of the guesses above + var pbr_ao = 1.0; + if (material.pbr.x > 0.5 && !terrain) { + var tn = textureSampleBias(mx_tex2d[mx_mat.pbr_normal], mx_samplers[mx_mat.sampler], duv, camera.lod.x).xyz * 2.0 - vec3(1.0); + // (an OpenGL-style map, green up: `_gl` in its name) + if (material.pbr.x > 1.5) { + tn.y = -tn.y; + } + n = perturb_normal(n, in.world, duv, tn); + } + if (material.pbr.y + material.pbr.z + material.pbr.w > 0.5 && !terrain) { + let orm = textureSampleBias(mx_tex2d[mx_mat.pbr_orm], mx_samplers[mx_mat.sampler], duv, camera.lod.x).rgb; + if (material.pbr.y > 0.5) { + pbr_ao = orm.r; + } + if (material.pbr.z > 0.5) { + rough = clamp(orm.g, 0.03, 1.0); + } + if (material.pbr.w > 0.5) { + metal = orm.b; + f0 = mix(vec3(0.04), albedo, metal); + } + } + // rain: roads with [moisture] turn dark and smooth, everything outside a little glossier + // (not under snow: a snowy road took the rain's gloss and the snow on it shone like + // plastic in every headlight) + let dry_snow = 1.0 - clamp(enh.weather.y, 0.0, 1.0); + let wet_road = camera.shadow.w * material.params2.z * outside * dry_snow; + let wet_any = camera.shadow.w * outside * select(0.35, 0.0, glass) * dry_snow; + var puddle = 0.0; + if (wet_road > 0.0) { + albedo = albedo * mix(1.0, 0.5, wet_road); + ambient_albedo = ambient_albedo * mix(1.0, 0.5, wet_road); + rough = mix(rough, 0.12, wet_road); + f0 = mix(f0, vec3(0.02), wet_road); + // Puddles: standing water pools in low, flat spots rather than spreading evenly + // over the whole carriageway the way the sheen above does. A world-space mask at a + // frequency of its own (unrelated to the road's detail noise, so the two do not + // look tied together) picks out patches that grow with the wetness and vanish again + // as the road dries; a puddle goes glass-flat and mirrors what is above it. While it + // is actually raining rather than merely wet, and never while it is snow settling + // instead (`enh.weather.z` is fed by any precipitation, `.y` singles snow back out), + // concentric rings cross a puddle where drops land, fading as they widen - the other + // half of the wheel splashes in `puddles.rs`. + let pattern_xy = world_pattern_xy(in.world); + // (the pools: see `road_puddle_coverage`, shared with the classic picture) + puddle = road_puddle_coverage(in.world, n, wet_road); + if (puddle > 0.001) { + // A drop is a few millimetres across and its ring dies away within a hand's + // breadth, so the shared ripple grid is 12.5 cm wide and a ring grows + // to RIPPLE_MAX of a cell, about 5 cm: at 2 m cells with rings a metre and a half + // across, every drop looked like a puddle of its own. Cells run at their own pace + // and only some of them carry a drop at a time, so the surface reads as many small + // impacts rather than one pulsing pattern. + let raining = enh.weather.z * (1.0 - enh.weather.y); + // (faded out where the pixel is wider than half a ring's wave: past a few + // metres they only made the water shimmer) + let ripple_fp = max(length(dpdx(in.world)), length(dpdy(in.world))); + let ripple = puddle_ripple_seen(pattern_xy, camera.post.y, raining, puddle, ripple_fp); + // Standing water hides most of the fine asphalt grain. Keep dry and damp + // asphalt's detail, but let the reflected image read across a filled pool. + albedo = albedo * (1.0 - 0.68 * puddle) / mix(1.0, detail_factor, puddle * 0.8); + ambient_albedo = ambient_albedo * (1.0 - 0.68 * puddle) / mix(1.0, detail_factor, puddle * 0.8); + rough = clamp(mix(rough, 0.03, puddle) - ripple.z * 0.12, 0.02, 1.0); + f0 = mix(f0, vec3(enh.debug.y), puddle); + n = normalize(mix(n, geo_n, puddle) + vec3(ripple.xy, 0.0)); + } + } else if (wet_any > 0.0) { + // (a body's paint wears a film of water as smooth as glass: the street and the sky + // mirror in a wet bus as sharply as in its windows) + // (Lagarde's wet surfaces: the water stands on what faces up and runs off a wall, + // so a wall only darkens where a ledge or a step goes glossy) + let up = smoothstep(0.1, 0.9, geo_n.z); + // (the rougher, the more porous - soil, plaster, unglazed stone - and the more water + // it takes in; a smooth, sealed surface keeps its colour under the film) + let porous = smoothstep(0.25, 0.7, rough); + if (!terrain) { + rough = mix(rough, select(mix(rough * 0.75, min(rough, 0.2), up), min(rough, 0.04), reflective_env), select(wet_any, min(wet_any * 2.6, 1.0), reflective_env)); + } + // Soaked by the rain, a porous surface - soil, a paving stone, plaster, bark - + // turns darker and deeper in colour: the light that enters the water film and is + // scattered back by the surface under it is partly reflected down again at the + // film's top (total internal reflection), and meets the surface once more, which + // absorbs a share of it each time (Lekner and Dorf, "Why some things are darker + // when wet", Applied Optics 1988). Painted metal, glass and leaves shed the water. + let soak = camera.shadow.w * outside * dry_snow * select(0.75, 1.0, terrain) * mix(0.3, 1.0, porous) + * mix(0.45, 1.0, clamp(n.z, 0.0, 1.0)) * select(1.0, 0.0, reflective_env || glass || is_water || thin || metal > 0.5); + albedo = mix(albedo, wet_albedo(albedo), soak); + ambient_albedo = mix(ambient_albedo, wet_albedo(ambient_albedo), soak); + } + // snow lies on what faces up + // (not on a shadow blob: whitened, it lit the snow under the bus instead of shading it) + // (nor on a texture that is the season's snow picture, which shows the map's own snow + // as OMSI 2 does: see the vanilla shader, #879) + let snow_ok = outside * select(1.0, 0.0, in.params2.w > 1.5 || material.ambient.w > 0.5); + // a carriageway under snow that builds up: its own cover, ruts and tracks (road_snow.wgsl) + let carriageway = !terrain && material.params2.z > 0.0 && road_snow_dynamic(); + var rs = vec3(0.0); + if (carriageway && snow_ok > 0.0) { + rs = road_snow(in.world); + } + // a vehicle's part: the snow its own roof has gathered, where that is kept (another + // player's bus keeps the weather's) + let vehicle = vehicle_snow_kept(in.params2.w); + var on_vehicle = 0.0; + if (vehicle && snow_ok > 0.0) { + on_vehicle = vehicle_snow(in.params2.w, in.local); + } + let snow = select(select(enh.weather.y, rs.x, carriageway), on_vehicle, vehicle) * snow_ok; + if (rs.y > 0.0) { + // the slush in the ruts and the tracks: wet and grey, darker than the snow, glossy + let slush = rs.y * snow_ok; + albedo = mix(albedo, albedo * 0.55 + vec3(0.08), slush); + ambient_albedo = mix(ambient_albedo, ambient_albedo * 0.55 + vec3(0.08), slush); + rough = mix(rough, 0.35, slush); + } + if (snow > 0.0) { + let up = clamp(n.z, 0.0, 1.0); + let ground = select(0.0, 1.0, terrain || material.params2.z > 0.0); + // (a road kept clear - "snow on road" off - stays asphalt: whitened, it turned the + // roads white exactly when the weather says they are cleared, #1362; built-up snow + // brings its own cover) + let cleared = select(1.0, 0.0, !carriageway && camera.post.z > 0.5 && !terrain && material.params2.z > 0.0); + // (a vehicle's gathered snow lies thick enough to hide the paint) + let cover = min(cleared * snow * clamp(max(ground, smoothstep(0.78, 0.95, up) * 0.8), 0.0, 1.0) * select(0.55 + 0.35 * tex.a, 1.2, vehicle), 1.0); + albedo = mix(albedo, vec3(0.82, 0.84, 0.88), cover); + ambient_albedo = mix(ambient_albedo, vec3(0.82, 0.84, 0.88), cover); + // fresh snow is all but matte: it scatters the light and shows no highlight + rough = mix(rough, 0.95, cover); + f0 = mix(f0, vec3(0.02), cover); + metal = metal * (1.0 - cover); + } + // specular antialiasing: where the normal turns quickly across a pixel (a low-poly + // bonnet close up, a curved body far away) the surface cannot reflect sharper than that + // spread, or the interpolated normals show as bands in a mirror-like finish + if (reflective_env && !glass) { + let dndx = dpdx(n); + let dndy = dpdy(n); + let spread = min((dot(dndx, dndx) + dot(dndy, dndy)) * 2.0, 0.4); + rough = sqrt(min(rough * rough + spread, 1.0)); + } else if (!thin && !glass) { + rough = rough_aa(rough, n); + } + let env_share = select(1.0, camera.cam_pos.w, reflective_env && !glass); + var sf: Surface; + sf.albedo = albedo * (1.0 - metal); + ambient_albedo = ambient_albedo * (1.0 - metal); + sf.f0 = f0; + sf.rough = rough; + let nv = clamp(mix(face_v, dot(n, v), face_w), 1e-4, 1.0); + // the specular reflectance over the hemisphere, its multiple scattering included: one + // minus it is the share the diffuse part gets, so a surface never sends out more than falls + // on it (and a rough metal is not darker than its colour) + let spec_e = spec_ms(f0, rough, nv); + sf.kd = vec3(1.0) - spec_e.rgb; + sf.comp = spec_e.w; + // (how wide a patch of the surface the pixel covers, m: see `relief_masking`) + let relief_footprint = length(dpdx(in.world)) + length(dpdy(in.world)); + // The same depth-aware traced sample feeds the sun, AO and the debug view. Repeating + // rt_at here and inside ao_gi_at overflowed the optimizer's stack in the DX12 FXC + // fallback (used when dxcompiler.dll cannot be loaded); DXC compiles either form. + // Read it once after the early material returns, with the same taps and their order, + // so that the fallback can compile fs_enhanced too. + let surface_rt = rt_at(in.clip.xy, in.world); + // --- the sun + let s = camera.sun_dir.xyz; + let nl = dot(n, s); + var direct = vec3(0.0); + if (enh.lights.w > 0.0 && max(enh.sun.r, enh.sun.g) > 1e-5) { + var shadow = 0.0; + // (Enhanced+ without a traced shadow for the surface: the far map's as well, below - + // one call of it for both cases: two, each inlined, made the scene shader too big for + // Apple's M4 compiler, whose service crashed on every scene pipeline) + var far = false; + if (glass && nl > 0.0) { + // a pane lets nearly all of it through: the sun on it is its glint, for which one + // compare says enough (the soft filter over a cab's windscreen, doors and side + // windows was a millisecond of the frame) + shadow = sun_shadow_hard(in.world, n); + far = camera.clouds.w > 1.5; + } else if (nl > 0.0 || thin) { + // Enhanced+: the traced shadow where there is one for this surface + // (whose cut-out leaves and fences the shadow map holds alone: see `render_inner`) + let traced = surface_rt; + shadow = sun_shadow_soft(in.world, n, thin); + if (traced.w > 0.5 && traced.z >= 0.0) { + shadow = shadow * traced.z; + } else { + far = camera.clouds.w > 1.5 && traced.w < 0.5; + } + } + if (far) { + shadow = shadow * sun_shadow_far(in.world, n); + } + // (only the beam casts the shadow: what the clouds scatter of it is the sky's, below) + let e_sun = enh.sun.rgb * (shadow * cloud_shadow_ratio(in.world) * sun_beam_share()); + if (thin) { + // foliage: a crown of leaves facing every way, whose normals OMSI points up + // only to light it evenly - lit by the sun from any side (the shadow map + // darkens its far side), a little through the leaves as well. A crown is + // hundreds of leaves at every angle: on average about half of the sun falls on + // them square on, whatever the sun's height (with the up-pointing normals alone a + // low sun left every tree dull and dark while the walls beside it glowed). Seen + // against the sun a leaf glows with what comes through it - yellow-green, the + // light having passed the leaf's colour twice. + let through = pow(clamp(dot(-v, s), 0.0, 1.0), 3.0); + let leaf = sf.albedo / PI; + direct = e_sun * (leaf * (0.42 + 0.3 * max(nl, 0.0) + 0.08 * max(-nl, 0.0)) + + leaf * min(sf.albedo * 2.2, vec3(1.0)) * through * 0.45); + } else if (nl > 0.0) { + // the sun is a disc, not a point: no highlight sharper than it + let a = max(rough * rough, 0.012); + let h = normalize(s + v); + var spec = d_ggx(max(dot(n, h), 0.0), a) * v_smith(nv, nl, a) * f_schlick(f0, dot(v, h)); + // (a rough, unpolished surface's own relief hides its glint from a low sun: see + // `relief_masking`; glass, paint, chrome, water and a wet film keep theirs) + if (!glass && !reflective_env && !is_water && metal < 0.5) { + spec = spec * relief_masking(nl, nv, rough, relief_footprint); + } + // Optional road glare: only the specular sun highlight on terrain or roads. + // Diffuse sunlight, wet reflections and vehicle paint remain unchanged. + if ((terrain || material.params2.z > 0.0) && !is_water) { + spec = spec * camera.lod.z; + } + spec = select(spec, vec3(0.0), dot(geo_n, v) < 0.0 && !is_water); + direct = e_sun * nl * (sf.albedo / PI * sf.kd + spec * sf.comp); + } + } + // --- the moon: by night a directional light as the sun is, with its shadow when the + // maps are drawn along it + let em = enh.moon_light.rgb; + if (max(em.r, em.g) > 1e-9) { + let m = enh.moon.xyz; + let nlm = dot(n, m); + if (nlm > 0.0 || thin) { + var ms = 1.0; + if (enh.moon_light.w > 0.5) { + ms = sun_shadow_soft(in.world, n, thin); + } + let leaf = sf.albedo / PI; + if (thin) { + direct = direct + em * ms * leaf * (0.42 + 0.3 * max(nlm, 0.0)); + } else { + direct = direct + em * ms * nlm * leaf; + } + } + } + // --- sky and ground + var ao = 1.0; + let screen_ao = camera.clouds.w > 0.5 && !capture; + var bounce = vec3(0.0); + if (screen_ao) { +//VK ao = ao_traced_at(in.clip.xy, in.world, surface_rt); + let ag = ao_gi_at(in.clip.xy, in.world, surface_rt); + ao = ag.x; + bounce = ag.yzw; + } + // AO is generated from the opaque depth buffer. A transparent bus pane therefore + // samples the seats/dashboard behind it and makes their dark outlines crawl across the + // glass as the camera moves. The pane has its own transmission/reflection path; it must + // not inherit occlusion belonging to geometry on the far side of the window. + // (nor any other blended surface: a van's translucent door showed the shade of what + // stood behind it) + if (glass || mode > 1.5) { + ao = 1.0; + } + ao = ao * pbr_ao; + let fr = f_schlick(f0, nv); + // inside the player's vehicle the light comes in through the windows and off the + // cabin's own walls: less of it, and neither as blue nor as directional as the sky's + let in_cab = 1.0 - outside; + // The cab's light is one even ambient already (cab_e below); the screen-space occlusion + // on top of it went black in the hollow under the windscreen - the steering wheel and + // the dashboard stood dark beside a brightly lit cash desk. Inside the cab it is taken + // at a third of its strength. + ao = mix(ao, 1.0 - (1.0 - ao) * 0.35, in_cab); + let avg_e = enh.fog_color.rgb * (PI / 0.9); + let cab_e = vec3(dot(avg_e, vec3(0.2126, 0.7152, 0.0722))) * vec3(1.0, 0.98, 0.95); + // (the sun the clouds scatter: shadowless, a light of the sky's kind) + var sky_e = sh_irradiance(n); + let beam = sun_beam_share(); + if (beam < 0.999 && enh.lights.w > 0.0) { + sky_e = sky_e + sun_scattered(n, enh.sun.rgb * cloud_shadow_ratio(in.world) * (1.0 - beam)); + } + var e_amb = mix(sky_e, cab_e * CAB_AMBIENT, 0.6 * in_cab) * ao_bounce(ao, ambient_albedo) + + flash_irradiance(n) * ao * (1.0 - 0.7 * in_cab); +//VK if (screen_ao && in_cab < 1.0) { +//VK e_amb = e_amb + bounce_at(in.clip.xy, in.world) * mix(1.0, ao, 0.5) * (1.0 - in_cab); +//VK } + e_amb = e_amb + bounce * mix(1.0, ao, 0.5) * (1.0 - in_cab); + var ambient = e_amb * ambient_albedo / PI * (vec3(1.0) - spec_e.rgb * env_share); + // --- reflections: the sky probe, as sharp as the surface is smooth + var r = reflect(-v, normalize(mix(face_n, n, face_w))); + let bend_n = normalize(mix(face_n, geo_n, face_w)); + let horizon = horizon_occlusion(r, bend_n); + // a reflection pointing into the surface would show the probe's ground: bend it up + let below = dot(r, bend_n); + if (below < 0.0) { + r = normalize(r - bend_n * below * 1.02); + } + // A wet road, a wet pavement is no mirror: a soft, dim sheen of what stands round it, a + // puddle a blurred picture of it (panes, envmapped paint and still water keep their own + // smoothness). Its reflection is taken this rough, at this share. + let wet_only = !(reflective_env || glass || is_water || ((material.pbr.z > 0.5 || material.pbr.w > 0.5) && !terrain)); + let refl_rough = select(rough, max(rough, mix(0.2, 0.16, puddle)), wet_only); + let wet_share = select(1.0, mix(0.6, 0.7, puddle), wet_only); + let lod = refl_rough * (enh.lights.x - 1.0); + var env = textureSampleLevel(t_probe, s_lin, to_cube(r), lod).rgb * enh.fog_color.w; + // the probe holds only the sky: in a street the low sky is hidden behind houses and + // trees, which reflect about as much light as a quarter-white wall (without this every + // surface wore a milky sheen of the bright horizon, strongest against a low sun) + let surround = enh.fog_color.rgb * (0.25 / 0.9); + let open = smoothstep(-0.05, 0.35, r.z); + env = mix(surround, env, mix(open, 1.0, select(0.25, 0.5, reflective_env && !(glass && probe_only)))); + // the cabin reflects the cabin, not the sky - and so does the bus's own glass seen + // from the driver's seat + let cab_view = max(in_cab, near_player_vehicle(in.world) * inside_vehicle(camera.cam_pos.xyz)); + // From inside the player bus the pane is near the cabin, but it must still show the + // outside sky/street. Using the opaque-surface cabin weight here made every window a + // flat pale patch and hid the useful reflection while driving. + // A pane is the boundary between the cabin and the outside. Mixing the cabin + // irradiance into its reflection made every windscreen look like a pale grey sheet + // from the driver's seat; the interior is already behind the alpha-blended pane. + let cabin_reflection = select(0.85, 0.0, glass); + env = mix(env, cab_e * 0.35 / PI, cabin_reflection * cab_view); + // ... but the inner face of the bus's own glass cannot mirror the sky, which lies + // behind it: it mirrors the cab, far darker than the street seen through it. Taken as + // the sky, the doors (seen at a grazing angle from the driver's seat) went a milky + // grey sheet in fog and snow, when the probe is bright all round. + let own_pane = select(0.0, near_player_vehicle(in.world) * inside_vehicle(camera.cam_pos.xyz), glass); + if (reflective_env) { + // OMSI's photographed environment gives the reflection its structure (trees, + // houses, the street), the probe its light + // A pane looks it up by the reflection's direction in the world, not in the + // camera's frame as Direct3D's sphere map does: taken from the camera, what a + // standing bus's windows mirrored changed whenever the view turned, trees sliding + // in from nowhere over the street seen through them. Height gives the photo's rows + // (sky, the horizon's trees and houses, the ground), the compass direction a + // gentle drift across it that stays put in the world. + let az = atan2(r.y, r.x); + var env_uv = vec2(0.5 + 0.3 * sin(az), 0.5 + 0.45 * clamp(r.z, -1.0, 1.0)); + // The paint reads the photo as Omsi.exe's environment stage lays it on: Direct3D's + // sphere map of the reflection in the camera's frame (`sphere_map_uv`, 0x7ff670 sets + // D3DTSS_TCI_SPHEREMAP and no texture matrix), so the picture on a body turns with + // the camera's yaw and pitch as it does in OMSI. (A pane keeps the world's: through + // it the street itself is seen, and the photo turning over it read as a smear.) + if (!glass) { + env_uv = in.env_uv; + } + if (material.bump.y > 0.5) { + env_uv = env_uv + bump_offset(duv); + } + // (with the mip level its footprint needs on top of the blur: a fixed level showed + // the photo's trees as contour lines across a car's curved bonnet close up, and + // paint takes it as blurred as the vanilla path does) + let photo = textureSampleBias(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], env_uv, max(rough * 16.0, select(2.0, 0.0, glass))).rgb; + let photo_avg = textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], vec2(0.5, 0.5), 12.0).rgb; + let lum_avg = max(dot(photo_avg, vec3(0.2126, 0.7152, 0.0722)), 0.02); + // (a tint, not a picture: an unbounded ratio drew the photo's trees as bands) + // (the photo's own contrast, as the vanilla picture shows it, held only off black + // and off a blinding white; clamped to 0.35 .. 2 and laid on at two thirds, the + // windows mirrored a flat grey where the vanilla ones mirror trees and sky) + let ratio = clamp(photo / lum_avg, vec3(0.12), vec3(select(3.5, 1.0, glass && probe_only))); + let band = 1.0 - smoothstep(0.25, 0.7, abs(r.z)); + // Only a smooth surface mirrors the photo; a satin one a quarter of its contrast. + // (A car's bonnet is a handful of triangles: the photo's mip level by its footprint + // above keeps its trees from turning into contour lines across it close up.) + let sharpness = 1.0 - smoothstep(0.05, 0.25, rough); + // ... and only as far as the reflection is of the outside at all: the driver's own + // windscreen reflects the cab, and the photo's trees drawn over that stood as + // contour lines across everything seen through it (a car's bonnet close up) + let outside_env = 1.0 - cab_view; + // ... and not in a fog: there is nothing sharp out there to mirror. The photo's + // trees stood as flat grey silhouettes on every pane in fog, in front of the real + // (fogged) trees behind the glass - outlines of trees that are not there + let clear_air = exp(-enh.fog.x * 150.0); + env = env * mix(vec3(1.0), ratio, band * mix(0.25, 1.0, sharpness) * outside_env * clear_air * enh.debug.z); + } + // what the SSAO darkens, it also keeps reflections out of + let spec_occ = clamp(pow(nv + ao, exp2(-16.0 * rough - 1.0)) - 1.0 + ao, 0.0, 1.0); + // (a PBR set's roughness or metalness map says how it reflects: the probe, as for an envmap) + let pbr_reflects = (material.pbr.z > 0.5 || material.pbr.w > 0.5) && !terrain; + // (a wet road mirrors the sky probe as well; and what reflects nothing keeps the light + // the Fresnel term took off its ambient above - at a grazing angle that term is near 1, + // and the far road and ground went dark with no reflection in its place, #374) + // Every solid surface reflects its few per cent: a dielectric's 4 % at normal incidence + // rising towards grazing, by its roughness and the light its microfacets pass on (the + // diffuse part took that share off above). Leaves and fences are left out: alpha-tested + // silhouettes, whose grazing sheen was white sparkle. A wet road's film reflects at its + // own share. + let reflects = !thin; + var refl_f = spec_e.rgb * spec_occ * horizon * select(1.0, mix(1.0, wet_share, wet_road), wet_only); + if (!reflects) { + ambient = e_amb * ambient_albedo / PI; + } + if (glass) { + // Transparent bus panes need a readable outside reflection from the driver's + // viewpoint; opaque paint must never receive this boost. + refl_f = refl_f * (1.0 - 0.85 * own_pane); + } + refl_f = refl_f * env_share; + var reflection = select(vec3(0.0), env * refl_f, reflects); + // Enhanced+: traced instead (rough surfaces keep the probe, which is as good as a + // ray there): the windows, the chrome and the paint's clear coat mirror the real street + // round them - the coat as sharply as the glass, where it is polished (`coat_rough`) + // (a dry plain surface - plaster, plastic, a satin wall - is traced up to a lesser + // roughness: its few per cent of a blurred street are as good from the probe, and the rays + // are spent where the reflection is seen; between the two the traced one fades in) + let trace_top = select(0.75, 0.5, wet_only && wet_road <= 0.0); + let trace_k = 1.0 - smoothstep(trace_top - 0.15, trace_top, refl_rough); + // (not the player's own panes seen from inside: their faint reflection of the cab is the + // glass's own, and the street behind them - a wet road through the windscreen - keeps + // its traced one, see below) + let traced = camera.clouds.w > 1.5 && reflects && trace_k > 0.0 && !capture && !(glass && own_pane > 0.5); + if (traced) { + var w = dot(refl_f, vec3(0.2126, 0.7152, 0.0722)) * aer.a * trace_k; + if (glass) { + // A pane mirrors what the rays find as glass does: 4 % at the normal, Fresnel's + // rise towards grazing (a tinted one a little more against what little comes + // through it). The share above is the vanilla picture's, which lays a dim photo + // over the pane; the traced street at that share - a fifth to a half - turned + // every window into a mirror of the bright sky. + let f0_glass = vec3(mix(0.04, 0.07, clamp(alpha * 1.5, 0.0, 1.0))); + w = dot(spec_ms(f0_glass, rough, nv).rgb, vec3(0.2126, 0.7152, 0.0722)) * spec_occ * horizon * env_share * aer.a * trace_k; + w = w * smoothstep(0.0, 0.05, alpha); + } else if (mode > 1.5) { + // (a blended layer reflects only where it is there: a painted ground's brush mask) + w = w * clamp(alpha, 0.0, 1.0); + } + let rough_t = refl_rough; + if (w > 0.002) { + reflection = reflection * (1.0 - trace_k); + rt_gbuf = vec4(n * w, w); + rt_aux = vec4(dist * w, rough_t * w, 0.0, w); + if (glass) { + // A pane takes the pixel's surface over (coverage 1, its weight in the + // normal's length, rt_reflect.wgsl): blended over the seats behind it by its + // own few per cent, the saloon's surfaces had weighed nine tenths - the rays + // left from a point between the pane and the seats along a normal halfway + // between theirs, and the window wore white blotches of the sky with the + // seats' outlines. + rt_gbuf = vec4(n * w, 1.0); + rt_aux = vec4(dist, rough_t, 0.0, 1.0); + } + } + } + // --- the lamps, the cabin light and what glows by itself + // ([nomaplighting] objects are not lit by the map's lamps; light-mapped roads are, with + // the tile light map on top) + // (no shadows inside the player's own vehicle, whose cab the depth hardly shows, nor in + // the probe's capture) + let film = select(vec3(0.0), vec3(wet_road, refl_rough, wet_share), wet_only && wet_road > 0.0); + // A clear pane scatters nothing: what lights it shows only in what it mirrors (the + // lamps' glints, the sky, the street) and in the little its tint takes from the daylight + // through it. Lit as a grey Lambertian layer, every lamp and the cab's own lamps laid a + // milky veil over the windows at night, over everything seen through them. + var sf_lit = sf; + if (glass) { + sf_lit.albedo = vec3(0.0); + } + if ((terrain || material.params2.z > 0.0) && !is_water) { + sf_lit.f0 = sf_lit.f0 * camera.lod.z; + } + let lamps = lamp_light(in.world, n, v, sf_lit, thin, !capture, film, dot(geo_n, v) < 0.0 && !is_water) * select(1.0, 0.0, material.params.y > 0.2 && material.params.y < 0.3); + // [interiorlight]: OMSI adds its lamps' light to the lit meshes whatever the daylight, + // so a switched-on saloon is brighter by day as well and only stands out more at night. + // Taken as a lamp against the daylight exposure it vanished by day altogether. + // (in the picture's own terms, as the vanilla pass adds it: scaled with the metering it + // grew with the night and whitened the saloon) + // (the lamps' light does not reach into the gaps under the seats and round the + // handrails either: without the ambient occlusion on it they glowed through there) + // A sphere-mapped pane or body mirrors the street round it: at night that is lit by the + // lamps, not by the sky the probe holds (dark then). The street's radiance under them + // (`lamp_ground`) is laid into the reflection where it points at the street and the + // walls: a bus's windows and paint under a street lamp show the lit street, the ones on + // an unlit road stay dark. (Not through the photo's structure: its bright rows are the + // day's sky, which the lamps do not light.) + if ((reflective_env || glass) && !traced) { + let lit_round = lamp_ground * (1.0 - open); + reflection = reflection + lit_round * refl_f * (1.0 - cab_view); + } + // (in the player's saloon: what its lamps' light meets on the way, see `cabin_visibility`) + var cabin_vis = 1.0; + if (in_cab > 0.5 && camera.lamp_atlas.w > 0.5) { + cabin_vis = cabin_visibility(in.world, n); + } + let cabin_light = interior_lamps(in.world, n, in.params2.z) * cabin_vis; + let cabin = sf_lit.albedo * cabin_light * mix(1.0, ao, 0.85); + var rgb = (direct + ambient + lamps) * pre + cabin; + // A material's own emissive colour ([matl_allcolor], an .x's emissive) is the texture at + // full brightness in Omsi.exe: shown at the screen's white, not scaled with the eye's + // night adaptation - a texture lit that way by [matl_allcolor] glared at several times + // white at night (#1228, #1236). (The night maps of lit windows keep their light.) + // (not a pane's: glass gives off no light of its own, see `sf_lit`) + var emit = select(tex.rgb * material.emissive.rgb * clamp(enh.exposure.z * 2.0, 0.8, 1.0), vec3(0.0), glass); + // (the tile light map on the splines and [LightMapMapping] objects is the vanilla + // path's: here the map's lamps light them, tinted from that map, as they light every + // other surface - added on top it lit the roads twice, with a hard edge where a road + // met a square that is an object) + if (material.extra.w > 0.5) { + let switched = material.extra.w > 1.5; + let night = select(rain_lit_windows(in.local), 1.0, switched); + // (a switched one is the display's own state: not dimmed with the instance's night + // lighting, which is 0 by day and left the Procity's pressure screen black) + let nm = night_sample.rgb * night * select(clamp(in.params2.y, 0.0, 1.0), 1.0, switched); + // (The ground gets no light from the tile's light map here: it is the lamps' pools as + // OMSI bakes them, a `[maplight]`'s colour times (radius / distance)^2 out to sixteen + // radii, taken through every wall and roof, with no shadow of anything and with a + // tail past where the lamp itself reaches. The lamps are lights of their own in this + // picture - the same inverse square, cut off where their reach ends, shadowed by the + // maps of `LampShadow` - and what the map added three times over was a snow-covered + // lawn in a courtyard lit orange by floodlights across a building, or the ground of a + // whole street glowing with one lamp's tail.) + if (!terrain) { + // lit windows and signs; a switched lamp or display holds up against daylight + // as the self-illuminated materials do + // (a window lit from inside shows some 80 cd/m² - a room's 300 lux off its + // walls and through a curtain - an illuminated sign more: over the dark street + // round it, a little over the screen's white, so that it keeps its colour) + emit = emit + nm * select(min(enh.exposure.z * 3.6, 1.2), mix(max(enh.exposure.z * 2.0, 0.8), 0.8, near_player_vehicle(in.world) * inside_vehicle(camera.cam_pos.xyz) * (1.0 - outside)), switched); + } + } + if (material.params2.x > 0.5 && !terrain && !glass) { + // [matl_lightmap]: laid onto the light with ADDSMOOTH in Omsi.exe (see the vanilla + // shader), so it adds what the surface's own light leaves: little by day, fully at + // night, and less where the saloon lamps light the surface already. (As an emission + // at 0.6 of the texture by day and on top of the lamps at night, a switched-on + // cabin's light-mapped parts were flat white.) + let lm = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], buv, camera.lod.x).rgb * clamp(in.params2.x, 0.0, 1.0); + if (material.emissive.w < -1.5) { + let night = clamp(camera.sun_color.w, 0.0, 1.0); + let left = (vec3(1.0) - clamp(cabin_light, vec3(0.0), vec3(1.0))) * (0.12 + 0.88 * night); + emit = emit + tex.rgb * lm * left * max(enh.exposure.z * 2.0, 0.6); + } else { + // (By day as by night: ADDSMOOTH lifts the surface to its texture's colour by the + // map whatever light it has, and what the light already gives - the day's, the + // saloon lamps' - is taken off below. Lifted by an eighth of that by day, a + // display in the cab's shade was far darker than in Vanilla+, #2051.) + // ... and as there it lifts the surface to its texture's own colour at the + // most, shown as a display is (see the unlit path): taken as a light of the + // night's level on top, a white light map (`weiss.bmp`, laid on a display so + // it shows at night) went past the tone curve's knee and bleached its colours - + // the Procity's red and blue gauges pink and lavender (#827). (An LED panel's + // light map stays as it was: its dots are meant to burn above their colour.) + // The map's script variable controls its backlight. Dimming every light-mapped + // surface as a cab screen hid instrument backlights even with the lights on. + // (the lift is the saloon lamps' light: where their light does not reach for a + // handrail or a seat standing in it, the map does not lift the surface either) + emit = emit + max(display_level(tex.rgb) * enh.exposure.y - rgb, vec3(0.0)) * lm * cabin_vis; + } + } + if (material.emissive.w < -1.5) { + // an LED panel (see MaterialExtra::led): the lit dots - the alpha the `\S:n` script + // texture carries, in the colour of the panel's own texture - are the panel's own + // light, drawn as bright as the settings ask for (`Led glow`, 16 levels, 0 = off). + // The glow takes them where it leaves every other screen out of its source + // (`post.wgsl`) and blooms a halo around the panel. (Kept at their own brightness + // however the metering treats the scene, as a display's text is.) Its light is its + // white light map's, so it goes out with that map's variable (the busbar, the + // lights) as the Omsi.exe stage does. + let lm_gate = select(1.0, clamp(in.params2.x, 0.0, 1.0), material.params2.x > 0.5); + // (in the cab - a dashboard's LCD lit by a white map reads as a panel - it dims at night; + // not a page's destination sign (-3), which is read from the street through the windscreen) + let cab_dim = select(1.0 - outside, 0.0, material.emissive.w < -2.5); + // (`material.glow.y`: the share of it the modeller gives the panel, `[led_glow_effect]`) + emit = emit + tex.rgb * enh.led.x * material.glow.y * alpha * lm_gate * max(enh.exposure.z * 2.0, 0.8) * mix(1.0, display_dim(1.0), cab_dim); + } else if (material.emissive.w < -0.5) { + // a display's text (see MaterialExtra::display) + emit = emit + tex.rgb * 0.35 * max(enh.exposure.z * 2.0, 0.8) * display_dim(1.0); + } + if (material.glow.x > 0.0) { + // [matl_glow] (see `matl_glow_light`): the material is its own light, drawn in HDR. + // The classic picture does not know the keyword (`params2.x` is off, see + // `add_material_extra`). + emit = emit + matl_glow_light(buv, tex.rgb); + } + rgb = rgb + emit; + if (enh.debug.x > 0.5) { + // OMSI_DEBUG_ENHANCED: one term alone, as it lands on the screen + let dm = i32(enh.debug.x); + var dc = vec3(0.0); + switch dm { + case 1: { + let tr = surface_rt; + let sm = sun_shadow_soft(in.world, n, thin); + dc = select(vec3(sm), vec3(tr.z * sm, tr.z * sm, tr.z * 0.6 + 0.4), tr.w > 0.5 && tr.z >= 0.0); + } + case 2: { dc = vec3(ao); } + case 3: { dc = n * 0.5 + vec3(0.5); } + case 4: { dc = vec3(aer.a); } + case 5: { dc = e_amb * pre * 0.1; } + case 6: { dc = reflection * pre; } + case 7: { dc = sf.albedo; } + case 8: { dc = direct * pre; } + case 9: { dc = aer.rgb * pre; } + case 11: { dc = vec3(fract(dist / 10.0), dist / 1000.0, in.clip.z * 100.0); } + case 12: { dc = vec3(mode * 0.5, f32(terrain), in.params2.w); } + case 13: { dc = vec3(in_cab, ao, spec_occ); } + case 14: { dc = (ambient + direct) * pre; } + case 15: { dc = lamps * pre; } + case 16: { dc = emit; } + case 17: { dc = vec3(rough, f0.g * 10.0, metal); } + default: { dc = vec3(alpha, f32(glass), f32(has_env)); } + } + return vec4(dc, 1.0); + } + if (glass) { + // see-through glass: the reflection is added on top of what shows through, so + // the blend keeps it where the glass itself is faint - but not where the texture + // is not there at all: Omsi.exe leaves the alpha as the texture has it, so a + // see-through part of a blended layer (the clear ground of a sticker on the + // cab's wall, #861) shows no reflection; made up to a quarter opaque by it, the + // whole rectangle of the sticker mirrored the sky + let cover = smoothstep(0.0, 0.05, alpha); + // (or, from inside the player's bus, the lit cabin it mirrors: `glass_reflection`) + let refl_rgb = glass_reflection(in.world, n, v, reflection * pre) * cover; + let rl = dot(refl_rgb, vec3(0.2126, 0.7152, 0.0722)); + // (a pane passes most light: a reflection making it up to 60 % opaque laid a grey + // veil over the destination display behind the windscreen and the saloon) + var a2 = clamp(alpha + (1.0 - alpha) * clamp(rl * 0.25 + fr.g, 0.0, 0.25) * (1.0 - 0.85 * own_pane) * cover, alpha, 1.0); + var c = (rgb * alpha + refl_rgb) / max(a2, 1e-3); + // the rain on a pane without a film of its own (`pane_rain`): the traffic's windows + { + let pr = pane_rain(in.world, in.local, in.normal); + if ((pr.cover > 0.001 || pr.veil > 0.001 || pr.mist > 0.001) && cover > 0.0) { + let o = pane_rain_compose(pr, c, a2, v, rain_env_enhanced(reflect(-v, pr.n), 1.0) * pre, sh_irradiance(pr.out) / PI * 0.9 * pre); + c = o.rgb; + a2 = o.a; + } + } + // the condensation on the player's bus's panes (omsi-app condensation.rs): a film of + // droplets, each many wavelengths wide, takes twice its shadow out of the light + // (the extinction paradox): half of what it scatters is diffracted a degree or two + // forward - what lies behind goes soft, in the tone mapping (post.wgsl `misted`) - + // and half is refracted and reflected every way, a milky veil lit by the street + // through the glass and, the part the droplets send back, by the cabin + let fog = glass_condensation(in.world, n) * cover; + glass_fog = fog; + if (fog > 0.001) { + // (of the widely scattered half, some 30 % goes back: a fully misted pane sends + // some 15 % of the light back, Briscoe and Galvin 1991) + let back = 0.3; + let lit_street = avg_e / PI * pre; + let lit_cabin = cab_e * CAB_AMBIENT / PI * pre + cabin_light; + let milky = lit_street * (1.0 - back) + lit_cabin * back; + let veil = 0.5 * fog; + let a3 = a2 + (1.0 - a2) * veil; + c = (c * a2 * (1.0 - veil) + milky * veil) / max(a3, 1e-3); + a2 = a3; + } + return vec4(c * aer.a + aer.rgb * pre, a2); + } + rgb = rgb + reflection * pre; + // The later screen-space pass replaces only this fraction of the sky reflection. + // A miss adds zero, so the existing sky, Fresnel and fog stay the fallback. Colour + // and coverage are resolved together, including terrain painting and glass over roads. + if (!glass && !reflective_env) { + // (a pool mirrors by its Fresnel term and its share of the road; so does the sheen of a wet + // road, at the Fresnel term of water a little under full - the lamps' and the cars' + // streaks down a wet street at night, which come from the light's own brightness and so + // need no more than that share - and still water as a whole) + let fresnel = 0.02 + 0.98 * pow(1.0 - clamp(nv, 0.0, 1.0), 5.0); + let pool = puddle * env_brdf(f0, rough, nv).g * select(wet_road, 1.0, pbr_reflects) * wet_share * aer.a; + let sheen = select(0.8 * smoothstep(0.55, 0.95, wet_road), 1.0, is_water) * fresnel * aer.a; + let weight = clamp(max(pool, sheen), 0.0, 1.0); + *puddle_weight = vec2(weight, weight * spec_occ); + } + // water hides what lies under it as far as it reflects (Fresnel): see-through from + // above, a mirror of the sky towards the horizon + let a_out = select(alpha, clamp(alpha + (1.0 - alpha) * fr.g, alpha, 1.0), is_water); + return vec4(rgb * aer.a + aer.rgb * pre, a_out); +} + +// Small waves on the water at map point `p` (m) and time `t` (s): the slope of four wave +// trains of 1.3 to 4.7 m running different ways. +fn water_ripple(p: vec2, t: f32) -> vec2 { + var g = vec2(0.0); + let dirs = array, 4>(vec2(0.8, 0.6), vec2(-0.45, 0.89), vec2(0.96, -0.28), vec2(-0.7, -0.71)); + let lens = array(4.7, 2.9, 1.9, 1.3); + for (var i = 0; i < 4; i = i + 1) { + let k = 6.2831853 / lens[i]; + // deep-water waves: their speed goes with the square root of their length + let w = sqrt(9.81 * k); + g = g + dirs[i] * cos(dot(p, dirs[i]) * k - w * t) * 0.045; + } + return g; +} + +// Shade the complete local vehicle from the reflected eye. Main-camera ambient +// occlusion is not applicable to this view beneath the road. +@fragment +fn fs_puddle_vehicle(input: FsIn) -> @location(0) vec4 { + // One reflected camera for the complete vehicle, including its transparent panes. + let plane = vehicle_reflection.plane; + let height = dot(plane.xyz, input.world) - plane.w; + if (height < 0.0 || material.emissive.w > 1.5) { discard; } + var unused = vec2(0.0); + let eye = camera.cam_pos.xyz - 2.0 * plane.xyz * (dot(plane.xyz, camera.cam_pos.xyz) - plane.w); + if (camera.post.x < 0.5) { + var unused_vanilla = 0.0; + return shade_vanilla(input, &unused_vanilla, eye); + } + return shade_enhanced(input, &unused, true, eye); +} + +@fragment +fn fs_puddle_chassis() -> @location(0) vec4 { + if (camera.post.x < 0.5) { return vec4(camera.ambient.rgb * 0.025, 1.0); } + return vec4(sh_irradiance(vec3(0.0, 0.0, -1.0)) * enh.exposure.x * 0.025, 1.0); +} + +// The painted ground's albedo (`Renderer::encode_ground`): the terrain's base and its paint +// layers laid over each other into one picture of what the surface is made of - texture, +// detail and tint, blended by each layer's coverage - which the main pass then lights once +// (`from_ground` in `shade_enhanced`) instead of lighting every layer in full and blending +// the lit colours. The base writes it, the layers blend into it (the pipeline's blend: the +// coverage over what is there; the alpha channel is left as the base wrote it). +@fragment +fn fs_ground(in: FsIn) -> @location(0) vec4 { + let duv = in.uv * material.extra.z; + let buv = tex_address(in.uv - in.params.zw); + let mode = material.params.x; + // (a brush mask that covers nothing here: the layer's texture need not be read) + if (TERRAIN_PAINT && mode > 1.5 && material.params.z > 0.5 && material.params.w > 0.5) { + let cover = smoothstep(0.32, 0.68, sample_transmap(buv).a); + if (cover * material.color.a * in.params.x == 0.0) { + discard; + } + } + var tex = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv); + if (material.extra.y > 0.0) { + let det = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], in.uv * material.extra.y, camera.lod.x); + tex = vec4(clamp(tex.rgb * det.rgb, vec3(0.0), vec3(1.0)), tex.a); + } + var cover = tex.a; + if (material.params.z > 0.5) { + cover = select(1.0, sample_transmap(buv).a, material.params.w > 0.5); + if (mode > 1.5) { + cover = smoothstep(0.32, 0.68, cover); + } + } + var alpha = cover * material.color.a; + if (mode < 0.5) { + alpha = 1.0; + } + alpha = alpha * clamp(in.params.x, 0.0, 1.0); + if (TERRAIN_PAINT && alpha == 0.0) { + discard; + } + return vec4(tex.rgb * material.color.rgb, alpha); +} + +// The bus's windows in the enhanced picture: the rain on their outer face, the snow that +// settles there and the condensation on their inner face. (The drops and the snow are the classic pictures' too: scene/08_rain_glass.wgsl.) + +// The pane at a pixel, in the vehicle's own frame (the film's vertices as its mesh has them, +// `FsIn.local`): the drops are laid out there, so they stay on the glass however the body +// rolls and pitches and on a door that swings open. The modellers' texture coordinates of +// a film are no measure of the glass: on the windscreen of the NL202 they run half as fast +// again one way as the other and at sixty degrees to each other, from triangle to triangle +// anew, and every drop drawn in them came out a slanting streak. So a pane is laid flat by +// the axes of the vehicle (`pane_proj`): the windscreen and the rear window onto its +// across and up, the side windows onto its along and up, a roof light onto its plan. A +// raked or curved pane is foreshortened in that projection; a drop is drawn round all the +// same, its offsets taken back onto the glass (`m`) before its shape is worked out. The +// drops' grid alone stays in the projection: on a pane at an angle to it a cell covers +// more glass, and the drops are a little fewer there. + +// (The drops on a pane, the runners, the blur's picture and the pane's own frame - +// `glass_water`, `glass_blur` - are the classic pictures' too: scene/08_rain_glass.wgsl.) + +// The rain film on a pane (the enhanced pass's `emissive.w` 2 layer), drawn over the +// clean picture of the frame: the drops, each a small lens that shows the street behind +// it upside down, a shade darker at its rim where the light is bent away, with the sky's +// glint on it, and between them the soft blur of the wet glass. +fn glass_film(in: FsIn, water: f32) -> vec4 { + let v = camera.cam_pos.xyz - in.world; + let dist = length(v); + let vn = v / max(dist, 1e-4); + let in_cab = inside_vehicle(camera.cam_pos.xyz) * near_player_vehicle(in.world) > 0.5; + let g = glass_water(in.world, in.local, in.normal, water, camera.post.y, in_cab); + if (g.cover <= 0.001 && g.mist <= 0.001 && g.veil <= 0.001) { + return vec4(0.0); + } + let pre = enh.exposure.x; + let has_picture = camera.flags.z < -0.5; + let dims = vec2(textureDimensions(mx_tex2d[mx_mat.env])); + let uv0 = in.clip.xy / dims; + let mist_col = sh_irradiance(g.out) / PI * 0.9 * pre; + // the view through the wet glass between the drops: softened by the film of water + // (a running film scatters the light by a fraction of a degree: some 0.7 % of the + // picture's height in a downpour, a third of that in a drizzle) + let veil_lod = log2(max(dims.y * mix(0.002, 0.006, clamp(g.veil / 0.3, 0.0, 1.0)), 1.0)); + var behind = mist_col; + if (has_picture) { + behind = finite_or(glass_blur(uv0, veil_lod), mist_col); + } + // --- a drop: a small lens. Through it the street shows small and upside down (each + // point of the drop looks out along its own bent way, `tilt` across the screen), the + // more bent the further out on it; at its rim the light is bent so far that little of + // it reaches the eye, a darker ring. + var drop_col = behind; + var a_drop = 0.0; + if (g.cover > 0.001) { + let tilt = g.n - g.out * dot(g.n, g.out); + let right = camera.cam_right.xyz; + let up = camera.cam_up.xyz; + // (a drop is a wide lens: from its rim it looks out some 30 degrees aside, the sky + // in the bottom of a drop against a wall) + let o = vec2(dot(tilt, right), -dot(tilt, up)) * 0.3; + var seen = behind; + if (has_picture) { + var uv = clamp(uv0 - o, vec2(0.001), vec2(0.999)); + // (only what lies beyond the glass: where the bent way lands on the cab's own + // dashboard or pillar, in front of the pane, the drop shows what is straight + // behind it instead) + if (camera.clouds.w > 0.5 && camera.clouds.w < 1.5) { + let asz = vec2(textureDimensions(t_ao)); + let z = textureLoad(t_ao, min(vec2(uv * asz), vec2(asz) - vec2(1)), 0).g; + let zg = (camera.view_proj * vec4(in.world, 1.0)).w; + let beyond = select(smoothstep(zg + 0.05, zg + 0.4, z), 1.0, z <= 0.0); + uv = mix(uv0, uv, beyond); + } + seen = finite_or(glass_blur(uv, 0.8 + 1.5 * g.mist), behind); + } + let rim = smoothstep(0.55, 1.0, g.rim); + let facing = dot(g.out, vn) > 0.0; + let cosv = clamp(abs(dot(g.n, vn)), 0.0, 1.0); + let f = select(0.02, 0.02 + 0.98 * pow(1.0 - cosv, 5.0), facing); + let mirrored = rain_env_enhanced(reflect(-vn, g.n), 1.0) * pre; + var c = seen * (1.0 - 0.45 * rim) * (1.0 - f) + mirrored * f; + // the sun: a pinpoint where the dome mirrors it + if (facing) { + let r = reflect(-vn, g.n); + c = c + enh.sun.rgb / PI * pre * pow(max(dot(r, camera.sun_dir.xyz), 0.0), 900.0) * f * 60.0; + } + // A drop of a pixel or less is no lens one can see: its many ways average to the + // view behind it, a little dimmer for its rim - a faint grain, not a dark speck. + let detail = smoothstep(0.5, 1.6, g.size_px); + drop_col = mix(behind * 0.93, c, detail); + a_drop = g.cover * mix(select(0.15, 0.5, has_picture), 0.95, detail); + } + // Drops a few pixels across are a pane's sparkle close up; seen from the street they + // fade out over the first fifteen metres. The haze stays further. + let aer = air(-vn, fog_distance(in.world), camera.cam_pos.z - enh.fog.z, in.world.z - enh.fog.z); + a_drop = a_drop * (1.0 - smoothstep(5.0, 15.0, dist)); + // the fine mist of droplets: a faint grey scatter of the light about + let a_mist = g.mist * 0.5; + var a_veil = 0.0; + if (g.veil > 0.001 && has_picture) { + a_veil = g.veil * (1.0 - smoothstep(25.0, 60.0, dist)); + } + let a_under = a_veil + a_mist * (1.0 - a_veil); + let under = (behind * a_veil + mix(mist_col, behind, 0.9) * a_mist * (1.0 - a_veil)) / max(a_under, 1e-4); + var a = a_drop + a_under * (1.0 - a_drop); + if (a <= 1e-4) { + return vec4(0.0); + } + let col = (drop_col * aer.a * a_drop + under * a_under * (1.0 - a_drop)) / a; + // From inside, the rain is seen through the condensation on the glass's inner face + // (drawn with the pane before this film): a misted pane shows the drops behind it as + // soft shadows, not sharp lenses. + if (in_cab) { + a = a * (1.0 - 0.5 * glass_condensation(in.world, g.out)); + } + return vec4(col, a); +} + +// The snow a wiped pane holds while it snows (`is_snow_pane`; the mask's cover: 0 clear +// glass, up to 1 a pane closed by snow, above 1 the bank a blade pushed to the end of its +// sweep, below 0 glass a blade has just cleared). Crystals land one by one and stick, hold +// a while and melt into a little water - soon on the windscreen, whose glass the warm air +// of the defroster heats, slowly on a side window. As the cover grows they close into a +// milky layer, and it lies deepest along the windscreen's bottom edge and in its lower +// corners, where the blades and the airstream do not reach. +fn glass_snow(in: FsIn, cover: f32) -> vec4 { + // (the windscreen's defroster from the cabin's air, the height on the glass in the bus's + // own frame with the body's tilt: see `glass_snow_with`, which the classic pictures + // share) + let l = pane_local(in.world); + let fz = clamp(l.z / max(camera.inside_b.w, 0.1), -1.0, 1.0); + return glass_snow_with(in, cover, enh.condensation.w, fz); +} + +// A direction in the frame of the bus the camera is in (`pane_local` without the shift). +fn pane_dir(d: vec3) -> vec3 { + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let v = vec3(d.x * ch - d.y * sh, d.x * sh + d.y * ch, d.z); + let t = enh.pane_tilt; + let p = vec3(v.x, v.y * t.y + v.z * t.x, v.z * t.y - v.y * t.x); + return vec3(p.x * t.w - p.z * t.z, p.y, p.z * t.w + p.x * t.z); +} + +// How close the edge of the pane at `world` (normal `n`) is: 1 against it, falling to 0 +// some 25 cm in; -1 where it cannot be told. A pane's edge is where its frame begins - the +// rubber, the pillar, the trim, the dashboard under the windscreen: opaque and in the depth +// prepass, lying on the glass's own plane, where the glass is not. So points on the pane's +// plane round the pixel, in eight ways out to 26 cm, are looked up in the prepass's depth +// (the ambient occlusion's texture keeps it): where an opaque surface lies there on the +// plane - within a centimetre or two of it, not a wiper's arm a hand's breadth outside - the +// pane has ended. The nearest such end in each way, averaged over the ways: in a corner +// two ways find it close, along an edge one, in the middle of a pane none. +fn glass_frame_near(world: vec3, n: vec3) -> f32 { + if (camera.clouds.w < 0.5 || camera.clouds.w > 1.5) { + return -1.0; + } + let size = vec2(textureDimensions(t_ao)); + let nn = safe_normal(n); + let up0 = vec3(0.0, 0.0, 1.0) - nn * nn.z; + let a = select(vec3(1.0, 0.0, 0.0), normalize(up0), dot(up0, up0) > 0.04); + let b = cross(nn, a); + var sum = 0.0; + for (var i = 0; i < 8; i = i + 1) { + let ang = f32(i) * 0.7853982 + 0.2; + let dir = a * cos(ang) + b * sin(ang); + var near = 0.0; + for (var k = 0; k < 6; k = k + 1) { + let dist = 0.03 + 0.046 * f32(k); + let c = camera.view_proj * vec4(world + dir * dist, 1.0); + if (c.w <= 0.05) { + break; + } + let uv = vec2(c.x / c.w * 0.5 + 0.5, 0.5 - c.y / c.w * 0.5); + if (any(uv < vec2(0.0)) || any(uv > vec2(1.0))) { + break; + } + let z = textureLoad(t_ao, min(vec2(uv * size), vec2(size) - vec2(1)), 0).g; + if (z > 0.0 && abs(z - c.w) < 0.015 + 0.006 * c.w) { + near = 1.0 - (dist - 0.03) / 0.26; + break; + } + } + sum = sum + near; + } + return clamp(sum / 3.0, 0.0, 1.0); +} + +// How much of the light crossing the player's bus's pane at `world` (normal `n`) its +// condensation scatters (0..1). One cabin air mists all the glass much alike: each +// window's film (enh.condensation: the optical depths of the windscreen's, the side +// windows' and the rear window's, omsi-weather condensation.rs) is taken two thirds from +// their mean. The film starts where the glass is coldest and the air stillest, in a pane's +// corners and along its frame (and low down), and grows inward as it thickens, its front +// wandering with the glass's own patchiness, until it closes over the pane. A heavy film +// gathers into drops that trickle down and leave clear tracks; on the windscreen the +// defroster's warm air clears it from the bottom up. +fn glass_condensation(world: vec3, n: vec3) -> f32 { + if (camera.inside_c.w < 0.5) { + return 0.0; + } + let l = pane_local(world); + let h = camera.inside_b.yzw; + if (any(abs(l) >= h + vec3(0.25))) { + return 0.0; + } + let nl = safe_normal(pane_dir(n)); + let gap = h - abs(l); + // (the panes in the body's skin only, by the way they face: not the instruments' glass + // behind the windscreen or a partition in the saloon) + var own = -1.0; + var front = false; + if (abs(nl.y) > 0.55 && gap.y < 0.45) { + front = l.y > 0.0; + own = select(enh.condensation.z, enh.condensation.x, front); + } else if (abs(nl.x) > 0.5 && gap.x < 0.35) { + own = enh.condensation.y; + } + if (own < 0.0) { + return 0.0; + } + let depth = mix((enh.condensation.x + enh.condensation.y + enh.condensation.z) / 3.0, own, 0.35); + if (depth <= 0.001) { + return 0.0; + } + // the pane's own frame in metres: across, and up the glass + let up0 = vec3(0.0, 0.0, 1.0) - nl * nl.z; + let up = select(vec3(1.0, 0.0, 0.0), normalize(up0), dot(up0, up0) > 0.04); + let s = vec2(dot(l, cross(up, nl)), dot(l, up)); + let fz = clamp(l.z / max(h.z, 0.1), -1.0, 1.0); + let low = 1.0 - clamp(fz * 0.5 + 0.5, 0.0, 1.0); + let edge_seen = glass_frame_near(world, n); + let edge = select(edge_seen, 0.15 + 0.3 * low, edge_seen < 0.0); + let n1 = snow_noise(s * 3.0 + vec2(11.0, 3.0)); + let n2 = snow_noise(s * 9.0 + vec2(3.0, 17.0)); + let patchy = n1 * 0.7 + n2 * 0.3; + // (the front: into the corners and along the frame at first, the glass's patchiness + // breaking its line, over the whole pane at a depth of two; a soft front, the film + // thinning out over a few centimetres) + let grow = 1.0 - exp(-depth * 1.3); + let potential = 0.45 * edge + 0.15 * low + 0.45 * patchy; + let front_line = 1.0 - grow * 1.3; + let covered = smoothstep(front_line - 0.18, front_line + 0.18, potential); + var amount = covered * (1.0 - exp(-depth * (0.9 + 0.5 * patchy))); + // the fine grain of the droplets themselves + amount = amount * (0.92 + 0.08 * snow_noise(s * 140.0)); + if (depth > 1.4) { + // trickles: drops grown heavy run down a few centimetres a minute, each clearing a + // narrow track below where it started + let lane = floor(s.x / 0.03); + let h1 = rain_hash(vec2(lane, 71.0)); + if (h1.x < clamp((depth - 1.4) * 0.35, 0.0, 0.6)) { + let h2 = rain_hash(vec2(lane, 13.0)); + let x0 = (lane + 0.3 + 0.4 * h2.x) * 0.03 + 0.003 * sin(s.y * 40.0 + h2.y * 6.283185); + let period = 90.0 + 120.0 * h1.y; + let tau = fract(camera.post.y / period + h2.y) * period; + let start = h.z * (0.75 - 0.9 * h2.x); + let end = start - min(tau * 0.004, 0.6); + let fade = smoothstep(0.0, 5.0, tau) * (1.0 - smoothstep(period - 10.0, period, tau)); + let dx = abs(s.x - x0); + let in_track = step(end, s.y) * step(s.y, start) * (1.0 - smoothstep(0.0012, 0.0025, dx)); + let head = 1.0 - smoothstep(0.0018, 0.0028, length(vec2(dx, s.y - end))); + amount = amount * (1.0 - 0.8 * max(in_track, head) * fade); + } + } + if (front && enh.condensation.w > 0.02) { + // the defroster's warm air clears the windscreen from its bottom edge up, first in + // the middle over its outlets + let u = clamp((fz + 0.35) / 1.2, 0.0, 1.0); + let fx = l.x / max(h.x, 0.1); + let reach = enh.condensation.w / 0.85 * 1.15 - 0.2 * fx * fx + 0.06 * (n1 - 0.5); + amount = amount * smoothstep(reach - 0.12, reach, u); + } + return clamp(amount, 0.0, 1.0); +} + +// The reflection a pane adds over what shows through it (pre-exposed `reflection`): the +// street and the sky it mirrors, seen from outside or on another vehicle; none on the inner +// face of the player's own bus's glass. (A box-projected cube of the cabin was mirrored +// there; it lagged behind the camera, shook with the head and showed a blurred picture, and +// was taken out on the user's word, 2026-11-22.) +fn glass_reflection(world: vec3, n: vec3, v: vec3, reflection: vec3) -> vec3 { + let inside = inside_vehicle(camera.cam_pos.xyz) * near_player_vehicle(world); + return reflection * (1.0 - step(0.5, inside)); +} diff --git a/crates/mx/tests/openomsi/sky.wgsl b/crates/mx/tests/openomsi/sky.wgsl new file mode 100644 index 0000000..c16e183 --- /dev/null +++ b/crates/mx/tests/openomsi/sky.wgsl @@ -0,0 +1,1615 @@ +fn srgb_encode(c: vec3) -> vec3 { + let x = max(c, vec3(0.0)); + return select(1.055 * pow(x, vec3(1.0 / 2.4)) - 0.055, x * 12.92, x <= vec3(0.0031308)); +} +fn srgb_decode(c: vec3) -> vec3 { + let x = max(c, vec3(0.0)); + return select(pow((x + 0.055) / 1.055, vec3(2.4)), x / 12.92, x <= vec3(0.04045)); +} + +// Sky dome: the envir.cfg gradient textures (day / twilight / night), u = azimuth relative +// to the sun, v = elevation (0 zenith … 1 horizon), blended by the sun altitude. +struct Camera { + view_proj: mat4x4, + cam_pos: vec4, + // Kept in lockstep with `CameraUniform` in lib.rs. The sky does not use the + // floating-origin reconstruction itself, but omitting this member shifts every + // following field one vec4 earlier: vanilla then reads the light-grid as `sky` + // weights (usually all zero) and clears/draws a black sky. + world_origin: vec4, + sun_dir: vec4, + ambient: vec4, + fog: vec4, + sun_color: vec4, + sky_color: vec4, + light_grid: vec4, + sky: vec4, // x sun azimuth (rad), y day weight, z twilight weight, w night weight + cam_right: vec4, + cam_up: vec4, + clouds: vec4, // x density 0..1, yz texture offset (wind drift) + light_view_proj: mat4x4, + light_view_proj_far: mat4x4, + shadow: vec4, + post: vec4, // x enhanced, y time + inside_a: vec4, + inside_b: vec4, + inside_c: vec4, + flags: vec4, + light_view_proj_close: mat4x4, + wind: vec4, + // Enhanced: the lamps' shadow maps (the tiles under the far map; zero where nothing is + // drawn) and where the tiles lie: x a tile's side, y tiles to a row, z the far map's + // texture height, w the number of tiles (`LampAtlas::uniform`) + lamp_view_proj: array, 56>, + lamp_atlas: vec4, + tree_wind: vec4, + inside2_a: vec4, + inside2_b: vec4, + inside2_c: vec4, + cookies: array, 8>, + cabin_lamps: array, 4>, + // x: the textures' mip bias (FSR 1: negative, see `CameraUniform::lod`) + lod: vec4, + // (the classic picture's headlight, `CameraUniform::spot`: unread here) + spot: array, 4>, +}; + +// A hash of a lattice point, from its integer bits. +// +// It was the old `fract(sin(dot(q, k)) * 43758)` trick, and that is what put flat slabs across +// the top of the sky. `cloud_fbm` below walks `q` up by 2.1 an octave from a world coordinate +// that is kilometres wide, and once the argument of the `sin` reaches a few times 1e5 a +// 32-bit float can no longer say where the fractional part of it lands: the hash comes out +// constant over a whole lattice cell, so the noise reads as flat squares with hard edges in a +// grid that turns with the camera - and only where the layer is thin enough to see through, +// which is why it showed as a "seam" in the sky "only when there are clouds": the high thin +// layer is the only thing up there in a clear sky, and it is faint. Integer bits do not lose +// precision with distance. +fn hash2(q: vec2) -> f32 { + let x = bitcast(i32(floor(q.x))); + let y = bitcast(i32(floor(q.y))); + // (integer arithmetic in WGSL wraps, so these multiplications are modular already) + var h = (x * 0x8da6b343u) ^ (y * 0xd8163841u); + h = h ^ (h >> 13u); + h = h * 0x5bd1e995u; + h = h ^ (h >> 15u); + return f32(h & 0xffffu) / 65535.0; +} + +fn vnoise(p: vec2) -> f32 { + let i = floor(p); + let f = fract(p); + let u = f * f * (3.0 - 2.0 * f); + return mix(mix(hash2(i), hash2(i + vec2(1.0, 0.0)), u.x), mix(hash2(i + vec2(0.0, 1.0)), hash2(i + vec2(1.0, 1.0)), u.x), u.y); +} + +// Cloud density field: the map's cloud texture as the large shape, fractal noise as the +// small one, two layers at different heights drifting at different speeds. +fn cloud_fbm(p: vec2) -> f32 { + var v = 0.0; + var a = 0.5; + var q = p; + for (var i = 0; i < 4; i = i + 1) { + v = v + a * vnoise(q); + q = q * 2.1 + vec2(17.0, 9.0); + a = a * 0.5; + } + return v; +} +@group(0) @binding(0) var camera: Camera; +@group(1) @binding(0) var t_day: texture_2d; +@group(1) @binding(1) var t_twilight: texture_2d; +@group(1) @binding(2) var t_night: texture_2d; +@group(1) @binding(3) var s_sky: sampler; +@group(1) @binding(4) var t_clouds: texture_2d; +@group(1) @binding(5) var s_repeat: sampler; + +/// How far the cloud field reaches before it repeats (m): a cumulus is then half a +/// kilometre to two across. +const CLOUD_FIELD_TILE: f32 = 14000.0; + +// The ground point under the sky at distance `t` along the view ray `d`, in the clouds' own +// frame (world coordinates modulo 70 km, lib.rs `CLOUD_ORIGIN_PERIOD`), so that the cloud +// field stays where it is when the floating render origin moves on. +fn cloud_ground(d: vec3, t: f32) -> vec2 { + return camera.cam_pos.xy + camera.world_origin.zw + d.xy * t; +} + +// The cloud cover over ground point p (x, 0..1, its edges frayed by the billows), how tall +// the cloud there grows (y, 0..1) and the cover without the billows (z: the enhanced sky +// raises its rounded tops on that, the billows would stand on them as spikes). From the +// cloud field: its equalised shape (G) cut at 1 - the cover, the weather's own picture (R) +// nudging where the clouds gather, billows (B) fraying the edges near by. +fn cloud_cover_at(p: vec2, lod: f32) -> vec3 { + let uv = p / CLOUD_FIELD_TILE + camera.clouds.yz * (2500.0 / CLOUD_FIELD_TILE); + let t = textureSampleLevel(t_clouds, s_repeat, uv, lod); + let thr = 1.0 - clamp(camera.clouds.x, 0.0, 1.0); + let smooth_shape = t.g + (t.r - 0.5) * 0.15; + var shape = smooth_shape; + // the billows only where they are big enough to see + let fray = 1.0 - smoothstep(2.0, 5.0, lod); + if (fray > 0.0) { + let detail = textureSampleLevel(t_clouds, s_repeat, uv * 3.7 + vec2(0.31, 0.73), lod + 1.9).b; + shape = shape + (detail - 0.5) * 0.2 * fray; + } + return vec3(clamp((shape - thr) / 0.14, 0.0, 1.0), t.a, clamp((smooth_shape - thr) / 0.14, 0.0, 1.0)); +} + +struct VsOut { + @builtin(position) clip: vec4, + @location(0) dir: vec3, +}; + +@vertex +fn vs_main(@location(0) pos: vec3) -> VsOut { + var out: VsOut; + // the dome rides with the camera; pushed onto the far plane (0 with reversed Z), the + // depth the pass starts from: its depth test (equal or nearer than that) keeps it to the + // pixels nothing was drawn into, when it is drawn after the scenery's depth was laid + // (main_pass.rs `encode_sky`) + let wp = camera.cam_pos.xyz + pos * 4000.0; + var clip = camera.view_proj * vec4(wp, 1.0); + clip.z = 0.0; + out.clip = clip; + out.dir = pos; + return out; +} + +// The classic sky's weather (lib.rs `VanillaSky`): the cloud type's own texture and +// cloud: x height H (m over the map's zero), y the type's size (m a tile; 0: no clouds), +// zw the wind's drift (m); haze: x the weather's fog range (m), y the visibility (m), +// z 1 for an overcast type, w the render origin's height. +struct VanillaSkyUniform { + cloud: vec4, + haze: vec4, +}; +@group(1) @binding(9) var t_vclouds: texture_2d; +@group(1) @binding(10) var vsky: VanillaSkyUniform; +@group(1) @binding(11) var t_sun: texture_2d; + +fn vanilla_sun(d: vec3) -> vec3 { + let s = normalize(camera.sun_dir.xyz); + let c = dot(d, s); + let right = normalize(select(vec3(s.y, -s.x, 0.0), vec3(1.0, 0.0, 0.0), length(s.xy) < 1e-4)); + let up = cross(right, s); + let p = d * (3.0 / max(c, 1e-4)); + let uv = vec2((dot(p, right) + 0.0803) / 0.1606, (0.0821 - dot(p, up)) / 0.1606); + let t = srgb_encode(textureSampleLevel(t_sun, s_sky, clamp(uv, vec2(0.0), vec2(1.0)), 0.0).rgb); + let inside = c > 0.0 && all(uv >= vec2(0.0)) && all(uv <= vec2(1.0)); + return select(vec3(0.0), t * vec3(1.0, 1.0, 0.0), inside); +} + +// The v of the sky textures towards elevation `e` (rad), as Omsi.exe's dome +// (helper\skybox.x) has it: rings at the horizon, at 45 degrees and at the zenith with v +// 0.9833, 0.4868 and 0.0236, flat bands between them along which v runs linearly - along +// the chord, not with the angle - and the horizon's v all the way down below it. +fn dome_v(e: f32) -> f32 { + if (e <= 0.0) { + return 0.9833; + } + let upper = e > 0.7853982; + let e0 = select(0.0, 0.7853982, upper); + let e1 = select(0.7853982, 1.5707963, upper); + let v0 = select(0.9833, 0.4868, upper); + let v1 = select(0.4868, 0.0236, upper); + // (where the ray at e meets the chord from the ring at e0 to the one at e1) + let t = sin(e - e0) / ((sin(e1) - sin(e0)) * cos(e) - (cos(e1) - cos(e0)) * sin(e)); + return mix(v0, v1, clamp(t, 0.0, 1.0)); +} + +// The haze Omsi.exe lays over its sky (0x5d8e98): the dome again with Texture\nebel.tga, +// white with an alpha running linearly over its 32 rows from 0 at the zenith to 1 at the +// horizon, in the fog colour, its alpha moved by the fog range f and the cloud height H: +// down by 1 - 4 asin(H/f)/pi where f > H sqrt 2 (no haze at all under a clear sky, H 0), +// up by 1 - 4 acos(H/f)/pi below that, and the whole sky fog where f <= H. +fn vanilla_haze(v: f32) -> f32 { + let f = vsky.haze.x; + let h = vsky.cloud.x; + if (f <= 0.0) { + return 0.0; + } + if (f <= h) { + return 1.0; + } + let tex_a = clamp((v * 32.0 - 0.5) / 31.0, 0.0, 1.0); + let q = h / f; + if (q < 0.70710678) { + return clamp(tex_a - (1.0 - 4.0 * asin(q) / 3.14159265), 0.0, 1.0); + } + return clamp(tex_a + (1.0 - 4.0 * acos(q) / 3.14159265), 0.0, 1.0); +} + +// The classic cloud layer towards d: rgb (in the sky's own terms, `fog` its fog colour) and +// how much it covers. Omsi.exe (0x754e44) draws helper\clouds.o3d, a flat cone over the +// camera - its apex H over the map's zero, its rim on the zero 9.363 H away - with the cloud +// type's texture laid on the ground plan, one tile every `size` metres, moved by the wind; +// its colour is the texture times the fog colour, its alpha the texture's (an `ovc` deck is +// opaque), and the fixed-function fog takes it into the fog colour by its depth in the +// view over the visibility. +fn vanilla_clouds(d: vec3, fog: vec3, tex: vec4, r: f32, encoded: bool) -> vec4 { + let hl = max(length(d.xy), 1e-4); + // (the hit point lies along d, r / hl from the camera; its depth along the view's axis) + let fwd = normalize(cross(camera.cam_up.xyz, camera.cam_right.xyz)); + let depth = r / hl * dot(d, fwd); + let vis = max(vsky.haze.y, 1.0); + let k = clamp(1.0 - depth / vis, 0.0, 1.0); + var rgb = select(tex.rgb, srgb_encode(tex.rgb), encoded) * fog; + rgb = mix(fog, rgb, k); + return vec4(rgb, select(tex.a, 1.0, vsky.haze.z > 0.5)); +} + +// How far (over the ground plan) the ray d meets the cloud cone, and whether it does. +fn vanilla_cloud_reach(d: vec3) -> vec2 { + let h = vsky.cloud.x; + let h0 = camera.cam_pos.z + vsky.haze.w; + let hl = max(length(d.xy), 1e-4); + let rim = 9.363 * h; + let den = d.z / hl + 1.0 / 9.363; + if (vsky.cloud.y <= 0.0 || h <= h0 || h <= 0.0) { + return vec2(rim, 0.0); + } + // Below the rim the cone's skirt (helper\clouds.o3d goes on down and in under the + // horizon) lies so far away that the fog takes it whole: nothing of the clouds shows + // there. Every ray below the rim drawn at the rim instead smeared the texture's one row + // into upright streaks above the horizon, wherever the ground did not reach that far. + if (den <= 0.0) { + return vec2(rim, 0.0); + } + let r = (h - h0) / den; + if (r > rim) { + return vec2(rim, 0.0); + } + return vec2(r, 1.0); +} + +@fragment +fn fs_main(in: VsOut) -> @location(0) vec4 { + let d = normalize(in.dir); + // the dome turned so that the texture's column 0.5036 faces the sun, u growing + // anticlockwise (from above) away from it (0x5d92a0: the dome rotated by the sun's + // azimuth) + let az = atan2(d.x, d.y); + let u = 0.503645 + (camera.sky.x - az) / 6.2831853; + let elev = asin(clamp(d.z, -1.0, 1.0)); + let v = dome_v(elev); + let uv = vec2(u, v); + // (Omsi.exe blends two of its pictures by the sun's height, see `Daylight::sky_weights`; + // the sky textures have no mip levels, so the seam of u behind the sun is not seen) + let sky = textureSample(t_day, s_sky, uv).rgb * camera.sky.y + textureSample(t_twilight, s_sky, uv).rgb * camera.sky.z + textureSample(t_night, s_sky, uv).rgb * camera.sky.w; + // the cloud texture on the ground plan where the ray meets the cone, sampled outside + // any branch (its mip levels by the screen's derivatives) + let reach = vanilla_cloud_reach(d); + let hl = max(length(d.xy), 1e-4); + let ground = camera.cam_pos.xy + camera.world_origin.zw + d.xy / hl * reach.x; + let size = max(vsky.cloud.y, 1.0); + let cuv = (ground + vsky.cloud.zw) / size + vec2(0.5, -0.5) * (vsky.cloud.x / size); + let ctex = textureSample(t_vclouds, s_repeat, vec2(cuv.x, cuv.y)); + // Vanilla blends in the 8-bit sRGB terms of Omsi.exe's fixed-function stages, + // Vanilla+ in linear light + let encoded = camera.sky_color.w > 0.5; + let fog = camera.fog.xyz; + let lit = min(srgb_encode(sky) + vanilla_sun(d), vec3(1.0)); + var col = select(srgb_decode(lit), lit, encoded); + col = mix(col, fog, vanilla_haze(v)); + if (reach.y > 0.5) { + let c = vanilla_clouds(d, fog, ctex, reach.x, encoded); + col = mix(col, c.rgb, c.a); + } + if (encoded) { + return vec4(srgb_decode(col), 1.0); + } + return vec4(col, 1.0); +} + +// Enhanced graphics: what the enhanced main pass, the sky and the coronas share - the +// light of the physically based sky (see atmosphere.rs), in its units (1 = 10 000 lux), +// and the air between the camera and what it sees. The scene is drawn pre-exposed: +// radiance times `enh.exposure.x`, so that the half-float target keeps its precision by +// night as well as by day. +struct Enhanced { + // x pre-exposure, y the level unlit things are drawn at, z a lit window's radiance + // (pre-exposed), w how bright a light's corona is drawn + exposure: vec4, + // rgb irradiance of the sun after the clouds, w its angular radius (rad) + sun: vec4, + // irradiance from the sky and the ground: order-2 spherical harmonics, rgb + sh: array, 9>, + // rgb radiance of the ground, w the sky table's scale + ground: vec4, + // x weather fog extinction (1/m) at its base, y its height falloff (1/m), z the base + // height (render-origin relative), w clear-air extinction (1/m) at the ground + fog: vec4, + // rgb fog radiance from the light around it (the sun's part is added by angle), + // w the table scale the reflection probe was drawn with + fog_color: vec4, + // x wet roads, y snow cover, z rain, w cloud cover in front of the sun + weather: vec4, + // x mip levels of the probe, y illuminance of a light's core (maplight colour 1), + // z cabin light illuminance, w how much of the sun the clouds let through + lights: vec4, + // rgb the sun disc's irradiance before the clouds, w frame time (s) + sun_disc: vec4, + // x which term the main pass shows alone (OMSI_DEBUG_ENHANCED, 0 = the picture), + // y the puddles' F0, z the envmap photo's strength, w the tone curve's contrast + debug: vec4, + // xyz where the sky cube is drawn from, relative to the camera + eye: vec4, + // x how bright an LED panel's dots burn (0 = off), y whether the LED panels' `\S:n` + // masks keep their mip chain (0: at full resolution, the dots stay visible when small), z 1 + // when lights glare and glow in the night air (the settings' `light_glow`) + led: vec4, + // xyz towards the moon, w its angular radius (rad) + moon: vec4, + // rgb the moon disc's irradiance before the clouds, w how much of the starry sky shows + moon_disc: vec4, + // rgb the sun's irradiance at 1400, 2100 and 2800 m (the cumulus layer) and 7000 m + // (the high thin layer), through the atmosphere from up there + cloud_sun: array, 4>, + // rgb the moonlight on a surface facing the moon (after the clouds), w 1 while the + // shadow maps are the moon's + moon_light: vec4, + // the condensation on the player's bus's panes (optical depths): windscreen, sides, + // rear, and how far the defroster has cleared the windscreen (0..1; omsi-app + // condensation.rs) + condensation: vec4, + // x the cumulus layer's base, y its top (m over the ground), z the altocumulus cover, + // w the storm's activity + layers: vec4, + // the lightning of this frame: x the light it throws on a surface facing it (1 = 10 000 + // lux), yz towards it (horizontal unit vector), w its elevation (rad) + flash: vec4, + // xyz towards the flash (unit vector), w how bright its channel is + flash2: vec4, + // x a number the channel's shape is drawn from + flash3: vec4, + // the clouds' shadow field (cloud_field.rs): xy its middle in cloud space, z one over its + // width, w 1 when there is one + cloud_f1: vec4, + // xy what takes a world point to cloud space, z the height of the plane it is taken on, + // w the share of the sun the main pass has taken off already for the clouds over the camera + cloud_f2: vec4, + // the player's bus's pitch and roll: sin, cos of each (its panes' condensation sits on + // the glass on a slope, `pane_local`) + pane_tilt: vec4, + // Slots of the weather overhaul, one owner each (zero until it fills them): + // the volumetric clouds, the volumetric fog, the precipitation, the bus's panes, the + // surfaces' PBR and the ray tracing, and two spare. + clouds_ext: vec4, + clouds_ext2: vec4, + vol_fog: vec4, + vol_fog2: vec4, + precip_ext: vec4, + glass_ext: vec4, + // (pbr_ext: x the share of the sun's light that still comes as a beam - the rest the + // clouds scatter, `sun_scattered` - y 1 when x is set) + pbr_ext: vec4, + rt_ext: vec4, +}; +@group(0) @binding(11) var enh: Enhanced; +@group(0) @binding(13) var s_lin: sampler; +@group(0) @binding(14) var t_sky_lut: texture_2d; + +const PI: f32 = 3.14159265; + +// Irradiance from the sky and the ground on a surface facing n. +fn sh_irradiance(n: vec3) -> vec3 { + let c = enh.sh; + let e = c[0].rgb * 0.282095 + + c[1].rgb * (0.488603 * n.y) + c[2].rgb * (0.488603 * n.z) + c[3].rgb * (0.488603 * n.x) + + c[4].rgb * (1.092548 * n.x * n.y) + c[5].rgb * (1.092548 * n.y * n.z) + + c[6].rgb * (0.315392 * (3.0 * n.z * n.z - 1.0)) + c[7].rgb * (1.092548 * n.x * n.z) + + c[8].rgb * (0.546274 * (n.x * n.x - n.y * n.y)); + return max(e, vec3(0.0)); +} + +// The lightning's light on a surface facing n: half of it from the cloud overhead and +// round it (a hemisphere), half along the way to the flash itself. +fn flash_irradiance(n: vec3) -> vec3 { + if (enh.flash.x <= 0.0) { + return vec3(0.0); + } + return vec3(0.80, 0.90, 1.0) * enh.flash.x * (0.5 * (0.5 + 0.5 * n.z) + 0.5 * max(dot(n, enh.flash2.xyz), 0.0)); +} + +// Sky radiance towards d (unscaled: times enh.ground.w is the radiance). The table runs +// over the azimuth from the sun (0..π) and the elevation (denser at the horizon). +// The sky table's texture: the table (32 x 48) in its corner and the clouds' shadow field +// (192 x 192) beside it, one texel clear (cloud_field.rs `SKY_TEX_W`, `FIELD_X0`). +const SKY_TEX: vec2 = vec2(225.0, 192.0); +const SKY_TABLE: vec2 = vec2(32.0, 48.0); +const FIELD_ORIGIN: f32 = 33.0; +const FIELD_N: f32 = 192.0; + +fn sky_table_raw(d: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let ls = length(s.xy); + let ld = length(d.xy); + var az = 0.0; + if (ls > 1e-4 && ld > 1e-4) { + az = acos(clamp(dot(s.xy / ls, d.xy / ld), -1.0, 1.0)); + } + let el = asin(clamp(d.z, -1.0, 1.0)); + let v = 0.5 + 0.5 * sign(el) * sqrt(min(abs(el) / 1.5707963, 1.0)); + // (kept a half texel inside the table: its neighbours in the texture are not the sky) + let tx = clamp(vec2(az / PI, v) * SKY_TABLE, vec2(0.5), SKY_TABLE - vec2(0.5)); + return textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).rgb; +} + +// The share of the sun that reaches the point p through the clouds, as against what the main +// pass's sun (`enh.sun`) already has for the camera's own place: the cumulus layer's shadow +// field read where the sun's way through p meets the layer's middle. 1 where there is no +// field, beyond its edge and where the sun is low (the camera's own factor stands there). +fn cloud_shadow_ratio(p: vec3) -> f32 { + let s = camera.sun_dir.xyz; + if (enh.cloud_f1.w < 0.5 || s.z < 0.06) { + return 1.0; + } + let cs = p.xy + s.xy / s.z * (enh.cloud_f2.z - p.z) + enh.cloud_f2.xy; + let uv = (cs - enh.cloud_f1.xy) * enh.cloud_f1.z + vec2(0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + let w = 1.0 - smoothstep(0.36, 0.48, edge); + if (w <= 0.0) { + return 1.0; + } + let tx = vec2(FIELD_ORIGIN, 0.0) + clamp(uv * FIELD_N, vec2(0.5), vec2(FIELD_N - 0.5)); + let f = textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).r; + let ratio = min(f / max(enh.cloud_f2.w, 0.02), 6.0); + return mix(1.0, ratio, w); +} + +fn sky_table(d: vec3) -> vec3 { + return sky_table_raw(d) * enh.ground.w; +} + +// Henyey-Greenstein phase function. +fn hg_phase(c: f32, g: f32) -> f32 { + let g2 = g * g; + return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * c, 1e-4), 1.5)); +} + +// Optical depth of an exponentially thinning layer (extinction sigma at height 0, falling +// off with k per metre) along a straight path of length dist from height h0 to h1. +fn layer_depth(sigma: f32, k: f32, h0: f32, h1: f32, dist: f32) -> f32 { + if (sigma <= 0.0) { + return 0.0; + } + let a = max(h0, 0.0); + let b = max(h1, 0.0); + let dh = b - a; + if (abs(k * dh) < 1e-3) { + return sigma * dist * exp(-k * 0.5 * (a + b)); + } + return sigma * dist * (exp(-k * a) - exp(-k * b)) / (k * dh); +} + +// The air between the camera and a point dist metres away in direction dir (from the +// camera), at heights h0 (camera) and h1 (point) above the fog's base: rgb the light it +// scatters towards the camera (radiance), a what it lets through of the point. +fn air(dir: vec3, dist: f32, h0: f32, h1: f32) -> vec4 { + return air_of(dir, dist, h0, h1, 1.0); +} + +// The same with the clear air's share scaled (0 for the sky, whose table holds it already). +fn air_of(dir: vec3, dist: f32, h0: f32, h1: f32, clear: f32) -> vec4 { + let tau_fog = layer_depth(enh.fog.x, enh.fog.y, h0, h1, dist); + let tau_air = layer_depth(enh.fog.w * clear, 1.0 / 1500.0, h0, h1, dist); + let tau = tau_fog + tau_air; + let t = exp(-tau); + if (tau < 1e-5) { + return vec4(0.0, 0.0, 0.0, 1.0); + } + // clear air takes on the sky's own colour at the horizon in this direction (which + // already holds the glow round the sun); a weather fog glows with the light around it + // and brighter towards the sun + let horizon = sky_table(normalize(vec3(dir.x, dir.y, max(dir.z, 0.0) * 0.3 + 0.03))); + let fog_in = enh.fog_color.rgb + enh.sun.rgb * hg_phase(dot(dir, camera.sun_dir.xyz), 0.55) * 0.9; + let inscatter = mix(horizon, fog_in, tau_fog / tau); + return vec4(inscatter * (1.0 - t), t); +} + +// Enhanced graphics: the sky - the physical sky table, clouds lit by the sun and the sky, +// the sun's disc and the air - and the reflection probe drawn from it. + +// Clouds: a ray-marched volume on the curved Earth, built the way Guerrilla's Horizon Zero +// Dawn and Nubis clouds are (and Frostbite's and Unreal's after them): +// * the layer is a spherical shell over the ground of an Earth of 6371 km (the weather +// model's condensation level up to where its convection stops; 1400-2800 m for the stock +// weather), so the clouds sink to the horizon and thin out into the distance; +// * the weather map (clouds.rs) says where the clouds stand - its field cut by the +// weather's cover, so a cover of 0.3 leaves some 30 % of the sky under cloud - what type +// they are there and how tall they grow; the weather's type (heaps, the flat sheet of an +// overcast deck, a storm's towers with their anvil) gives each its height profile; +// * the base volume (Perlin-Worley) is the body of every cloud, cut by that profile and +// the local coverage; the detail volume, twisted by the curl map, erodes its edges - into +// wisps under a cloud, into cauliflower on its top; +// * the light: the key light (the sun, by night the moon) through the cloud towards it, +// in growing steps, with Hillaire's octaves of multiple scattering, a two-lobe +// Henyey-Greenstein phase (a silver lining towards the sun, a little back-scatter away +// from it) and Schneider's powder term (the dark creases of a cloud seen away from the +// sun); the sky's light from above and the ground's from below by height; integrated per +// step the energy-conserving Frostbite way; far clouds take on the air's colour. +// The window's picture draws them per pixel at a quarter of its size and accumulates them +// over the frames (clouds_ss.wgsl); the sky cube (the reflection probe's source) marches +// a cheaper version of them. +fn cloud_bottom() -> f32 { return enh.layers.x; } +fn cloud_top() -> f32 { return enh.layers.y; } +// The storm's activity: the layer is a cumulonimbus, dense, dark, with its anvil. +fn storm_cb() -> f32 { return enh.layers.w; } +const EARTH_R: f32 = 6371000.0; +// Extinction per metre of the densest cloud (a cumulus' 0.05 - an optical depth of some +// 20 through one a few hundred metres deep). +const CLOUD_SIGMA: f32 = 0.05; +// How far the pictures reach before they repeat (m): all of them divide the clouds' frame +// of 70 km (lib.rs `CLOUD_ORIGIN_PERIOD`), or the clouds would jump where it wraps. +const WEATHER_PERIOD: f32 = 35000.0; +const BASE_PERIOD: f32 = 5000.0; +const DETAIL_PERIOD: f32 = 625.0; +const CURL_PERIOD: f32 = 3500.0; +// How far the curl map twists the detail (in the detail's periods). +const CURL_STRENGTH: f32 = 0.35; +// How much faster than the weather map the base volume and the detail drift: the clouds +// change their shape slowly as they go (cloud_field.rs `BASE_DRIFT` alike). +const BASE_DRIFT: f32 = 1.12; +const DETAIL_DRIFT: f32 = 1.4; +// How much of a cloud the detail erodes at most, and its mean (which the cheap march takes +// off instead). +const DETAIL_ERODE: f32 = 0.32; +const DETAIL_MEAN: f32 = 0.5; +// How far the weather map's field spreads the cover from place to place. +const COVER_SPREAD: f32 = 1.1; +// The droplets' asymmetry: how far forward they scatter (Mie, cumulus droplets, visible light). +const CLOUD_G: f32 = 0.85; +const CLOUD_MAX_DIST: f32 = 60000.0; +// Single scattering and three octaves hold only part of the light a cloud scatters on +// inside it; a cumulus's sunlit side is about as bright as white paper in the sun, E/π, +// which this factor brings it to. +const CLOUD_MS_GAIN: f32 = 2.4; +// The powder term's depth scale (1/extinction): how far into a cloud its sun-facing edge +// keeps its full brightness seen from the side away from the sun. +const CLOUD_POWDER: f32 = 140.0; + +@group(1) @binding(6) var t_cloud_weather: texture_2d; +@group(1) @binding(7) var t_cloud_detail: texture_3d; +@group(1) @binding(8) var s_cloud: sampler; +// (the passes that march the clouds only: the sky cube's and the screen's) +@group(0) @binding(20) var t_cloud_base: texture_3d; +@group(0) @binding(21) var t_cloud_curl: texture_2d; + +fn linearstep(a: f32, b: f32, v: f32) -> f32 { + return clamp((v - a) / (b - a), 0.0, 1.0); +} + +// Height over the curved ground of the point t metres along d from the camera. +fn cloud_height(d: vec3, t: f32) -> f32 { + return camera.cam_pos.z + d.z * t + t * t * (1.0 - d.z * d.z) / (2.0 * EARTH_R); +} + +// Distance along d at which the ray reaches height h over the curved ground (the first +// crossing ahead; -1 when it never does). +fn cloud_shell(d: vec3, h: f32) -> f32 { + let a = (1.0 - d.z * d.z) / (2.0 * EARTH_R); + let b = d.z; + let c = camera.cam_pos.z - h; + if (a < 1e-12) { + return select(-1.0, -c / b, abs(b) > 1e-6 && -c / b > 0.0); + } + let disc = b * b - 4.0 * a * c; + if (disc < 0.0) { + return -1.0; + } + let q = -0.5 * (b + select(-1.0, 1.0, b >= 0.0) * sqrt(disc)); + let r0 = q / a; + let r1 = c / q; + let lo = min(r0, r1); + let hi = max(r0, r1); + if (lo > 0.0) { + return lo; + } + return select(-1.0, hi, hi > 0.0); +} + +// Where along d the ray is inside the layer: from x to y (x < 0: it never is). +fn cloud_span(d: vec3) -> vec2 { + let z = camera.cam_pos.z; + let tb = cloud_shell(d, cloud_bottom()); + let tt = cloud_shell(d, cloud_top()); + var t0 = -1.0; + var t1 = -1.0; + if (z < cloud_bottom()) { + t0 = tb; + t1 = tt; + } else if (z < cloud_top()) { + t0 = 0.0; + t1 = select(tt, tb, d.z < 0.0 && tb > 0.0); + } else { + t0 = tt; + t1 = select(t0 + 8000.0, tb, tb > 0.0); + } + if (t0 < 0.0 || t0 > CLOUD_MAX_DIST) { + return vec2(-1.0, -1.0); + } + if (t1 <= t0) { + t1 = t0 + 8000.0; + } + return vec2(t0, min(t1, t0 + 15000.0)); +} + +// The sun's irradiance at height z (as `cloud_height` gives it) in the cloud layer: +// between the base, middle and top of `enh.cloud_sun`. +fn cloud_sun_at(z: f32) -> vec3 { + let t = clamp((z - cloud_bottom()) / (cloud_top() - cloud_bottom()), 0.0, 1.0) * 2.0; + return select(mix(enh.cloud_sun[1].rgb, enh.cloud_sun[2].rgb, t - 1.0), mix(enh.cloud_sun[0].rgb, enh.cloud_sun[1].rgb, t), t < 1.0); +} + +// The weather's clouds as a whole (cloud_field.rs `CloudParams` alike): the cover; how much +// of it is a closed deck (a full cover, or a sky that rain falls from); the storm; the type +// (1 heaps, a deck's flat sheet ~0.3, thicker as a raining nimbostratus, a storm's towers); +// how much the detail erodes (less on a deck: a textured grey underside, not torn rags) and +// how dense they are (a raining deck and a storm hold more water). +struct CloudSky { + cover: f32, + deck: f32, + storm: f32, + kind: f32, + erode: f32, + dens: f32, +}; + +fn cloud_sky() -> CloudSky { + let cover = clamp(camera.clouds.x, 0.0, 1.0); + let deck = max(smoothstep(0.8, 1.0, cover), smoothstep(0.55, 1.0, enh.weather.w)); + let rain = enh.weather.z; + let storm = storm_cb(); + let kind = max(mix(1.0, 0.3 + 0.35 * rain, deck), storm); + return CloudSky(cover, deck, storm, kind, DETAIL_ERODE * (1.0 - 0.3 * deck), 1.0 + 1.2 * max(deck * (0.4 + 0.6 * rain), storm)); +} + +fn cloud_drift() -> vec2 { + return camera.clouds.yz * 2500.0; +} + +// The weather's own cloud picture over tens of kilometres: a little more or less cover. +fn cloud_picture_bias(p: vec2) -> f32 { + let uv = p / CLOUD_FIELD_TILE + camera.clouds.yz * (2500.0 / CLOUD_FIELD_TILE); + return (textureSampleLevel(t_clouds, s_repeat, uv * 0.35, 5.0).g - 0.5) * 0.16; +} + +// How much of its layer a cloud type fills at height fraction h (cloud_field.rs +// `cloud_profile`): a sheet low in the layer with a flat top; heaps with a flat base and a +// rounded top that narrows (the coverage cut takes ever more of a heap as the profile falls); +// as tall as the weather map's `tall` lets them grow, a storm's to the top. +fn cloud_profile(h: f32, kind: f32, tall: f32) -> f32 { + let top = mix(0.16, 1.0, kind) * mix(0.6, 1.0, tall); + let bottom = linearstep(0.0, 0.05 + 0.05 * kind, h); + return bottom * (1.0 - linearstep(top * mix(0.75, 0.35, kind), top, h)); +} + +// The cloud's density (0..1) at p (h: 0 at the base, 1 at the top of the layer); `lod` the +// base volume's level for the pixel's footprint; without `fine` the detail is taken off on +// average (the sky cube, and the light's far steps). +fn cloud_density(p: vec3, h: f32, lod: f32, sky: CloudSky, fine: bool) -> f32 { + if (h <= 0.0 || h >= 1.0) { + return 0.0; + } + let w = textureSampleLevel(t_cloud_weather, s_cloud, (p.xy + cloud_drift()) / WEATHER_PERIOD, max(lod - 0.5, 0.0)); + let f = w.r * 0.7 + w.a * 0.3; + var cov = clamp(sky.cover + (f - 0.5) * COVER_SPREAD + cloud_picture_bias(p.xy), 0.0, 1.0); + cov = mix(cov, 1.0, sky.deck); + if (cov <= 0.001) { + return 0.0; + } + let kind = clamp(sky.kind + (w.g - 0.5) * 0.5 * (1.0 - sky.deck), 0.0, 1.0); + let prof = cloud_profile(h, kind, max(w.b, sky.storm)); + if (prof <= 0.0 && sky.storm < 0.05) { + return 0.0; + } + let bxy = p.xy + cloud_drift() * BASE_DRIFT; + let bz = h * (cloud_top() - cloud_bottom()); + let b = textureSampleLevel(t_cloud_base, s_cloud, vec3(bxy, bz) / BASE_PERIOD, lod).r; + // (a deck keeps the base volume's picture in its underside, but no holes) + let base = mix(b, 0.5 + 0.5 * b, sky.deck); + var m = clamp((base * prof - (1.0 - cov)) / max(cov, 1e-3), 0.0, 1.0) * cov; + if (sky.storm > 0.05) { + // the storm's anvil: under the tropopause the tower spreads into a flat sheet of ice, + // wide as the coarse picture of the weather round it, which the upper wind pulls + // downwind; thin and torn at its edges + let wide = textureSampleLevel(t_cloud_weather, s_cloud, (p.xy + cloud_drift() + vec2(1500.0, 800.0) * (h - 0.8)) / WEATHER_PERIOD, lod + 3.0).r; + let spread = smoothstep(0.35, 0.7, mix(wide, f, 0.5)); + let anvil = sky.storm * smoothstep(0.74, 0.86, h) * (1.0 - smoothstep(0.9, 1.0, h)) * spread * spread; + m = max(m, anvil * (0.15 + 0.85 * b)); + } + if (m <= 0.0) { + return 0.0; + } + var e = DETAIL_MEAN * sky.erode; + if (fine) { + // the detail, twisted by the curl map (more under a cloud, where the wind tears it) + let curl = textureSampleLevel(t_cloud_curl, s_cloud, bxy / CURL_PERIOD, max(lod + 0.5, 0.0)).rg * 2.0 - vec2(1.0); + let q = vec3(p.xy + cloud_drift() * DETAIL_DRIFT, bz) / DETAIL_PERIOD + vec3(curl * CURL_STRENGTH * (1.0 - h), 0.0); + // (the detail texel is half the base's: one level coarser; read too sharp, a + // repeating 625 m volume drew moire arcs over the sky) + let dl = max(lod + 1.0, 0.0); + let dn = textureSampleLevel(t_cloud_detail, s_cloud, q, dl).r; + // (wispy at the base, billowy higher up; its mean where it can no longer be resolved) + let ed = mix(dn, 1.0 - dn, clamp(h * 4.0, 0.0, 1.0)); + e = mix(ed, DETAIL_MEAN, smoothstep(1.5, 3.0, dl)) * sky.erode; + } + return clamp((m - e) / (1.0 - e), 0.0, 1.0); +} + +// Extinction (1/m) at p. +fn cloud_sigma(p: vec3, h: f32, lod: f32, sky: CloudSky, fine: bool) -> f32 { + return cloud_density(p, h, lod, sky, fine) * CLOUD_SIGMA * sky.dens; +} + +// The clouds along d: the light they scatter towards the camera (radiance, the air's +// colour taken on in the distance from `below`, the sky behind them), how much of the sky +// behind gets through, and how far they are seen (their transmittance-weighted depth). +struct CloudMarch { + light: vec3, + trans: f32, + dist: f32, +}; + +// The march: `steps` through the layer, starting `jitter` (0..1) into the first; `pix` a +// pixel's angular size; without `fine` the detail is left out. +fn cloud_march(d: vec3, below: vec3, steps: i32, jitter: f32, pix: f32, fine: bool) -> CloudMarch { + var out = CloudMarch(vec3(0.0), 1.0, 1e6); + let sky = cloud_sky(); + if (sky.cover <= 0.001) { + return out; + } + let span = cloud_span(d); + if (span.x < 0.0) { + return out; + } + let t0 = span.x; + let t1 = span.y; + out.dist = t0; + // (more steps for the long, low rays: a fixed count across up to 15 km slices the layer + // into horizontal planes, drawn as rings round the zenith and bands at the horizon) + let n = i32(clamp(f32(steps) * (1.0 + 2.0 * (1.0 - abs(d.z))), f32(steps), f32(steps) * 3.0)); + let ds = (t1 - t0) / f32(n); + // the key light: the sun, and the moon once the sun has gone from the clouds too + let night = camera.sun_dir.z < -0.12; + let ld = select(normalize(camera.sun_dir.xyz), normalize(enh.moon.xyz), night); + let cos_l = dot(d, ld); + // (the phase of each octave: weaker and flatter, Hillaire 2016) + var phase: array; + var c = 1.0; + for (var o = 0; o < 3; o = o + 1) { + phase[o] = mix(hg_phase(cos_l, 0.8 * c), hg_phase(cos_l, -0.3 * c), 0.3); + c = c * 0.5; + } + let sky_top = sh_irradiance(vec3(0.0, 0.0, 1.0)) / PI; + let ground = sh_irradiance(vec3(0.0, 0.0, -1.0)) / PI; + let deep = max(sky.deck, sky.storm); + let shade = mix(0.20, 0.03, deep); + let tau_deck = max(enh.clouds_ext2.x, 1.0); + // (a texel of the base volume, m) + let texel = BASE_PERIOD / f32(textureDimensions(t_cloud_base).x); + var trans = 1.0; + var acc = vec3(0.0); + var hit = 0.0; + var hit_w = 0.0; + var t = t0 + ds * jitter; + for (var i = 0; i < n; i = i + 1) { + let p = vec3(cloud_ground(d, t), cloud_height(d, t)); + let h = (p.z - cloud_bottom()) / (cloud_top() - cloud_bottom()); + // (the step's length counts as the footprint too: a long step through a sharp volume + // reads it as contour lines) + let lod = log2(max(max(t * pix, 0.5 * ds) / texel, 1.0)); + let sigma = cloud_sigma(p, h, lod, sky, fine); + if (sigma > 1e-6) { + // the key light reaching p through the cloud towards it, in steps growing 1.9 + // times (2 km in all; the detail in the first three only) + var od = 0.0; + var ls = 40.0; + var lt = 0.0; + for (var k = 0; k < 6; k = k + 1) { + let q = p + ld * (lt + fract(jitter + 0.61803399 * f32(k + 1)) * ls); + let hq = (q.z - cloud_bottom()) / (cloud_top() - cloud_bottom()); + if (hq >= 1.0 || hq <= 0.0) { + break; + } + od = od + cloud_sigma(q, hq, lod + 0.5 + f32(k) * 0.5, sky, fine && k < 3) * ls; + lt = lt + ls; + ls = ls * 1.9; + } + let key = select(cloud_sun_at(p.z), enh.moon_disc.rgb, night); + var direct = vec3(0.0); + var a = 1.0; + var b = 1.0; + for (var o = 0; o < 3; o = o + 1) { + direct = direct + key * (a * phase[o] * exp(-od * b)); + a = a * 0.5; + b = b * 0.4; + } + // the powder term: seen away from the light, a cloud's thin outer edge facing + // it has scattered less light back out than its depths + let powder = 1.0 - exp(-sigma * CLOUD_POWDER); + direct = direct * mix(powder, 1.0, 0.35 + 0.65 * clamp(0.5 + 0.5 * cos_l, 0.0, 1.0)); + // The sky's light from above (and the ground's from below, low in the layer) + // gets down through the cloud over this point by scattering: the two-stream + // 1 / (1 + 3/4 (1 - g) od) rather than Beer's beam, so that a deck stays twice + // as bright where it is half as deep and its underside keeps a picture of its + // own; the depth towards the light stands for the depth overhead. The floor is + // what comes in sideways through the gaps. Under a shut deck the sky's light is + // already what the deck lets through (the sky model's, `clouds_ext2.x` its depth): + // there the depth over this point only makes it brighter or darker than the mean. + let through = 1.0 / (1.0 + 0.75 * (1.0 - CLOUD_G) * od); + let rel = clamp((1.0 + 0.75 * (1.0 - CLOUD_G) * tau_deck) / (1.0 + 0.75 * (1.0 - CLOUD_G) * od * max(ld.z, 0.15)), 0.35, 2.0); + let amb = mix(ground * 0.45 + sky_top * 0.55, sky_top * 1.1, clamp(h * 1.4, 0.0, 1.0)) * mix(shade + (1.0 - shade) * through, rel, deep); + let light = direct * CLOUD_MS_GAIN + amb; + // Frostbite: the light scattered over the step, dimmed by the cloud before it + let dt = exp(-sigma * ds); + acc = acc + trans * light * (1.0 - dt); + hit = hit + t * trans * (1.0 - dt); + hit_w = hit_w + trans * (1.0 - dt); + trans = trans * dt; + if (trans < 0.005) { + trans = 0.0; + break; + } + } + t = t + ds; + } + // far clouds take on the colour of the air in front of them, and beyond 40 km fade out + let dist = select(t0, hit / max(hit_w, 1e-4), hit_w > 1e-4); + let aerial = 1.0 - exp(-dist / 22000.0); + let fade = (1.0 - smoothstep(40000.0, CLOUD_MAX_DIST, dist)) * smoothstep(-0.01, 0.02, d.z + select(0.0, 1.0, camera.cam_pos.z > cloud_bottom())); + out.light = mix(acc, below * (1.0 - trans), aerial) * fade; + out.trans = 1.0 - (1.0 - trans) * fade; + out.dist = dist; + return out; +} + +// Fractal value noise with its octaves faded out where they get finer than the pixel's +// footprint `fp` (in p's units): left in, the fine octaves of a distant layer alias into a +// marbled pattern of contour lines; faded to their mean, the layer softens into the haze it +// is at that distance. +fn hc_fbm(p: vec2, fp: f32, octaves: i32) -> f32 { + var v = 0.0; + var a = 0.5; + var q = p; + var f = fp; + for (var i = 0; i < octaves; i = i + 1) { + let keep = 1.0 - smoothstep(0.1, 0.35, f); + v = v + a * mix(0.5, vnoise(q), keep); + q = q * 2.03 + vec2(17.0, 9.0); + f = f * 2.03; + a = a * 0.5; + } + return v / (1.0 - 2.0 * a); +} + +// The high layers over the cumulus, analytic (drawn at the picture's own resolution, `pix` +// a pixel's angular size): altocumulus, a sheet of cells at 4 km (the middle levels' +// moisture ahead of a front), and cirrus, thin wisps of ice at 8 km drawn out by the upper +// wind. Both are sparse: cirrus in patches tens of kilometres apart, many skies without +// any; thicker and wider spread as a front's veil comes (the veil's milky light itself is in +// the sky table, atmosphere.rs). rgb: the sky `bg` with them over it, a: how much they +// cover. A shut deck hides them. +fn high_clouds(d: vec3, bg: vec3, pix: f32) -> vec4 { + let sky = cloud_sky(); + let closed = max(sky.deck, smoothstep(0.85, 1.0, sky.cover)); + var col = bg; + var cover = 0.0; + if (d.z <= 0.0 || closed >= 0.999) { + return vec4(col, 0.0); + } + let sd = normalize(camera.sun_dir.xyz); + let cos_sun = dot(d, sd); + let sky_top = sh_irradiance(vec3(0.0, 0.0, 1.0)) / PI; + let drift = cloud_drift(); + // altocumulus + let alto_cover = enh.layers.z * (1.0 - closed) * smoothstep(0.03, 0.2, d.z); + if (alto_cover > 0.01 && camera.cam_pos.z < 4000.0) { + let t_alto = (4000.0 - camera.cam_pos.z) / max(d.z, 0.03); + let pa = cloud_ground(d, t_alto) + drift * 1.4; + // (a pixel's footprint on the sheet, m: stretched along the view towards the horizon) + let fa = t_alto * pix / max(d.z, 0.05); + // (its cells: the detail volume's billows on a slice, at the mip level of the + // footprint, in patches the weather map's small field lays out) + let rolls = textureSampleLevel(t_cloud_weather, s_cloud, pa / 9000.0, log2(max(fa / (9000.0 / 512.0), 1.0))).a; + let cl = log2(max(fa / (1400.0 / 32.0), 1.0)); + let cells = 1.0 - textureSampleLevel(t_cloud_detail, s_cloud, vec3(pa / 1400.0, 0.37), cl).r; + let dens = rolls * 0.6 + cells * 0.4; + let edge = 0.1 + 0.1 * min(cl, 3.0); + let thick = smoothstep(1.0 - alto_cover * 0.9 - edge, 1.0 - alto_cover * 0.9 + edge, dens); + let sun = mix(enh.cloud_sun[2].rgb, enh.cloud_sun[3].rgb, 0.4); + let lit = sun * (0.10 + 0.55 * hg_phase(cos_sun, 0.7)) / PI; + let under = mix(1.0, 0.55, thick * thick); + let alto_col = (lit * mix(0.6, 1.0, cells) + sky_top * 0.85) * under; + let alto_a = thick * 0.75 * (1.0 - smoothstep(25000.0, 70000.0, t_alto)); + col = mix(col, alto_col, alto_a); + cover = alto_a; + } + // cirrus: how much of the sky it may take - the veil of a coming front, and a few + // wisps of fair weather over the heaps (none in a clear sky's dry air) + let veil = enh.cloud_sun[0].w; + let amount = clamp(0.7 * veil + 0.45 * smoothstep(0.1, 0.45, sky.cover) * (1.0 - sky.deck), 0.0, 1.0) * (1.0 - closed); + var hi_cover = 0.0; + if (amount > 0.01 && camera.cam_pos.z < 8000.0) { + let t_hi = (8000.0 - camera.cam_pos.z) / max(d.z, 0.02); + let ph = cloud_ground(d, t_hi) + drift * 1.7; + let fp = t_hi * pix / max(d.z, 0.05); + // (where: patches of some 20 km) + let field = hc_fbm(ph / 22000.0 + vec2(3.1, 7.7), fp / 22000.0, 3); + let patchy = smoothstep(0.62 - 0.3 * amount, 0.85 - 0.2 * amount, field); + if (patchy > 0.001) { + // (the wind aloft lays the fibres out; it turns slowly across the sky) + let turn = 0.6 + 1.2 * (hc_fbm(ph / 60000.0, 0.0, 2) - 0.5); + let ax = vec2(cos(turn), sin(turn)); + let r = vec2(dot(ph, ax), dot(ph, vec2(-ax.y, ax.x))); + // (the wisps: soft elongated tufts some kilometres long, their edges fading over + // hundreds of metres - real cirrus has no hard rim) + let warp = hc_fbm(r / vec2(12000.0, 6000.0) + vec2(1.7, 4.2), fp / 6000.0, 2) - 0.5; + let body = hc_fbm((r + vec2(0.0, 1500.0 * warp)) / vec2(14000.0, 2600.0) + vec2(5.3, 1.9), fp / 2600.0, 4); + // (its edge kept some pixels wide: low towards the horizon a wisp seen across its + // width is only a few pixels high, and an edge sharpened to the noise drew thin + // bright lines there; further down it is taken at its mean, an even sheen) + let we = 2.0 * fp / 2600.0; + let wisp = mix(smoothstep(0.42 - we, 0.8 + we, body), 0.25, smoothstep(0.04, 0.16, fp / 2600.0)); + // (the fibres in them: fine streaks along the wind, combed and bent by the same + // slow field, that only shade the wisp - a hair-like grain of brighter and + // fainter ice, never a line of its own. A threshold on them drew sharp parallel + // contour lines over the sky.) + // (a finer field of its own lets the strands part and gather like hair, not run + // side by side as one bent comb) + let comb = hc_fbm(r / vec2(3500.0, 1400.0) + vec2(8.1, 2.6), fp / 1400.0, 2) - 0.5; + let f = vec2(r.x / 2600.0, (r.y + 1500.0 * warp + 500.0 * comb) / 450.0); + let fib = hc_fbm(f, 2.0 * fp / 450.0, 4); + // (what the footprint has blurred out: the grain evens out into the wisp's sheen + // well before a strand narrows to a pixel) + let lost = smoothstep(0.05, 0.45, fp / 450.0); + let he = 2.0 * fp / 450.0; + let hair = mix(1.0, 0.45 + 1.1 * smoothstep(0.25 - he, 0.85 + he, fib), 0.4 * (1.0 - lost)); + let dens = patchy * wisp * hair; + hi_cover = clamp(dens, 0.0, 1.0) * mix(0.3, 0.6, clamp(veil, 0.0, 1.0)) * smoothstep(0.02, 0.15, d.z); + // (lit by the sun at its own height, through thin ice: forward scattering + // towards the sun, a soft grey-white away from it) + let hi_sun = enh.cloud_sun[3].rgb * (0.2 + 0.4 * hg_phase(cos_sun, 0.6) * PI); + // (never darker than the sky behind, but kept in its own colour: a per-channel + // max took the sky's blue and the sun's red and tinted the fibres pink) + let lw = vec3(0.2126, 0.7152, 0.0722); + let veiled = mix(col, hi_sun / PI + sky_top, hi_cover); + col = veiled * max(1.0, dot(col, lw) / max(dot(veiled, lw), 1e-6)); + } + } + return vec4(col, 1.0 - (1.0 - cover) * (1.0 - hi_cover)); +} + +// The lightning's colour: a channel of plasma at some 30 000 K, scattered by the cloud +const FLASH_COLOUR: vec3 = vec3(0.80, 0.90, 1.0); + +fn flash_dir() -> vec3 { + return enh.flash2.xyz; +} + +// The light a flash puts into the cloud at p (as radiance towards the camera): the cloud +// lights up round the flash, brightest next to its channel, fading with the distance from +// it through the cloud (a cell's size is some ten kilometres; the light spreads by +// multiple scattering far beyond the flash itself). +fn flash_in_cloud(p: vec3, d: vec3) -> vec3 { + if (enh.flash.x <= 0.0) { + return vec3(0.0); + } + let fd = flash_dir(); + let ang = acos(clamp(dot(d, fd), -1.0, 1.0)); + let near = exp(-ang * ang / (2.0 * 0.22 * 0.22)); + let broad = exp(-ang * ang / (2.0 * 0.9 * 0.9)); + return FLASH_COLOUR * enh.flash.x * (8.0 * near + 1.0 * broad); +} + +// The channel of a cloud-to-ground stroke: a jagged line from the cloud's base to the +// ground (a fractal in the real thing; sines of three scales with the flash's seed make the +// same crooked path, one branch breaking off a third of the way down), seen as a thin hot +// core in a wider halo. +fn flash_channel(d: vec3) -> vec3 { + let k = enh.flash2.w; + if (k <= 0.01) { + return vec3(0.0); + } + let az = vec2(enh.flash.y, enh.flash.z); + // angle sideways from the flash's vertical plane, and the elevation, of this pixel + let across = (d.x * az.y - d.y * az.x); + let along = d.x * az.x + d.y * az.y; + if (along <= 0.0) { + return vec3(0.0); + } + let el = atan2(d.z, along); + let top = enh.flash.w + 0.14; + let bottom = 0.0; + if (el > top || el < bottom - 0.02) { + return vec3(0.0); + } + let u = clamp((top - el) / (top - bottom), 0.0, 1.0); + let seed = enh.flash3.x; + let amp = (top - bottom) * 0.22; + let path = amp * (0.5 * sin(6.0 * u + seed) + 0.28 * sin(17.0 * u + 2.3 * seed) + 0.14 * sin(41.0 * u + 3.1 * seed)); + var dist = abs(across - path); + // the branch: leaves the channel at a third of its way down and bends away from it + let ub = 0.33; + if (u > ub && u < ub + 0.4) { + let pb = amp * (0.5 * sin(6.0 * ub + seed) + 0.28 * sin(17.0 * ub + 2.3 * seed) + 0.14 * sin(41.0 * ub + 3.1 * seed)); + let side = select(-1.0, 1.0, fract(seed * 7.0) > 0.5); + let branch = pb + side * (u - ub) * (top - bottom) * 0.45 + amp * 0.12 * sin(33.0 * (u - ub) + seed); + dist = min(dist, abs(across - branch) * 1.6); + } + let core = exp(-dist * dist / (2.0 * 0.0009 * 0.0009)); + let halo = exp(-dist * dist / (2.0 * 0.008 * 0.008)); + return FLASH_COLOUR * k * (60.0 * core + 1.5 * halo) * (1.0 - 0.5 * u); +} + +// --- the dome + +// Where the screen's clouds were traced from (cloud_pass.rs `CloudView`): the inverse of the +// view-projection without its translation (clip to direction), that matrix this frame and +// for the picture in the history, how far the camera and the clouds moved since (xyz, m; +// w the history's weight, 0 without one), the trace's and the history's sizes, the +// picture's own size, x the frame's number (with this pass's round added, `probe.p.x`) and +// w the march's steps, and x 1 when the dome may look the clouds up, y the old table +// scale over the new one (the history is kept divided by it), z a traced pixel's angular +// size (rad). +struct CloudView { + inv_vp: mat4x4, + vp: mat4x4, + prev_vp: mat4x4, + moved: vec4, + size: vec4, + full: vec4, + frame: vec4, + params: vec4, +}; +@group(1) @binding(12) var cview: CloudView; +// The screen's clouds, accumulated (clouds_ss.wgsl `fs_enhanced_cloud_resolve`): rgb the +// light they scatter (divided by the table scale), a what they let through of the sky behind. +@group(0) @binding(17) var t_clouds_ss: texture_2d; +// The reflection probe (its sharpest level is the sky cube: the sky, the clouds, and their +// cover in alpha): the sky of a view the screen's clouds do not cover. +@group(0) @binding(12) var t_env_probe: texture_cube; + +// The weather's fog towards the sky from height h0 over its base, 30 km of it. The weather's +// fog range is the game's draw distance as much as the air's haze (a fair day's two +// kilometres, a rainy one's two hundred metres: the game's sky stayed blue or showed its +// clouds over them), so the sky takes a sixth of its density: the horizon is lost in it +// and the sky low over it whitens, but a fair sky stays blue overhead and an overcast one +// keeps the shapes of its deck - a uniform grey sheet hid them; only a real fog (some tens +// of metres) still hides the sky. +fn sky_air(d: vec3, h0: f32) -> vec4 { + let k = 0.16; + let tau_fog = layer_depth(enh.fog.x * k, enh.fog.y, h0, h0 + 30000.0 * max(d.z, 0.0), 30000.0); + if (tau_fog < 1e-5) { + return vec4(0.0, 0.0, 0.0, 1.0); + } + let t = exp(-tau_fog); + let fog_in = enh.fog_color.rgb + enh.sun.rgb * hg_phase(dot(d, camera.sun_dir.xyz), 0.55) * 0.9; + return vec4(fog_in * (1.0 - t), t); +} + +// The screen's clouds towards d, and whether there are any (a < 0: none - not traced, or +// outside the traced view). +fn screen_clouds(d: vec3) -> vec4 { + if (cview.params.x < 0.5) { + return vec4(-1.0); + } + let c = cview.vp * vec4(d, 1.0); + if (c.w <= 1e-6) { + return vec4(-1.0); + } + let ndc = c.xy / c.w; + if (abs(ndc.x) > 1.002 || abs(ndc.y) > 1.002) { + return vec4(-1.0); + } + let uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + return clouds_ss_bicubic(uv); +} + +// The screen's clouds at uv, filtered up from their picture of half the window's size with +// a Catmull-Rom spline (nine bilinear taps): a plain bilinear lookup blurred their edges +// over four of the window's pixels. Clamped to the four nearest texels, so the spline's +// overshoot leaves no dark or bright rims. +fn clouds_ss_bicubic(uv: vec2) -> vec4 { + let size = vec2(textureDimensions(t_clouds_ss)); + let sp = uv * size; + let tc1 = floor(sp - vec2(0.5)) + vec2(0.5); + let f = sp - tc1; + let w0 = f * (vec2(-0.5) + f * (vec2(1.0) - 0.5 * f)); + let w1 = vec2(1.0) + f * f * (vec2(-2.5) + 1.5 * f); + let w2 = f * (vec2(0.5) + f * (vec2(2.0) - 1.5 * f)); + let w3 = f * f * (vec2(-0.5) + 0.5 * f); + let w12 = w1 + w2; + let tc0 = (tc1 - vec2(1.0)) / size; + let tc3 = (tc1 + vec2(2.0)) / size; + let tc12 = (tc1 + w2 / w12) / size; + var c = textureSampleLevel(t_clouds_ss, s_lin, vec2(tc0.x, tc0.y), 0.0) * (w0.x * w0.y); + c = c + textureSampleLevel(t_clouds_ss, s_lin, vec2(tc12.x, tc0.y), 0.0) * (w12.x * w0.y); + c = c + textureSampleLevel(t_clouds_ss, s_lin, vec2(tc3.x, tc0.y), 0.0) * (w3.x * w0.y); + c = c + textureSampleLevel(t_clouds_ss, s_lin, vec2(tc0.x, tc12.y), 0.0) * (w0.x * w12.y); + c = c + textureSampleLevel(t_clouds_ss, s_lin, vec2(tc12.x, tc12.y), 0.0) * (w12.x * w12.y); + c = c + textureSampleLevel(t_clouds_ss, s_lin, vec2(tc3.x, tc12.y), 0.0) * (w3.x * w12.y); + c = c + textureSampleLevel(t_clouds_ss, s_lin, vec2(tc0.x, tc3.y), 0.0) * (w0.x * w3.y); + c = c + textureSampleLevel(t_clouds_ss, s_lin, vec2(tc12.x, tc3.y), 0.0) * (w12.x * w3.y); + c = c + textureSampleLevel(t_clouds_ss, s_lin, vec2(tc3.x, tc3.y), 0.0) * (w3.x * w3.y); + let i = vec2(tc1 - vec2(0.5)); + let mx = vec2(size) - vec2(1); + let a = textureLoad(t_clouds_ss, clamp(i, vec2(0), mx), 0); + let b = textureLoad(t_clouds_ss, clamp(i + vec2(1, 0), vec2(0), mx), 0); + let e = textureLoad(t_clouds_ss, clamp(i + vec2(0, 1), vec2(0), mx), 0); + let g = textureLoad(t_clouds_ss, clamp(i + vec2(1, 1), vec2(0), mx), 0); + return clamp(c, min(min(a, b), min(e, g)), max(max(a, b), max(e, g))); +} + +@fragment +fn fs_enhanced(in: VsOut) -> @location(0) vec4 { + return enhanced_sky(in, true); +} + +// The sky towards the dome's pixel: the table, the high layers and the screen's clouds over +// it, the weather's fog, the sun's disc, the moon and the stars, the lightning; where the +// screen's clouds were not traced (`screen` false: a mirror, or another view beyond the +// window's) the reflection probe's sky cube instead. +fn enhanced_sky(in: VsOut, screen: bool) -> vec4 { + let d = normalize(in.dir); + let pre = enh.exposure.x; + // (a pixel's angular size, for the high layers' filtering) + let pix = max(length(fwidth(d)), 1e-5); + var ss = vec4(-1.0); + if (screen) { + ss = screen_clouds(d); + } + var col = vec3(0.0); + var cover = 0.0; + if (ss.a >= 0.0) { + let hi = high_clouds(d, sky_table(d), pix); + col = hi.rgb * ss.a + ss.rgb * enh.ground.w; + cover = 1.0 - ss.a * (1.0 - hi.a); + // the weather's fog along the whole way to the horizon (the clear air is in the + // table already: taken again, it whitened the whole sky) + let h0 = camera.cam_pos.z - enh.fog.z; + let a = sky_air(d, h0); + col = col * a.a + a.rgb; + } else { + let p = textureSampleLevel(t_env_probe, s_lin, vec3(d.x, d.z, d.y), 0.0); + col = p.rgb * enh.fog_color.w; + cover = clamp(p.a, 0.0, 1.0); + } + var sun_px = vec3(0.0); + // the sun: a limb-darkened disc as bright as its irradiance spread over its size, + // behind whatever cloud there is + let sd = normalize(camera.sun_dir.xyz); + let r = enh.sun.w; + let cosang = dot(d, sd); + if (cosang > cos(r * 1.5) && d.z > -0.02) { + let x = clamp(acos(clamp(cosang, -1.0, 1.0)) / r, 0.0, 1.5); + let disc = 1.0 - smoothstep(0.85, 1.1, x); + let limb = 1.0 - 0.6 * (1.0 - sqrt(max(1.0 - min(x, 1.0) * min(x, 1.0), 0.0))); + let h0 = camera.cam_pos.z - enh.fog.z; + let t = sky_air(d, h0).a; + sun_px = enh.sun_disc.rgb / (PI * r * r) * disc * limb * (1.0 - cover) * enh.lights.w * t; + } + col = col + night_sky(d, cover, fwidth(d)); + // lightning (not part of the accumulated clouds: a flash lasts a tenth of a second): + // the cloud lit from inside, the haze lit a little, and the channel + if (enh.flash.x > 0.0) { + col = col + flash_in_cloud(vec3(0.0), d) * (0.12 + 0.88 * cover); + col = col + flash_channel(d); + } + // the dome is drawn pre-exposed; the disc only a little over white: the eye's glare round + // it is drawn from its light (fog_lamps.wgsl `sun_glare`), and from the disc's pixels + // as well the glow would have counted it twice + return vec4(min(col * pre, vec3(4000.0)) + min(sun_px * pre, vec3(24.0)), 1.0); +} + +// The mirrors of an Enhanced picture are drawn with the plain shading (lib.rs, the cost of +// the enhanced shader in a small picture), but their sky is this one, tone-mapped here +// with the window's curve (post.wgsl `natural_tone`): the plain envir.cfg sky showed a blue +// dusk in the mirrors over the window's grey one, or the other way round (#1754, #1449). +// The meter's correction is left out (by day a few tenths of a stop at most). +fn mirror_tone(color: vec3, contrast: f32) -> vec3 { + let knee = 0.66; + let x = max(color, vec3(0.0)); + let y = 0.18 * pow(x / 0.18 + vec3(1e-7), vec3(contrast)); + let peak = max(y.r, max(y.g, y.b)); + if (peak <= knee) { + return y; + } + let d = 1.0 - knee; + let shoulder = vec3(knee) + d * (vec3(1.0) - exp(-(y - vec3(knee)) / d)); + let soft = select(y, shoulder, y > vec3(knee)); + let np = knee + d * (1.0 - exp(-(peak - knee) / d)); + let o = mix(y * (np / peak), soft, 0.4); + let g = 1.0 - 1.0 / (0.3 * (peak - np) + 1.0); + return mix(o, vec3(np), g); +} + +@fragment +fn fs_enhanced_mirror(in: VsOut) -> @location(0) vec4 { + let hdr = enhanced_sky(in, false).rgb; + return vec4(clamp(mirror_tone(hdr, max(enh.debug.w, 1.0)), vec3(0.0), vec3(1.0)), 1.0); +} + +fn star_hash(c: vec3) -> vec4 { + var x = vec4(bitcast>(c), 0x9e3779b9u).xyzw; + x = x * 1664525u + 1013904223u; + x.x = x.x + x.y * x.w; + x.y = x.y + x.z * x.x; + x.z = x.z + x.x * x.y; + x.w = x.w + x.y * x.z; + x = x ^ (x >> vec4(16u)); + x.x = x.x + x.y * x.w; + x.y = x.y + x.z * x.x; + x.z = x.z + x.x * x.y; + x.w = x.w + x.y * x.z; + return vec4(x & vec4(0xffffffu)) / 16777216.0; +} + +// The moon and the stars towards d (radiance), behind what cloud covers it. The moon is a +// lit sphere: its lit side faces the sun, its phase is what the sun's direction makes of +// it, and its grey seas darken parts of the disc. The stars are a few thousand points +// fixed in the sky, of a few magnitudes, slightly coloured; they show only where the sky +// behind them is dark - a lit city's glow and the haze leave the brightest few. +fn night_sky(d: vec3, cover: f32, pix: vec3) -> vec3 { + var col = vec3(0.0); + if (d.z < -0.01) { + return col; + } + let h0 = camera.cam_pos.z - enh.fog.z; + let through = sky_air(d, h0).a * (1.0 - cover); + if (through < 0.01) { + return col; + } + let m = enh.moon.xyz; + let r = enh.moon.w; + let cm = dot(d, m); + if (cm > cos(r * 1.3) && max(enh.moon_disc.r, enh.moon_disc.g) > 0.0) { + // the point on the moon's sphere seen in direction d + let right = normalize(cross(m, vec3(0.0, 0.0, 1.0)) + vec3(1e-5, 0.0, 0.0)); + let up = cross(right, m); + let q = vec2(dot(d, right), dot(d, up)) / r; + let q2 = dot(q, q); + let rim = 1.0 - smoothstep(0.92, 1.05, sqrt(q2)); + let nz = sqrt(max(1.0 - q2, 0.0)); + let n = normalize(right * q.x + up * q.y - m * nz); + let sun_side = smoothstep(-0.04, 0.08, dot(n, normalize(camera.sun_dir.xyz))); + // the seas: a few broad dark patches fixed on the face + let sea = smoothstep(0.45, 0.7, cloud_fbm(q * 1.7 + vec2(3.1, 7.7))); + let albedo = 1.0 - 0.38 * sea; + // (as bright as the lit part's share of the irradiance spread over the disc; the + // dark part keeps a trace of earthshine) + let lit_share = max(0.5 + 0.5 * dot(-m, normalize(camera.sun_dir.xyz)), 0.03); + let l = enh.moon_disc.rgb / (PI * r * r * lit_share) * (sun_side + 0.004) * albedo * rim; + col = col + l * through; + } + // the stars: one candidate in some of the cells of a grid on the sphere + let vis = enh.moon_disc.w; + if (vis > 0.0 && d.z > 0.0) { + let cells = 140.0; + let g = d * cells; + let c = vec3(floor(g)); + let h = star_hash(c); + let density = 0.014; + if (h.x < density) { + let p = (vec3(c) + vec3(0.25) + h.yzw * 0.5) / cells; + let sd = normalize(p); + let ang = acos(clamp(dot(d, sd), -1.0, 1.0)); + // a point of light about a pixel across + let size = clamp(length(pix) * 0.6, 1e-5, 0.004); + let spot = exp(-ang * ang / (size * size)); + // brightness: many faint ones, a few bright (a power law of the magnitudes) + let b = pow(1.0 - h.x / density, 4.0); + let tint = mix(vec3(1.0, 0.86, 0.72), vec3(0.8, 0.88, 1.0), h.w); + // the faintest that shows against the sky behind it (in the picture's own + // units): a dark country sky shows thousands, a city's glow the few dozen + // brightest, a twilight none + let sky_l = dot(sky_table(d), vec3(0.2126, 0.7152, 0.0722)) * enh.exposure.x; + let limit = clamp(sky_l * 90.0 + (1.0 - vis), 0.0, 1.2); + let shows = smoothstep(limit, limit + 0.15, b) * (1.0 - smoothstep(0.03, 0.1, sky_l)); + col = col + tint * (0.04 + 1.4 * b) * spot * shows * through / max(enh.exposure.x, 1e-6) * smoothstep(0.0, 0.15, d.z); + } + } + return col; +} + +// --- the reflection probe: a cube map of the sky seen from the camera, drawn now and then +// and blurred into its mip levels for rough surfaces (divided by the table scale, which +// the main pass multiplies back in). +struct ProbeParams { + // x first face of this pass (0 or 3), y roughness, z face size of level 0, w level + p: vec4, +}; +@group(0) @binding(15) var probe: ProbeParams; +@group(0) @binding(16) var t_probe_src: texture_cube; + +// Direction of a texel of cube face f (u, v in -1..1, v down), in cube coordinates. +fn face_dir(f: i32, u: f32, v: f32) -> vec3 { + var c = vec3(-u, -v, -1.0); + switch f { + case 0: { c = vec3(1.0, -v, -u); } + case 1: { c = vec3(-1.0, -v, u); } + case 2: { c = vec3(u, 1.0, v); } + case 3: { c = vec3(u, -1.0, -v); } + case 4: { c = vec3(u, -v, 1.0); } + default: {} + } + return normalize(c); +} + +fn cube_to_world(c: vec3) -> vec3 { + return vec3(c.x, c.z, c.y); +} + +struct ProbeOut { + @location(0) a: vec4, + @location(1) b: vec4, + @location(2) c: vec4, +}; + +struct FsIn { + @builtin(position) clip: vec4, +}; + +@vertex +fn vs_probe(@builtin(vertex_index) i: u32) -> FsIn { + let x = f32(i32(i & 1u) * 4 - 1); + let y = f32(i32(i >> 1u) * 4 - 1); + return FsIn(vec4(x, y, 0.0, 1.0)); +} + +fn probe_sky(f: i32, uv: vec2) -> vec4 { + let c = face_dir(f, uv.x, uv.y); + let d = cube_to_world(c); + var col: vec3; + if (d.z >= 0.0) { + // the sky cube (lib.rs binds it as level 0's source), already divided by the table + // scale, with the clouds' cover in alpha (the dome hides the sun's disc by it where + // it reads the probe) + return textureSampleLevel(t_probe_src, s_lin, c, 0.0); + } else { + // below the horizon: the table's distant ground, with the houses and trees of a + // town darkening the band just under the horizon + col = sky_table(d); + let band = smoothstep(0.02, 0.25, -d.z); + col = mix(col, enh.ground.rgb * 0.8, 1.0 - band * 0.6); + } + return vec4(col / max(enh.ground.w, 1e-8), 0.0); +} + +@fragment +fn fs_probe_sky(in: FsIn) -> ProbeOut { + let size = probe.p.z; + let uv = in.clip.xy / size * 2.0 - vec2(1.0); + let f0 = i32(probe.p.x); + return ProbeOut(probe_sky(f0, uv), probe_sky(f0 + 1, uv), probe_sky(f0 + 2, uv)); +} + +fn radical_inverse(i: u32) -> f32 { + var b = i; + b = (b << 16u) | (b >> 16u); + b = ((b & 0x55555555u) << 1u) | ((b & 0xAAAAAAAAu) >> 1u); + b = ((b & 0x33333333u) << 2u) | ((b & 0xCCCCCCCCu) >> 2u); + b = ((b & 0x0F0F0F0Fu) << 4u) | ((b & 0xF0F0F0F0u) >> 4u); + b = ((b & 0x00FF00FFu) << 8u) | ((b & 0xFF00FF00u) >> 8u); + return f32(b) * 2.3283064365386963e-10; +} + +// GGX-filtered radiance around n (the split-sum assumption: view = normal), sampling the +// sharper levels at a lod that matches each sample's footprint. +fn prefilter(n: vec3) -> vec3 { + let rough = probe.p.y; + let a = rough * rough; + let up = select(vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), abs(n.z) < 0.999); + let tx = normalize(cross(up, n)); + let ty = cross(n, tx); + let count = 32u; + let texel_sa = 4.0 * PI / (6.0 * probe.p.z * probe.p.z); + var sum = vec3(0.0); + var wsum = 0.0; + for (var i = 0u; i < count; i = i + 1u) { + let xi = vec2(f32(i) / f32(count), radical_inverse(i)); + let phi = 2.0 * PI * xi.x; + let cos_t = sqrt((1.0 - xi.y) / (1.0 + (a * a - 1.0) * xi.y)); + let sin_t = sqrt(1.0 - cos_t * cos_t); + let h = tx * (cos(phi) * sin_t) + ty * (sin(phi) * sin_t) + n * cos_t; + let l = 2.0 * dot(n, h) * h - n; + let nl = dot(n, l); + if (nl <= 0.0) { + continue; + } + let nh = max(dot(n, h), 0.0); + let d2 = nh * nh * (a * a - 1.0) + 1.0; + let dd = a * a / (PI * d2 * d2); + let pdf = dd * 0.25; + let sample_sa = 1.0 / (f32(count) * pdf + 1e-4); + let lod = clamp(0.5 * log2(sample_sa / texel_sa) + 1.0, 0.0, probe.p.w - 1.0); + sum = sum + textureSampleLevel(t_probe_src, s_lin, l, lod).rgb * nl; + wsum = wsum + nl; + } + return sum / max(wsum, 1e-4); +} + +@fragment +fn fs_probe_filter(in: FsIn) -> ProbeOut { + let size = probe.p.z / pow(2.0, probe.p.w); + let uv = in.clip.xy / size * 2.0 - vec2(1.0); + let f0 = i32(probe.p.x); + return ProbeOut( + vec4(prefilter(face_dir(f0, uv.x, uv.y)), 1.0), + vec4(prefilter(face_dir(f0 + 1, uv.x, uv.y)), 1.0), + vec4(prefilter(face_dir(f0 + 2, uv.x, uv.y)), 1.0), + ); +} + +// The steps of the sky cube's clouds: the cube is the reflections' sky and the mirrors', +// redrawn a slice a frame and averaged over its rounds. +const CUBE_CLOUD_STEPS: i32 = 40; + +// One face of the sky cube: the sky radiance (the table, the clouds, the air) divided by the +// table scale, and the cloud cover in alpha (the sun's disc is hidden by it). +@fragment +fn fs_sky_cube(in: FsIn) -> @location(0) vec4 { + let size = probe.p.z; + let uv = in.clip.xy / size * 2.0 - vec2(1.0); + let d = cube_to_world(face_dir(i32(probe.p.x), uv.x, uv.y)); + let pix = 1.4 / size; + // a new start point for the steps each redraw (p.y counts the redraws): interleaved + // gradient noise over the face, shifted by the golden ratio + let ign = fract(52.9829189 * fract(dot(in.clip.xy, vec2(0.06711056, 0.00583715)))); + let jitter = fract(ign + (probe.p.y + 8.0 * f32(probe.p.x)) * 0.61803399); + let bg = sky_table(d); + let hi = high_clouds(d, bg, pix); + let c = cloud_march(d, bg, CUBE_CLOUD_STEPS, jitter, pix, false); + var col = hi.rgb * c.trans + c.light; + let h0 = camera.cam_pos.z - enh.fog.z; + let a = sky_air(d, h0); + col = col * a.a + a.rgb; + return vec4(col / max(enh.ground.w, 1e-8), 1.0 - c.trans * (1.0 - hi.a)); +} + +// Enhanced graphics: the window's clouds, drawn per pixel the way games draw volumetric +// clouds (Horizon Zero Dawn, Frostbite, Unreal): +// * `fs_enhanced_cloud_trace` marches them (sky_enhanced.wgsl `cloud_march`) for a pixel +// in four each way, its ray through another quarter of the pixel each frame and its +// steps started at another point (interleaved gradient noise moved on by the golden +// ratio), and keeps how far the clouds are seen; where the scene's geometry covers the pixel and every +// pixel round it (the depth prepass) it marches nothing; +// * `fs_enhanced_cloud_resolve` takes that into a picture at half the window's size: each +// pixel finds where its clouds were in the last frame's picture (their depth and the last +// frame's view, the camera's and the clouds' own movement), takes the history from there +// clamped to what the traced pixels round it allow (so nothing ghosts when a cloud or +// the view changes), and blends in the new trace - most where a traced ray landed on it +// this frame. Turning the view, driving and the clouds' drift move nothing but what moves; +// * the dome (`enhanced_sky`) looks the result up only where the sky shows: the geometry is +// drawn first, so the clouds never cover it. + +// The scene's depth (the prepass, reversed: 0 where nothing was drawn); a texel when there +// is none. +@group(2) @binding(0) var t_scene_depth: texture_depth_2d; +// The trace (`fs_enhanced_cloud_trace`): its light and transmittance, and the clouds' depth +// (m; < 0 where the geometry covers it); the accumulated picture of the frame before. +@group(0) @binding(23) var t_trace: texture_2d; +@group(0) @binding(24) var t_trace_depth: texture_2d; +@group(0) @binding(25) var t_cloud_hist: texture_2d; + +// This pass's frame number: the frame's, with the round of a picture drawn on its own +// (`probe.p.x`) added. +fn cloud_frame() -> f32 { + return cview.frame.x + probe.p.x; +} + +// Where in its pixel the trace's ray goes this frame (in traced pixels): the four quarters +// in turn, each the centre of one of the resolved picture's pixels. +fn trace_jitter(frame: f32) -> vec2 { + let k = u32(frame) % 4u; + return vec2(select(-0.25, 0.25, k == 1u || k == 2u), select(-0.25, 0.25, k == 1u || k == 3u)); +} + +// The view's direction through the point uv (0..1, y down) of the picture. +fn cloud_view_dir(uv: vec2) -> vec3 { + let p = cview.inv_vp * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.5, 1.0); + return normalize(p.xyz / p.w); +} + +// Whether the scene's geometry covers the traced pixel at `px` and a traced pixel round it +// (what the resolve and the dome's filter read), every other pixel of it looked at. +fn cloud_covered(px: vec2) -> bool { + let dims = vec2(textureDimensions(t_scene_depth)); + if (dims.x < 4) { + return false; + } + let scale = vec2(dims) / cview.size.xy; + let c = vec2((floor(px) + vec2(0.5)) * scale); + let n = i32(ceil(max(scale.x, scale.y) * 1.5)); + for (var y = -n; y <= n; y = y + 2) { + for (var x = -n; x <= n; x = x + 2) { + let q = clamp(c + vec2(x, y), vec2(0), dims - vec2(1)); + if (textureLoad(t_scene_depth, q, 0) <= 0.0) { + return false; + } + } + } + return true; +} + +struct TraceOut { + @location(0) col: vec4, + @location(1) depth: f32, +}; + +@fragment +fn fs_enhanced_cloud_trace(in: FsIn) -> TraceOut { + if (cloud_covered(in.clip.xy)) { + return TraceOut(vec4(0.0, 0.0, 0.0, 1.0), -1.0); + } + let frame = cloud_frame(); + let uv = (in.clip.xy + trace_jitter(frame)) / cview.size.xy; + let d = cloud_view_dir(uv); + let ign = fract(52.9829189 * fract(dot(floor(in.clip.xy), vec2(0.06711056, 0.00583715)))); + let jitter = fract(ign + frame * 0.61803399); + let bg = sky_table(d); + let c = cloud_march(d, bg, i32(cview.frame.w), jitter, cview.params.z, true); + return TraceOut(vec4(c.light / max(enh.ground.w, 1e-8), c.trans), c.dist); +} + +@fragment +fn fs_enhanced_cloud_resolve(in: FsIn) -> @location(0) vec4 { + let frame = cloud_frame(); + let ts = cview.size.xy; + let tsi = vec2(ts); + let uv = in.clip.xy / cview.size.zw; + // where this pixel lies among the traced ones (their centres at i + 0.5 this frame) + let x = uv * ts - trace_jitter(frame); + let ic = clamp(vec2(floor(x)), vec2(0), tsi - vec2(1)); + let fresh = all(abs(fract(x) - vec2(0.5)) < vec2(0.15)); + var cur = textureSampleLevel(t_trace, s_lin, x / ts, 0.0); + if (fresh) { + cur = textureLoad(t_trace, ic, 0); + } + // the traced pixels round it: their mean and spread (the geometry's left out) + var m1 = vec4(0.0); + var m2 = vec4(0.0); + var n = 0.0; + for (var dy = -1; dy <= 1; dy = dy + 1) { + for (var dx = -1; dx <= 1; dx = dx + 1) { + let q = clamp(ic + vec2(dx, dy), vec2(0), tsi - vec2(1)); + if (textureLoad(t_trace_depth, q, 0).r >= 0.0) { + let s = textureLoad(t_trace, q, 0); + m1 = m1 + s; + m2 = m2 + s * s; + n = n + 1.0; + } + } + } + if (n < 0.5) { + return cur; + } + let mean = m1 / n; + let spread = sqrt(max(m2 / n - mean * mean, vec4(0.0))); + // where the clouds this pixel sees were in the last frame's picture + let depth = textureLoad(t_trace_depth, ic, 0).r; + let p = cloud_view_dir(uv) * select(1e6, depth, depth > 0.0) + cview.moved.xyz; + let pc = cview.prev_vp * vec4(p, 1.0); + let manual = probe.p.y >= 0.0; + var w = select(cview.moved.w, probe.p.y, manual); + if (pc.w <= 1e-6) { + w = 0.0; + } + let puv = vec2(pc.x / pc.w * 0.5 + 0.5, 0.5 - pc.y / pc.w * 0.5); + if (any(puv < vec2(0.0)) || any(puv > vec2(1.0))) { + w = 0.0; + } + if (w <= 0.0) { + return cur; + } + var hist = textureSampleLevel(t_cloud_hist, s_lin, puv, 0.0); + hist = vec4(hist.rgb * cview.params.y, hist.a); + if (!manual) { + // (the history only within what the neighbourhood allows; a fresh ray replaces + // more of it than the upsampled trace between them) + let g = 1.25; + hist = clamp(hist, mean - g * spread - vec4(1e-4), mean + g * spread + vec4(1e-4)); + w = w * select(0.985, 0.9, fresh); + } + return mix(cur, hist, w); +} diff --git a/crates/mx/tests/openomsi/snow.wgsl b/crates/mx/tests/openomsi/snow.wgsl new file mode 100644 index 0000000..9620a8b --- /dev/null +++ b/crates/mx/tests/openomsi/snow.wgsl @@ -0,0 +1,1022 @@ +// What the snowfall (snow.wgsl) and the rainfall (rain.wgsl) share: the camera, a hash of +// a particle's number, and the player's vehicle the weather is kept out of. +struct Camera { + view_proj: mat4x4, + cam_pos: vec4, + // (kept in lockstep with `CameraUniform` in lib.rs, as sky.wgsl's) + world_origin: vec4, + sun_dir: vec4, + ambient: vec4, + fog: vec4, + sun_color: vec4, + sky_color: vec4, + light_grid: vec4, + sky: vec4, + cam_right: vec4, + cam_up: vec4, + clouds: vec4, + light_view_proj: mat4x4, + light_view_proj_far: mat4x4, + shadow: vec4, + post: vec4, + inside_a: vec4, + inside_b: vec4, + inside_c: vec4, + flags: vec4, + light_view_proj_close: mat4x4, + wind: vec4, + lamp_view_proj: array, 56>, + lamp_atlas: vec4, + tree_wind: vec4, + inside2_a: vec4, + inside2_b: vec4, + inside2_c: vec4, + cookies: array, 8>, + cabin_lamps: array, 4>, + // x: the textures' mip bias (FSR 1: negative, see `CameraUniform::lod`) + lod: vec4, + // (the classic picture's headlight, `CameraUniform::spot`: unread here) + spot: array, 4>, +}; +@group(0) @binding(0) var camera: Camera; + +fn hash4(n: u32) -> vec4 { + var x = vec4(n, n * 747796405u + 2891336453u, n ^ 0x9e3779b9u, n * 1664525u + 1013904223u); + x = x * 1664525u + 1013904223u; + x.x = x.x + x.y * x.w; + x.y = x.y + x.z * x.x; + x.z = x.z + x.x * x.y; + x.w = x.w + x.y * x.z; + x = x ^ (x >> vec4(16u)); + x.x = x.x + x.y * x.w; + x.y = x.y + x.z * x.x; + x.z = x.z + x.x * x.y; + return vec4(x & vec4(0xffffffu)) / 16777216.0; +} + +// The precipitation's roof map (passes/precip_map.rs): what stands over the ground round +// the camera, its depth seen from straight above. +@group(1) @binding(1) var roof_map: texture_depth_2d; +fn roof_depth(t: vec2) -> f32 { return textureLoad(roof_map, t, 0); } + +// Whether something solid stands over `p` (the map's matrix `m`; `on` 0 without a map): a +// bus's or a car's roof, a shelter, a bridge, a house - no drop or flake falls there. +fn under_roof(p: vec3, m: mat4x4, on: f32) -> bool { + let c = m * vec4(p, 1.0); + let uv = vec2(c.x * 0.5 + 0.5, 0.5 - c.y * 0.5); + let side = f32(textureDimensions(roof_map).x); + let t = vec2(clamp(uv, vec2(0.0), vec2(0.9999)) * side); + let top = roof_depth(t); + // (5 cm under it: the map's depth reaches 300 m) + return on > 0.5 && all(abs(c.xy) < vec2(1.0)) && c.z > top + 0.00017; +} + +// 1 inside the player's own vehicle (its box, a little wider): no snow falls in the cab +fn in_own_vehicle(p: vec3) -> bool { + // (the front and, of an articulated bus, the rear section: it snowed in the back, #1967; + // without branches - two boxes tested with early returns and short-circuits brought + // Apple's M4 shader compiler service down, XPC_ERROR_CONNECTION_INTERRUPTED, and the + // game fell back to no snowfall) + return any(vec2(in_box(p, camera.inside_a, camera.inside_b, camera.inside_c), in_box(p, camera.inside2_a, camera.inside2_b, camera.inside2_c))); +} + +fn in_box(p: vec3, a: vec4, b: vec4, c: vec4) -> bool { + let d = p - a.xyz; + let sh = a.w; + let ch = b.x; + let q = vec3(d.x * ch - d.y * sh - c.x, d.x * sh + d.y * ch - c.y, d.z - c.z); + let h = b.yzw + vec3(0.3); + return select(false, all(abs(q) < h), c.w >= 0.5); +} + +// Enhanced: the sun's far shadow map (the scene's camera group), which keeps every caster - +// a drop or a flake in the shade of a house or under the trees does not catch the sun. +@group(0) @binding(6) var s_shadow: sampler_comparison; +@group(0) @binding(7) var t_shadow_far: texture_depth_2d; + +// Enhanced: the procedural flake atlas (precip.rs `FlakeAtlas`): eight cells of snow +// crystals and flakes, R how much of a texel they cover, G how bright it is. +@group(1) @binding(2) var t_flakes: texture_2d; +@group(1) @binding(3) var s_flakes: sampler; + +// How far `p` is over whatever stands uppermost there by the roof map (m): below 0 under a +// roof, and far over everything where there is no map. +fn roof_clearance(p: vec3, m: mat4x4, on: f32) -> f32 { + let c = m * vec4(p, 1.0); + let uv = vec2(c.x * 0.5 + 0.5, 0.5 - c.y * 0.5); + let side = f32(textureDimensions(roof_map).x); + let top = roof_depth(vec2(clamp(uv, vec2(0.0), vec2(0.9999)) * side)); + // (the map looks straight down: its depth goes against the height, m[2].z < 0) + let h = (c.z - top) / m[2].z; + return select(1e4, h, on > 0.5 && all(abs(c.xy) < vec2(1.0)) && top < 0.9999); +} + +// The wind's gusts: it swells and slackens over some seconds, each swell running downwind +// over the ground as a wave some 70 m long, so that neighbouring drops and flakes are blown +// together and a gust is seen to sweep through the rain. x: the time's worth of the mean +// wind the gusts have added to a particle's way by `t` (the swell's integral, s), y: the +// swell now (a share of the mean wind). +fn precip_gust(x: vec2, t: f32, wind: vec2, strength: f32) -> vec2 { + let speed = length(wind); + let along = dot(x, wind / max(speed, 1e-3)) * (6.2831853 / 70.0); + let across = dot(x, vec2(-wind.y, wind.x) / max(speed, 1e-3)) * (6.2831853 / 160.0); + let w1 = 0.42; + let w2 = 1.17; + let a1 = 0.38 * strength; + let a2 = 0.17 * strength; + let p1 = w1 * t - along + 0.6 * sin(across); + let p2 = w2 * t - 2.3 * along + 1.7 + across; + return vec2(-a1 * cos(p1) / w1 - a2 * cos(p2) / w2, a1 * sin(p1) + a2 * sin(p2)); +} + +// How much of the sun reaches `p` (Enhanced): one compare in the far cascade, lit beyond it +// and without shadow maps. +fn precip_sun(p: vec3) -> f32 { + if (camera.shadow.x < 0.5 || enh.sun.r + enh.sun.g < 1e-4) { + return 1.0; + } + let lp = camera.light_view_proj_far * vec4(p, 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (any(uv < vec2(0.0)) || any(uv > vec2(1.0)) || lp.z < 0.0 || lp.z > 1.0) { + return 1.0; + } + return textureSampleCompareLevel(t_shadow_far, s_shadow, uv, lp.z - 0.0004); +} + +// A hash of a cell of the plane (0..1 each), its integer coordinates taken modulo 4096 so +// that the world's large figures stay exact. +fn cell_hash(c: vec2) -> vec4 { + let w = c - 4096.0 * floor(c / 4096.0); + let i = vec2(w); + return hash4(i.x * 4099u + i.y * 7919u + 17u); +} + +// The panels of a far veil of rain or snow (Enhanced): rings of upright panels round the +// camera, twelve a ring, each a strip of four vertices. Beyond the particles' layers the +// drops or flakes are too many and too small to draw one by one, and a heavy fall is seen +// there as what it is, a grey sheet streaked or speckled by them, sweeping by with the +// wind. `c`: the corner (0..1 each way); returns the corner's place (render frame) in xyz +// and its ring's radius in w. +fn veil_corner(panel: u32, c: vec2) -> vec4 { + var radii = array(30.0, 48.0, 78.0); + let ring = min(panel / 12u, 2u); + let r = radii[ring]; + // (each panel a little wider than its twelfth, so that the chords close the ring; the + // rings turned against each other, so their joins do not line up) + let a = (f32(panel % 12u) + c.x * 1.04 - 0.02 + 0.37 * f32(ring)) * (6.2831853 / 12.0); + let z = camera.cam_pos.z + mix(-6.0, 26.0 + 0.4 * r, c.y); + return vec4(camera.cam_pos.xy + vec2(cos(a), sin(a)) * r, z, r); +} + +// The snowfall, every mode: a field of flakes that lives on the GPU alone - each flake's +// place is worked out here from its number, the time, the wind and the camera, so that a +// heavy fall is a hundred and fifty thousand flakes for the cost of one draw (nothing is +// simulated or sent per flake). The field is the world's, repeating every few metres round +// the camera in three layers - dense close by, where every flake is a few pixels wide, +// thinner further out, where it is a speck; beyond them the snowfall's extinction takes the +// view (Enhanced). Flakes are a few millimetres across (an exponential spread, Gunn and +// Marshall 1958; a light fall single crystals of a millimetre), fall at about a metre a +// second (aggregates at 0.8 D^0.16 m/s, Locatelli and Hobbs 1974), sway as they go and +// drift with the wind; opaque and lit by what lights them - the classic picture's +// envir.cfg light, or the enhanced picture's sky, sun and lamps (`precip_light`). + +struct SnowParams { + // xyz the wind the flakes drift with (m/s), w the time (s) + wind: vec4, + // x how hard it snows (0..1), y the flakes' mean diameter (m), zw how many flakes the + // first two layers hold (the rest are the third's) + fall: vec4, + // the precipitation's roof map: its matrix, and x 1 when there is one + roof: mat4x4, + roof_on: vec4, + // Enhanced: x the instance the veil's panels begin at (the flakes' end), y how many + // panels there are, z how strong the wind's gusts are (0..1), w the picture's height (px) + ext: vec4, +}; +@group(1) @binding(0) var sp: SnowParams; + +struct SnowOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + // the flake's cover (alpha), and its place (for its light) + @location(1) cover: f32, + @location(2) pos: vec3, +}; + +// The layers round the camera: half width, bottom and top (m). +const LAYER_H = array, 3>(vec3(4.0, -2.5, 5.5), vec3(10.0, -3.0, 9.0), vec3(24.0, -3.0, 16.0)); + +@vertex +fn vs_snow(@builtin(vertex_index) vid: u32, @builtin(instance_index) k: u32) -> SnowOut { + let corners = array, 6>(vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, 1.0)); + let c = corners[vid % 6u]; + var out: SnowOut; + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + let n0 = u32(sp.fall.z); + let n1 = u32(sp.fall.w); + var layer = 2u; + if (k < n0) { + layer = 0u; + } else if (k < n0 + n1) { + layer = 1u; + } + let lh = LAYER_H[layer]; + let size = vec3(2.0 * lh.x, 2.0 * lh.x, lh.z - lh.y); + let h1 = hash4(k * 2u + 1u); + let h2 = hash4(k * 2u + 7919u); + // the flake: its diameter, fall speed and sway + let r = sp.fall.x; + let d = min(0.0005 - sp.fall.y * log(max(1.0 - h1.w, 1e-6)), 0.015); + let fall = max(0.8 * pow(d * 1000.0, 0.16) * (0.75 + 0.25 * r) * (0.85 + 0.3 * h2.x), 0.3); + let t = sp.wind.w; + let pace = 1.5 + 2.5 * h2.y; + let sway = 0.05 + 0.15 * h2.z; + let ph = h2.w * 6.2831853 + pace * t; + // its place in the world: where it started, carried by the wind, swaying round, falling; + // then the copy of the field nearest the camera (the field's figures in the world's + // own, modulo a kilometre, so that it stays put while the render origin moves) + let world_cam = camera.cam_pos.xyz + vec3(camera.world_origin.xy, 0.0); + let start = h1.xyz * size; + let drift = sp.wind.xyz * (0.6 * t) + vec3(cos(ph), sin(ph), 0.0) * sway - vec3(0.0, 0.0, fall * t); + let lo = world_cam + vec3(-lh.x, -lh.x, lh.y); + let q = lo + (((start + drift - lo) % size) + size) % size; + let p = q - vec3(camera.world_origin.xy, 0.0); + if (in_own_vehicle(p) || under_roof(p, sp.roof, sp.roof_on.x)) { + return out; + } + // a denser layer fades out towards its edges, into the thinner one round it + let rel = q - lo; + let soft = lh.x * 0.3; + var fade = 1.0; + if (layer < 2u) { + let e = min(rel, size - rel) / soft; + fade = clamp(min(min(e.x, e.y), e.z), 0.0, 1.0); + } + let to_cam = camera.cam_pos.xyz - p; + let dist = length(to_cam); + let vdir = to_cam / max(dist, 0.001); + // a flake close by is out of focus (its blur as wide as the pupil, some 2.5 mm), one far + // off at least a pixel and a half wide; as bright as it is seen - a small point's + // brightness goes with the square root of its light (Stevens' power law) + let rad = d * 0.5; + let rs = max(sqrt(rad * rad + 0.0025 * 0.0025), dist * 0.0016); + out.cover = fade * sqrt(rad / rs); + if (out.cover < 0.004) { + return out; + } + var ax = cross(vec3(0.0, 0.0, 1.0), vdir); + ax = select(vec3(1.0, 0.0, 0.0), normalize(ax), length(ax) > 1e-4); + let ay = cross(vdir, ax); + out.clip = camera.view_proj * vec4(p + (ax * c.x + ay * c.y) * rs, 1.0); + out.uv = c; + out.pos = p; + return out; +} + +fn flake_alpha(in: SnowOut) -> f32 { + let r = length(in.uv); + return clamp(in.cover * (1.0 - smoothstep(0.55, 1.0, r)), 0.0, 1.0); +} + +// the classic picture: white, lit as the scene is (envir.cfg's ambient and sun light) +@fragment +fn fs_snow(in: SnowOut) -> @location(0) vec4 { + let a = flake_alpha(in); + let light = min(camera.ambient.rgb + camera.sun_color.rgb * 0.5, vec3(1.0)); + return vec4(light * 0.9 * a, a); +} + + +// ---- The enhanced snowfall +// +// The same field of flakes, each drawn as what it is (precip.rs `FlakeAtlas`): in a light +// fall single crystals - stellar and fernlike dendrites, sectored and plain hexagonal +// plates - in a heavier one aggregates of many, a centimetre across. A flake turns as it +// falls and a plate tips over and back (seen edge-on it thins to a line), flutters on two +// periods of its own besides its slow sway, and is blown on by the wind's gusts with its +// neighbours. Close to the eye it is out of focus, a soft disc; far off a speck. A plate +// turned to the sun flashes for a moment. Lit as the classic snowfall is by the sky and the +// lamps, the sun's share shaded by the far shadow map and thrown a little forwards; beyond +// the flakes' layers a heavy fall is a speckled veil (`veil_corner`). + +struct SnowOutE { + @builtin(position) clip: vec4, + // across the quad (-1..1 each way); the veil: the panel's corner (0..1) + @location(0) uv: vec2, + // x the cover, y the atlas cell (-1 the veil), z its mip level, w how far out of focus + // (0 sharp .. 1 a soft disc) + @location(1) @interpolate(flat) shape: vec4, + @location(2) pos: vec3, + // the flake's turn (cos, sin), how far it faces the eye (1 face on), how much it glints + @location(3) @interpolate(flat) turn: vec4, + // x the quad's radius over the flake's, y the veil's radius (m), z its ring + @location(4) @interpolate(flat) extra: vec4, +}; + +fn snow_none() -> SnowOutE { + var out: SnowOutE; + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + out.uv = vec2(0.0); + out.shape = vec4(0.0); + out.pos = vec3(0.0); + out.turn = vec4(1.0, 0.0, 1.0, 0.0); + out.extra = vec4(1.0, 0.0, 0.0, 0.0); + return out; +} + +@vertex +fn vs_snow_enhanced(@builtin(vertex_index) vid: u32, @builtin(instance_index) k: u32) -> SnowOutE { + let corners = array, 6>(vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, 1.0)); + let c = corners[vid % 6u]; + if (k >= u32(sp.ext.x)) { + return snow_veil(c * 0.5 + vec2(0.5), k - u32(sp.ext.x)); + } + var out = snow_none(); + let n0 = u32(sp.fall.z); + let n1 = u32(sp.fall.w); + let layer = select(select(2u, 1u, k < n0 + n1), 0u, k < n0); + let lh = LAYER_H[layer]; + let size = vec3(2.0 * lh.x, 2.0 * lh.x, lh.z - lh.y); + let h1 = hash4(k * 2u + 1u); + let h2 = hash4(k * 2u + 7919u); + let h3 = hash4(k * 5u + 15485863u); + // the flake: its diameter and fall speed as `vs_snow` has them - but a heavy fall's + // aggregates bigger: half a centimetre across on the mean, the big wet flakes of a + // thick fall up to two (the classic sizes, two millimetres, are those of a moderate + // fall's single crystals, and a heavy fall showed as a fine dust) + let r = sp.fall.x; + let mean = max(sp.fall.y, 0.0012 + 0.0062 * smoothstep(0.2, 0.9, r)); + let d = min(0.0005 - mean * log(max(1.0 - h1.w, 1e-6)), 0.02); + let fall = max(0.8 * pow(d * 1000.0, 0.16) * (0.75 + 0.25 * r) * (0.85 + 0.3 * h2.x), 0.3); + let t = sp.wind.w; + let world_cam = camera.cam_pos.xyz + vec3(camera.world_origin.xy, 0.0); + let lo = world_cam + vec3(-lh.x, -lh.x, lh.y); + let base = sp.wind.xyz * (0.6 * t) - vec3(0.0, 0.0, fall * t); + let q0 = lo + (((h1.xyz * size + base - lo) % size) + size) % size; + // its sway, a slow circle, and its flutter, quicker and smaller, up and down as well; + // and the gusts + let ph = h2.w * 6.2831853 + (1.5 + 2.5 * h2.y) * t; + let ph2 = h3.x * 6.2831853 + (4.0 + 3.0 * h3.y) * t; + let sway = vec3(cos(ph), sin(ph), 0.0) * (0.05 + 0.15 * h2.z); + let flutter = vec3(cos(ph2), sin(1.3 * ph2), 0.5 * sin(0.7 * ph2)) * (0.015 + 0.03 * h3.z); + let g = precip_gust(q0.xy, t, sp.wind.xy, sp.ext.z); + let q = q0 + sway + flutter + vec3(sp.wind.xy * (0.6 * g.x), 0.0); + let p = q - vec3(camera.world_origin.xy, 0.0); + if (in_own_vehicle(p)) { + return out; + } + // under a roof none; one about to land on the ground or a roof fades into it (the + // surface would cut it in half) + let clear = roof_clearance(p, sp.roof, sp.roof_on.x); + if (clear < -0.05) { + return out; + } + let landing = smoothstep(-0.03, 0.04, clear); + // every layer fades out at its edges, where its flakes come round again + let rel = q0 - lo; + let e = min(rel, size - rel) / (lh.x * 0.3); + let fade = clamp(min(min(e.x, e.y), e.z), 0.0, 1.0) * landing; + let to_cam = camera.cam_pos.xyz - p; + let dist = length(to_cam); + let vdir = to_cam / max(dist, 0.001); + let ch = camera.view_proj * vec4(p, 1.0); + if (fade < 0.004 || ch.w < 0.05 || abs(ch.x) > 1.3 * ch.w || abs(ch.y) > 1.3 * ch.w) { + return out; + } + let cu = camera.view_proj * vec4(p + camera.cam_up.xyz, 1.0); + let px_per_m = max(abs(cu.y / cu.w - ch.y / ch.w) * 0.5 * sp.ext.w, 1e-3); + // In focus a few metres off (the street the eye is on): nearer, a flake's blur grows to + // a few millimetres (as a camera's lens draws it: a big flake right in front of the eye + // is a soft blot, not a sharp star); it is a pixel and a half wide at the least, and as + // bright as `vs_snow` has it. + let rad = d * 0.5; + let blur = 0.004 * clamp(1.0 - dist / 5.0, 0.0, 1.0); + let rs = max(sqrt(rad * rad + blur * blur), 1.5 / px_per_m); + let cover = fade * sqrt(rad / rs); + if (cover < 0.004) { + return out; + } + let sharp = rad / rs; + // single crystals in a light fall, the bigger flakes aggregates of them + let aggregate = h3.w < smoothstep(0.0012, 0.004, d); + let cell = select(floor(h3.z * 3.99), 4.0 + floor(fract(h3.z * 7.0) * 3.99), aggregate); + // turning, and tipping over and back (an aggregate hardly shows it) + let spin = (h3.y - 0.5) * 5.0; + let ang = h3.x * 6.2831853 + spin * t; + let tip = cos((0.8 + 2.2 * h2.x) * t + h1.x * 6.2831853); + let face = select(0.25 + 0.75 * abs(tip), 0.8 + 0.2 * abs(tip), aggregate); + let glint = pow(0.5 + 0.5 * sin((2.0 + 3.0 * h2.x) * t + h2.w * 20.0), 60.0) * select(1.0, 0.25, aggregate); + // the atlas's level: the flake's 58 texels over its pixels + let level = clamp(log2(58.0 / max(2.0 * rad * px_per_m, 1e-3)), 0.0, 4.0); + var ax = cross(vec3(0.0, 0.0, 1.0), vdir); + ax = select(vec3(1.0, 0.0, 0.0), normalize(ax), length(ax) > 1e-4); + let ay = cross(vdir, ax); + out.clip = camera.view_proj * vec4(p + (ax * c.x + ay * c.y) * rs, 1.0); + out.uv = c; + out.shape = vec4(cover, cell, level, 1.0 - smoothstep(0.35, 0.9, sharp)); + out.pos = p; + out.turn = vec4(cos(ang), sin(ang), face, glint); + out.extra = vec4(1.0 / max(sharp, 1e-3), 0.0, 0.0, 0.0); + return out; +} + +fn snow_veil(c: vec2, panel: u32) -> SnowOutE { + var out = snow_none(); + let v = veil_corner(panel, c); + let ring = f32(panel / 12u); + if (sp.fall.x < 0.08) { + return out; + } + out.clip = camera.view_proj * vec4(v.xyz, 1.0); + out.uv = c; + out.shape = vec4(pow(sp.fall.x, 1.2) * 0.11 * (0.8 + 0.2 * ring), -1.0, 0.0, 0.0); + out.pos = v.xyz; + out.extra = vec4(1.0, v.w, ring, 0.0); + return out; +} + +fn flake_alpha_e(in: SnowOutE) -> vec2 { + // the flake's own figure, turned and tipped, the crystal's rim at 1 + let u = vec2(in.turn.x * in.uv.x - in.turn.y * in.uv.y, in.turn.y * in.uv.x + in.turn.x * in.uv.y); + let f = vec2(u.x, u.y / max(in.turn.z, 0.05)) * in.extra.x; + let cell = vec2(in.shape.y % 4.0, floor(in.shape.y / 4.0)); + let cuv = clamp(vec2(0.5) + f * 0.45, vec2(0.0), vec2(1.0)); + let tex = textureSampleLevel(t_flakes, s_flakes, (cell + cuv) * vec2(0.25, 0.5), in.shape.z); + let crisp = select(0.0, tex.r, all(abs(f) < vec2(1.1))); + // out of focus: a soft disc, a touch brighter at its rim, as a lens draws a point + let rr = length(in.uv); + let disc = (1.0 - smoothstep(0.55, 1.0, rr)) * (0.85 + 0.15 * smoothstep(0.3, 0.8, rr)); + let a = mix(crisp, disc, in.shape.w) * in.shape.x; + return vec2(clamp(a, 0.0, 1.0), mix(tex.g, 1.0, in.shape.w)); +} + +fn veil_snow_alpha(in: SnowOutE) -> f32 { + let r = in.extra.y; + let ring = in.extra.z; + let d = in.pos - camera.cam_pos.xyz; + let theta = atan2(d.y, d.x); + let t = sp.wind.w; + let tang = vec2(-sin(theta), cos(theta)); + // The flakes beyond, each a speck a pixel or two across, falling a metre a second and + // drifting with the wind: two lattices of specks, a fixed angle apart, each cell with a + // flake of its own somewhere in it - more of them showing the harder it snows. + var specks = 0.0; + for (var j = 0u; j < 2u; j = j + 1u) { + let fj = f32(j); + let cols = round((900.0 + 150.0 * ring) * (1.0 + 0.41 * fj)); + let cw = 6.2831853 * r / cols; + let drift = dot(sp.wind.xy, tang) * 0.6 * t; + let x = vec2(theta / 6.2831853 * cols - drift / cw, (in.pos.z + (0.9 + 0.3 * fj) * t) / cw) + vec2(0.5 * fj); + let ci = floor(x); + let h = cell_hash(ci + vec2(311.0 * ring, 57.0 * fj)); + let centre = vec2(0.2) + 0.6 * h.xy + 0.08 * vec2(sin(t * 1.7 + h.z * 30.0), 0.0); + let s = (1.0 - smoothstep(0.08, 0.22, length(fract(x) - centre))) * step(h.w, 0.35 + 0.5 * sp.fall.x); + specks = max(specks, s * (0.5 + 0.5 * h.z)); + } + let g = precip_gust(in.pos.xy + camera.world_origin.xy, t, sp.wind.xy, sp.ext.z); + // (as the rain's veil, rain.wgsl `veil_rain_alpha`: gentler gusts, kept to the horizon, and + // little flat grey under the specks - looked up at, the panels stood in the sky as a ring + // of pale sheets) + let sweep = clamp(1.0 + 0.6 * g.y, 0.7, 1.3); + let up = in.pos.z - camera.cam_pos.z; + let height = smoothstep(-3.0, 3.0, up) * (1.0 - smoothstep(0.08, 0.3, up / r)); + return clamp(in.shape.x * (0.2 + 0.8 * specks) * sweep * height, 0.0, 1.0); +} + +// the enhanced picture: what the flake scatters of the sky's, the sun's and the lamps' +// light, at the albedo of snow +@fragment +fn fs_snow_enhanced(in: SnowOutE) -> @location(0) vec4 { + let veil = in.shape.y < -0.5; + var a = 0.0; + var bright = 1.0; + if (veil) { + a = veil_snow_alpha(in); + } else { + let fa = flake_alpha_e(in); + a = fa.x; + bright = fa.y; + } + if (a < 0.002) { + discard; + } + let to_eye = normalize(camera.cam_pos.xyz - in.pos); + let sun = precip_sun(in.pos); + // the sun's share: `precip_light` takes it as even and unshaded; here it is shaded, and + // thrown a little forwards (a fall lit from behind is brighter), and a tipping plate + // flashes as it faces it + let c = dot(-camera.sun_dir.xyz, to_eye); + let lobe = 0.7 * hg_phase(c, 0.35) * 4.0 * PI + 0.3; + let sun_part = enh.sun.rgb * (0.25 / PI * (sun * lobe - 1.0) + sun * in.turn.w * 0.6); + let up = sh_irradiance(vec3(0.0, 0.0, 1.0)) / PI; + var l = vec3(0.0); + if (veil) { + l = (enh.fog_color.rgb / 0.9 + enh.sun.rgb * 0.25 / PI + up) * 0.5 * 0.85 + sun_part * 0.425; + } else { + l = (precip_light(in.pos, to_eye, true) + up) * 0.5 * 0.85 + sun_part * 0.425; + } + l = max(l, vec3(0.0)) * mix(0.75, 1.05, bright); + return vec4(min(l * enh.exposure.x, vec3(60.0)) * a, a); +} + +// Enhanced graphics: what the enhanced main pass, the sky and the coronas share - the +// light of the physically based sky (see atmosphere.rs), in its units (1 = 10 000 lux), +// and the air between the camera and what it sees. The scene is drawn pre-exposed: +// radiance times `enh.exposure.x`, so that the half-float target keeps its precision by +// night as well as by day. +struct Enhanced { + // x pre-exposure, y the level unlit things are drawn at, z a lit window's radiance + // (pre-exposed), w how bright a light's corona is drawn + exposure: vec4, + // rgb irradiance of the sun after the clouds, w its angular radius (rad) + sun: vec4, + // irradiance from the sky and the ground: order-2 spherical harmonics, rgb + sh: array, 9>, + // rgb radiance of the ground, w the sky table's scale + ground: vec4, + // x weather fog extinction (1/m) at its base, y its height falloff (1/m), z the base + // height (render-origin relative), w clear-air extinction (1/m) at the ground + fog: vec4, + // rgb fog radiance from the light around it (the sun's part is added by angle), + // w the table scale the reflection probe was drawn with + fog_color: vec4, + // x wet roads, y snow cover, z rain, w cloud cover in front of the sun + weather: vec4, + // x mip levels of the probe, y illuminance of a light's core (maplight colour 1), + // z cabin light illuminance, w how much of the sun the clouds let through + lights: vec4, + // rgb the sun disc's irradiance before the clouds, w frame time (s) + sun_disc: vec4, + // x which term the main pass shows alone (OMSI_DEBUG_ENHANCED, 0 = the picture), + // y the puddles' F0, z the envmap photo's strength, w the tone curve's contrast + debug: vec4, + // xyz where the sky cube is drawn from, relative to the camera + eye: vec4, + // x how bright an LED panel's dots burn (0 = off), y whether the LED panels' `\S:n` + // masks keep their mip chain (0: at full resolution, the dots stay visible when small), z 1 + // when lights glare and glow in the night air (the settings' `light_glow`) + led: vec4, + // xyz towards the moon, w its angular radius (rad) + moon: vec4, + // rgb the moon disc's irradiance before the clouds, w how much of the starry sky shows + moon_disc: vec4, + // rgb the sun's irradiance at 1400, 2100 and 2800 m (the cumulus layer) and 7000 m + // (the high thin layer), through the atmosphere from up there + cloud_sun: array, 4>, + // rgb the moonlight on a surface facing the moon (after the clouds), w 1 while the + // shadow maps are the moon's + moon_light: vec4, + // the condensation on the player's bus's panes (optical depths): windscreen, sides, + // rear, and how far the defroster has cleared the windscreen (0..1; omsi-app + // condensation.rs) + condensation: vec4, + // x the cumulus layer's base, y its top (m over the ground), z the altocumulus cover, + // w the storm's activity + layers: vec4, + // the lightning of this frame: x the light it throws on a surface facing it (1 = 10 000 + // lux), yz towards it (horizontal unit vector), w its elevation (rad) + flash: vec4, + // xyz towards the flash (unit vector), w how bright its channel is + flash2: vec4, + // x a number the channel's shape is drawn from + flash3: vec4, + // the clouds' shadow field (cloud_field.rs): xy its middle in cloud space, z one over its + // width, w 1 when there is one + cloud_f1: vec4, + // xy what takes a world point to cloud space, z the height of the plane it is taken on, + // w the share of the sun the main pass has taken off already for the clouds over the camera + cloud_f2: vec4, + // the player's bus's pitch and roll: sin, cos of each (its panes' condensation sits on + // the glass on a slope, `pane_local`) + pane_tilt: vec4, + // Slots of the weather overhaul, one owner each (zero until it fills them): + // the volumetric clouds, the volumetric fog, the precipitation, the bus's panes, the + // surfaces' PBR and the ray tracing, and two spare. + clouds_ext: vec4, + clouds_ext2: vec4, + vol_fog: vec4, + vol_fog2: vec4, + precip_ext: vec4, + glass_ext: vec4, + // (pbr_ext: x the share of the sun's light that still comes as a beam - the rest the + // clouds scatter, `sun_scattered` - y 1 when x is set) + pbr_ext: vec4, + rt_ext: vec4, +}; +@group(0) @binding(11) var enh: Enhanced; +@group(0) @binding(13) var s_lin: sampler; +@group(0) @binding(14) var t_sky_lut: texture_2d; + +const PI: f32 = 3.14159265; + +// Irradiance from the sky and the ground on a surface facing n. +fn sh_irradiance(n: vec3) -> vec3 { + let c = enh.sh; + let e = c[0].rgb * 0.282095 + + c[1].rgb * (0.488603 * n.y) + c[2].rgb * (0.488603 * n.z) + c[3].rgb * (0.488603 * n.x) + + c[4].rgb * (1.092548 * n.x * n.y) + c[5].rgb * (1.092548 * n.y * n.z) + + c[6].rgb * (0.315392 * (3.0 * n.z * n.z - 1.0)) + c[7].rgb * (1.092548 * n.x * n.z) + + c[8].rgb * (0.546274 * (n.x * n.x - n.y * n.y)); + return max(e, vec3(0.0)); +} + +// The lightning's light on a surface facing n: half of it from the cloud overhead and +// round it (a hemisphere), half along the way to the flash itself. +fn flash_irradiance(n: vec3) -> vec3 { + if (enh.flash.x <= 0.0) { + return vec3(0.0); + } + return vec3(0.80, 0.90, 1.0) * enh.flash.x * (0.5 * (0.5 + 0.5 * n.z) + 0.5 * max(dot(n, enh.flash2.xyz), 0.0)); +} + +// Sky radiance towards d (unscaled: times enh.ground.w is the radiance). The table runs +// over the azimuth from the sun (0..π) and the elevation (denser at the horizon). +// The sky table's texture: the table (32 x 48) in its corner and the clouds' shadow field +// (192 x 192) beside it, one texel clear (cloud_field.rs `SKY_TEX_W`, `FIELD_X0`). +const SKY_TEX: vec2 = vec2(225.0, 192.0); +const SKY_TABLE: vec2 = vec2(32.0, 48.0); +const FIELD_ORIGIN: f32 = 33.0; +const FIELD_N: f32 = 192.0; + +fn sky_table_raw(d: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let ls = length(s.xy); + let ld = length(d.xy); + var az = 0.0; + if (ls > 1e-4 && ld > 1e-4) { + az = acos(clamp(dot(s.xy / ls, d.xy / ld), -1.0, 1.0)); + } + let el = asin(clamp(d.z, -1.0, 1.0)); + let v = 0.5 + 0.5 * sign(el) * sqrt(min(abs(el) / 1.5707963, 1.0)); + // (kept a half texel inside the table: its neighbours in the texture are not the sky) + let tx = clamp(vec2(az / PI, v) * SKY_TABLE, vec2(0.5), SKY_TABLE - vec2(0.5)); + return textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).rgb; +} + +// The share of the sun that reaches the point p through the clouds, as against what the main +// pass's sun (`enh.sun`) already has for the camera's own place: the cumulus layer's shadow +// field read where the sun's way through p meets the layer's middle. 1 where there is no +// field, beyond its edge and where the sun is low (the camera's own factor stands there). +fn cloud_shadow_ratio(p: vec3) -> f32 { + let s = camera.sun_dir.xyz; + if (enh.cloud_f1.w < 0.5 || s.z < 0.06) { + return 1.0; + } + let cs = p.xy + s.xy / s.z * (enh.cloud_f2.z - p.z) + enh.cloud_f2.xy; + let uv = (cs - enh.cloud_f1.xy) * enh.cloud_f1.z + vec2(0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + let w = 1.0 - smoothstep(0.36, 0.48, edge); + if (w <= 0.0) { + return 1.0; + } + let tx = vec2(FIELD_ORIGIN, 0.0) + clamp(uv * FIELD_N, vec2(0.5), vec2(FIELD_N - 0.5)); + let f = textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).r; + let ratio = min(f / max(enh.cloud_f2.w, 0.02), 6.0); + return mix(1.0, ratio, w); +} + +fn sky_table(d: vec3) -> vec3 { + return sky_table_raw(d) * enh.ground.w; +} + +// Henyey-Greenstein phase function. +fn hg_phase(c: f32, g: f32) -> f32 { + let g2 = g * g; + return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * c, 1e-4), 1.5)); +} + +// Optical depth of an exponentially thinning layer (extinction sigma at height 0, falling +// off with k per metre) along a straight path of length dist from height h0 to h1. +fn layer_depth(sigma: f32, k: f32, h0: f32, h1: f32, dist: f32) -> f32 { + if (sigma <= 0.0) { + return 0.0; + } + let a = max(h0, 0.0); + let b = max(h1, 0.0); + let dh = b - a; + if (abs(k * dh) < 1e-3) { + return sigma * dist * exp(-k * 0.5 * (a + b)); + } + return sigma * dist * (exp(-k * a) - exp(-k * b)) / (k * dh); +} + +// The air between the camera and a point dist metres away in direction dir (from the +// camera), at heights h0 (camera) and h1 (point) above the fog's base: rgb the light it +// scatters towards the camera (radiance), a what it lets through of the point. +fn air(dir: vec3, dist: f32, h0: f32, h1: f32) -> vec4 { + return air_of(dir, dist, h0, h1, 1.0); +} + +// The same with the clear air's share scaled (0 for the sky, whose table holds it already). +fn air_of(dir: vec3, dist: f32, h0: f32, h1: f32, clear: f32) -> vec4 { + let tau_fog = layer_depth(enh.fog.x, enh.fog.y, h0, h1, dist); + let tau_air = layer_depth(enh.fog.w * clear, 1.0 / 1500.0, h0, h1, dist); + let tau = tau_fog + tau_air; + let t = exp(-tau); + if (tau < 1e-5) { + return vec4(0.0, 0.0, 0.0, 1.0); + } + // clear air takes on the sky's own colour at the horizon in this direction (which + // already holds the glow round the sun); a weather fog glows with the light around it + // and brighter towards the sun + let horizon = sky_table(normalize(vec3(dir.x, dir.y, max(dir.z, 0.0) * 0.3 + 0.03))); + let fog_in = enh.fog_color.rgb + enh.sun.rgb * hg_phase(dot(dir, camera.sun_dir.xyz), 0.55) * 0.9; + let inscatter = mix(horizon, fog_in, tau_fog / tau); + return vec4(inscatter * (1.0 - t), t); +} + +struct PointLight { + pos: vec4, + color: vec4, + dir: vec4, + extra: vec4, +}; +@group(0) @binding(3) var lights: array; +@group(0) @binding(4) var grid: array; +const CELL_CAP: u32 = 32u; + +// `beam_shadow.wgsl` for the shaders without the lamp shadow tiles: nothing stands in a beam. +fn beam_tile(li: u32, l: PointLight) -> u32 { + return 0xffffffffu; +} + +fn beam_reaches(k: u32, x: vec3) -> f32 { + return 1.0; +} + +// Enhanced graphics: the lamps as the scene and the sky share them - a headlamp's beam +// and the light the weather's fog scatters from the lamps towards the camera (needs the +// point lights, their grid and `camera.light_grid`). + +// A headlamp's intensity towards `t` (from the lamp) by the angles of a road lamp, not +// around its axis: wide across, brightest just under the lamp's horizon where it reaches +// far down the road, weak straight down, and with a low beam a sharp cut-off above it. +// `dir` is the lamp's axis in its vehicle's floor: its rise tilts the horizon with the +// vehicle, up a ramp and down (#1897). +fn headlamp(t: vec3, dir: vec3, low: bool) -> f32 { + let fwd = normalize(dir.xy + vec2(1e-6, 0.0)); + let ahead = dot(t.xy, fwd); + if (ahead <= 0.0) { + return 0.0; + } + let across = abs(t.x * fwd.y - t.y * fwd.x) / ahead; + let wide = 0.12 * smoothstep(1.0, 0.45, across) + 0.88 * exp(-across * across / 0.06); + let rise = t.z / max(length(t.xy), 1e-3); + let tilt = dir.z / max(length(dir.xy), 1e-3); + // (the tangent of the angle under that horizon) + let drop = (tilt - rise) / max(1.0 + rise * tilt, 1e-3); + // full out to where the road is 0.06 under the lamp's horizon, then less as the cube of + // the drop and a little more: the road is lit evenly from the bumper on, a little + // brighter as far as the beam reaches, and not as one hot pool where its axis lands + var up = min(1.0, pow(0.06 / max(abs(drop), 1e-4), 3.4)); + if (low) { + up = up * smoothstep(-0.012, 0.025, drop); + return wide * up; + } + // a full beam reaches far: a narrow, bright core along the lamp's horizon + let hot = exp(-across * across / 0.012 - drop * drop / 0.0004); + return wide * up + 6.0 * hot; +} + +// The lamps' light the weather's fog scatters towards the camera (radiance, not +// pre-exposed): single scattering along the view ray from `start` to `len` metres in +// direction `d` - the glow round a street lamp in the mist, its cone under it, a bus's +// beams reaching ahead into the fog or the falling snow. The droplets scatter strongly +// forward (fog and cloud droplets of some ten micrometres: g about 0.8), so the glow is +// brightest looking towards a lamp and a cone shows faintly from the side. +// +// Each lamp is taken once, over the whole stretch of the ray within its reach, in the grid +// cell the ray's point nearest to it lies in (the ray's cells are walked through; every +// cell lists the lamps reaching into it). Along a straight ray past a point source, with +// t - t0 = h tan(phi) (h the ray's distance from the lamp, t0 where it passes nearest), +// the inverse square cancels against the path element: dt / r^2 = dphi / h, and what is +// left is the phase function over the angle, cos(theta) = -sin(phi) - a smooth integral +// taken with five Gauss-Legendre nodes, at each of which a spot's or a headlamp's beam is +// asked how much it sends that way. The fog's extinction dims the light on its way from +// the lamp and to the camera (taken at the nearest point). A beam's light, which reaches +// only part of the way, is summed along the ray instead, its steps staggered by `jitter`. +// The droplets' phase function: a strong forward peak and the back-scattered light a +// fog's lidar ratio of some 18 sr asks for (0.055 per steradian straight back) - a single +// Henyey-Greenstein lobe of g 0.8 gave a tenth of it, and a bus's own headlights lit no +// wall of fog in front of the driver. Two lobes, 0.9 of g 0.85 and 0.1 of g -0.5. +fn fog_phase(c: f32) -> f32 { + return 0.9 * hg_phase(c, 0.85) + 0.1 * hg_phase(c, -0.5); +} +const AIRLIGHT_CELLS: u32 = 16u; + +// The clear night air's own haze, which lights a lamp's halo and a headlamp's beam as the fog's +// droplets do, only fainter: the lowest hundred metres of a city's air hold its dust, exhaust +// and humidity at several times the column's average aerosol extinction (`enh.fog.w`), 1-3e-4 +// per metre (a visibility of 15-40 km). A lamp then has a soft glow round it and a low beam +// a faint cone, as in any night photograph, instead of a lit disc on a black ground. +const GROUND_HAZE_GAIN: f32 = 8.0; + +// `droplets`: how much of the weather's extinction scatters like fog (see `FogLampUniform`). +fn lamp_airlight(c: vec3, d: vec3, start: f32, len: f32, jitter: f32, droplets: f32) -> vec3 { + var sum = vec3(0.0); + let sigma0 = enh.fog.x * droplets + enh.fog.w * GROUND_HAZE_GAIN * enh.led.z; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (sigma0 < 4e-5 || cell <= 0.0 || side == 0u || len <= start) { + return sum; + } + // (past a few optical depths nothing comes back) + let end = min(len, start + 4.0 / sigma0); + let gx = array(-0.9061798, -0.5384693, 0.0, 0.5384693, 0.9061798); + let gw = array(0.2369269, 0.4786287, 0.5688889, 0.4786287, 0.2369269); + // the walk through the grid's cells along the ray's plan + let o = (c.xy - camera.light_grid.xy) / cell; + let dd = d.xy / cell; + var ix = i32(floor(o.x + dd.x * start)); + var iy = i32(floor(o.y + dd.y * start)); + let sx = select(-1, 1, dd.x >= 0.0); + let sy = select(-1, 1, dd.y >= 0.0); + let inv_x = select(1e9, 1.0 / abs(dd.x), abs(dd.x) > 1e-7); + let inv_y = select(1e9, 1.0 / abs(dd.y), abs(dd.y) > 1e-7); + var tx = select((f32(ix) - o.x) / dd.x, (f32(ix + 1) - o.x) / dd.x, dd.x >= 0.0); + var ty = select((f32(iy) - o.y) / dd.y, (f32(iy + 1) - o.y) / dd.y, dd.y >= 0.0); + if (abs(dd.x) <= 1e-7) { tx = 1e9; } + if (abs(dd.y) <= 1e-7) { ty = 1e9; } + var t = start; + for (var k = 0u; k < AIRLIGHT_CELLS; k = k + 1u) { + if (t >= end) { + break; + } + let t_out = min(min(tx, ty), end); + if (ix >= 0 && iy >= 0 && ix < i32(side) && iy < i32(side)) { + let base = (u32(iy) * side + u32(ix)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let to_l = l.pos.xyz - c; + let t0 = dot(to_l, d); + // the ray's point nearest to the lamp: taken in this cell only + let tc = clamp(t0, start, end); + if (tc < t || tc > t_out) { + continue; + } + let range = l.extra.w; + let h = length(to_l - d * t0); + if (h >= range) { + continue; + } + // A beam (a headlamp, a spot) is lit in the weather's fog only: its cone is a sliver of + // sixteen jittered steps at half size, which the fog's density hides and the clear + // air's haze shows as shimmer and soap. The lamps' halo alone has the ground haze. + let beam_lamp = l.extra.z != 0.0 || l.dir.w > -1.5; + let fog_sigma = enh.fog.x * droplets; + if (beam_lamp && enh.fog.x < 2e-4) { + continue; + } + let s0 = select(sigma0, fog_sigma, beam_lamp); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + // (inside its core a lamp is as bright as at the core's edge) + let hh = max(h, select(core * 0.7, 0.4, l.extra.z != 0.0)); + let w = sqrt(range * range - h * h); + let ta = max(start, t0 - w); + let tb = min(end, t0 + w); + if (tb <= ta) { + continue; + } + var acc = 0.0; + var half = 0.0; + if (l.extra.z != 0.0 || l.dir.w > -1.5) { + // a beam (a headlamp, a spot): lit only where its cone or cut-off lets + // it - a sliver of the angles the lamp is seen under, which the five + // nodes missed. Sixteen even steps over that angle instead (dphi = + // h dt / r^2: the inverse square is in the step). (Sixteen even steps + // along the way put the few next to the lamp, where nearly all of its + // light is, a metre or more apart: the pixels' staggered steps came + // out as a coarse checker in the fog round every headlamp.) + let pa = atan((ta - t0) / hh); + let dphi = (atan((tb - t0) / hh) - pa) / 16.0; + let tile_k = beam_tile(li, l); + for (var q = 0u; q < 16u; q = q + 1u) { + let tq = t0 + hh * tan(pa + (f32(q) + jitter) * dphi); + let to = l.pos.xyz - (c + d * tq); + let ld = to * inverseSqrt(max(dot(to, to), 1e-6)); + var beam = 0.0; + if (l.extra.z != 0.0) { + beam = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0); + } else { + beam = smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } + // (the map is looked at only where the beam shines at all, and only for + // the few lamps that have a tile: no shadows, no tile, no tap) + var reach = 1.0; + if (beam > 0.002 && tile_k < 44u) { + reach = beam_reaches(tile_k, c + d * tq); + } + acc = acc + beam * reach * fog_phase(dot(ld, d)) * dphi; + } + half = 1.0; + } else { + let pa = atan((ta - t0) / hh); + let pb = atan((tb - t0) / hh); + half = 0.5 * (pb - pa); + let mid = 0.5 * (pa + pb); + let tile_p = beam_tile(li, l); + for (var q = 0u; q < 5u; q = q + 1u) { + let phi = mid + half * gx[q]; + let tq = t0 + hh * tan(phi); + let ld = normalize(l.pos.xyz - (c + d * tq)); + var beam = 1.0; + if (l.dir.z < -0.5) { + // (a lamp in a housing: see `lamp_light`) + beam = 0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z); + } + // (a lamp with a shadow map: what stands between it and the air + // keeps its light out of that air, as the headlamps' beams) + var reach = 1.0; + if (beam > 0.002 && tile_p < 44u) { + reach = beam_reaches(tile_p, c + d * tq); + } + acc = acc + gw[q] * beam * reach * fog_phase(-sin(phi)); + } + } + // a lamp's irradiance is core^2 / r^2 of its colour's (a headlamp's 1 / r^2) + let strength = select(core * core, 1.0, l.extra.z != 0.0); + let xc = c + d * tc; + let sigma = s0 * exp(-enh.fog.y * max(xc.z - enh.fog.z, 0.0)); + let dl = distance(xc, l.pos.xyz); + let atten = exp(-layer_depth(s0, enh.fog.y, c.z - enh.fog.z, xc.z - enh.fog.z, tc - start) - sigma * dl); + sum = sum + l.color.rgb * (l.color.w * strength * acc * half / hh * sigma * atten); + } + } + t = t_out; + if (tx < ty) { + tx = tx + inv_x; + ix = ix + sx; + } else { + ty = ty + inv_y; + iy = iy + sy; + } + } + return sum * enh.lights.y; +} + +// Enhanced: the light a raindrop or a snowflake sends towards the eye - what it scatters of +// the sky's light, the sun's and the lamps' round it, the drop's strongly forward (a +// streak flashes against a lamp seen through the rain, and is next to invisible in the +// dark between the lamps), the flake's nearly every way. (Drawn at the display's level +// whatever the light, the flakes of a snowfall at night shone white in the dark, far from +// any lamp.) +fn precip_light(x: vec3, to_eye: vec3, snow: bool) -> vec3 { + // the sky's and the ground's light round it, and the sun's on a small sphere + var e = enh.fog_color.rgb * (PI / 0.9) + enh.sun.rgb * 0.25; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell > 0.0 && side > 0u) { + let f = (x.xy - camera.light_grid.xy) / cell; + let gx = i32(floor(f.x)); + let gy = i32(floor(f.y)); + if (gx >= 0 && gy >= 0 && gx < i32(side) && gy < i32(side)) { + let base = (u32(gy) * side + u32(gx)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let dl = l.pos.xyz - x; + let dist2 = dot(dl, dl); + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let ld = dl * inverseSqrt(max(dist2, 1e-6)); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var k = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + if (l.extra.z != 0.0) { + k = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + k = k * smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } else if (l.dir.z < -0.5) { + k = k * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + // (the scattering towards the eye relative to an even one: a drop's light + // goes on forwards, a flake's every way. The angle is the one between the + // light's way from the lamp, -ld, and on to the eye: taken against -to_eye + // it put the forward peak behind the drop, and the drops in a bus's own + // beams, seen from behind the lamps, shone a hundred times too bright as + // white streaks down the road ahead) + let c = dot(-ld, to_eye); + let lobe = select(fog_phase(c), 0.7 * hg_phase(c, 0.3) + 0.3 / (4.0 * PI), snow) * 4.0 * PI; + e = e + l.color.rgb * l.color.w * enh.lights.y * k * lobe; + } + } + } + return e / PI; +} + diff --git a/crates/mx/tests/openomsi/snow_basic.wgsl b/crates/mx/tests/openomsi/snow_basic.wgsl new file mode 100644 index 0000000..d227c7d --- /dev/null +++ b/crates/mx/tests/openomsi/snow_basic.wgsl @@ -0,0 +1,1022 @@ +// What the snowfall (snow.wgsl) and the rainfall (rain.wgsl) share: the camera, a hash of +// a particle's number, and the player's vehicle the weather is kept out of. +struct Camera { + view_proj: mat4x4, + cam_pos: vec4, + // (kept in lockstep with `CameraUniform` in lib.rs, as sky.wgsl's) + world_origin: vec4, + sun_dir: vec4, + ambient: vec4, + fog: vec4, + sun_color: vec4, + sky_color: vec4, + light_grid: vec4, + sky: vec4, + cam_right: vec4, + cam_up: vec4, + clouds: vec4, + light_view_proj: mat4x4, + light_view_proj_far: mat4x4, + shadow: vec4, + post: vec4, + inside_a: vec4, + inside_b: vec4, + inside_c: vec4, + flags: vec4, + light_view_proj_close: mat4x4, + wind: vec4, + lamp_view_proj: array, 56>, + lamp_atlas: vec4, + tree_wind: vec4, + inside2_a: vec4, + inside2_b: vec4, + inside2_c: vec4, + cookies: array, 8>, + cabin_lamps: array, 4>, + // x: the textures' mip bias (FSR 1: negative, see `CameraUniform::lod`) + lod: vec4, + // (the classic picture's headlight, `CameraUniform::spot`: unread here) + spot: array, 4>, +}; +@group(0) @binding(0) var camera: Camera; + +fn hash4(n: u32) -> vec4 { + var x = vec4(n, n * 747796405u + 2891336453u, n ^ 0x9e3779b9u, n * 1664525u + 1013904223u); + x = x * 1664525u + 1013904223u; + x.x = x.x + x.y * x.w; + x.y = x.y + x.z * x.x; + x.z = x.z + x.x * x.y; + x.w = x.w + x.y * x.z; + x = x ^ (x >> vec4(16u)); + x.x = x.x + x.y * x.w; + x.y = x.y + x.z * x.x; + x.z = x.z + x.x * x.y; + return vec4(x & vec4(0xffffffu)) / 16777216.0; +} + +// The precipitation's roof map (passes/precip_map.rs): what stands over the ground round +// the camera, its depth seen from straight above. +@group(1) @binding(1) var roof_map: texture_depth_2d; +fn roof_depth(t: vec2) -> f32 { return textureLoad(roof_map, t, 0); } + +// Whether something solid stands over `p` (the map's matrix `m`; `on` 0 without a map): a +// bus's or a car's roof, a shelter, a bridge, a house - no drop or flake falls there. +fn under_roof(p: vec3, m: mat4x4, on: f32) -> bool { + let c = m * vec4(p, 1.0); + let uv = vec2(c.x * 0.5 + 0.5, 0.5 - c.y * 0.5); + let side = f32(textureDimensions(roof_map).x); + let t = vec2(clamp(uv, vec2(0.0), vec2(0.9999)) * side); + let top = roof_depth(t); + // (5 cm under it: the map's depth reaches 300 m) + return on > 0.5 && all(abs(c.xy) < vec2(1.0)) && c.z > top + 0.00017; +} + +// 1 inside the player's own vehicle (its box, a little wider): no snow falls in the cab +fn in_own_vehicle(p: vec3) -> bool { + // (the front and, of an articulated bus, the rear section: it snowed in the back, #1967; + // without branches - two boxes tested with early returns and short-circuits brought + // Apple's M4 shader compiler service down, XPC_ERROR_CONNECTION_INTERRUPTED, and the + // game fell back to no snowfall) + return any(vec2(in_box(p, camera.inside_a, camera.inside_b, camera.inside_c), in_box(p, camera.inside2_a, camera.inside2_b, camera.inside2_c))); +} + +fn in_box(p: vec3, a: vec4, b: vec4, c: vec4) -> bool { + let d = p - a.xyz; + let sh = a.w; + let ch = b.x; + let q = vec3(d.x * ch - d.y * sh - c.x, d.x * sh + d.y * ch - c.y, d.z - c.z); + let h = b.yzw + vec3(0.3); + return select(false, all(abs(q) < h), c.w >= 0.5); +} + +// Enhanced: the sun's far shadow map (the scene's camera group), which keeps every caster - +// a drop or a flake in the shade of a house or under the trees does not catch the sun. +@group(0) @binding(6) var s_shadow: sampler_comparison; +@group(0) @binding(7) var t_shadow_far: texture_depth_2d; + +// Enhanced: the procedural flake atlas (precip.rs `FlakeAtlas`): eight cells of snow +// crystals and flakes, R how much of a texel they cover, G how bright it is. +@group(1) @binding(2) var t_flakes: texture_2d; +@group(1) @binding(3) var s_flakes: sampler; + +// How far `p` is over whatever stands uppermost there by the roof map (m): below 0 under a +// roof, and far over everything where there is no map. +fn roof_clearance(p: vec3, m: mat4x4, on: f32) -> f32 { + let c = m * vec4(p, 1.0); + let uv = vec2(c.x * 0.5 + 0.5, 0.5 - c.y * 0.5); + let side = f32(textureDimensions(roof_map).x); + let top = roof_depth(vec2(clamp(uv, vec2(0.0), vec2(0.9999)) * side)); + // (the map looks straight down: its depth goes against the height, m[2].z < 0) + let h = (c.z - top) / m[2].z; + return select(1e4, h, on > 0.5 && all(abs(c.xy) < vec2(1.0)) && top < 0.9999); +} + +// The wind's gusts: it swells and slackens over some seconds, each swell running downwind +// over the ground as a wave some 70 m long, so that neighbouring drops and flakes are blown +// together and a gust is seen to sweep through the rain. x: the time's worth of the mean +// wind the gusts have added to a particle's way by `t` (the swell's integral, s), y: the +// swell now (a share of the mean wind). +fn precip_gust(x: vec2, t: f32, wind: vec2, strength: f32) -> vec2 { + let speed = length(wind); + let along = dot(x, wind / max(speed, 1e-3)) * (6.2831853 / 70.0); + let across = dot(x, vec2(-wind.y, wind.x) / max(speed, 1e-3)) * (6.2831853 / 160.0); + let w1 = 0.42; + let w2 = 1.17; + let a1 = 0.38 * strength; + let a2 = 0.17 * strength; + let p1 = w1 * t - along + 0.6 * sin(across); + let p2 = w2 * t - 2.3 * along + 1.7 + across; + return vec2(-a1 * cos(p1) / w1 - a2 * cos(p2) / w2, a1 * sin(p1) + a2 * sin(p2)); +} + +// How much of the sun reaches `p` (Enhanced): one compare in the far cascade, lit beyond it +// and without shadow maps. +fn precip_sun(p: vec3) -> f32 { + if (camera.shadow.x < 0.5 || enh.sun.r + enh.sun.g < 1e-4) { + return 1.0; + } + let lp = camera.light_view_proj_far * vec4(p, 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (any(uv < vec2(0.0)) || any(uv > vec2(1.0)) || lp.z < 0.0 || lp.z > 1.0) { + return 1.0; + } + return textureSampleCompareLevel(t_shadow_far, s_shadow, uv, lp.z - 0.0004); +} + +// A hash of a cell of the plane (0..1 each), its integer coordinates taken modulo 4096 so +// that the world's large figures stay exact. +fn cell_hash(c: vec2) -> vec4 { + let w = c - 4096.0 * floor(c / 4096.0); + let i = vec2(w); + return hash4(i.x * 4099u + i.y * 7919u + 17u); +} + +// The panels of a far veil of rain or snow (Enhanced): rings of upright panels round the +// camera, twelve a ring, each a strip of four vertices. Beyond the particles' layers the +// drops or flakes are too many and too small to draw one by one, and a heavy fall is seen +// there as what it is, a grey sheet streaked or speckled by them, sweeping by with the +// wind. `c`: the corner (0..1 each way); returns the corner's place (render frame) in xyz +// and its ring's radius in w. +fn veil_corner(panel: u32, c: vec2) -> vec4 { + var radii = array(30.0, 48.0, 78.0); + let ring = min(panel / 12u, 2u); + let r = radii[ring]; + // (each panel a little wider than its twelfth, so that the chords close the ring; the + // rings turned against each other, so their joins do not line up) + let a = (f32(panel % 12u) + c.x * 1.04 - 0.02 + 0.37 * f32(ring)) * (6.2831853 / 12.0); + let z = camera.cam_pos.z + mix(-6.0, 26.0 + 0.4 * r, c.y); + return vec4(camera.cam_pos.xy + vec2(cos(a), sin(a)) * r, z, r); +} + +// The snowfall, every mode: a field of flakes that lives on the GPU alone - each flake's +// place is worked out here from its number, the time, the wind and the camera, so that a +// heavy fall is a hundred and fifty thousand flakes for the cost of one draw (nothing is +// simulated or sent per flake). The field is the world's, repeating every few metres round +// the camera in three layers - dense close by, where every flake is a few pixels wide, +// thinner further out, where it is a speck; beyond them the snowfall's extinction takes the +// view (Enhanced). Flakes are a few millimetres across (an exponential spread, Gunn and +// Marshall 1958; a light fall single crystals of a millimetre), fall at about a metre a +// second (aggregates at 0.8 D^0.16 m/s, Locatelli and Hobbs 1974), sway as they go and +// drift with the wind; opaque and lit by what lights them - the classic picture's +// envir.cfg light, or the enhanced picture's sky, sun and lamps (`precip_light`). + +struct SnowParams { + // xyz the wind the flakes drift with (m/s), w the time (s) + wind: vec4, + // x how hard it snows (0..1), y the flakes' mean diameter (m), zw how many flakes the + // first two layers hold (the rest are the third's) + fall: vec4, + // the precipitation's roof map: its matrix, and x 1 when there is one + roof: mat4x4, + roof_on: vec4, + // Enhanced: x the instance the veil's panels begin at (the flakes' end), y how many + // panels there are, z how strong the wind's gusts are (0..1), w the picture's height (px) + ext: vec4, +}; +@group(1) @binding(0) var sp: SnowParams; + +struct SnowOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + // the flake's cover (alpha), and its place (for its light) + @location(1) cover: f32, + @location(2) pos: vec3, +}; + +// The layers round the camera: half width, bottom and top (m). +const LAYER_H = array, 3>(vec3(4.0, -2.5, 5.5), vec3(10.0, -3.0, 9.0), vec3(24.0, -3.0, 16.0)); + +@vertex +fn vs_snow(@builtin(vertex_index) vid: u32, @builtin(instance_index) k: u32) -> SnowOut { + let corners = array, 6>(vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, 1.0)); + let c = corners[vid % 6u]; + var out: SnowOut; + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + let n0 = u32(sp.fall.z); + let n1 = u32(sp.fall.w); + var layer = 2u; + if (k < n0) { + layer = 0u; + } else if (k < n0 + n1) { + layer = 1u; + } + let lh = LAYER_H[layer]; + let size = vec3(2.0 * lh.x, 2.0 * lh.x, lh.z - lh.y); + let h1 = hash4(k * 2u + 1u); + let h2 = hash4(k * 2u + 7919u); + // the flake: its diameter, fall speed and sway + let r = sp.fall.x; + let d = min(0.0005 - sp.fall.y * log(max(1.0 - h1.w, 1e-6)), 0.015); + let fall = max(0.8 * pow(d * 1000.0, 0.16) * (0.75 + 0.25 * r) * (0.85 + 0.3 * h2.x), 0.3); + let t = sp.wind.w; + let pace = 1.5 + 2.5 * h2.y; + let sway = 0.05 + 0.15 * h2.z; + let ph = h2.w * 6.2831853 + pace * t; + // its place in the world: where it started, carried by the wind, swaying round, falling; + // then the copy of the field nearest the camera (the field's figures in the world's + // own, modulo a kilometre, so that it stays put while the render origin moves) + let world_cam = camera.cam_pos.xyz + vec3(camera.world_origin.xy, 0.0); + let start = h1.xyz * size; + let drift = sp.wind.xyz * (0.6 * t) + vec3(cos(ph), sin(ph), 0.0) * sway - vec3(0.0, 0.0, fall * t); + let lo = world_cam + vec3(-lh.x, -lh.x, lh.y); + let q = lo + (((start + drift - lo) % size) + size) % size; + let p = q - vec3(camera.world_origin.xy, 0.0); + if (in_own_vehicle(p) || under_roof(p, sp.roof, sp.roof_on.x)) { + return out; + } + // a denser layer fades out towards its edges, into the thinner one round it + let rel = q - lo; + let soft = lh.x * 0.3; + var fade = 1.0; + if (layer < 2u) { + let e = min(rel, size - rel) / soft; + fade = clamp(min(min(e.x, e.y), e.z), 0.0, 1.0); + } + let to_cam = camera.cam_pos.xyz - p; + let dist = length(to_cam); + let vdir = to_cam / max(dist, 0.001); + // a flake close by is out of focus (its blur as wide as the pupil, some 2.5 mm), one far + // off at least a pixel and a half wide; as bright as it is seen - a small point's + // brightness goes with the square root of its light (Stevens' power law) + let rad = d * 0.5; + let rs = max(sqrt(rad * rad + 0.0025 * 0.0025), dist * 0.0016); + out.cover = fade * sqrt(rad / rs); + if (out.cover < 0.004) { + return out; + } + var ax = cross(vec3(0.0, 0.0, 1.0), vdir); + ax = select(vec3(1.0, 0.0, 0.0), normalize(ax), length(ax) > 1e-4); + let ay = cross(vdir, ax); + out.clip = camera.view_proj * vec4(p + (ax * c.x + ay * c.y) * rs, 1.0); + out.uv = c; + out.pos = p; + return out; +} + +fn flake_alpha(in: SnowOut) -> f32 { + let r = length(in.uv); + return clamp(in.cover * (1.0 - smoothstep(0.55, 1.0, r)), 0.0, 1.0); +} + +// the classic picture: white, lit as the scene is (envir.cfg's ambient and sun light) +@fragment +fn fs_snow(in: SnowOut) -> @location(0) vec4 { + let a = flake_alpha(in); + let light = min(camera.ambient.rgb + camera.sun_color.rgb * 0.5, vec3(1.0)); + return vec4(light * 0.9 * a, a); +} + + +// ---- The enhanced snowfall +// +// The same field of flakes, each drawn as what it is (precip.rs `FlakeAtlas`): in a light +// fall single crystals - stellar and fernlike dendrites, sectored and plain hexagonal +// plates - in a heavier one aggregates of many, a centimetre across. A flake turns as it +// falls and a plate tips over and back (seen edge-on it thins to a line), flutters on two +// periods of its own besides its slow sway, and is blown on by the wind's gusts with its +// neighbours. Close to the eye it is out of focus, a soft disc; far off a speck. A plate +// turned to the sun flashes for a moment. Lit as the classic snowfall is by the sky and the +// lamps, the sun's share shaded by the far shadow map and thrown a little forwards; beyond +// the flakes' layers a heavy fall is a speckled veil (`veil_corner`). + +struct SnowOutE { + @builtin(position) clip: vec4, + // across the quad (-1..1 each way); the veil: the panel's corner (0..1) + @location(0) uv: vec2, + // x the cover, y the atlas cell (-1 the veil), z its mip level, w how far out of focus + // (0 sharp .. 1 a soft disc) + @location(1) @interpolate(flat) shape: vec4, + @location(2) pos: vec3, + // the flake's turn (cos, sin), how far it faces the eye (1 face on), how much it glints + @location(3) @interpolate(flat) turn: vec4, + // x the quad's radius over the flake's, y the veil's radius (m), z its ring + @location(4) @interpolate(flat) extra: vec4, +}; + +fn snow_none() -> SnowOutE { + var out: SnowOutE; + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + out.uv = vec2(0.0); + out.shape = vec4(0.0); + out.pos = vec3(0.0); + out.turn = vec4(1.0, 0.0, 1.0, 0.0); + out.extra = vec4(1.0, 0.0, 0.0, 0.0); + return out; +} + +@vertex +fn vs_snow_enhanced(@builtin(vertex_index) vid: u32, @builtin(instance_index) k: u32) -> SnowOutE { + let corners = array, 6>(vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, 1.0)); + let c = corners[vid % 6u]; + if (k >= u32(sp.ext.x)) { + return snow_veil(c * 0.5 + vec2(0.5), k - u32(sp.ext.x)); + } + var out = snow_none(); + let n0 = u32(sp.fall.z); + let n1 = u32(sp.fall.w); + let layer = select(select(2u, 1u, k < n0 + n1), 0u, k < n0); + let lh = LAYER_H[layer]; + let size = vec3(2.0 * lh.x, 2.0 * lh.x, lh.z - lh.y); + let h1 = hash4(k * 2u + 1u); + let h2 = hash4(k * 2u + 7919u); + let h3 = hash4(k * 5u + 15485863u); + // the flake: its diameter and fall speed as `vs_snow` has them - but a heavy fall's + // aggregates bigger: half a centimetre across on the mean, the big wet flakes of a + // thick fall up to two (the classic sizes, two millimetres, are those of a moderate + // fall's single crystals, and a heavy fall showed as a fine dust) + let r = sp.fall.x; + let mean = max(sp.fall.y, 0.0012 + 0.0062 * smoothstep(0.2, 0.9, r)); + let d = min(0.0005 - mean * log(max(1.0 - h1.w, 1e-6)), 0.02); + let fall = max(0.8 * pow(d * 1000.0, 0.16) * (0.75 + 0.25 * r) * (0.85 + 0.3 * h2.x), 0.3); + let t = sp.wind.w; + let world_cam = camera.cam_pos.xyz + vec3(camera.world_origin.xy, 0.0); + let lo = world_cam + vec3(-lh.x, -lh.x, lh.y); + let base = sp.wind.xyz * (0.6 * t) - vec3(0.0, 0.0, fall * t); + let q0 = lo + (((h1.xyz * size + base - lo) % size) + size) % size; + // its sway, a slow circle, and its flutter, quicker and smaller, up and down as well; + // and the gusts + let ph = h2.w * 6.2831853 + (1.5 + 2.5 * h2.y) * t; + let ph2 = h3.x * 6.2831853 + (4.0 + 3.0 * h3.y) * t; + let sway = vec3(cos(ph), sin(ph), 0.0) * (0.05 + 0.15 * h2.z); + let flutter = vec3(cos(ph2), sin(1.3 * ph2), 0.5 * sin(0.7 * ph2)) * (0.015 + 0.03 * h3.z); + let g = precip_gust(q0.xy, t, sp.wind.xy, sp.ext.z); + let q = q0 + sway + flutter + vec3(sp.wind.xy * (0.6 * g.x), 0.0); + let p = q - vec3(camera.world_origin.xy, 0.0); + if (in_own_vehicle(p)) { + return out; + } + // under a roof none; one about to land on the ground or a roof fades into it (the + // surface would cut it in half) + let clear = roof_clearance(p, sp.roof, sp.roof_on.x); + if (clear < -0.05) { + return out; + } + let landing = smoothstep(-0.03, 0.04, clear); + // every layer fades out at its edges, where its flakes come round again + let rel = q0 - lo; + let e = min(rel, size - rel) / (lh.x * 0.3); + let fade = clamp(min(min(e.x, e.y), e.z), 0.0, 1.0) * landing; + let to_cam = camera.cam_pos.xyz - p; + let dist = length(to_cam); + let vdir = to_cam / max(dist, 0.001); + let ch = camera.view_proj * vec4(p, 1.0); + if (fade < 0.004 || ch.w < 0.05 || abs(ch.x) > 1.3 * ch.w || abs(ch.y) > 1.3 * ch.w) { + return out; + } + let cu = camera.view_proj * vec4(p + camera.cam_up.xyz, 1.0); + let px_per_m = max(abs(cu.y / cu.w - ch.y / ch.w) * 0.5 * sp.ext.w, 1e-3); + // In focus a few metres off (the street the eye is on): nearer, a flake's blur grows to + // a few millimetres (as a camera's lens draws it: a big flake right in front of the eye + // is a soft blot, not a sharp star); it is a pixel and a half wide at the least, and as + // bright as `vs_snow` has it. + let rad = d * 0.5; + let blur = 0.004 * clamp(1.0 - dist / 5.0, 0.0, 1.0); + let rs = max(sqrt(rad * rad + blur * blur), 1.5 / px_per_m); + let cover = fade * sqrt(rad / rs); + if (cover < 0.004) { + return out; + } + let sharp = rad / rs; + // single crystals in a light fall, the bigger flakes aggregates of them + let aggregate = h3.w < smoothstep(0.0012, 0.004, d); + let cell = select(floor(h3.z * 3.99), 4.0 + floor(fract(h3.z * 7.0) * 3.99), aggregate); + // turning, and tipping over and back (an aggregate hardly shows it) + let spin = (h3.y - 0.5) * 5.0; + let ang = h3.x * 6.2831853 + spin * t; + let tip = cos((0.8 + 2.2 * h2.x) * t + h1.x * 6.2831853); + let face = select(0.25 + 0.75 * abs(tip), 0.8 + 0.2 * abs(tip), aggregate); + let glint = pow(0.5 + 0.5 * sin((2.0 + 3.0 * h2.x) * t + h2.w * 20.0), 60.0) * select(1.0, 0.25, aggregate); + // the atlas's level: the flake's 58 texels over its pixels + let level = clamp(log2(58.0 / max(2.0 * rad * px_per_m, 1e-3)), 0.0, 4.0); + var ax = cross(vec3(0.0, 0.0, 1.0), vdir); + ax = select(vec3(1.0, 0.0, 0.0), normalize(ax), length(ax) > 1e-4); + let ay = cross(vdir, ax); + out.clip = camera.view_proj * vec4(p + (ax * c.x + ay * c.y) * rs, 1.0); + out.uv = c; + out.shape = vec4(cover, cell, level, 1.0 - smoothstep(0.35, 0.9, sharp)); + out.pos = p; + out.turn = vec4(cos(ang), sin(ang), face, glint); + out.extra = vec4(1.0 / max(sharp, 1e-3), 0.0, 0.0, 0.0); + return out; +} + +fn snow_veil(c: vec2, panel: u32) -> SnowOutE { + var out = snow_none(); + let v = veil_corner(panel, c); + let ring = f32(panel / 12u); + if (sp.fall.x < 0.08) { + return out; + } + out.clip = camera.view_proj * vec4(v.xyz, 1.0); + out.uv = c; + out.shape = vec4(pow(sp.fall.x, 1.2) * 0.11 * (0.8 + 0.2 * ring), -1.0, 0.0, 0.0); + out.pos = v.xyz; + out.extra = vec4(1.0, v.w, ring, 0.0); + return out; +} + +fn flake_alpha_e(in: SnowOutE) -> vec2 { + // the flake's own figure, turned and tipped, the crystal's rim at 1 + let u = vec2(in.turn.x * in.uv.x - in.turn.y * in.uv.y, in.turn.y * in.uv.x + in.turn.x * in.uv.y); + let f = vec2(u.x, u.y / max(in.turn.z, 0.05)) * in.extra.x; + let cell = vec2(in.shape.y % 4.0, floor(in.shape.y / 4.0)); + let cuv = clamp(vec2(0.5) + f * 0.45, vec2(0.0), vec2(1.0)); + let tex = textureSampleLevel(t_flakes, s_flakes, (cell + cuv) * vec2(0.25, 0.5), in.shape.z); + let crisp = select(0.0, tex.r, all(abs(f) < vec2(1.1))); + // out of focus: a soft disc, a touch brighter at its rim, as a lens draws a point + let rr = length(in.uv); + let disc = (1.0 - smoothstep(0.55, 1.0, rr)) * (0.85 + 0.15 * smoothstep(0.3, 0.8, rr)); + let a = mix(crisp, disc, in.shape.w) * in.shape.x; + return vec2(clamp(a, 0.0, 1.0), mix(tex.g, 1.0, in.shape.w)); +} + +fn veil_snow_alpha(in: SnowOutE) -> f32 { + let r = in.extra.y; + let ring = in.extra.z; + let d = in.pos - camera.cam_pos.xyz; + let theta = atan2(d.y, d.x); + let t = sp.wind.w; + let tang = vec2(-sin(theta), cos(theta)); + // The flakes beyond, each a speck a pixel or two across, falling a metre a second and + // drifting with the wind: two lattices of specks, a fixed angle apart, each cell with a + // flake of its own somewhere in it - more of them showing the harder it snows. + var specks = 0.0; + for (var j = 0u; j < 2u; j = j + 1u) { + let fj = f32(j); + let cols = round((900.0 + 150.0 * ring) * (1.0 + 0.41 * fj)); + let cw = 6.2831853 * r / cols; + let drift = dot(sp.wind.xy, tang) * 0.6 * t; + let x = vec2(theta / 6.2831853 * cols - drift / cw, (in.pos.z + (0.9 + 0.3 * fj) * t) / cw) + vec2(0.5 * fj); + let ci = floor(x); + let h = cell_hash(ci + vec2(311.0 * ring, 57.0 * fj)); + let centre = vec2(0.2) + 0.6 * h.xy + 0.08 * vec2(sin(t * 1.7 + h.z * 30.0), 0.0); + let s = (1.0 - smoothstep(0.08, 0.22, length(fract(x) - centre))) * step(h.w, 0.35 + 0.5 * sp.fall.x); + specks = max(specks, s * (0.5 + 0.5 * h.z)); + } + let g = precip_gust(in.pos.xy + camera.world_origin.xy, t, sp.wind.xy, sp.ext.z); + // (as the rain's veil, rain.wgsl `veil_rain_alpha`: gentler gusts, kept to the horizon, and + // little flat grey under the specks - looked up at, the panels stood in the sky as a ring + // of pale sheets) + let sweep = clamp(1.0 + 0.6 * g.y, 0.7, 1.3); + let up = in.pos.z - camera.cam_pos.z; + let height = smoothstep(-3.0, 3.0, up) * (1.0 - smoothstep(0.08, 0.3, up / r)); + return clamp(in.shape.x * (0.2 + 0.8 * specks) * sweep * height, 0.0, 1.0); +} + +// the enhanced picture: what the flake scatters of the sky's, the sun's and the lamps' +// light, at the albedo of snow +@fragment +fn fs_snow_enhanced(in: SnowOutE) -> @location(0) vec4 { + let veil = in.shape.y < -0.5; + var a = 0.0; + var bright = 1.0; + if (veil) { + a = veil_snow_alpha(in); + } else { + let fa = flake_alpha_e(in); + a = fa.x; + bright = fa.y; + } + if (a < 0.002) { + discard; + } + let to_eye = normalize(camera.cam_pos.xyz - in.pos); + let sun = precip_sun(in.pos); + // the sun's share: `precip_light` takes it as even and unshaded; here it is shaded, and + // thrown a little forwards (a fall lit from behind is brighter), and a tipping plate + // flashes as it faces it + let c = dot(-camera.sun_dir.xyz, to_eye); + let lobe = 0.7 * hg_phase(c, 0.35) * 4.0 * PI + 0.3; + let sun_part = enh.sun.rgb * (0.25 / PI * (sun * lobe - 1.0) + sun * in.turn.w * 0.6); + let up = sh_irradiance(vec3(0.0, 0.0, 1.0)) / PI; + var l = vec3(0.0); + if (veil) { + l = (enh.fog_color.rgb / 0.9 + enh.sun.rgb * 0.25 / PI + up) * 0.5 * 0.85 + sun_part * 0.425; + } else { + l = (up + up) * 0.5 * 0.85 + sun_part * 0.425; + } + l = max(l, vec3(0.0)) * mix(0.75, 1.05, bright); + return vec4(min(l * enh.exposure.x, vec3(60.0)) * a, a); +} + +// Enhanced graphics: what the enhanced main pass, the sky and the coronas share - the +// light of the physically based sky (see atmosphere.rs), in its units (1 = 10 000 lux), +// and the air between the camera and what it sees. The scene is drawn pre-exposed: +// radiance times `enh.exposure.x`, so that the half-float target keeps its precision by +// night as well as by day. +struct Enhanced { + // x pre-exposure, y the level unlit things are drawn at, z a lit window's radiance + // (pre-exposed), w how bright a light's corona is drawn + exposure: vec4, + // rgb irradiance of the sun after the clouds, w its angular radius (rad) + sun: vec4, + // irradiance from the sky and the ground: order-2 spherical harmonics, rgb + sh: array, 9>, + // rgb radiance of the ground, w the sky table's scale + ground: vec4, + // x weather fog extinction (1/m) at its base, y its height falloff (1/m), z the base + // height (render-origin relative), w clear-air extinction (1/m) at the ground + fog: vec4, + // rgb fog radiance from the light around it (the sun's part is added by angle), + // w the table scale the reflection probe was drawn with + fog_color: vec4, + // x wet roads, y snow cover, z rain, w cloud cover in front of the sun + weather: vec4, + // x mip levels of the probe, y illuminance of a light's core (maplight colour 1), + // z cabin light illuminance, w how much of the sun the clouds let through + lights: vec4, + // rgb the sun disc's irradiance before the clouds, w frame time (s) + sun_disc: vec4, + // x which term the main pass shows alone (OMSI_DEBUG_ENHANCED, 0 = the picture), + // y the puddles' F0, z the envmap photo's strength, w the tone curve's contrast + debug: vec4, + // xyz where the sky cube is drawn from, relative to the camera + eye: vec4, + // x how bright an LED panel's dots burn (0 = off), y whether the LED panels' `\S:n` + // masks keep their mip chain (0: at full resolution, the dots stay visible when small), z 1 + // when lights glare and glow in the night air (the settings' `light_glow`) + led: vec4, + // xyz towards the moon, w its angular radius (rad) + moon: vec4, + // rgb the moon disc's irradiance before the clouds, w how much of the starry sky shows + moon_disc: vec4, + // rgb the sun's irradiance at 1400, 2100 and 2800 m (the cumulus layer) and 7000 m + // (the high thin layer), through the atmosphere from up there + cloud_sun: array, 4>, + // rgb the moonlight on a surface facing the moon (after the clouds), w 1 while the + // shadow maps are the moon's + moon_light: vec4, + // the condensation on the player's bus's panes (optical depths): windscreen, sides, + // rear, and how far the defroster has cleared the windscreen (0..1; omsi-app + // condensation.rs) + condensation: vec4, + // x the cumulus layer's base, y its top (m over the ground), z the altocumulus cover, + // w the storm's activity + layers: vec4, + // the lightning of this frame: x the light it throws on a surface facing it (1 = 10 000 + // lux), yz towards it (horizontal unit vector), w its elevation (rad) + flash: vec4, + // xyz towards the flash (unit vector), w how bright its channel is + flash2: vec4, + // x a number the channel's shape is drawn from + flash3: vec4, + // the clouds' shadow field (cloud_field.rs): xy its middle in cloud space, z one over its + // width, w 1 when there is one + cloud_f1: vec4, + // xy what takes a world point to cloud space, z the height of the plane it is taken on, + // w the share of the sun the main pass has taken off already for the clouds over the camera + cloud_f2: vec4, + // the player's bus's pitch and roll: sin, cos of each (its panes' condensation sits on + // the glass on a slope, `pane_local`) + pane_tilt: vec4, + // Slots of the weather overhaul, one owner each (zero until it fills them): + // the volumetric clouds, the volumetric fog, the precipitation, the bus's panes, the + // surfaces' PBR and the ray tracing, and two spare. + clouds_ext: vec4, + clouds_ext2: vec4, + vol_fog: vec4, + vol_fog2: vec4, + precip_ext: vec4, + glass_ext: vec4, + // (pbr_ext: x the share of the sun's light that still comes as a beam - the rest the + // clouds scatter, `sun_scattered` - y 1 when x is set) + pbr_ext: vec4, + rt_ext: vec4, +}; +@group(0) @binding(11) var enh: Enhanced; +@group(0) @binding(13) var s_lin: sampler; +@group(0) @binding(14) var t_sky_lut: texture_2d; + +const PI: f32 = 3.14159265; + +// Irradiance from the sky and the ground on a surface facing n. +fn sh_irradiance(n: vec3) -> vec3 { + let c = enh.sh; + let e = c[0].rgb * 0.282095 + + c[1].rgb * (0.488603 * n.y) + c[2].rgb * (0.488603 * n.z) + c[3].rgb * (0.488603 * n.x) + + c[4].rgb * (1.092548 * n.x * n.y) + c[5].rgb * (1.092548 * n.y * n.z) + + c[6].rgb * (0.315392 * (3.0 * n.z * n.z - 1.0)) + c[7].rgb * (1.092548 * n.x * n.z) + + c[8].rgb * (0.546274 * (n.x * n.x - n.y * n.y)); + return max(e, vec3(0.0)); +} + +// The lightning's light on a surface facing n: half of it from the cloud overhead and +// round it (a hemisphere), half along the way to the flash itself. +fn flash_irradiance(n: vec3) -> vec3 { + if (enh.flash.x <= 0.0) { + return vec3(0.0); + } + return vec3(0.80, 0.90, 1.0) * enh.flash.x * (0.5 * (0.5 + 0.5 * n.z) + 0.5 * max(dot(n, enh.flash2.xyz), 0.0)); +} + +// Sky radiance towards d (unscaled: times enh.ground.w is the radiance). The table runs +// over the azimuth from the sun (0..π) and the elevation (denser at the horizon). +// The sky table's texture: the table (32 x 48) in its corner and the clouds' shadow field +// (192 x 192) beside it, one texel clear (cloud_field.rs `SKY_TEX_W`, `FIELD_X0`). +const SKY_TEX: vec2 = vec2(225.0, 192.0); +const SKY_TABLE: vec2 = vec2(32.0, 48.0); +const FIELD_ORIGIN: f32 = 33.0; +const FIELD_N: f32 = 192.0; + +fn sky_table_raw(d: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let ls = length(s.xy); + let ld = length(d.xy); + var az = 0.0; + if (ls > 1e-4 && ld > 1e-4) { + az = acos(clamp(dot(s.xy / ls, d.xy / ld), -1.0, 1.0)); + } + let el = asin(clamp(d.z, -1.0, 1.0)); + let v = 0.5 + 0.5 * sign(el) * sqrt(min(abs(el) / 1.5707963, 1.0)); + // (kept a half texel inside the table: its neighbours in the texture are not the sky) + let tx = clamp(vec2(az / PI, v) * SKY_TABLE, vec2(0.5), SKY_TABLE - vec2(0.5)); + return textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).rgb; +} + +// The share of the sun that reaches the point p through the clouds, as against what the main +// pass's sun (`enh.sun`) already has for the camera's own place: the cumulus layer's shadow +// field read where the sun's way through p meets the layer's middle. 1 where there is no +// field, beyond its edge and where the sun is low (the camera's own factor stands there). +fn cloud_shadow_ratio(p: vec3) -> f32 { + let s = camera.sun_dir.xyz; + if (enh.cloud_f1.w < 0.5 || s.z < 0.06) { + return 1.0; + } + let cs = p.xy + s.xy / s.z * (enh.cloud_f2.z - p.z) + enh.cloud_f2.xy; + let uv = (cs - enh.cloud_f1.xy) * enh.cloud_f1.z + vec2(0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + let w = 1.0 - smoothstep(0.36, 0.48, edge); + if (w <= 0.0) { + return 1.0; + } + let tx = vec2(FIELD_ORIGIN, 0.0) + clamp(uv * FIELD_N, vec2(0.5), vec2(FIELD_N - 0.5)); + let f = textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).r; + let ratio = min(f / max(enh.cloud_f2.w, 0.02), 6.0); + return mix(1.0, ratio, w); +} + +fn sky_table(d: vec3) -> vec3 { + return sky_table_raw(d) * enh.ground.w; +} + +// Henyey-Greenstein phase function. +fn hg_phase(c: f32, g: f32) -> f32 { + let g2 = g * g; + return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * c, 1e-4), 1.5)); +} + +// Optical depth of an exponentially thinning layer (extinction sigma at height 0, falling +// off with k per metre) along a straight path of length dist from height h0 to h1. +fn layer_depth(sigma: f32, k: f32, h0: f32, h1: f32, dist: f32) -> f32 { + if (sigma <= 0.0) { + return 0.0; + } + let a = max(h0, 0.0); + let b = max(h1, 0.0); + let dh = b - a; + if (abs(k * dh) < 1e-3) { + return sigma * dist * exp(-k * 0.5 * (a + b)); + } + return sigma * dist * (exp(-k * a) - exp(-k * b)) / (k * dh); +} + +// The air between the camera and a point dist metres away in direction dir (from the +// camera), at heights h0 (camera) and h1 (point) above the fog's base: rgb the light it +// scatters towards the camera (radiance), a what it lets through of the point. +fn air(dir: vec3, dist: f32, h0: f32, h1: f32) -> vec4 { + return air_of(dir, dist, h0, h1, 1.0); +} + +// The same with the clear air's share scaled (0 for the sky, whose table holds it already). +fn air_of(dir: vec3, dist: f32, h0: f32, h1: f32, clear: f32) -> vec4 { + let tau_fog = layer_depth(enh.fog.x, enh.fog.y, h0, h1, dist); + let tau_air = layer_depth(enh.fog.w * clear, 1.0 / 1500.0, h0, h1, dist); + let tau = tau_fog + tau_air; + let t = exp(-tau); + if (tau < 1e-5) { + return vec4(0.0, 0.0, 0.0, 1.0); + } + // clear air takes on the sky's own colour at the horizon in this direction (which + // already holds the glow round the sun); a weather fog glows with the light around it + // and brighter towards the sun + let horizon = sky_table(normalize(vec3(dir.x, dir.y, max(dir.z, 0.0) * 0.3 + 0.03))); + let fog_in = enh.fog_color.rgb + enh.sun.rgb * hg_phase(dot(dir, camera.sun_dir.xyz), 0.55) * 0.9; + let inscatter = mix(horizon, fog_in, tau_fog / tau); + return vec4(inscatter * (1.0 - t), t); +} + +struct PointLight { + pos: vec4, + color: vec4, + dir: vec4, + extra: vec4, +}; +@group(0) @binding(3) var lights: array; +@group(0) @binding(4) var grid: array; +const CELL_CAP: u32 = 32u; + +// `beam_shadow.wgsl` for the shaders without the lamp shadow tiles: nothing stands in a beam. +fn beam_tile(li: u32, l: PointLight) -> u32 { + return 0xffffffffu; +} + +fn beam_reaches(k: u32, x: vec3) -> f32 { + return 1.0; +} + +// Enhanced graphics: the lamps as the scene and the sky share them - a headlamp's beam +// and the light the weather's fog scatters from the lamps towards the camera (needs the +// point lights, their grid and `camera.light_grid`). + +// A headlamp's intensity towards `t` (from the lamp) by the angles of a road lamp, not +// around its axis: wide across, brightest just under the lamp's horizon where it reaches +// far down the road, weak straight down, and with a low beam a sharp cut-off above it. +// `dir` is the lamp's axis in its vehicle's floor: its rise tilts the horizon with the +// vehicle, up a ramp and down (#1897). +fn headlamp(t: vec3, dir: vec3, low: bool) -> f32 { + let fwd = normalize(dir.xy + vec2(1e-6, 0.0)); + let ahead = dot(t.xy, fwd); + if (ahead <= 0.0) { + return 0.0; + } + let across = abs(t.x * fwd.y - t.y * fwd.x) / ahead; + let wide = 0.12 * smoothstep(1.0, 0.45, across) + 0.88 * exp(-across * across / 0.06); + let rise = t.z / max(length(t.xy), 1e-3); + let tilt = dir.z / max(length(dir.xy), 1e-3); + // (the tangent of the angle under that horizon) + let drop = (tilt - rise) / max(1.0 + rise * tilt, 1e-3); + // full out to where the road is 0.06 under the lamp's horizon, then less as the cube of + // the drop and a little more: the road is lit evenly from the bumper on, a little + // brighter as far as the beam reaches, and not as one hot pool where its axis lands + var up = min(1.0, pow(0.06 / max(abs(drop), 1e-4), 3.4)); + if (low) { + up = up * smoothstep(-0.012, 0.025, drop); + return wide * up; + } + // a full beam reaches far: a narrow, bright core along the lamp's horizon + let hot = exp(-across * across / 0.012 - drop * drop / 0.0004); + return wide * up + 6.0 * hot; +} + +// The lamps' light the weather's fog scatters towards the camera (radiance, not +// pre-exposed): single scattering along the view ray from `start` to `len` metres in +// direction `d` - the glow round a street lamp in the mist, its cone under it, a bus's +// beams reaching ahead into the fog or the falling snow. The droplets scatter strongly +// forward (fog and cloud droplets of some ten micrometres: g about 0.8), so the glow is +// brightest looking towards a lamp and a cone shows faintly from the side. +// +// Each lamp is taken once, over the whole stretch of the ray within its reach, in the grid +// cell the ray's point nearest to it lies in (the ray's cells are walked through; every +// cell lists the lamps reaching into it). Along a straight ray past a point source, with +// t - t0 = h tan(phi) (h the ray's distance from the lamp, t0 where it passes nearest), +// the inverse square cancels against the path element: dt / r^2 = dphi / h, and what is +// left is the phase function over the angle, cos(theta) = -sin(phi) - a smooth integral +// taken with five Gauss-Legendre nodes, at each of which a spot's or a headlamp's beam is +// asked how much it sends that way. The fog's extinction dims the light on its way from +// the lamp and to the camera (taken at the nearest point). A beam's light, which reaches +// only part of the way, is summed along the ray instead, its steps staggered by `jitter`. +// The droplets' phase function: a strong forward peak and the back-scattered light a +// fog's lidar ratio of some 18 sr asks for (0.055 per steradian straight back) - a single +// Henyey-Greenstein lobe of g 0.8 gave a tenth of it, and a bus's own headlights lit no +// wall of fog in front of the driver. Two lobes, 0.9 of g 0.85 and 0.1 of g -0.5. +fn fog_phase(c: f32) -> f32 { + return 0.9 * hg_phase(c, 0.85) + 0.1 * hg_phase(c, -0.5); +} +const AIRLIGHT_CELLS: u32 = 16u; + +// The clear night air's own haze, which lights a lamp's halo and a headlamp's beam as the fog's +// droplets do, only fainter: the lowest hundred metres of a city's air hold its dust, exhaust +// and humidity at several times the column's average aerosol extinction (`enh.fog.w`), 1-3e-4 +// per metre (a visibility of 15-40 km). A lamp then has a soft glow round it and a low beam +// a faint cone, as in any night photograph, instead of a lit disc on a black ground. +const GROUND_HAZE_GAIN: f32 = 8.0; + +// `droplets`: how much of the weather's extinction scatters like fog (see `FogLampUniform`). +fn lamp_airlight(c: vec3, d: vec3, start: f32, len: f32, jitter: f32, droplets: f32) -> vec3 { + var sum = vec3(0.0); + let sigma0 = enh.fog.x * droplets + enh.fog.w * GROUND_HAZE_GAIN * enh.led.z; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (sigma0 < 4e-5 || cell <= 0.0 || side == 0u || len <= start) { + return sum; + } + // (past a few optical depths nothing comes back) + let end = min(len, start + 4.0 / sigma0); + let gx = array(-0.9061798, -0.5384693, 0.0, 0.5384693, 0.9061798); + let gw = array(0.2369269, 0.4786287, 0.5688889, 0.4786287, 0.2369269); + // the walk through the grid's cells along the ray's plan + let o = (c.xy - camera.light_grid.xy) / cell; + let dd = d.xy / cell; + var ix = i32(floor(o.x + dd.x * start)); + var iy = i32(floor(o.y + dd.y * start)); + let sx = select(-1, 1, dd.x >= 0.0); + let sy = select(-1, 1, dd.y >= 0.0); + let inv_x = select(1e9, 1.0 / abs(dd.x), abs(dd.x) > 1e-7); + let inv_y = select(1e9, 1.0 / abs(dd.y), abs(dd.y) > 1e-7); + var tx = select((f32(ix) - o.x) / dd.x, (f32(ix + 1) - o.x) / dd.x, dd.x >= 0.0); + var ty = select((f32(iy) - o.y) / dd.y, (f32(iy + 1) - o.y) / dd.y, dd.y >= 0.0); + if (abs(dd.x) <= 1e-7) { tx = 1e9; } + if (abs(dd.y) <= 1e-7) { ty = 1e9; } + var t = start; + for (var k = 0u; k < AIRLIGHT_CELLS; k = k + 1u) { + if (t >= end) { + break; + } + let t_out = min(min(tx, ty), end); + if (ix >= 0 && iy >= 0 && ix < i32(side) && iy < i32(side)) { + let base = (u32(iy) * side + u32(ix)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let to_l = l.pos.xyz - c; + let t0 = dot(to_l, d); + // the ray's point nearest to the lamp: taken in this cell only + let tc = clamp(t0, start, end); + if (tc < t || tc > t_out) { + continue; + } + let range = l.extra.w; + let h = length(to_l - d * t0); + if (h >= range) { + continue; + } + // A beam (a headlamp, a spot) is lit in the weather's fog only: its cone is a sliver of + // sixteen jittered steps at half size, which the fog's density hides and the clear + // air's haze shows as shimmer and soap. The lamps' halo alone has the ground haze. + let beam_lamp = l.extra.z != 0.0 || l.dir.w > -1.5; + let fog_sigma = enh.fog.x * droplets; + if (beam_lamp && enh.fog.x < 2e-4) { + continue; + } + let s0 = select(sigma0, fog_sigma, beam_lamp); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + // (inside its core a lamp is as bright as at the core's edge) + let hh = max(h, select(core * 0.7, 0.4, l.extra.z != 0.0)); + let w = sqrt(range * range - h * h); + let ta = max(start, t0 - w); + let tb = min(end, t0 + w); + if (tb <= ta) { + continue; + } + var acc = 0.0; + var half = 0.0; + if (l.extra.z != 0.0 || l.dir.w > -1.5) { + // a beam (a headlamp, a spot): lit only where its cone or cut-off lets + // it - a sliver of the angles the lamp is seen under, which the five + // nodes missed. Sixteen even steps over that angle instead (dphi = + // h dt / r^2: the inverse square is in the step). (Sixteen even steps + // along the way put the few next to the lamp, where nearly all of its + // light is, a metre or more apart: the pixels' staggered steps came + // out as a coarse checker in the fog round every headlamp.) + let pa = atan((ta - t0) / hh); + let dphi = (atan((tb - t0) / hh) - pa) / 16.0; + let tile_k = beam_tile(li, l); + for (var q = 0u; q < 16u; q = q + 1u) { + let tq = t0 + hh * tan(pa + (f32(q) + jitter) * dphi); + let to = l.pos.xyz - (c + d * tq); + let ld = to * inverseSqrt(max(dot(to, to), 1e-6)); + var beam = 0.0; + if (l.extra.z != 0.0) { + beam = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0); + } else { + beam = smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } + // (the map is looked at only where the beam shines at all, and only for + // the few lamps that have a tile: no shadows, no tile, no tap) + var reach = 1.0; + if (beam > 0.002 && tile_k < 44u) { + reach = beam_reaches(tile_k, c + d * tq); + } + acc = acc + beam * reach * fog_phase(dot(ld, d)) * dphi; + } + half = 1.0; + } else { + let pa = atan((ta - t0) / hh); + let pb = atan((tb - t0) / hh); + half = 0.5 * (pb - pa); + let mid = 0.5 * (pa + pb); + let tile_p = beam_tile(li, l); + for (var q = 0u; q < 5u; q = q + 1u) { + let phi = mid + half * gx[q]; + let tq = t0 + hh * tan(phi); + let ld = normalize(l.pos.xyz - (c + d * tq)); + var beam = 1.0; + if (l.dir.z < -0.5) { + // (a lamp in a housing: see `lamp_light`) + beam = 0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z); + } + // (a lamp with a shadow map: what stands between it and the air + // keeps its light out of that air, as the headlamps' beams) + var reach = 1.0; + if (beam > 0.002 && tile_p < 44u) { + reach = beam_reaches(tile_p, c + d * tq); + } + acc = acc + gw[q] * beam * reach * fog_phase(-sin(phi)); + } + } + // a lamp's irradiance is core^2 / r^2 of its colour's (a headlamp's 1 / r^2) + let strength = select(core * core, 1.0, l.extra.z != 0.0); + let xc = c + d * tc; + let sigma = s0 * exp(-enh.fog.y * max(xc.z - enh.fog.z, 0.0)); + let dl = distance(xc, l.pos.xyz); + let atten = exp(-layer_depth(s0, enh.fog.y, c.z - enh.fog.z, xc.z - enh.fog.z, tc - start) - sigma * dl); + sum = sum + l.color.rgb * (l.color.w * strength * acc * half / hh * sigma * atten); + } + } + t = t_out; + if (tx < ty) { + tx = tx + inv_x; + ix = ix + sx; + } else { + ty = ty + inv_y; + iy = iy + sy; + } + } + return sum * enh.lights.y; +} + +// Enhanced: the light a raindrop or a snowflake sends towards the eye - what it scatters of +// the sky's light, the sun's and the lamps' round it, the drop's strongly forward (a +// streak flashes against a lamp seen through the rain, and is next to invisible in the +// dark between the lamps), the flake's nearly every way. (Drawn at the display's level +// whatever the light, the flakes of a snowfall at night shone white in the dark, far from +// any lamp.) +fn precip_light(x: vec3, to_eye: vec3, snow: bool) -> vec3 { + // the sky's and the ground's light round it, and the sun's on a small sphere + var e = enh.fog_color.rgb * (PI / 0.9) + enh.sun.rgb * 0.25; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell > 0.0 && side > 0u) { + let f = (x.xy - camera.light_grid.xy) / cell; + let gx = i32(floor(f.x)); + let gy = i32(floor(f.y)); + if (gx >= 0 && gy >= 0 && gx < i32(side) && gy < i32(side)) { + let base = (u32(gy) * side + u32(gx)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let dl = l.pos.xyz - x; + let dist2 = dot(dl, dl); + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let ld = dl * inverseSqrt(max(dist2, 1e-6)); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var k = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + if (l.extra.z != 0.0) { + k = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + k = k * smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } else if (l.dir.z < -0.5) { + k = k * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + // (the scattering towards the eye relative to an even one: a drop's light + // goes on forwards, a flake's every way. The angle is the one between the + // light's way from the lamp, -ld, and on to the eye: taken against -to_eye + // it put the forward peak behind the drop, and the drops in a bus's own + // beams, seen from behind the lamps, shone a hundred times too bright as + // white streaks down the road ahead) + let c = dot(-ld, to_eye); + let lobe = select(fog_phase(c), 0.7 * hg_phase(c, 0.3) + 0.3 / (4.0 * PI), snow) * 4.0 * PI; + e = e + l.color.rgb * l.color.w * enh.lights.y * k * lobe; + } + } + } + return e / PI; +} + diff --git a/crates/mx/tests/openomsi/ssao.wgsl b/crates/mx/tests/openomsi/ssao.wgsl new file mode 100644 index 0000000..8d97f43 --- /dev/null +++ b/crates/mx/tests/openomsi/ssao.wgsl @@ -0,0 +1,312 @@ +// Screen-space ambient occlusion from the single-sampled depth prepass, and a blur. +struct SsaoParams { + inv_proj: mat4x4, + // x radius (m), y strength, z width, w height + params: vec4, + // xy: the projection's off-centre shift (m20, m21), zero for a symmetric frustum + shift: vec4, + // x the wide occlusion's reach (m), y its strength (0 = off), z the bounced light's + // gain (0 = off), w the largest radiance a bounce is taken from (1 = 10 000 cd/m²) + wide: vec4, + // from a view-space point to the last frame's clip space, and in x whether that + // frame's picture (`t_hist`) can be read at all (not after a cut) + reproj: mat4x4, + history: vec4, +}; +@group(0) @binding(0) var p: SsaoParams; +@group(0) @binding(1) var t_depth: texture_depth_2d; +// The last frame's picture at this size, as absolute radiance (1 = 10 000 cd/m²): what the +// surfaces round a point send to it (post.wgsl `fs_history`). Read where the surface was +// then (`reproj`), and only where the last frame's depth (the blurred AO's g, still in +// `t_ao` when this pass runs) agrees: a surface that was hidden then has no picture to read. +@group(0) @binding(3) var t_hist: texture_2d; + +struct VsOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +}; + +@vertex +fn vs_main(@builtin(vertex_index) i: u32) -> VsOut { + // one triangle over the whole screen + let x = f32(i32(i & 1u) * 4 - 1); + let y = f32(i32(i >> 1u) * 4 - 1); + var out: VsOut; + out.clip = vec4(x, y, 0.0, 1.0); + out.uv = vec2((x + 1.0) * 0.5, (1.0 - y) * 0.5); + return out; +} + +// view-space position of a pixel (reversed Z: the depth is 0 at the far plane) +fn view_pos(px: vec2) -> vec3 { + let size = vec2(i32(p.params.z), i32(p.params.w)); + let c = clamp(px, vec2(0), size - vec2(1)); + // the AO runs at half the picture's size; the depth prepass is full size + let d = textureLoad(t_depth, c * 2, 0); + let ndc = vec2((f32(c.x) + 0.5) / p.params.z * 2.0 - 1.0, 1.0 - (f32(c.y) + 0.5) / p.params.w * 2.0); + let h = p.inv_proj * vec4(ndc, d, 1.0); + return h.xyz / h.w; +} + +// view-space depth (negative, metres) of a raw depth value +fn lin(d: f32) -> f32 { + let h = p.inv_proj * vec4(0.0, 0.0, d, 1.0); + return h.z / h.w; +} + +// A 4x4 ordered pattern rather than white noise: every 4x4 block of pixels holds the same +// sixteen sample rotations, so the 6x6 blur that follows averages them out completely. +// White noise per pixel left a grain that stood still on the screen while the world moved +// under it - a faint film of static in front of the eyes. +fn hash(v: vec2) -> f32 { + let p = vec2(i32(v.x) & 3, i32(v.y) & 3); + let bayer = array(0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0); + return (bayer[p.y * 4 + p.x] + 0.5) / 16.0; +} + +// The bounced light (irradiance, rgb) in two channels of the AO texture's four: its +// luminance as it is, and the colour's red and blue relative to it (0 .. 2, five bits +// each) in one number - the green follows from the luminance. Blurred and read back +// decoded, so the quantisation of one tap is not mixed with another's. +const BOUNCE_RANGE: f32 = 2.0; +fn bounce_pack(e: vec3) -> vec2 { + let y = dot(e, vec3(0.2126, 0.7152, 0.0722)); + if (y < 1e-6) { + return vec2(0.0, 0.0); + } + let u = clamp(e.r / y / BOUNCE_RANGE, 0.0, 1.0); + let v = clamp(e.b / y / BOUNCE_RANGE, 0.0, 1.0); + return vec2(y, round(u * 31.0) * 32.0 + round(v * 31.0)); +} + +fn bounce_unpack(t: vec4) -> vec3 { + let y = t.b; + let iu = floor(t.a / 32.0 + 0.001); + let iv = t.a - iu * 32.0; + let r = iu / 31.0 * BOUNCE_RANGE * y; + let b = iv / 31.0 * BOUNCE_RANGE * y; + let g = max((y - 0.2126 * r - 0.0722 * b) / 0.7152, 0.0); + return vec3(r, g, b); +} + +@fragment +fn fs_ssao(in: VsOut) -> @location(0) vec4 { + let px = vec2(in.clip.xy); + let d0 = textureLoad(t_depth, px * 2, 0); + if (d0 <= 0.0) { + return vec4(1.0, 60000.0, 0.0, 0.0); // sky + } + let pos = view_pos(px); + // the normal from the depth neighbourhood (the smaller step of each pair, so an edge + // between two objects does not bend it) + let dx1 = view_pos(px + vec2(1, 0)) - pos; + let dx2 = pos - view_pos(px - vec2(1, 0)); + let dy1 = view_pos(px + vec2(0, 1)) - pos; + let dy2 = pos - view_pos(px - vec2(0, 1)); + let dx = select(dx2, dx1, length(dx1) < length(dx2)); + let dy = select(dy2, dy1, length(dy1) < length(dy2)); + var n = normalize(cross(dx, dy)); + if (dot(n, -pos) < 0.0) { + n = -n; + } + // a hemisphere of samples around the normal, turned by a per-pixel angle + let a = hash(in.clip.xy) * 6.2831853; + let rnd = vec3(cos(a), sin(a), 0.0); + let t = normalize(rnd - n * dot(rnd, n)); + let b = cross(n, t); + // A metre and a half of radius is right for a house corner across the street, but in + // a bus the hand straps darkened the ceiling a metre away from them, in blotches that + // moved as the head turned: close to the camera the radius shrinks with the distance. + let radius = min(p.params.x, 0.3 + 0.1 * -pos.z); + var occ = 0.0; + let count = 12; + for (var i = 0; i < count; i = i + 1) { + let fi = f32(i); + // a spiral over the hemisphere, denser near the middle + let ang = fi * 2.399963 + a; + let r = (fi + 0.5) / f32(count); + let scale = mix(0.15, 1.0, r * r); + let s = vec3(cos(ang) * r, sin(ang) * r, sqrt(max(0.0, 1.0 - r * r))); + let sp = pos + (t * s.x + b * s.y + n * s.z) * radius * scale; + // back to the screen + // project: we only have inv_proj, so search the depth at the sample's screen position + // using the perspective relation x_ndc = x / (-z * tan) - reconstruct from two points + let q = project(sp); + if (q.x < 0.0 || q.y < 0.0 || q.x >= p.params.z || q.y >= p.params.w) { + continue; + } + let qz = lin(textureLoad(t_depth, vec2(q) * 2, 0)); + // occluded when the scene surface is in front of the sample, within range + let dz = qz - sp.z; + let range = smoothstep(0.0, 1.0, radius / max(abs(pos.z - qz), 0.0001)); + if (dz > 0.03) { + occ = occ + range; + } + } + var ao = 1.0 - p.params.y * occ / f32(count); + // --- the street's scale: how much of the sky a point sees past the houses, trees and + // hills round it (a hemisphere reaching `wide.x` metres, cosine-weighted), and the + // light the surfaces that block it send back (their picture of the last frame) + var wide = 1.0; + var bounce = vec3(0.0); + if (p.wide.y > 0.0) { + let wr = p.wide.x; + let wcount = 8; + var wocc = 0.0; + var gi = vec3(0.0); + let a2 = a + 1.7; + for (var i = 0; i < wcount; i = i + 1) { + let fi = f32(i); + let ang = fi * 2.399963 + a2; + let r = (fi + 0.5) / f32(wcount); + let scale = mix(0.2, 1.0, fract(fi * 0.618034 + a * 0.159155)); + let s = vec3(cos(ang) * r, sin(ang) * r, sqrt(max(0.0, 1.0 - r * r))); + let sp = pos + (t * s.x + b * s.y + n * s.z) * wr * scale; + let q = project(sp); + if (q.x < 0.0 || q.y < 0.0 || q.x >= p.params.z || q.y >= p.params.w) { + continue; + } + let qc = vec2(q); + let qz = lin(textureLoad(t_depth, qc * 2, 0)); + let dz = qz - sp.z; + // a surface counts for what it takes of the hemisphere: not further in front of + // the sample than the sample is from the point (a wall over the point, not + // another object's edge), and never the cab round the camera: a dashboard and its + // pillars are not the street's houses + let reach = max(wr * scale, 1.0); + let range = (1.0 - smoothstep(0.25 * reach, 0.6 * reach, dz)) * smoothstep(2.0, 6.0, -qz); + if (dz > 0.25 && range > 0.0) { + wocc = wocc + range; + if (p.wide.z > 0.0 && p.history.x > 0.5) { + // (a lamp or a lit sign among the hits would be one sample of eight worth + // a hundred of its neighbours' and stand in the picture as a pattern of + // spots: what is brighter than a sunlit white wall is compressed) + let lc = history_light(qc, qz); + gi = gi + lc / (vec3(1.0) + lc * 0.35) * range; + } + } + } + wide = 1.0 - p.wide.y * wocc / f32(wcount); + bounce = gi * (3.14159265 / f32(wcount)) * p.wide.z; + } + ao = ao * wide; + // far away a screen-space radius covers whole buildings: fade the effect out with + // distance, where it only added shimmer + let dist = -pos.z; + ao = mix(ao, wide, clamp((dist - 60.0) / 140.0, 0.0, 1.0)); + // (the wide occlusion reaches farther: it fades over the next two hundred metres) + ao = mix(ao, 1.0, clamp((dist - 200.0) / 250.0, 0.0, 1.0)); + bounce = bounce * (1.0 - clamp((dist - 200.0) / 250.0, 0.0, 1.0)); + // (clamp of a NaN is not safe on every GPU: a black blotch of shade on Windows) + let ao_ok = select(1.0, clamp(ao, 0.0, 1.0), (bitcast(ao) & 0x7f800000u) != 0x7f800000u); + let bounce_ok = select(vec3(0.0), bounce, all((bitcast>(bounce) & vec3(0x7f800000u)) != vec3(0x7f800000u))); + let pk = bounce_pack(bounce_ok); + return vec4(ao_ok, dist, pk.x, pk.y); +} + +// What the surface seen at pixel `qc` (view depth `qz`) sent to the last frame's picture: +// where it was in that frame, if it was seen there. +fn history_light(qc: vec2, qz: f32) -> vec3 { + // (the surface's view position from its pixel and depth: no second depth load) + let ndc0 = vec2((f32(qc.x) + 0.5) / p.params.z * 2.0 - 1.0, 1.0 - (f32(qc.y) + 0.5) / p.params.w * 2.0); + let sp = vec3((ndc0.x + p.shift.x) * -qz * p.inv_proj[0][0], (ndc0.y + p.shift.y) * -qz * p.inv_proj[1][1], qz); + let pc = p.reproj * vec4(sp, 1.0); + if (pc.w <= 0.01) { + return vec3(0.0); + } + let ndc = pc.xy / pc.w; + let q = vec2((ndc.x + 1.0) * 0.5 * p.params.z, (1.0 - ndc.y) * 0.5 * p.params.w); + if (q.x < 0.0 || q.y < 0.0 || q.x >= p.params.z || q.y >= p.params.w) { + return vec3(0.0); + } + let pq = vec2(q); + // (disoccluded: the surface's depth then, from the last frame's own AO, is not where + // it should be) + let was = textureLoad(t_ao, pq, 0).g; + if (abs(was - pc.w) > 0.2 + 0.04 * pc.w) { + return vec3(0.0); + } + // (the picture's outliers are cut where it is made: post.wgsl `fs_history`) + let l = max(textureLoad(t_hist, pq, 0).rgb, vec3(0.0)); + return min(l, vec3(p.wide.w)); +} + +// pixel position of a view-space point, through the same projection the depth was made with +fn project(v: vec3) -> vec2 { + // inv_proj is the inverse of a perspective matrix: recover the projection's scale terms + // from it (m00 = 1/(f/aspect), m11 = 1/f); an off-centre frustum (a headset eye, a + // triple screen's side panel) adds its shift: x_ndc = (sx x + m20 z) / -z + let sx = 1.0 / p.inv_proj[0][0]; + let sy = 1.0 / p.inv_proj[1][1]; + let ndc = vec2(v.x * sx, v.y * sy) / (-v.z) - p.shift.xy; + return vec2((ndc.x + 1.0) * 0.5 * p.params.z, (1.0 - ndc.y) * 0.5 * p.params.w); +} + +// --- blur: 6x6 window over the raw AO, keeps edges by depth +@group(0) @binding(2) var t_ao: texture_2d; + +const TENT = array( + 0.09901, 0.18498, 0.26915, 0.30498, 0.26915, 0.18498, + 0.18498, 0.34559, 0.50283, 0.56978, 0.50283, 0.34559, + 0.26915, 0.50283, 0.73162, 0.82903, 0.73162, 0.50283, + 0.30498, 0.56978, 0.82903, 0.93941, 0.82903, 0.56978, + 0.26915, 0.50283, 0.73162, 0.82903, 0.73162, 0.50283, + 0.18498, 0.34559, 0.50283, 0.56978, 0.50283, 0.34559, +); + +@fragment +fn fs_blur(in: VsOut) -> @location(0) vec4 { + let px = vec2(in.clip.xy); + let size = vec2(i32(p.params.z), i32(p.params.w)); + let z0 = lin(textureLoad(t_depth, px * 2, 0)); + // Without bounced light (every pipeline but the Enhanced one, and the Enhanced with the + // bounce off) the blur is the plain 6x6 one: as cheap and as it always was. + if (p.wide.z <= 0.0) { + var sum0 = 0.0; + var wsum0 = 0.0; + // 6x6 window: covers every rotation of the 4x4 pattern at least once in each row and + // column, and the depth weight keeps the occlusion from bleeding across an edge (a + // relative tolerance: far surfaces are allowed a larger step) + for (var y = -3; y <= 2; y = y + 1) { + for (var x = -3; x <= 2; x = x + 1) { + let c = clamp(px + vec2(x, y), vec2(0), size - vec2(1)); + let z = lin(textureLoad(t_depth, c * 2, 0)); + let tol0 = 0.3 + 0.02 * abs(z0); + let w = select(0.0, 1.0, abs(z - z0) < tol0); + sum0 = sum0 + textureLoad(t_ao, c, 0).r * w; + wsum0 = wsum0 + w; + } + } + let blurred0 = select(1.0, sum0 / wsum0, wsum0 > 0.0); + return vec4(select(1.0, blurred0, (bitcast(blurred0) & 0x7f800000u) != 0x7f800000u), select(-z0, 60000.0, textureLoad(t_depth, px * 2, 0) <= 0.0), 0.0, 0.0); + } + var sum = 0.0; + var gi_sum = vec3(0.0); + var wsum = 0.0; + var gsum = 0.0; + // With the bounce the same 6x6 window for both: the occlusion's weight falls off + // smoothly (a hard cut left the pattern standing wherever a slanting ground's steps from + // pixel to pixel came near it); the bounced light, smooth by nature and noisier by its + // few hits, takes a looser depth tolerance and a tent over the window, so one hit + // leaves a soft spot, not a square. + let tol = 0.3 + 0.04 * abs(z0); + let gtol = 0.5 + 0.1 * abs(z0); + for (var y = -3; y <= 2; y = y + 1) { + for (var x = -3; x <= 2; x = x + 1) { + let c = clamp(px + vec2(x, y), vec2(0), size - vec2(1)); + let z = lin(textureLoad(t_depth, c * 2, 0)); + let dz = abs(z - z0); + let tap = textureLoad(t_ao, c, 0); + let w = 1.0 - smoothstep(0.5 * tol, tol, dz); + sum = sum + tap.r * w; + wsum = wsum + w; + let gw = (1.0 - smoothstep(0.5 * gtol, gtol, dz)) * TENT[(y + 3) * 6 + x + 3]; + gi_sum = gi_sum + bounce_unpack(tap) * gw; + gsum = gsum + gw; + } + } + let blurred = select(1.0, sum / wsum, wsum > 0.0); + let gi = select(vec3(0.0), gi_sum / gsum, gsum > 0.0); + let pk = bounce_pack(gi); + return vec4(select(1.0, blurred, (bitcast(blurred) & 0x7f800000u) != 0x7f800000u), select(-z0, 60000.0, textureLoad(t_depth, px * 2, 0) <= 0.0), pk.x, pk.y); +} diff --git a/crates/mx/tests/openomsi/temporal_motion.wgsl b/crates/mx/tests/openomsi/temporal_motion.wgsl new file mode 100644 index 0000000..5535a4b --- /dev/null +++ b/crates/mx/tests/openomsi/temporal_motion.wgsl @@ -0,0 +1,5968 @@ +fn srgb_encode(c: vec3) -> vec3 { + let x = max(c, vec3(0.0)); + return select(1.055 * pow(x, vec3(1.0 / 2.4)) - 0.055, x * 12.92, x <= vec3(0.0031308)); +} +fn srgb_decode(c: vec3) -> vec3 { + let x = max(c, vec3(0.0)); + return select(pow((x + 0.055) / 1.055, vec3(2.4)), x / 12.92, x <= vec3(0.04045)); +} + +struct Camera { + view_proj: mat4x4, + cam_pos: vec4, + world_origin: vec4, // world-space origin removed from render coordinates + sun_dir: vec4, // xyz direction to the sun, w intensity + ambient: vec4, // rgb ambient (envir light C) + fog: vec4, // rgb, density + sun_color: vec4, // rgb (envir light A), w night factor 0..1 (nightmap strength) + sky_color: vec4, // rgb secondary light from above (envir light B), w 1 = vanilla (as OMSI 2), 0 = Vanilla+ + light_grid: vec4, // x,y grid origin (render-origin relative), z cell size, w cells per side + sky: vec4, + cam_right: vec4, + cam_up: vec4, + clouds: vec4, + light_view_proj: mat4x4, + light_view_proj_far: mat4x4, + shadow: vec4, // x enabled, y texel size, z near cascade half range + post: vec4, // x enhanced, y time, zw sun ndc + inside_a: vec4, // player vehicle box: origin xyz, sin(heading) + inside_b: vec4, // cos(heading), half extents xyz + inside_c: vec4, // box centre offset xyz, w = 1 when there is a box, 2 with the eye in it + flags: vec4, // x detail texturing, y enhanced graphics, z never set (see fs_main's end), w close cascade half range + light_view_proj_close: mat4x4, + wind: vec4, // the player's vehicle's velocity (m/s, world): the airstream on its glass + // Enhanced: the lamps' shadow maps (the tiles under the far map; zero where nothing is + // drawn) and where the tiles lie: x a tile's side, y tiles to a row, z the far map's + // texture height, w the number of tiles (`LampAtlas::uniform`) + lamp_view_proj: array, 56>, + lamp_atlas: vec4, + // Windy trees: xy the weather's wind (m/s, world; 0 with the setting off), zw how far + // the air has carried the gusts since the start (m, modulo PATTERN_PERIOD) + tree_wind: vec4, + // an articulated bus's rear section (as inside_*): read by the snowfall only - a test of + // it here, inlined into every use of inside_vehicle, brought Apple's M4 shader compiler + // down (see 0.2.21's Metal note) + inside2_a: vec4, + inside2_b: vec4, + inside2_c: vec4, + // Enhanced: the field each light cookie layer covers (xy: the tangents of its half + // angles across and up; z: its first record in the light buffer), see enhanced.wgsl + // `cookie_light` + cookies: array, 8>, + // Enhanced: the lights of the player's saloon that have a shadow map (their places in the + // light buffer, 4 a vector, -1 for none): see `cabin_visibility` + cabin_lamps: array, 4>, + // x: the textures' mip bias (FSR 1: negative, see `CameraUniform::lod`) + lod: vec4, // x mip bias, y ground-prepass flag, z road sunlight glare, w air temperature (degC) + // the classic picture's headlight (`CameraUniform::spot`, see `classic_spot`) + spot: array, 4>, +}; + +// 1 when the point lies inside the player's vehicle (its [boundingbox], shrunk a little so +// that the outer skin, the glass and the roof stay outside): weather stays out of the cab. +// The side/front/back shrink was a bare 0.12 m, which left an interior fixture close to the +// wall (a window sill, the handbrake by the windscreen) just outside the box, wearing the +// up-facing wet/snow coat meant for the body panel beside it (see the `outside` weight +// below). A previous fix WIDENED this margin to 0.6 m, reasoning by analogy with the falling- +// particle exclusion box in `rain.rs` - but that box works the other way round (its margin +// is added, growing the excluded region outward, away from the body) from this one (whose +// margin is subtracted, shrinking the "inside" region inward, toward the body): widening it +// here shrank the cabin's own "inside" zone and threw the *whole* cabin outside it, coating +// the entire interior in snow instead of just the ledge. Narrowed to 0.03 m instead - just +// enough that the true outer skin and glass stay outside, without giving up real interior +// floor space near the wall. +// A normal of no length (a mesh saved with zero normals) is upright instead of NaN: +// normalize(0) is NaN on Vulkan and Metal and the pixel went black. +fn safe_normal(v: vec3) -> vec3 { + let d = dot(v, v); + if (d > 1e-20) { + return v * inverseSqrt(d); + } + return vec3(0.0, 0.0, 1.0); +} + +fn inside_vehicle(world: vec3) -> f32 { + if (camera.inside_c.w < 0.5) { + return 0.0; + } + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let x = d.x * ch - d.y * sh - camera.inside_c.x; + let y = d.x * sh + d.y * ch - camera.inside_c.y; + let z = d.z - camera.inside_c.z; + let h = camera.inside_b.yzw; + let in_x = abs(x) < h.x - 0.03; + let in_y = abs(y) < h.y - 0.03; + let in_z = z > -h.z - 0.6 && z < h.z - 0.03; + return select(0.0, 1.0, in_x && in_y && in_z); +} + +// 1 when the point belongs to the player's vehicle: its `[boundingbox]` grown a little, +// so that the skin and the glass the cab test (`inside_vehicle`) leaves out are in. +fn near_player_vehicle(world: vec3) -> f32 { + if (camera.inside_c.w < 0.5) { + return 0.0; + } + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let x = d.x * ch - d.y * sh - camera.inside_c.x; + let y = d.x * sh + d.y * ch - camera.inside_c.y; + let z = d.z - camera.inside_c.z; + let h = camera.inside_b.yzw + vec3(0.25); + return select(0.0, 1.0, abs(x) < h.x && abs(y) < h.y && abs(z) < h.z); +} + +// How much of the way from the camera to `world` lies outside the player's vehicle: there is +// no fog in the cab. From the driver's seat the whole saloon (seats 2 m away, the doors 5 m +// away) took the fog of that distance and in thick ground fog the interior went milky, the +// door panes nearly opaque - outside the bus there was nothing of the kind. The box is the +// one `inside_vehicle` uses; the part of the ray inside it is taken off the fogged distance. +fn fog_distance(world: vec3) -> f32 { + let full = distance(world, camera.cam_pos.xyz); + if (camera.inside_c.w < 0.5) { + return full; + } + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let to_local = fn_box_local(camera.cam_pos.xyz); + let p1 = fn_box_local(world); + let d = p1 - to_local; + let h = camera.inside_b.yzw; + // slab test of the segment against the box (x, y the plan, z height) + var t0 = 0.0; + var t1 = 1.0; + for (var k = 0; k < 3; k = k + 1) { + let o = to_local[k]; + let dk = d[k]; + let hk = h[k]; + if (abs(dk) < 1e-6) { + if (abs(o) > hk) { + return full; + } + } else { + let a = (-hk - o) / dk; + let b = (hk - o) / dk; + t0 = max(t0, min(a, b)); + t1 = min(t1, max(a, b)); + } + } + if (t1 <= t0) { + return full; + } + return max(full * (1.0 - (t1 - t0)), 0.0); +} + +// A point in the player's vehicle box frame (centred, x across, y along, z up). +fn fn_box_local(world: vec3) -> vec3 { + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + return vec3(d.x * ch - d.y * sh - camera.inside_c.x, d.x * sh + d.y * ch - camera.inside_c.y, d.z - camera.inside_c.z); +} + +fn own_vehicle_blocks(p: vec3, l: vec3) -> bool { + if (camera.inside_c.w < 1.5) { + return false; + } + let a = fn_box_local(l); + let d = fn_box_local(p) - a; + let h = camera.inside_b.yzw - vec3(0.15); + if (all(abs(a) < h)) { + return false; + } + var t0 = 0.0; + var t1 = 1.0; + for (var k = 0; k < 3; k = k + 1) { + let o = a[k]; + let dk = d[k]; + let hk = h[k]; + if (abs(dk) < 1e-6) { + if (abs(o) >= hk) { + return false; + } + } else { + let lo = (-hk - o) / dk; + let hi = (hk - o) / dk; + t0 = max(t0, min(lo, hi)); + t1 = min(t1, max(lo, hi)); + } + } + return t1 > t0; +} + +// 1 where the weather reaches the point. The cab test above reaches 0.6 m below the +// vehicle's box so that the floor stays dry, and that takes in the road under the bus as +// well: the snow on it vanished in a bus-shaped patch of bare asphalt (which read as the +// bus's shadow wiping the snow off). The ground - terrain, roads, painted ground, flagged +// by `terrain` or the instance's surface flag - is never inside a vehicle. +fn weather_outside(world: vec3, terrain: bool, surface: f32) -> f32 { + if (terrain || surface > 0.5) { + return 1.0; + } + return 1.0 - inside_vehicle(world); +} + +// As `weather_outside`, knowing the surface's normal: the bus's own outer skin is outside +// even where it lies inside the box. A side wall leans in towards the roof (and bulges over +// the wheel arches), so the box's side plane cuts through the panel: above the cut the paint +// took the cab's light and stayed dry, below it the sky's - the wall looked half glossy, +// half matt, along a sharp line. A face within 0.35 m of a side, the front, the back or the +// roof of the box and turned out through it is skin, not cabin. +fn weather_outside_n(world: vec3, n: vec3, terrain: bool, surface: f32) -> f32 { + if (terrain || surface > 0.5) { + return 1.0; + } + // a vehicle's part (lib.rs `Instance::roof`): under its roof it is dry, whichever + // vehicle it is - the one the camera is in, another player's, a timetable bus + // (what faces up only: taken for every face below the roof, the whole outer skin of + // every car and bus below the roof's edge was cab - lit by the dim cab light in the + // enhanced picture, dry in the rain - with a hard seam round the body 0.3 m under the + // roof where the sky's light began, #805) + if (surface < -500.0) { + // (the code carries the roof's snow in its ten thousands, see scene/upload.rs) + let code = -surface; + let roof = code - 10000.0 * floor(code / 10000.0) - 5000.0; + if (world.z < roof - 0.3 && n.z > 0.5) { + return 0.0; + } + } + if (inside_vehicle(world) < 0.5) { + return 1.0; + } + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let x = d.x * ch - d.y * sh - camera.inside_c.x; + let y = d.x * sh + d.y * ch - camera.inside_c.y; + let z = d.z - camera.inside_c.z; + let nx = n.x * ch - n.y * sh; + let ny = n.x * sh + n.y * ch; + let h = camera.inside_b.yzw; + let skin_x = h.x - abs(x) < 0.35 && nx * sign(x) > 0.5; + let skin_y = h.y - abs(y) < 0.35 && ny * sign(y) > 0.5; + let skin_z = h.z - z < 0.35 && n.z > 0.5; + return select(0.0, 1.0, skin_x || skin_y || skin_z); +} +@group(0) @binding(0) var camera: Camera; +// Whether this pipeline draws alpha-tested materials. +// Opaque pipelines set the discard overrides false: a fragment +// function that can discard turns the GPU's early depth test off - on Apple's GPUs the +// hidden surface removal as well - for everything it draws, and the heavy shading then +// ran for every covered layer of the city, not once per pixel. +override ALPHA_TEST: bool = true; +// Multisampled cutout pipelines can turn filtered alpha directly into sample coverage. +override ALPHA_TO_COVERAGE: bool = false; +override DETAILED_TREES: bool = false; +@group(0) @binding(5) var t_shadow: texture_depth_2d; +@group(0) @binding(6) var s_shadow: sampler_comparison; +@group(0) @binding(7) var t_shadow_far: texture_depth_2d; +@group(0) @binding(8) var t_ao: texture_2d; +@group(0) @binding(9) var s_ao: sampler; + +// Enhanced+: the traced lighting at a pixel (rt.wgsl, full size; camera.clouds.w 2): x the +// ambient occlusion, z the sun's visibility (< 0 where it was not traced), w 1 where the +// texel lies at this surface's depth (the pixel's own or a neighbour's; 0: the surface is +// not in the depth prepass - a pane, a blended layer - and the shadow map stands in). +fn rt_at(frag: vec2, world: vec3) -> vec4 { + if (camera.clouds.w < 1.5) { + return vec4(1.0, 0.0, -1.0, 0.0); + } + let size = vec2(textureDimensions(t_ao)); + let z = (camera.view_proj * vec4(world, 1.0)).w; + let tol = 0.03 + 0.01 * z; + let px = vec2(frag); + var best = vec4(1.0, 0.0, -1.0, 0.0); + var best_d = tol; + for (var k = 0; k < 5; k = k + 1) { + var o = vec2(0, 0); + switch k { + case 1: { o = vec2(1, 0); } + case 2: { o = vec2(-1, 0); } + case 3: { o = vec2(0, 1); } + case 4: { o = vec2(0, -1); } + default: {} + } + let s = textureLoad(t_ao, clamp(px + o, vec2(0), size - vec2(1)), 0); + let d = abs(s.g - z); + if (s.g > 0.0 && d < best_d) { + best_d = d; + best = vec4(s.r, s.g, s.b, 1.0); + } + if (k == 0 && d < tol * 0.3) { + break; + } + } + return best; +} + +// The ambient occlusion at a pixel of the full picture. It is worked out at half size, and +// a plain bilinear lookup blended the occlusion of the ground behind an edge with that of +// the object in front: every wheel, pole and kerb stood in a pale outline on the shaded +// ground under the bus. Of the four half-size texels around the pixel only those at the +// pixel's own depth count (a depth-aware upsample); none of them: the closest in depth. +// The light the surfaces round a point send back to it (irradiance, rgb), packed by +// ssao.wgsl `bounce_pack` in the AO texture's b and a. +fn bounce_unpack(t: vec4) -> vec3 { + let y = t.b; + let iu = floor(t.a / 32.0 + 0.001); + let iv = t.a - iu * 32.0; + let r = iu / 31.0 * 2.0 * y; + let b = iv / 31.0 * 2.0 * y; + let g = max((y - 0.2126 * r - 0.0722 * b) / 0.7152, 0.0); + return vec3(r, g, b); +} + +// The occlusion (x) and the bounced light (yzw) at a pixel, upsampled by depth as `ao_at`. +fn ao_gi_at(frag: vec2, world: vec3, traced: vec4) -> vec4 { + if (camera.clouds.w > 1.5) { + return vec4(select(traced.x, 1.0, traced.w < 0.5), 0.0, 0.0, 0.0); + } + let size = vec2(textureDimensions(t_ao)); + let z = (camera.view_proj * vec4(world, 1.0)).w; + let f = frag * 0.5 - vec2(0.5); + let base = vec2(floor(f)); + let fr = f - floor(f); + let tol = 0.04 + 0.015 * z; + var sum = 0.0; + var wsum = 0.0; + var best = vec4(1.0, 0.0, 0.0, 0.0); + var best_d = 1e9; + for (var j = 0; j < 2; j = j + 1) { + for (var i = 0; i < 2; i = i + 1) { + let c = clamp(base + vec2(i, j), vec2(0), size - vec2(1)); + let s = textureLoad(t_ao, c, 0); + let bw = select(1.0 - fr.x, fr.x, i == 1) * select(1.0 - fr.y, fr.y, j == 1); + let dz = abs(s.g - z); + let w = bw * (1.0 - smoothstep(0.0, tol, dz)) + 1e-4 * bw; + sum = sum + s.r * w; + wsum = wsum + w; + if (dz < best_d) { + best_d = dz; + best = s; + } + } + } + // no AO sample at this surface's depth: the surface is not in the depth prepass (a + // door or panel drawn in front of what the AO saw) - the AO behind it must not show + if (best_d > tol * 1.5) { + return vec4(1.0, 0.0, 0.0, 0.0); + } + // (the bounced light is smooth already - the blur pass averaged it - so the tap at this + // surface's depth is enough) + return vec4(select(best.r, sum / wsum, wsum > 0.02), bounce_unpack(best)); +} + +fn ao_traced_at(frag: vec2, world: vec3, traced: vec4) -> f32 { + if (camera.clouds.w > 1.5) { + return select(traced.x, 1.0, traced.w < 0.5); + } + return ao_upsampled(frag, world); +} + +fn bounce_at(frag: vec2, world: vec3) -> vec3 { + if (camera.clouds.w > 1.5) { + return vec3(0.0); + } + let size = vec2(textureDimensions(t_ao)); + let z = (camera.view_proj * vec4(world, 1.0)).w; + let base = vec2(floor(frag * 0.5 - vec2(0.5))); + var best = base; + var best_d = 1e9; + for (var j = 0; j < 2; j = j + 1) { + for (var i = 0; i < 2; i = i + 1) { + let c = clamp(base + vec2(i, j), vec2(0), size - vec2(1)); + let dz = abs(textureLoad(t_ao, c, 0).g - z); + if (dz < best_d) { + best_d = dz; + best = c; + } + } + } + if (best_d > (0.04 + 0.015 * z) * 1.5) { + return vec3(0.0); + } + return bounce_unpack(textureLoad(t_ao, best, 0)); +} + +fn ao_at(frag: vec2, world: vec3) -> f32 { + if (camera.clouds.w > 1.5) { + let t = rt_at(frag, world); + return select(t.x, 1.0, t.w < 0.5); + } + return ao_upsampled(frag, world); +} + +fn ao_upsampled(frag: vec2, world: vec3) -> f32 { + let size = vec2(textureDimensions(t_ao)); + let z = (camera.view_proj * vec4(world, 1.0)).w; + let f = frag * 0.5 - vec2(0.5); + let base = vec2(floor(f)); + let fr = f - floor(f); + let tol = 0.04 + 0.015 * z; + var sum = 0.0; + var wsum = 0.0; + var best = 1.0; + var best_d = 1e9; + for (var j = 0; j < 2; j = j + 1) { + for (var i = 0; i < 2; i = i + 1) { + let c = clamp(base + vec2(i, j), vec2(0), size - vec2(1)); + let s = textureLoad(t_ao, c, 0); + let bw = select(1.0 - fr.x, fr.x, i == 1) * select(1.0 - fr.y, fr.y, j == 1); + let dz = abs(s.g - z); + let w = bw * (1.0 - smoothstep(0.0, tol, dz)) + 1e-4 * bw; + sum = sum + s.r * w; + wsum = wsum + w; + if (dz < best_d) { + best_d = dz; + best = s.r; + } + } + } + // no AO sample at this surface's depth: the surface is not in the depth prepass (a + // door or panel drawn in front of what the AO saw) - the AO behind it must not show + if (best_d > tol * 1.5) { + return 1.0; + } + return select(best, sum / wsum, wsum > 0.02); +} +// the tile light maps (`.map.LM.bmp`) of the 5x5 tiles around the camera, north up, and where +// they lie: x, y the south-west corner (render-origin relative), z the side, w 1 when set +@group(0) @binding(18) var t_lmap: texture_2d; +@group(0) @binding(19) var lmap: vec4; + +// The tile light map's light at a world point (black outside the loaded square). +fn light_map_at(p: vec3) -> vec3 { + if (lmap.w < 0.5) { + return vec3(0.0); + } + let uv = vec2((p.x - lmap.x) / lmap.z, 1.0 - (p.y - lmap.y) / lmap.z); + let c = textureSampleLevel(t_lmap, s_ao, clamp(uv, vec2(0.0), vec2(1.0)), 0.0).rgb; + let inside = uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0; + return select(vec3(0.0), c, inside); +} + +// A material lit at night by the tile light map (`[LightMapMapping]`, the splines): the +// unlit flag carries 0.35. +fn light_map_mapped(m: vec4) -> bool { + return m.y > 0.3 && m.y < 0.45; +} +// (the model matrices as their columns, four vec4 each: some phone GPUs (Mali, Adreno) read an +// array of matrices from a storage buffer wrongly, and every mesh came out flat and far away) +@group(0) @binding(1) var models: array>; +// The affine row carries the draw order level and its octahedral geometric normal. +// Neither belongs to the transform used by shading, shadows or motion vectors. +fn model_matrix(e: u32) -> mat4x4 { + let k = e * 4u; + return mat4x4(vec4(models[k].xyz, 0.0), vec4(models[k + 1u].xyz, 0.0), vec4(models[k + 2u].xyz, 0.0), models[k + 3u]); +} +// x: alpha multiplier, y: visible (0/1), zw: uv offset +@group(0) @binding(2) var inst_params: array>; +// the frame's draw list: the per-draw entry of each drawn instance. Draws of the same mesh +// and material are batched, so the instance index points into this list, not at an entry. +@group(0) @binding(10) var draw_list: array; +struct PointLight { + pos: vec4, // xyz relative to the render origin, w radius (0: an enhanced-only light) + color: vec4, // rgb, w intensity + dir: vec4, // spot direction, w cosine of the outer cone (< -1.5: a point light) + extra: vec4, // enhanced path: cosine of the inner cone, core radius, beam gain, radius +}; +@group(0) @binding(3) var lights: array; +// per cell CELL_CAP light indices, 0xffffffff = empty +@group(0) @binding(4) var grid: array; +const CELL_CAP: u32 = 32u; +// The cutout of `[matl_alpha] 1`: Omsi.exe sets ALPHAREF 0x80 with ALPHAFUNC GREATER, so a +// texel of alpha 128 is thrown away. Painters' window layers (a bus's glass unwrapped on its +// own texture to draw on) mark the clear glass with exactly 128: cut below one half, those +// texels stayed and every window was the layer's black. +const ALPHA_REF: f32 = 128.5 / 255.0; + +struct MaterialParams { + color: vec4, + // x: alpha mode (0 opaque, 1 test, 2 blend), y: unlit flag, z: has transmap, w: transmap uses alpha + params: vec4, + // x: terrain material (uv in tile space), y: detail texture repeats per tile (0 = none), + // z: ground texture repeats per tile, w: has nightmap + extra: vec4, + // x: has lightmap, y: envmap factor, z: moisture, w: has [matl_envmap_mask] + params2: vec4, + // emissive colour (the o3d material's or a [matl_allcolor]'s) + emissive: vec4, + // specular colour and power of the D3D material (power in w; 0 = no highlight) + specular: vec4, + // x: [matl_bumpmap] factor, y: has a bump map, z/w: noZwrite/noZcheck + bump: vec4, + // the PBR set beside the diffuse texture: x normal map, y occlusion, z roughness, + // w metalness (1 = the map has it; see mx_tex2d[mx_mat.pbr_normal] / mx_tex2d[mx_mat.pbr_orm]) + pbr: vec4, + // x: one of the bus's own screens (the enhanced glow and FXAA leave it alone) + flags: vec4, + // rgb: the D3D material's ambient colour, which takes the ambient light (C) + ambient: vec4, + // Windy trees: x 1 for foliage that sways, y the height (mesh units) of its pivot - where + // the crown leaves the trunk, nothing below it moves - z the crown's top, w how much the + // tree gives to the wind (1 a broadleaf, less a conifer) + sway: vec4, + // Window wetness mask in mesh X/Z: origin, inverse size; zero disables it. + wipe_bounds: vec4, + // x: [matl_glow] strength (0 = the keyword is not there; the material is its own light - + // its `mx_tex2d[mx_mat.light]` is a greyscale mask of how much shines where, its colour is its own, see + // the enhanced pass), y an LED panel's share of the `Led glow` ([led_glow_effect], + // 1 without it), z/w free + glow: vec4, +}; +@group(1) @binding(2) var material: MaterialParams; +// (the material's textures and samplers by their places in the heap, see `materials_from_heap`) +struct MxMaterial { row: u32, diffuse: u32, sampler: u32, trans: u32, night: u32, light: u32, env: u32, envmask: u32, bump: u32, pbr_normal: u32, pbr_orm: u32, tile_sampler: u32 }; +var mx_mat: MxMaterial; + +// Paint/cut masks and night light maps cover one tile. Wrapping at its edge blends in +// the opposite edge of the SAME tile, opening grass seams even when adjacent masks +// agree. The diffuse/detail textures still repeat through mx_samplers[mx_mat.sampler]. +fn sample_transmap(uv: vec2) -> vec4 { + return sample_transmap_bias(uv, camera.lod.x); +} + +// (`bias`: FSR 1's mip bias for the picture, `camera.lod`; 0 for the shadow and rain maps, +// drawn at their own size) +fn sample_transmap_bias(uv: vec2, bias: f32) -> vec4 { + if (material.extra.x > 0.5 || material.wipe_bounds.z != 0.0) { + return textureSampleBias(mx_tex2d[mx_mat.trans], mx_samplers[mx_mat.tile_sampler], uv, bias); + } + return textureSampleBias(mx_tex2d[mx_mat.trans], mx_samplers[mx_mat.sampler], uv, bias); +} + +fn sample_nightmap(uv: vec2) -> vec4 { + if (material.extra.x > 0.5) { + return textureSampleBias(mx_tex2d[mx_mat.night], mx_samplers[mx_mat.tile_sampler], uv, camera.lod.x); + } + return textureSampleBias(mx_tex2d[mx_mat.night], mx_samplers[mx_mat.sampler], uv, camera.lod.x); +} + +// Some vehicle lamps use a clear diffuse placeholder and put the entire lit +// picture, including its silhouette, in the switched night texture. A transmap +// still owns coverage when the model explicitly supplies one. +fn night_coverage(alpha: f32, night_alpha: f32) -> f32 { + return select(alpha, night_alpha, + (u32(material.params2.w + 0.5) & 16u) != 0u && material.params.z < 0.5); +} + +// The reflection mask of a [matl_envmap] material: the alpha of its [matl_envmap_mask] +// texture when it has one, else the diffuse texture's alpha - which reads 1 for a texture +// without an alpha channel (a 24-bit bitmap, DXT1, a JPEG), so its factor alone decides. +fn has_env_mask() -> bool { + return (u32(material.params2.w + 0.5) & 1u) != 0u; +} + +// [matl_transmap] was given (its file there or not: see MaterialExtra::transmap_declared) +fn has_transmap_declared() -> bool { + return (u32(material.params2.w + 0.5) & 2u) != 0u; +} + +// [matl_texadress_border]: where the diffuse texture's coordinates leave [0, 1] (a roller +// blind's band scrolled away by [texcoordtransX/Y]) Direct3D reads the border colour, not +// the texture's edge (the sampler only clamps). Its rgb comes packed in flags.z. +fn diffuse_border(tex: vec4, uv: vec2) -> vec4 { + let p = u32(material.flags.z + 0.5); + let border = vec4( + f32((p >> 16u) & 0xffu) / 255.0, + f32((p >> 8u) & 0xffu) / 255.0, + f32(p & 0xffu) / 255.0, + material.flags.w, + ); + let outside = any(uv < vec2(0.0)) || any(uv > vec2(1.0)); + return select(tex, border, material.flags.y > 0.5 && material.flags.y < 1.5 && outside); +} + +// [matl_texadress_mirroronce]: Direct3D mirrors the coordinates once about 0 and clamps +// them beyond; the clamping sampler does the rest. +fn tex_address(uv: vec2) -> vec2 { + return select(uv, abs(uv), material.flags.y > 1.5); +} + +fn reflection_mask(uv: vec2, diffuse_a: f32) -> f32 { + let mask = textureSampleBias(mx_tex2d[mx_mat.envmask], mx_samplers[mx_mat.sampler], uv, camera.lod.x).a; + return select(diffuse_a, mask, has_env_mask()); +} + +// The D3DCOLOR Omsi.exe packs for its environment stage (0x7ff8ed): each channel the +// [matl_envmap] factor x 255 x its light (at most 1), truncated, and OR-ed together shifted +// into place without saturation - a factor over 1 spills into the neighbouring channel +// exactly as there (a factor of 10 at full light reads almost white). +fn omsi_texture_factor(factor: f32, light: vec3) -> vec3 { + let m = min(max(light, vec3(0.0)), vec3(1.0)) * max(factor, 0.0) * 255.0; + let r = u32(m.r); + let g = u32(m.g); + let b = u32(m.b); + let packed = (0xffu << 24u) | (r << 16u) | (g << 8u) | b; + return vec3(f32((packed >> 16u) & 0xffu), f32((packed >> 8u) & 0xffu), f32(packed & 0xffu)) / 255.0; +} + +// [matl_bumpmap]: Direct3D's bump-mapped environment stage moves the sphere-map lookup by +// a du/dv map times the factor. Every bump map in the stock and mod content is a grey +// height map, so the du/dv map has to be its slope; it is taken here as the forward +// differences of the height, a byte of height difference counting as a signed-byte step +// (1/127, hence the 2). The stock bodies' noise (factor 0.05-0.1) makes their reflections a +// little wavy, and the panel lines of the O530 Facelift's map (factor 1) break its +// reflection at every seam. +fn bump_offset(uv: vec2) -> vec2 { + let texel = 1.0 / vec2(textureDimensions(mx_tex2d[mx_mat.bump])); + let h = textureSampleBias(mx_tex2d[mx_mat.bump], mx_samplers[mx_mat.sampler], uv, camera.lod.x).a; + let hx = textureSampleBias(mx_tex2d[mx_mat.bump], mx_samplers[mx_mat.sampler], uv + vec2(texel.x, 0.0), camera.lod.x).a; + let hy = textureSampleBias(mx_tex2d[mx_mat.bump], mx_samplers[mx_mat.sampler], uv + vec2(0.0, texel.y), camera.lod.x).a; + return clamp(vec2(h - hx, h - hy) * 2.0, vec2(-1.0), vec2(1.0)) * material.bump.x; +} + +struct VsIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, + @builtin(instance_index) inst: u32, +}; +struct VsOut { + // invariant: the depth prepass and the main pass must compute the same depth to the + // last bit, the main pass tests against the depth the prepass left + @builtin(position) @invariant clip: vec4, + @location(0) world: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + @location(4) @interpolate(flat) params2: vec4, + // the D3D material's highlight, lit at the vertex as Omsi.exe's fixed function lights + // it: from the sun (light A) and from the light above (light B) + @location(5) spec_sun: vec3, + @location(6) spec_sky: vec3, + // where a [matl_envmap] reads its sphere map, made at the vertex (see `sphere_map_uv`) + @location(7) env_uv: vec2, + @location(8) wipe_uv: vec3, + // The classic headlight is lit at the vertices, as OMSI's fixed function light is. + @location(9) spot_diffuse: vec3, + @location(10) spot_ambient: vec3, + // the vertex as its mesh has it: a vehicle's snow lies on the vehicle, not on the + // world it drives through (road_snow.wgsl `vehicle_snow`) + @location(11) local: vec3, +}; +// What the fragment shaders take: VsOut without the invariant on the position. The +// invariant belongs to the vertex output; on a fragment input naga's GLSL writer turns it +// into `invariant gl_FragCoord`, which desktop GL drivers and GLES reject. +struct FsIn { + @builtin(position) clip: vec4, + @location(0) world: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + @location(4) @interpolate(flat) params2: vec4, + @location(5) spec_sun: vec3, + @location(6) spec_sky: vec3, + @location(7) env_uv: vec2, + @location(8) wipe_uv: vec3, + @location(9) spot_diffuse: vec3, + @location(10) spot_ambient: vec3, + @location(11) local: vec3, +}; + +// Direct3D's D3DTSS_TCI_SPHEREMAP, by which Omsi.exe's environment stage reads the sphere +// map of a [matl_envmap] (0x7ff670): at the vertex, from the reflection R in camera space +// (x right, y up, z ahead), u = Rx/m + 0.5 and v = Ry/m + 0.5 with m = 2|R - (0, 0, 1)| - +// as Windows draws it (wine's d3d9 test_generated_texcoords, measured there). What a pane +// facing the camera mirrors is the map's middle, at half the scale of the u = Rx/2 + 0.5 +// taken before (which showed the whole street of the picture across a bus's flank); the +// map's rim is the reflection running on away from the camera, at a grazing angle, where +// the picture swings round between two vertices - the seam the original shows there. +// `eye` is the camera's position, or its mirror image under the road for the player +// vehicle seen in a puddle; the camera's own axes lay the map out either way. +// (The headset: laid out by the bus's heading, level, not by each eye's view.) +fn sphere_map_uv(world: vec3, n: vec3, eye: vec3) -> vec2 { + let r = reflect(normalize(world - eye), n); + let vr_env = camera.cam_up.w > 0.5; + let right = select(camera.cam_right.xyz, vec3(cos(camera.cam_right.w), -sin(camera.cam_right.w), 0.0), vr_env); + let up = select(camera.cam_up.xyz, vec3(0.0, 0.0, 1.0), vr_env); + let rc = vec3(dot(r, right), dot(r, up), dot(r, cross(up, right))); + let m = 2.0 * length(rc - vec3(0.0, 0.0, 1.0)); + return rc.xy / max(m, 1e-6) + 0.5; +} + +// Direct3D's specular term at a vertex (Omsi.exe switches it on in FormActivate, 0x8254e0): +// Omsi.exe's sun (light 0, 0x7089f0: directional, specular = light A) and the light from +// straight above (light 1: specular = light B), each (N.H)^power with the local viewer's +// half vector, only where the light falls on the face, times the material's specular colour +// and clamped at 1 - then interpolated across the face. Computed per pixel instead, every +// small flat part (a gear selector, a switch, a dashboard screen) caught a sharp spot of the +// sun in its middle that the original, lighting only at the corners, never shows. +fn vertex_specular(wp: vec3, n: vec3) -> array, 2> { + var out = array, 2>(vec3(0.0), vec3(0.0)); + if (material.specular.w <= 0.0 || material.params.y >= 0.5) { + return out; + } + let v = normalize(camera.cam_pos.xyz - wp); + let p = material.specular.w; + let l = camera.sun_dir.xyz; + if (dot(n, l) > 0.0) { + out[0] = camera.sun_color.rgb * camera.sun_dir.w * pow(max(dot(n, normalize(v + l)), 0.0), p); + } + let up = vec3(0.0, 0.0, 1.0); + if (n.z > 0.0) { + out[1] = camera.sky_color.rgb * pow(max(dot(n, normalize(v + up)), 0.0), p); + } + let total = out[0] + out[1]; + let k = min(vec3(1.0), total) / max(total, vec3(1e-6)); + out[0] = min(vec3(1.0), out[0] * k * material.specular.rgb); + out[1] = min(vec3(1.0), out[1] * k * material.specular.rgb); + return out; +} + +// Windy trees: how far the wind moves a vertex of a tree's foliage (world, m). `local` is +// the vertex in the mesh, `m` its model matrix, whose origin is the tree's foot. +// +// The tree is bent, not shifted: nothing under its pivot (`material.sway.y`, where the crown +// leaves the trunk) moves, and above it the crown bends over as a cantilever does, by the +// square of the height above the pivot, sinking a little so that its branches keep their +// length. The crown moves as one heavy body - a tree is a lightly damped oscillator, and +// what it does is smooth: no part of the picture moves on its own (each corner of a card +// wobbling in its own phase made the crown jelly). +// +// What bends it is the drag of the air: it grows with the wind speed to the power 1.5 rather +// than 2, as a crown streamlines itself (Vogel's reconfiguration exponent), from a few +// millimetres at 1 m/s to some 3.5 % of the tree's height at 20 m/s, a storm. The gusts are +// a frozen pattern of faster and slower air carried along at the mean wind (Taylor): three +// smooth waves 54 .. 149 m long, a turbulence intensity of 0.3 as over a town, so that +// neighbouring trees bow together as a gust passes and the ones further on follow - and, +// being smooth, the gusts never stop the tree dead as the corners of a value noise did. +// Around that lean the tree swings at its own natural frequency (0.2 .. 1 Hz, lower the +// taller it is), its amplitude and phase wandering slowly as a resonance driven by +// turbulence does, and a little across the wind; the crown's top lags its middle a little. +// With no wind nothing moves. +fn tree_sway(local: vec3, m: mat4x4) -> vec3 { + let sw = material.sway; + let wind = camera.tree_wind.xy; + let speed = length(wind); + if (sw.x < 0.5 || speed < 0.05) { + return vec3(0.0); + } + let h = clamp((local.z - sw.y) / max(sw.z - sw.y, 1e-4), 0.0, 1.0); + if (h <= 0.0) { + return vec3(0.0); + } + let scale = length(m[2].xyz); + let crown = max((sw.z - sw.y) * scale, 0.1); + let height = max(sw.z * scale, crown); + let foot = (m * vec4(0.0, 0.0, 0.0, 1.0)).xyz; + let foot_map = world_pattern_xy(foot); + let t = camera.post.y; + // each tree its own phase + let seed = hash_cell(floor(foot_map * 2.0), 2000.0); + let phase = seed * 6.2831853; + // the gusts at the tree: whole waves per PATTERN_PERIOD (the map position and the + // drift arrive modulo it), 149, 93 and 54 m long - a gust lasts some seconds; their sum has a standard deviation of + // 0.51 (0.6, 0.35, 0.2 over sqrt 2), scaled to the turbulence intensity 0.3 + let gp = (foot_map - camera.tree_wind.zw) * (6.2831853 / PATTERN_PERIOD); + let waves = 0.6 * sin(dot(gp, vec2(6.0, 3.0)) + 1.3) + + 0.35 * sin(dot(gp, vec2(-4.0, 10.0)) + 4.1) + + 0.2 * sin(dot(gp, vec2(17.0, -7.0)) + 2.2); + let gust = max(1.0 + 0.59 * waves, 0.0); + let along = wind / speed; + let across = vec2(-along.y, along.x); + // the lean under the gusting wind, and the tree's swing about it + let give = 0.035 * height * sw.w; + let lean = give * pow(speed * gust / 20.0, 1.5); + // (in strong wind the swing is of the order of the mean lean itself) + let swing_size = 0.7 * give * pow(speed / 20.0, 1.5); + let f0 = clamp(1.6 / sqrt(height), 0.2, 1.0); + let w0 = 6.2831853 * f0 * t + phase + 0.8 * sin(0.17 * t + 9.0 * seed); + let envelope = 0.65 + 0.35 * sin(0.23 * t + 5.0 * seed); + let swing = swing_size * envelope; + // (the top lags the middle by a fraction of a cycle: the crown bends, not only leans) + let lag = 0.35 * h; + let move_xy = along * (lean + swing * sin(w0 - lag)) + across * (0.35 * swing * sin(0.93 * w0 + 1.7 - lag)); + var d = vec3(move_xy * h * h, 0.0); + // the crown's big boughs: lobes about the crown's size swaying at about twice the tree's + // frequency, each with its own slowly wandering phase, harder in a gust - neighbouring + // parts of the picture move nearly together, so the crown stirs rather than wobbles + let lm = (m * vec4(local, 0.0)).xyz; + let bp = dot(lm, vec3(0.45, 0.35, 0.3) * (4.0 / crown)) + phase; + let fb = clamp(2.2 * f0, 0.8, 2.0); + let wb = 6.2831853 * fb * t + bp + 0.6 * sin(0.31 * t + bp); + let bough = 0.25 * give * pow(speed * gust / 20.0, 1.5) * h; + d = d + vec3(along * sin(wb) + across * 0.5 * sin(1.17 * wb + 2.0), 0.25 * sin(0.9 * wb + 1.0)) * bough; + // the bent crown keeps its length: it sinks as it leans + let above = max((local.z - sw.y) * scale, 0.3); + d.z = d.z - 0.5 * dot(d.xy, d.xy) / above; + return d; +} + +// Where a scene vertex lands on the screen: the main pass's and the depth passes' vertex +// shaders (`vs_main`, `vs_depth`) both take it from here, so that their depths agree to the +// last bit (the main pass tests against the depth the prepass left). +fn scene_clip(e: u32, wp: vec4, nw: vec3) -> vec4 { + // Road surfaces (splines, the objects lying on them, a shadow blob) are pulled towards + // the eye along the line of sight - the picture does not move, only the depth - so that + // they win over the flush ground beside them. Code 0.9 keeps the surface shading without + // the pull; painted ground (0.75) stays put. + let surf = inst_params[e * 2u + 1u].w; + var cp = wp.xyz; + if (surf > 0.9) { + let to = wp.xyz - camera.cam_pos.xyz; + let d = length(to); + // The same share of the way to the eye at every vertex (0.3 %, a few millimetres of + // height seen from the cab): the pulled road is still the plane it was, so a spline + // laid a millimetre over another - the rails or markings over a road - stays over it + // however the two are cut into triangles. A fixed 2 cm more along each vertex's own + // line of sight bowed the road's long triangles over the short ones of what lies on + // it, by millimetres near the eye, and the rails went under the road there (#1196). + // (surface objects, 1.25, a little more than the splines under them) + // (a vehicle's shadow blob, 2: drawn without a depth test in the original, right + // over the road it lies on - with the road's own pull alone the two fought for + // every pixel and the road mostly won; a few centimetres more bring it through the + // road and still leave it behind the body and the wheels standing on it) + // The share stops growing at 5 cm. The pull is a depth, not a place - the picture + // does not move - but the pole of a traffic light that a mod's map tagged as a + // surface is pulled with the road under it, and a share still growing at distance + // (a third of a metre at 90 m) carried the pole through the signal head it stands + // beside. Capped, the pole stays behind what it stands by, and the depth a road + // needs over flush ground is a few millimetres at most (a floor raised 3 cm above + // the road is still seen - `surface_bias_keeps_raised_floors_visible_at_a_distance`). + // (a road's painted lines, 1.4, a little more again: a crossing object laid over + // the road covered the lines it overlaps, which in Omsi.exe lie a millimetre over + // the road and win the depth test against it - #1694) + let decal = surf > 1.1 && surf < 1.35; + let paint = surf > 1.35 && surf < 1.5; + let share = select(select(select(0.003, 0.004, decal), 0.0045, paint), 0.005, surf > 1.5); + let fixed = select(select(select(0.0, 0.01, decal), 0.015, paint), 0.05, surf > 1.5); + // The cap on the share is for upright faces, the poles. A flat surface keeps its + // share all the way: pulled by the same part of the way to the eye at every vertex + // the road is still one plane, however long its triangles, and a marking on it keeps + // its place. Capped at 5 cm the pull of a triangle from the eye to the horizon + // stopped growing with the distance and turned the road's plane into a bowl: at + // 40 m from a low eye the road came in front of the lines on it, and they were + // gone, and back as the bus came on (#3085). (Half a metre of it, at 170 m and + // beyond: millimetres of height from a driver's eye.) + let flat = abs(safe_normal(nw).z) > 0.5; + let pull = min(min(share * d, select(0.05, 0.5, flat)) + fixed, d * 0.3); + cp = wp.xyz - to / max(d, 1e-3) * pull; + } + // Omsi.exe draws a model mesh by mesh and subset by subset with LESSEQUAL into a 24-bit + // depth buffer: of two of its surfaces in one plane - a dashboard and the instruments + // printed on it - the later one is seen. Here their depths differed by rounding alone + // and every pixel was a coin toss. A slot lying on an earlier surface of its object + // (`draw_order_level`, 1 to 3; everything else 0) is brought nearer by two steps, each + // the same over a whole plane however it is cut into triangles (a step worked out per + // vertex from its own distance bends the surface): the reversed depth times 1 + 1e-5 a + // level, above the vertices' rounding; and 2e-5 a level over the plane's distance from + // the eye, against the tilt the rasterizer's snapping of each corner to a fraction of a + // pixel gives a triangle's depth, the more the flatter it is seen. Seen from above the + // plane that lifts it by 3e-5 a level times the distance: 0.9 mm at 10 m at level 3. + // (The plane's distance is at least 5 % of the vertex's own: the edge of a curved mesh, + // whose tangent plane runs through the eye, is not pulled metres forward.) + let clip = camera.view_proj * vec4(cp, 1.0); + let level_code = u32(round(models[e * 4u].w)); + var level = f32(level_code & 3u); + if (level <= 0.0) { + return clip; + } + if ((level_code & 4096u) != 0u) { + // Keep the depth step within half the measured gap. + let cap = f32((level_code >> 2u) & 1023u) * 1e-6; + let distance = length(cp - camera.cam_pos.xyz); + level = min(level, cap / max(3e-5 * distance, 1e-9)); + if (level <= 0.0) { + return clip; + } + } + // (the depth of the eye's own point: n f / (f - n), about the near plane) + let at_eye = (camera.view_proj * vec4(camera.cam_pos.xyz, 1.0)).z; + // Use geometric plane normals; lighting normals may be smoothed or authored independently. + let encoded = vec2(models[e * 4u + 1u].w, models[e * 4u + 2u].w); + var depth_n = nw; + if (all(abs(encoded) <= vec2(1.0))) { + var n = vec3(encoded, 1.0 - abs(encoded.x) - abs(encoded.y)); + let t = clamp(-n.z, 0.0, 1.0); + n.x += select(t, -t, n.x >= 0.0); + n.y += select(t, -t, n.y >= 0.0); + depth_n = n; + } + let plane = max(abs(dot(safe_normal(depth_n), cp - camera.cam_pos.xyz)), 0.05 * length(cp - camera.cam_pos.xyz)); + let slant = level * 2e-5 * at_eye * clip.w / plane; + return vec4(clip.x, clip.y, clip.z * (1.0 + level * 1e-5) + slant, clip.w); +} + +fn is_tree_card() -> bool { + return material.params.y > 0.1 && material.params.y < 0.2; +} + +fn detailed_trees() -> bool { + return DETAILED_TREES; +} + +fn tree_crown_normal(local: vec3, m: mat4x4, up: vec3) -> vec3 { + let pivot = select(0.28, material.sway.y, material.sway.x > 0.5); + let centre = mix(pivot, select(1.0, material.sway.z, material.sway.x > 0.5), 0.45); + let out = (m * vec4(local.x, local.y, local.z - centre, 0.0)).xyz; + let crown = smoothstep(pivot * 0.5, pivot + 0.1, local.z); + return safe_normal(mix(up, safe_normal(out), 0.65 * crown)); +} + +fn tree_card_fade(world: vec3) -> f32 { + if (!detailed_trees() || (!is_tree_card() && material.sway.x < 0.5)) { + return 1.0; + } + let c = cross(dpdx(world), dpdy(world)); + let v = (camera.cam_pos.xyz - world).xy; + if (dot(c, c) < 1e-20 || dot(v, v) < 1e-6) { + return 1.0; + } + let n = normalize(c); + let upright = smoothstep(0.6, 0.9, length(n.xy)); + let facing = abs(dot(normalize(n.xy + vec2(1e-6, 0.0)), normalize(v))); + return mix(1.0, smoothstep(0.3, 0.62, facing), upright); +} + +@vertex +fn vs_main(in: VsIn) -> VsOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0); + var out: VsOut; + out.clip = scene_clip(e, wp, (m * vec4(in.normal, 0.0)).xyz); + out.world = wp.xyz; + out.local = in.pos; + out.normal = safe_normal((m * vec4(in.normal, 0.0)).xyz); + if (detailed_trees() && (is_tree_card() || (material.sway.x > 0.5 && material.sway.z - material.sway.y > 2.5))) { + out.normal = tree_crown_normal(in.pos, m, out.normal); + } + let sp = vertex_specular(wp.xyz, out.normal); + out.spec_sun = sp[0]; + out.spec_sky = sp[1]; + // Ray blocking is disabled for exterior cameras; never light our own body or cabin. + // The vehicle surface code keeps roads and scenery in the same box illuminated. + out.spot_diffuse = vec3(0.0); + out.spot_ambient = vec3(0.0); + let own_vehicle = inst_params[e * 2u + 1u].w < -500.0 && near_player_vehicle(wp.xyz) > 0.5; + if (!own_vehicle) { + let spot = classic_spot(wp.xyz, out.normal); + out.spot_diffuse = spot[0]; + out.spot_ambient = spot[1]; + } + out.env_uv = sphere_map_uv(wp.xyz, out.normal, camera.cam_pos.xyz); + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + out.params2 = inst_params[e * 2u + 1u]; + let side_pane = material.wipe_bounds.z < 0.0; + let pane = select(in.pos.xz, in.pos.yz, side_pane); + out.wipe_uv = vec3((pane - material.wipe_bounds.xy) * abs(material.wipe_bounds.zw), select(in.pos.y, in.pos.x, side_pane)); + if (pr.y < 0.5) { + // invisible: collapse the triangle + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +// What the depth-only passes (the depth prepass, the multisampled prefill) take from a +// vertex: its place and what a cut-out or a transmap needs to decide its coverage. The +// highlights, the sphere map and the normal of `vs_main` are not worked out for them. +struct DepthOut { + @builtin(position) @invariant clip: vec4, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + // the instance's surface code (`inst_params` w, see `scene_clip`) + @location(4) surf: f32, + @location(5) world: vec3, +}; +struct DepthIn { + @builtin(position) clip: vec4, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + @location(4) surf: f32, + @location(5) world: vec3, +}; + +struct ShadowOut { + @builtin(position) @invariant clip: vec4, + @location(0) uv: vec2, + @location(1) @interpolate(flat) params: vec4, +}; +struct ShadowIn { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + @location(1) @interpolate(flat) params: vec4, +}; + +@vertex +fn vs_depth(in: VsIn) -> DepthOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0); + var out: DepthOut; + out.clip = scene_clip(e, wp, (m * vec4(in.normal, 0.0)).xyz); + out.world = wp.xyz; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + out.surf = inst_params[e * 2u + 1u].w; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +struct VehicleBox { a: vec4, b: vec4, c: vec4 }; +struct VehicleReflection { plane: vec4, parts: array }; +@group(2) @binding(0) var vehicle_reflection: VehicleReflection; + +@vertex +fn vs_puddle_vehicle(in: VsIn) -> VsOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + var out: VsOut; + out.world = (m * vec4(in.pos, 1.0)).xyz; + out.normal = safe_normal((m * vec4(in.normal, 0.0)).xyz); + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + out.params2 = inst_params[e * 2u + 1u]; + out.spec_sun = vec3(0.0); + out.spec_sky = vec3(0.0); + out.spot_diffuse = vec3(0.0); + out.spot_ambient = vec3(0.0); + let plane = vehicle_reflection.plane; + // the sphere map from the reflected eye fs_puddle_vehicle shades the vehicle from + out.env_uv = sphere_map_uv(out.world, out.normal, camera.cam_pos.xyz - 2.0 * plane.xyz * (dot(plane.xyz, camera.cam_pos.xyz) - plane.w)); + let reflected = out.world - 2.0 * plane.xyz * (dot(plane.xyz, out.world) - plane.w); + out.clip = camera.view_proj * vec4(reflected, 1.0); + if (out.params.y < 0.5) { out.clip = vec4(0.0, 0.0, 2.0, 1.0); } + return out; +} + +// Close an open legacy underbody with one depth-tested face in the same reflected +// view. Wheels and authored panels occlude it normally; no screen-space bands. +@vertex +fn vs_puddle_chassis(@builtin(vertex_index) i: u32, @builtin(instance_index) part: u32) -> @builtin(position) vec4 { + let corners = array, 6>(vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), + vec2(-1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, 1.0)); + let box = vehicle_reflection.parts[part]; + let local = corners[i] * max(box.b.yz - vec2(0.12, 0.18), vec2(0.0)) + box.c.xy; + let sh = box.a.w; + let ch = box.b.x; + let xy = box.a.xy + vec2(local.x * ch + local.y * sh, -local.x * sh + local.y * ch); + let plane = vehicle_reflection.plane; + let road_z = (plane.w - dot(plane.xy, xy)) / plane.z; + let z = max(road_z + 0.18, box.a.z + box.c.z - box.b.w + 0.04); + let world = vec3(xy, z); + let reflected = world - 2.0 * plane.xyz * (dot(plane.xyz, world) - plane.w); + return camera.view_proj * vec4(reflected, 1.0); +} + +// Shadow map passes: depth from the sun, alpha-tested materials cut out by their texture. +// A surface that casts - a spline standing clear of the ground, a bridge deck - casts from +// half a metre further away from the sun: what lies right under it (the embankment object +// under a railway, the ground a ramp touches down on) is no darker for it, while the ground +// metres below a deck gets its shadow. +fn shadow_caster_pos(e: u32, wp: vec4) -> vec4 { + if (abs(inst_params[e * 2u + 1u].w - 1.0) < 0.01) { + return vec4(wp.xyz - camera.sun_dir.xyz * 0.5, wp.w); + } + return wp; +} + +@vertex +fn vs_shadow(in: VsIn) -> ShadowOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = shadow_caster_pos(e, m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0)); + var out: ShadowOut; + out.clip = camera.light_view_proj * wp; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +@vertex +fn vs_shadow_close(in: VsIn) -> ShadowOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = shadow_caster_pos(e, m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0)); + var out: ShadowOut; + out.clip = camera.light_view_proj_close * wp; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +@vertex +fn vs_shadow_far(in: VsIn) -> ShadowOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = shadow_caster_pos(e, m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0)); + var out: ShadowOut; + out.clip = camera.light_view_proj_far * wp; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +// Enhanced: a lamp's shadow map (one of the tiles under the far map). The draw list names +// the tile above the entry's own bits (`LAMP_ENTRY_BITS` in lamp_slots.rs), and the tile's +// matrix looks down from a street lamp's head or along the road from a vehicle's headlamps. +const LAMP_ENTRY_BITS: u32 = 26u; + +@vertex +fn vs_shadow_lamp(in: VsIn) -> ShadowOut { + let raw = draw_list[in.inst]; + let e = raw & ((1u << LAMP_ENTRY_BITS) - 1u); + let k = raw >> LAMP_ENTRY_BITS; + let m = model_matrix(e); + let wp = m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0); + var out: ShadowOut; + out.clip = camera.lamp_view_proj[k] * wp; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +@fragment +fn fs_shadow(in: ShadowIn) { +} + +// Reflection rays need the window surface as well as the opaque interior behind it. +// This writes a private hit-depth texture after colour compositing; ordinary depth and +// AO still leave glass transparent. Reject absent/fully faded layers and texture holes. +@fragment +fn fs_puddle_glass_depth(in: FsIn) { + // From the cabin we see the street through our own pane. Treating that pane as + // an SSR hit terminates every ray at the window instead of the outside vehicle. + if (inside_vehicle(camera.cam_pos.xyz) * near_player_vehicle(in.world) > 0.5) { + discard; + } + var a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], tex_address(in.uv), camera.lod.x), in.uv).a; + if (material.params.z > 0.5) { + let tm = sample_transmap(tex_address(in.uv - in.params.zw)); + a = select(1.0, tm.a, material.params.w > 0.5); + } + if (a * material.color.a * in.params.x < 0.002) { + discard; + } +} + +// (the shadow and rain maps, drawn at their own size: their textures' mips as they are) +@fragment +fn fs_shadow_test(in: ShadowIn) { + cutout_coverage(in.uv, in.params, 0.0, 1.0); +} + +// the depth-only passes' (`vs_depth`) fragment shaders: plain, cut out, a transmap's +// opaque part +@fragment +fn fs_depth(in: DepthIn) { +} + +// (the picture's depth: its textures read with the colour pass's mip bias, `camera.lod` - +// a cut-out's edge the prepass took from a blurrier mip than the colour pass wrote depth +// where the colour then discarded, and the sky showed through) +@fragment +fn fs_depth_test(in: DepthIn) { + cutout_coverage(in.uv, in.params, camera.lod.x, tree_card_fade(in.world)); +} + +// (a transmap's opaque part, see `transmap_coverage`) +@fragment +fn fs_depth_transmap(in: DepthIn) { + transmap_coverage(in.uv, in.params, camera.lod.x); +} + +//MS @group(3) @binding(0) var t_pane_depth: texture_depth_multisampled_2d; + +//MS @fragment +//MS fn fs_depth_masked(in: DepthIn, @builtin(sample_index) sample: u32) { +//MS if (in.clip.z <= textureLoad(t_pane_depth, vec2(in.clip.xy), i32(sample))) { +//MS discard; +//MS } +//MS } + +// The multisampled prefill's cut-outs (foliage): their depth only where the colour pass +// is sure to cover every sample - the alpha-to-coverage of an alpha of 1 (`shade_enhanced`: +// the texture's alpha past the cutoff's smoothed edge, a plain material at full opacity, +// no pane, LED panel, transmap, ground or shadow blob). The edges, which alpha-to-coverage +// covers in part, are left to the colour pass: a sample laid here that the colour then +// left uncovered would hide what lies behind it (the sky showed through the houses). +@fragment +fn fs_depth_cover(in: DepthIn) { + let mode = material.params.x; + if (mode < 0.5 || mode > 1.5 || material.params.z > 0.5 || material.extra.x > 0.5 + || material.wipe_bounds.z != 0.0 || abs(material.emissive.w) > 1.5 + || material.color.a < 1.0 || in.params.x < 1.0 || in.surf > 1.5) { + discard; + } + let duv = tex_address(in.uv); + let a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv).a * tree_card_fade(in.world); + let aa = max(fwidth(a) * 0.5, 1.0 / 255.0); + if (a < ALPHA_REF + aa + 4.0 / 255.0) { + discard; + } +} + +// A cut-out's texel: kept where its alpha reaches the cutoff (`bias`: the mip bias its +// pass reads the textures with, the colour pass's for the picture's depth). +fn cutout_coverage(uv: vec2, params: vec4, bias: f32, fade: f32) { + var duv = tex_address(uv); + if (material.extra.x > 0.5) { + duv = uv * material.extra.z; + } + // Use the light-pass footprint for cutout coverage. Forcing mip 0 here aliases dense + // foliage and alpha layers into a checkerboard when the light projection moves by a + // texel; the mip-aware sample keeps the caster coverage coherent with its resolution. + // For a material promoted to the shadow pass from Blend, diffuse alpha is commonly a + // paint/gloss value rather than coverage (vehicle bodies use values such as 0.03). Only + // alpha-test materials use diffuse alpha as a cutout; blended bodies are solid unless a + // real transmap supplies coverage. + var a = select(diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, bias), duv).a, 1.0, material.params.x > 1.5 && material.params.z < 0.5); + if (material.params.z > 0.5) { + // (the transmap stays where it is: [texcoordtransX/Y] only moves the diffuse stage) + let tm = sample_transmap_bias(tex_address(uv - params.zw), bias); + a = select(1.0, tm.a, material.params.w > 0.5); + } + if (a * fade < ALPHA_REF) { + discard; + } +} + +// Roads with feathered alpha borders stay blended while their overlaps compose. +// Once the surface phases are complete, only fully covered diffuse pixels occlude +// later scenery. The transparent borders must not become invisible depth walls. +@fragment +fn fs_surface_depth(in: FsIn) -> @location(0) vec4 { + let a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], tex_address(in.uv), camera.lod.x), in.uv).a + * material.color.a * in.params.x; + if (a < 0.999) { + discard; + } + return vec4(0.0); +} + +// A vehicle body and its windows are often one mesh/material. OMSI represents that +// material as alpha-blended because the transmap contains the window opacity, but the +// alpha-tested body pixels still have to occlude vehicles behind them. The normal depth prepass +// deliberately skips all blended materials, so those pixels would otherwise have no depth +// until the colour pass (where blend order can expose the bus through the car). Keep only +// the effectively opaque part of a transmap in a separate depth-only pass; window pixels +// remain out of the prepass and are composited normally. +fn transmap_coverage(uv: vec2, params: vec4, bias: f32) { + if (material.params.z < 0.5) { + discard; + } + let tm = sample_transmap_bias(tex_address(uv - params.zw), bias); + let a = select(1.0, tm.a, material.params.w > 0.5) * params.x; + // Only what the colour pass will cover completely may hide what lies behind it: a + // texel that is merely more opaque than not (the dimmer and anti-aliased dots of a + // display's text layer, whose transmap is its script texture) wrote depth here, the + // display's backplate behind it was then rejected, and the half-transparent text was + // blended over the sky - holes in the display. + if (a < 0.99) { + discard; + } +} + +// 1 = lit by the sun, 0 = in shadow. Three cascades: the close one (the bus and what is +// next to it), the near one around the camera and the far one covering the rest of the +// visible street. + +// Depth bias of the sun shadow, in metres along the sun's ray. The maps' depth runs over +// the light box's 2199 m, and the comparison used to take off 0.0015 (near) and 0.004 (far) +// of that: 3.3 m and 8.8 m. Nothing closer to the ground than that along the ray cast a +// shadow - not a car (1.4 m), not a bus (3 m; only its roof's shadow at a low sun, +// which lay detached and offset from the bus) - and the grass and kerbs had none either. +// The receiver plane below takes care of what the big constant stood in for. +const SHADOW_DEPTH_RANGE: f32 = 2199.0; +const SHADOW_BIAS_NEAR: f32 = 0.06; +const SHADOW_BIAS_FAR: f32 = 0.3; +const SHADOW_BIAS_CLOSE: f32 = 0.025; + +// How the receiver's depth in the shadow map changes across the map (per unit of uv), from +// its normal: the PCF taps around the pixel compare against the surface's own depth at the +// tap instead of the centre's, so a surface at a slant to the sun does not shadow itself +// within the filter radius (acne), which a big constant bias used to hide. `lvp` is the +// cascade's light matrix (orthographic, so the map from the world is affine). +fn shadow_receiver_slope(lvp: mat4x4, n: vec3) -> vec2 { + let a = select(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), abs(n.x) > 0.9); + let t1 = normalize(cross(n, a)); + let t2 = cross(n, t1); + let p1 = (lvp * vec4(t1, 0.0)).xyz; + let p2 = (lvp * vec4(t2, 0.0)).xyz; + // (uv = 0.5 x + 0.5, 0.5 - 0.5 y) + let d1 = vec3(p1.x * 0.5, -p1.y * 0.5, p1.z); + let d2 = vec3(p2.x * 0.5, -p2.y * 0.5, p2.z); + let det = d1.x * d2.y - d2.x * d1.y; + if (abs(det) < 1e-12) { + return vec2(0.0); + } + let g = vec2(d1.z * d2.y - d2.z * d1.y, d1.x * d2.z - d2.x * d1.z) / det; + // a surface seen edge-on by the sun: keep the slope finite (it is in shadow of itself + // there anyway, by its normal) + return clamp(g, vec2(-2.0), vec2(2.0)); +} + +// The filter's half width in texels. A tent of 2 texels covers 4 x 4 texels, two gathers a +// side - four in all, fewer texture reads than the Poisson kernel's five (sixteen on an +// edge) - and spreads an edge about as the old kernel did in the near and close cascades +// (0.82 of a texel's standard deviation against 0.9 and 1.0; a fifth sharper in the far one). +const SHADOW_TENT: f32 = 2.0; +// Percentage-closer filtering with a tent of `SHADOW_TENT` texels, every texel of the map +// under it compared and weighted by the tent at its centre: four gathers of 2 x 2 texels, +// the whole 4 x 4 footprint read. The sparse Poisson kernel this replaces (16 bilinear taps +// 1.6 to 2.2 texels apart, and only its 5 outermost-and-middle taps when those agreed) +// sampled the map coarser than its texels: a lit gap between leaves, a few texels wide, came +// out as a copy of the kernel - an X of five magnified texels - and a feature lying between +// the taps vanished and reappeared as the receiver moved by a texel, which made the shadows +// shimmer. Read in full, the result is a continuous function of the receiver's position. +// `widen` (Enhanced: a veil of high cloud enlarging the sun) spreads the four gathers that +// many texels apart, a tent as much wider, without reading more. +// `uv`: the receiver in the cascade's own 0..1; `size`: the cascade's texels a side; +// `origin`: where its first texel lies in the texture; `slope`: its receiver plane (per uv). +// The shadow maps' size, texels a side, from the uniforms (`camera.shadow.y` is a texel): the +// near map an atlas of two cascades side by side, the far one taller by the lamps' tiles under +// it (`camera.lamp_atlas.z` is its texture's height). (Asked of the textures with +// textureDimensions in every inlined use of the sun's shadow, they brought Apple's M4 shader +// compiler down on every scene pipeline.) +fn shadow_map_size() -> f32 { + return 1.0 / max(camera.shadow.y, 1e-6); +} + +fn shadow_tent_place(uv: vec2, size: f32, widen: f32) -> vec4 { + let k = max(1.0, floor(widen + 0.5)); + // (texel i of the cascade has its centre at p = i; the first texel the tent reaches) + let p = uv * size - vec2(0.5); + let lo = floor(p - vec2(SHADOW_TENT * k)) + vec2(1.0); + return vec4(p, lo); +} + +// The tent's weights of a gather's four texels starting at `t0` (gather order: (0, 1), +// (1, 1), (1, 0), (0, 0) of the quad). +fn shadow_tent_weights(t0: vec2, p: vec2, r: f32) -> vec4 { + let w0 = max(vec2(0.0), vec2(1.0) - abs(t0 - p) / r); + let w1 = max(vec2(0.0), vec2(1.0) - abs(t0 + vec2(1.0) - p) / r); + return vec4(w0.x * w1.y, w1.x * w1.y, w1.x * w0.y, w0.x * w0.y); +} + +fn shadow_tent_near(uv: vec2, size: f32, origin: vec2, z: f32, slope: vec2, widen: f32, bias: f32) -> f32 { + let dims = vec2(2.0, 1.0) * shadow_map_size(); + let pl = shadow_tent_place(uv, size, widen); + let k = max(1.0, floor(widen + 0.5)); + let r = SHADOW_TENT * k; + var sum = 0.0; + var wsum = 0.0; + for (var q = 0; q < 4; q = q + 1) { + let t0 = pl.zw + vec2(f32(q & 1), f32(q >> 1u)) * 2.0 * k; + let a = (origin + t0 + vec2(1.0)) / dims; + let zr = z + dot(slope, (t0 + vec2(0.5) - pl.xy) / size) - bias; + let w = shadow_tent_weights(t0, pl.xy, r); + sum = sum + dot(textureGatherCompare(t_shadow, s_shadow, a, zr), w); + wsum = wsum + w.x + w.y + w.z + w.w; + } + return sum / max(wsum, 1e-6); +} + +fn shadow_tent_far(uv: vec2, size: f32, z: f32, slope: vec2, widen: f32, bias: f32) -> f32 { + let dims = vec2(shadow_map_size(), camera.lamp_atlas.z); + let pl = shadow_tent_place(uv, size, widen); + let k = max(1.0, floor(widen + 0.5)); + let r = SHADOW_TENT * k; + var sum = 0.0; + var wsum = 0.0; + for (var q = 0; q < 4; q = q + 1) { + let t0 = pl.zw + vec2(f32(q & 1), f32(q >> 1u)) * 2.0 * k; + let a = (t0 + vec2(1.0)) / dims; + let zr = z + dot(slope, (t0 + vec2(0.5) - pl.xy) / size) - bias; + let w = shadow_tent_weights(t0, pl.xy, r); + sum = sum + dot(textureGatherCompare(t_shadow_far, s_shadow, a, zr), w); + wsum = wsum + w.x + w.y + w.z + w.w; + } + return sum / max(wsum, 1e-6); +} + +// The near map is an atlas two cascades wide: the near cascade in its left half, the close +// one (`camera.light_view_proj_close`) from the top left of its right half, drawn no bigger +// than 2048 texels (`SHADOW_CLOSE_MAX` in lib.rs). `widen`: how much wider than the +// cascade's own the filter is (Enhanced: a veil of high cloud enlarging the sun). +fn shadow_pcf_near(uv: vec2, z: f32, slope: vec2, widen: f32) -> f32 { + let size = shadow_map_size(); + return shadow_tent_near(uv, size, vec2(0.0), z, slope, widen, SHADOW_BIAS_NEAR / SHADOW_DEPTH_RANGE); +} + +fn shadow_pcf_close(uv: vec2, z: f32, slope: vec2) -> f32 { + // (camera.post.w: the close map's size over the near map's) + let half = shadow_map_size(); + let size = half * select(1.0, camera.post.w, camera.post.w > 0.0); + return shadow_tent_near(uv, size, vec2(half, 0.0), z, slope, 1.0, SHADOW_BIAS_CLOSE / SHADOW_DEPTH_RANGE); +} + +fn shadow_push_close(n: vec3, ndl: f32) -> vec3 { + return n * (0.015 + 0.03 * (1.0 - ndl)); +} + +// The close cascade's value and weight at a point (weight 0 outside it): it fades into the +// near cascade between 60 and 90 % of its range from the camera. +fn shadow_close(world: vec3, n: vec3, ndl: f32, thin: bool) -> vec2 { + let range = camera.flags.w; + if (range <= 0.0) { + return vec2(1.0, 0.0); + } + let radial = distance(world, camera.cam_pos.xyz); + let w = 1.0 - smoothstep(range * 0.6, range * 0.9, radial); + if (w <= 0.001) { + return vec2(1.0, 0.0); + } + let lp = camera.light_view_proj_close * vec4(world + shadow_push_close(n, ndl), 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + if (edge >= 0.48 || lp.z < 0.0 || lp.z > 1.0) { + return vec2(1.0, 0.0); + } + let slope = select(shadow_receiver_slope(camera.light_view_proj_close, n), vec2(0.0), thin); + return vec2(shadow_pcf_close(uv, lp.z, slope), w); +} + +// The far map takes the top of its texture (its texels are the texture's first rows); the +// lamps' tiles lie under it (`LampAtlas` in lights.rs). +fn shadow_pcf_far(uv: vec2, z: f32, slope: vec2, widen: f32) -> f32 { + let size = shadow_map_size(); + return shadow_tent_far(uv, size, z, slope, widen, SHADOW_BIAS_FAR / SHADOW_DEPTH_RANGE); +} + +// The shadow lookup point: pushed off the surface along its normal by about a texel of the +// cascade (0.14 m near, 0.68 m far), more where the surface turns away from the sun. +fn shadow_push_near(n: vec3, ndl: f32) -> vec3 { + return n * (0.06 + 0.12 * (1.0 - ndl)); +} + +fn shadow_push_far(n: vec3, ndl: f32) -> vec3 { + return n * (0.3 + 0.6 * (1.0 - ndl)); +} + +// `thin`: an alpha-tested card (leaves, fences), whose normal says nothing about its plane +// (OMSI points a tree's normals up): no receiver plane, the lookup moves half a metre +// towards the sun instead, which keeps a crown from speckling itself. +fn sun_shadow(world_in: vec3, n: vec3, thin: bool) -> f32 { + if (camera.shadow.x < 0.5) { + return 1.0; + } + let world = world_in + select(vec3(0.0), camera.sun_dir.xyz * 0.5, thin); + let ndl = clamp(dot(n, camera.sun_dir.xyz), 0.0, 1.0); + let close = shadow_close(world, n, ndl, thin); + if (close.y >= 0.999) { + return close.x; + } + let near_lp = camera.light_view_proj * vec4(world + shadow_push_near(n, ndl), 1.0); + let near_uv = vec2(near_lp.x * 0.5 + 0.5, 0.5 - near_lp.y * 0.5); + let inside = max(abs(near_uv.x - 0.5), abs(near_uv.y - 0.5)); + if (inside < 0.48 && near_lp.z >= 0.0 && near_lp.z <= 1.0) { + let nv = shadow_pcf_near(near_uv, near_lp.z, select(shadow_receiver_slope(camera.light_view_proj, n), vec2(0.0), thin), 1.0); + return mix(nv, close.x, close.y); + } + let lp = camera.light_view_proj_far * vec4(world + shadow_push_far(n, ndl), 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || lp.z < 0.0 || lp.z > 1.0) { + return 1.0; + } + let sum = shadow_pcf_far(uv, lp.z, select(shadow_receiver_slope(camera.light_view_proj_far, n), vec2(0.0), thin), 1.0); + let edge = clamp((0.5 - max(abs(uv.x - 0.5), abs(uv.y - 0.5))) * 12.0, 0.0, 1.0); + return mix(1.0, sum, edge); +} + +// Sum of the point lights registered in the grid cell of `p`. A light is registered in +// every cell its range touches, so the point's own cell holds every light that reaches it; +// looking into the neighbouring cells as well counted a light up to four times, and how +// often depended on where the cell edges fell - lamp pools brightened and dimmed as the +// camera moved. +// `map_k`: how much of the map's lamps a surface takes (0 on a light-mapped road in the +// classic picture, whose lamps are in its light map); a vehicle's own lights (dir.x 1, see +// lib.rs `gpu_light`) always shine - the headlights lit no road at all in vanilla. +fn point_lights(p: vec3, n: vec3, map_k: f32) -> vec3 { + var sum = vec3(0.0); + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell <= 0.0 || side == 0u) { + return sum; + } + let f = (p.xy - camera.light_grid.xy) / cell; + let x = i32(floor(f.x)); + let y = i32(floor(f.y)); + if (x >= 0 && y >= 0 && x < i32(side) && y < i32(side)) { + let base = (u32(y) * side + u32(x)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let d = l.pos.xyz - p; + let dist = length(d); + if (dist >= l.pos.w) { + continue; + } + if (!(l.dir.w < -1.5 && l.dir.z < -0.5) && own_vehicle_blocks(p, l.pos.xyz)) { + continue; + } + if (l.dir.w >= -1.5 && l.extra.z != 0.0) { + // a Direct3D spot of the classic picture (lights.rs `push_classic_spot`): a + // vehicle's [spotlight] (its range negative) is the player's alone, lit by + // `classic_spot` at the vertices; another - a [spotlight_2], a cookie's + // cone - is lit so here, its ambient light with the diffuse + if (l.extra.z < 0.0) { + continue; + } + let s = d3d_spot(p, n, l.pos.xyz, l.dir, l.extra.x, l.extra.z, l.color.rgb * l.color.w); + sum = sum + s[0] + s[1]; + continue; + } + // full intensity within 1/8 of the range, then inverse-square, cut off at the range; + // the strength was set by eye while a street lamp was still counted about three + // times (see above), so it is three times what it was, to keep the lamp pools + let r0 = l.pos.w * 0.125; + let att = min(1.0, (r0 * r0) / max(dist * dist, 0.01)) * clamp(1.0 - dist / l.pos.w, 0.0, 1.0) * 3.75; + let ndl = max(dot(n, d / max(dist, 0.01)), 0.15); + var k = select(map_k, 1.0, l.dir.x > 0.5 && l.dir.w < -1.5); + if (l.dir.w >= -1.5) { + // a spot (a vehicle's [spotlight], as Direct3D lights with it): full inside + // the inner cone, fading to nothing at the outer one; nothing behind it + let c = dot(-d / max(dist, 0.01), l.dir.xyz); + k = smoothstep(l.dir.w, max(l.extra.x, l.dir.w + 1e-3), c); + } + sum = sum + l.color.rgb * l.color.w * att * ndl * k; + } + } + return sum; +} + +// [interiorlight]: the light of a vehicle's saloon lamps on a mesh that names them in its +// [illumination_interior], 1 = a lamp's full light on a seat under it. `code` is the +// instance's lamp code (lib.rs `Instance::interior_lamps`): the first of its lamp slots in +// `lights` times 64 plus how many; below 1 it is a plain brightness (a passenger standing in +// a lit bus). Each lamp is OMSI's Direct3D point light: attenuation +// 1 / (d² / core²) with `core` the lamp's [interiorlight] range, no cut-off short of 100 m, +// times N·L; the sum saturates, as Direct3D's vertex colour does. +fn interior_lamps(p: vec3, n: vec3, code: f32) -> vec3 { + if (code < 1.0) { + return vec3(1.0, 0.96, 0.84) * clamp(code, 0.0, 1.0); + } + let c = u32(code + 0.5); + // (LAMP_CODE_STRIDE: 64 - up to 63 lamps a mesh) + let first = c >> 6u; + let count = c & 63u; + var sum = vec3(0.0); + for (var i = 0u; i < count; i = i + 1u) { + let l = lights[first + i]; + let r = l.extra.w; + let d = l.pos.xyz - p; + let dist2 = max(dot(d, d), 1e-4); + if (l.color.w <= 0.0 || dist2 >= r * r) { + continue; + } + let core = max(l.extra.y, 0.01); + let att = core * core / dist2; + let ndl = max(dot(n, d * inverseSqrt(dist2)), 0.0); + sum = sum + l.color.rgb * l.color.w * att * ndl; + } + return min(sum, vec3(1.0)); +} + + +// A Direct3D spot light of the classic picture at `p` (normal `n`), as Omsi.exe sets its +// up for a vehicle's [spotlight] (0x708acc, see lights.rs `push_classic_spot`): `source` +// is the spotlight's own world position; attenuation 1 / (0.2 + d / R + 40 d² / R²) +// (R the declared range), the cone (`dir`: direction and the cosine of half the outer cone; +// `inner` the inner one's) with a falloff of 2, 0.3 x `color` as diffuse light (times N.L) +// and 0.1 x as ambient light, which lights the material's ambient colour whichever way the +// surface faces. [0] the diffuse light, [1] the ambient light. +fn d3d_spot(p: vec3, n: vec3, source: vec3, dir: vec4, inner: f32, range: f32, color: vec3) -> array, 2> { + let to_light = source - p; + let dl = max(length(to_light), 0.01); + let att = 1.0 / (0.2 + dl / range + 40.0 * dl * dl / (range * range)); + let rho = dot(-to_light / dl, dir.xyz); + let cone = pow(clamp((rho - dir.w) / (max(inner, dir.w + 1e-4) - dir.w), 0.0, 1.0), 2.0); + let lit = color * att * cone; + return array, 2>(lit * 0.3 * max(dot(n, to_light / dl), 0.0), lit * 0.1); +} + +// The classic picture's headlight at a vertex: Omsi.exe's one Direct3D spot light, the +// player's [spotlight] (`camera.spot`, see setup.rs `classic_spot`), lit at the vertices as +// its fixed function lights them. Across a road, whose vertices lie at its edges, the pool +// is spread as OMSI 2 spreads it: lit per pixel it was brightest on the crown of the road +// in front of the bus and gone far sooner. `vs_main` excludes the player's own vehicle. +// [0] is the vehicle-face origin for occlusion; [3] is the declared source for lighting. +// Nothing beyond 4 x its range, as Direct3D cuts it off. +fn classic_spot(p: vec3, n: vec3) -> array, 2> { + let s = camera.spot; + let none = array, 2>(vec3(0.0), vec3(0.0)); + if (s[0].w <= 0.0 || distance(s[3].xyz, p) >= 4.0 * s[0].w || own_vehicle_blocks(p, s[0].xyz)) { + return none; + } + return d3d_spot(p, n, s[3].xyz, s[1], s[2].w, s[0].w, s[2].rgb); +} +// Value noise in three octaves: the "fractal" detail (the `detail_textures` setting) laid +// over the ground and the road surfaces close by, so that a blurred texture keeps some grain. +// +// The lattice cell is hashed as an integer. The old `fract(sin(dot(q, …)) * 43758.5)` +// hash took the cell's map coordinate - two and a half million at Spandau's 892 km - into +// a sine: in 32-bit floats its argument is a multiple of 64 there, and what came out was +// not noise but a ramp that repeated along straight lines, so every road wore thin +// diagonal streaks at an exact spacing. Cells are wrapped at `PATTERN_PERIOD` (the pattern +// coordinate is taken modulo that on the CPU, see `world_pattern_xy`), which keeps the +// hash's input small and the pattern seamless across the wrap. +const PATTERN_PERIOD: f32 = 1000.0; + +fn hash_cell(c: vec2, cells: f32) -> f32 { + // the cell index modulo the lattice's cells per period, as an exact integer + let w = c - cells * floor(c / cells); + var v = vec2(w) * 1664525u + vec2(1013904223u); + // (a PCG-style mix: two rounds of multiply, cross-add and xor-shift) + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + return f32(v.x >> 8u) / 16777215.0; +} + +// `freq`: lattice cells per metre of `p` (a whole number of cells per `PATTERN_PERIOD`). +fn vnoise_f(p: vec2, freq: f32, offset: vec2) -> f32 { + let q = p * freq + offset; + let cells = round(PATTERN_PERIOD * freq); + let i = floor(q); + let f = q - i; + let u = f * f * (3.0 - 2.0 * f); + let a = hash_cell(i, cells); + let b = hash_cell(i + vec2(1.0, 0.0), cells); + let c = hash_cell(i + vec2(0.0, 1.0), cells); + let d = hash_cell(i + vec2(1.0, 1.0), cells); + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); +} + + +fn detail_noise(p: vec2, near: f32) -> f32 { + // Anti-alias: point-sampling a lattice this fine aliases wherever one pixel's + // footprint spans more than about one cell of it - looking down a street at a + // grazing angle, or just driving away, constantly changes that footprint, and the + // alias pattern with it, which reads as the "fractal" texture re-rendering itself as + // the view angle changes. `fwidth` gives the footprint in the same units as `p`; an + // octave fades to its own mean (0.5, the hash is uniform 0..1) once a pixel can no + // longer resolve it, which is what an infinitely dense filter of it would give anyway. + let w = max(fwidth(p).x, fwidth(p).y); + let seen = select(0.0, 1.0, near > 0.0); + let fade0 = (1.0 - smoothstep(0.3, 1.2, w * 2.9)) * seen; + let fade1 = (1.0 - smoothstep(0.3, 1.2, w * 0.73)) * seen; + let fade2 = (1.0 - smoothstep(0.3, 1.2, w * 0.19)) * seen; + var n0 = 0.5; + var n1 = 0.5; + var n2 = 0.5; + if (fade0 > 0.0) { + n0 = mix(0.5, vnoise_f(p, 2.9, vec2(0.0)), fade0); + } + if (fade1 > 0.0) { + n1 = mix(0.5, vnoise_f(p, 0.73, vec2(0.0)), fade1); + } + if (fade2 > 0.0) { + n2 = mix(0.5, vnoise_f(p, 0.19, vec2(0.0)), fade2); + } + return n0 * 0.5 + n1 * 0.3 + n2 * 0.2; +} + +fn world_pattern_xy(p: vec3) -> vec2 { + // Geometry is relative to the floating render origin for f32 precision. Procedural + // patterns are not: reconstruct their stable map-space coordinate so crossing the + // renderer's 100 m origin cell cannot re-seed the asphalt/ground pattern. The origin + // arrives modulo PATTERN_PERIOD (lib.rs), so this stays a small, exact number: the map + // coordinate itself (892 km at Spandau) has a 6 cm step in 32 bits, a fifth of the + // finest noise cell. + return p.xy + camera.world_origin.xy; +} + +// Whether every component is a finite number, tested on the bits: Metal's fast maths takes +// `x != x` and comparisons with a NaN as it likes (a NaN colour happened to come out as +// something on the Mac), Direct3D 12 keeps the NaN and draws it black. +fn all_finite(v: vec3) -> bool { + let e = bitcast>(v) & vec3(0x7f800000u); + return all(e != vec3(0x7f800000u)); +} + +fn finite_or(v: vec3, fallback: vec3) -> vec3 { + return select(fallback, v, all_finite(v)); +} + +// The side of a tracked pane's wetness mask (`window_wipers::SIZE`). A constant, not the +// texture's own size: with `textureDimensions(mx_tex2d[mx_mat.trans])` in these functions Apple's Metal +// compiler crashed on the scene shader (the pipelines failed and the renderer fell back to +// 1x MSAA without snowfall and lamp shadows). +const WIPE_MASK_SIZE: i32 = 128; + +fn window_wetness(in: FsIn) -> f32 { + if (material.wipe_bounds.z != 0.0) { + // The mask packs the pane depth into R/G (high and low byte) and the wetness into + // B (the pane's unwiped wetness) and A (the local wetness). A filtered sample mixes + // the depth bytes of neighbouring texels into a depth that belongs to neither, so + // the pane test flickered between A and B from texel to texel: a staircase along + // every texel row where the raked glass changes depth. Read the four texels + // unfiltered, test each by its own depth, and blend the results bilinearly. + let dims = vec2(WIPE_MASK_SIZE); + let inside = all(in.wipe_uv.xy >= vec2(0.0)) && all(in.wipe_uv.xy <= vec2(1.0)); + let p = in.wipe_uv.xy * vec2(dims) - 0.5; + let base = vec2(floor(p)); + let f = p - floor(p); + var wet = 0.0; + for (var k = 0; k < 4; k++) { + let o = vec2(k & 1, k >> 1); + let w = select(1.0 - f.x, f.x, o.x == 1) * select(1.0 - f.y, f.y, o.y == 1); + let texel = textureLoad(mx_tex2d[mx_mat.trans], clamp(base + o, vec2(0), dims - 1), 0); + let depth = dot(texel.rg, vec2(256.0, 1.0)) * (64.0 / 257.0) - 32.0; + let local = (texel.a * 255.0 - 8.0) * (2.0 / 247.0); + wet += w * select(texel.b, local, inside && abs(depth - in.wipe_uv.z) <= 0.1); + } + return wet; + } + return in.params.x; +} + +// The snow variant of a tracked pane (`wipe_bounds.w` < 0): the snow the mask holds while it +// snows, drawn instead of water drops (scene/08_rain_glass.wgsl `glass_snow_with`). The mask +// value is the cover: 0 clear glass, up to 1 a pane closed by snow, above 1 the bank a blade +// pushed to the end of its sweep, below 0 glass a blade has just cleared. +fn is_snow_pane() -> bool { + return material.wipe_bounds.z != 0.0 && material.wipe_bounds.w < 0.0; +} + +// Smooth value noise (0..1) from the cell hash: the corners' values blended with a +// smoothstep, so it has no seams at the cell edges. +fn snow_noise(p: vec2) -> f32 { + let i = floor(p); + let f = p - i; + let u = f * f * (3.0 - 2.0 * f); + let a = rain_hash(i).x; + let b = rain_hash(i + vec2(1.0, 0.0)).x; + let c = rain_hash(i + vec2(0.0, 1.0)).x; + let d = rain_hash(i + vec2(1.0, 1.0)).x; + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); +} + +// By day in a downpour some of the houses' windows are lit, as people switch the light on when +// it gets that dark (`camera.wind.w` - 1: the share, `Lighting::rain_lights`, 0 with the +// setting off): the night maps of a few rooms here and there, chosen by a cell of the +// object's own frame some four metres wide and three high (`local`: the same rooms of a +// house stay lit, and a bus driving by does not flicker as it crosses cells of the world), +// each fading in at its own point of the rain. What a night map shows: the night's own +// strength or, where such a room is lit, the full light. +fn rain_lit_windows(local: vec3) -> f32 { + let night = clamp(camera.sun_color.w, 0.0, 1.0); + let share = clamp(camera.wind.w - 1.0, 0.0, 1.0); + if (share <= 0.0) { + return night; + } + let cell = floor(vec3(local.xy / 4.0, local.z / 3.0)); + let h = rain_hash(cell.xy + vec2(cell.z * 17.3, cell.z * 5.1)); + // (some a third of the rooms at the heaviest rain) + let lit = smoothstep(h.x, h.x + 0.08, share * 0.38); + return max(night, lit * (0.75 + 0.25 * h.y)); +} +fn rain_hash(p: vec2) -> vec2 { + // Integer mixing keeps neighbouring cells independent without the precision loss and + // repeated sine evaluations of a floating-point hash. + let cell = bitcast>(vec2(floor(p))); + var a = cell.x * 0x9e3779b9u ^ cell.y * 0x85ebca6bu; + a = (a ^ (a >> 16u)) * 0x7feb352du; + a = (a ^ (a >> 15u)) * 0x846ca68bu; + a = a ^ (a >> 16u); + var b = a ^ 0x68bc21ebu; + b = (b ^ (b >> 16u)) * 0x7feb352du; + b = (b ^ (b >> 15u)) * 0x846ca68bu; + b = b ^ (b >> 16u); + return vec2(f32(a), f32(b)) * (1.0 / 4294967296.0); +} + +// Smooth noise for water-film refraction and residual wiper streaks (0..1). +fn rain_patches(q: vec2) -> vec2 { + let c = floor(q); + let f = q - c; + let w = f * f * (3.0 - 2.0 * f); + let a = rain_hash(c); + let b = rain_hash(c + vec2(1.0, 0.0)); + let d = rain_hash(c + vec2(0.0, 1.0)); + let e = rain_hash(c + vec2(1.0, 1.0)); + return mix(mix(a, b, w.x), mix(d, e, w.x), w.y); +} + +// A grid of its own for each layer of drops: turned by its own angle and shifted, so that +// no two layers line up and none runs along the glass's edges. +fn rain_turn(q: vec2, a: f32) -> vec2 { + let cs = vec2(cos(a), sin(a)); + return vec2(q.x * cs.x - q.y * cs.y, q.x * cs.y + q.y * cs.x); +} + +// What a drop shows in the classic picture: the sky from the weather's colours, the +// horizon in the fog's, the ground darker. +fn rain_env_vanilla(d: vec3) -> vec3 { + let zenith = camera.sky_color.rgb + camera.ambient.rgb * 0.5; + let horizon = max(camera.fog.rgb, camera.ambient.rgb); + let ground = camera.ambient.rgb * 0.4 + camera.sun_color.rgb * camera.sun_dir.w * 0.06; + let sky = mix(horizon, zenith, smoothstep(0.0, 0.5, d.z)); + let c = mix(ground, sky, smoothstep(-0.06, 0.04, d.z)); + return select(c, srgb_decode(c), camera.sky_color.w > 0.5); +} + +// --- The rain on a pane as all the pictures draw it (the enhanced film, enhanced/07_glass.wgsl +// `glass_film`, and the classic one, scene/09_vanilla.wgsl `glass_film_classic`): the drops laid +// out in the vehicle's own frame (`FsIn.local`), so they stay on the glass however the body +// rolls and pitches and on a door that swings open. The modellers' texture coordinates of a +// film are no measure of the glass: on the windscreen of the NL202 they run half as fast +// again one way as the other and at sixty degrees to each other, from triangle to triangle +// anew, and every drop drawn in them came out a slanting streak (the classic pictures' old +// `rain_glass` did, and was replaced by this). So a pane is laid flat by the axes of the +// vehicle (`pane_proj`). + +// The glass at a pixel: the position and the flat normal in the vehicle's frame, the +// normal on the rain's side in the world, the pixel's footprint on the glass (m, its longer +// side and the side of a square of its area), and the screen derivatives of both positions. +struct PaneBase { + l: vec3, + nl: vec3, + out: vec3, + px: f32, + px_area: f32, + dlx: vec3, + dly: vec3, + dwx: vec3, + dwy: vec3, + ok: bool, +}; + +fn pane_base(world: vec3, local: vec3, n: vec3, outside_in: bool) -> PaneBase { + var b: PaneBase; + b.l = local; + b.dlx = dpdx(local); + b.dly = dpdy(local); + b.dwx = dpdx(world); + b.dwy = dpdy(world); + // the film faces the eye unless the eye is in the bus behind it (the triangle's own + // normal: a film mesh's vertex normals are not to be relied on, many have none, and + // the drops' size followed their noise) + let eye = normalize(camera.cam_pos.xyz - world); + let gn = cross(b.dwx, b.dwy); + var out = select(safe_normal(n), gn / max(length(gn), 1e-20), dot(gn, gn) > 1e-24); + out = select(-out, out, dot(out, eye) >= 0.0); + out = select(out, -out, outside_in); + b.out = out; + b.px = max(max(length(b.dwx), length(b.dwy)), 1e-5); + b.px_area = max(sqrt(length(cross(b.dwx, b.dwy))), 1e-5); + let c = cross(b.dlx, b.dly); + let cl = length(c); + b.ok = cl > 1e-12; + b.nl = select(vec3(0.0, 1.0, 0.0), c / max(cl, 1e-20), b.ok); + return b; +} + +// A direction on the glass in the vehicle's frame, in the world (through the two positions' +// screen derivatives). +fn pane_to_world(b: PaneBase, t: vec3) -> vec3 { + let g = vec3(dot(b.dlx, b.dlx), dot(b.dlx, b.dly), dot(b.dly, b.dly)); + let det = g.x * g.z - g.y * g.y; + if (abs(det) < 1e-24) { + return vec3(0.0); + } + let r = vec2(dot(b.dlx, t), dot(b.dly, t)); + let a = (g.z * r.x - g.y * r.y) / det; + let c = (g.x * r.y - g.y * r.x) / det; + return a * b.dwx + c * b.dwy; +} + +// The pane laid flat along two of the vehicle's axes (`axis`: 0 across and up, the +// windscreen and the rear window; 1 along and up, the side windows; 2 the plan, a roof +// light): where the pixel is (m: x across, y down), how an offset there is taken back onto +// the glass (`m`: metres along `side_w` and `down_w`, the glass's own across and down in +// the world), and the projection's screen derivatives (for the wiper's ridge). +struct PaneProj { + q: vec2, + m: mat2x2, + side_w: vec3, + down_w: vec3, + dqx: vec2, + dqy: vec2, + steep: bool, +}; + +fn pane_proj(b: PaneBase, axis: i32) -> PaneProj { + var p: PaneProj; + var ea = vec3(1.0, 0.0, 0.0); + var eb = vec3(0.0, 0.0, -1.0); + var ec = vec3(0.0, 1.0, 0.0); + if (axis == 1) { + ea = vec3(0.0, 1.0, 0.0); + ec = vec3(1.0, 0.0, 0.0); + } else if (axis == 2) { + eb = vec3(0.0, 1.0, 0.0); + ec = vec3(0.0, 0.0, 1.0); + } + let nl = b.nl; + let nc = dot(nl, ec); + let ncs = select(nc, select(-1e-3, 1e-3, nc >= 0.0), abs(nc) < 1e-3); + p.q = vec2(dot(b.l, ea), dot(b.l, eb)); + p.dqx = vec2(dot(b.dlx, ea), dot(b.dlx, eb)); + p.dqy = vec2(dot(b.dly, ea), dot(b.dly, eb)); + // the glass under a step of the projection's two axes + let t1 = ea - ec * (dot(nl, ea) / ncs); + let t2 = eb - ec * (dot(nl, eb) / ncs); + // the glass's own down (the steepest way on it) and across, in the vehicle's frame + p.steep = axis != 2; + var dl = vec3(0.0, 0.0, -1.0) + nl * nl.z; + dl = select(normalize(t2), dl / max(length(dl), 1e-6), dot(dl, dl) > 0.02 && p.steep); + var sl = t1 - dl * dot(t1, dl); + sl = sl / max(length(sl), 1e-6); + p.m = mat2x2(vec2(dot(t1, sl), dot(t1, dl)), vec2(dot(t2, sl), dot(t2, dl))); + // the same two ways in the world, square to the normal on the rain's side + var sw = pane_to_world(b, sl); + sw = sw - b.out * dot(sw, b.out); + var dw = pane_to_world(b, dl); + dw = dw - b.out * dot(dw, b.out); + p.side_w = sw / max(length(sw), 1e-6); + dw = dw - p.side_w * dot(dw, p.side_w); + p.down_w = dw / max(length(dw), 1e-6); + return p; +} + +// The water on a pane at a pixel: the surface's normal (world, out of the water), how much +// of the pixel a drop or a bead covers and how far out on it the pixel lies (0 its middle, +// 1 its rim), the drop's radius in pixels, the pane's normal on the rain's side, the fine +// mist of droplets under a millimetre, and how much of the view through the pane the +// connected water scatters into a soft blur (`veil`). +struct GlassWater { + n: vec3, + cover: f32, + out: vec3, + mist: f32, + veil: f32, + rim: f32, + size_px: f32, +}; + +// One drop of radius `r` (m) at `d` (m on the glass, across / down): the slope of its dome +// (the normal's part along the glass), its cover of the pixel (`px`: the pixel's size on +// the glass) and how far out on it the pixel lies. A shallow cap, as water spreading on +// glass makes; a drop smaller than the pixel keeps its share of it, its slopes flattened +// to their average. +fn glass_dome(d: vec2, r: f32, px: f32) -> vec4 { + let rr = length(d) / max(r, 1e-6); + let aa = clamp(px / max(r, 1e-6), 0.02, 1.0); + let cover = 1.0 - smoothstep(1.0 - aa, 1.0 + aa, rr); + let seen = smoothstep(0.0, 0.8, r / px); + let cap = mix(0.15, 0.55, smoothstep(0.7, 2.5, r / px)); + let s = d / max(r, 1e-6) * cap * (0.6 + 0.4 * rr * rr); + return vec4(s, cover * seen, min(rr, 1.0)); +} + +// What covers the pixel, gathered over the layers: the cover, the slope, the rim and the +// drop's size in pixels of the drop on top. +struct DropAcc { + cover: f32, + slope: vec2, + rim: f32, + size_px: f32, + track: f32, + // the cover of the drops too small for the pixel to see one by one, as their average + // (taken into the mist, so that they read as an even haze, not as random specks) + avg: f32, +}; + +fn drop_take(a: ptr, d: vec4, r: f32, px: f32) { + if (d.z > (*a).cover) { + (*a).cover = d.z; + (*a).slope = d.xy; + (*a).rim = d.w; + (*a).size_px = r / px; + } +} + +// One layer of the drops that sit on the glass: a jittered grid of cells `cell` metres +// wide (of the projection), each holding a drop now and then (`occ` the share of cells +// that hold one). A drop lands, spreads to its size within a moment and sits; after its +// own while it is gone again, taken by a runner or merged into a neighbour, and the next +// lands somewhere else in the cell - all fading, nothing popping. +fn glass_bead(a: ptr, p: PaneProj, layer: f32, cell: f32, occ: f32, r0: f32, size: f32, t: f32, px: f32) { + // (a layer whose drops are smaller than the pixel, or cells no wider than it - a mirror's + // small picture, the glass seen from afar - is taken at its average cover: sampled one + // random cell a pixel, it drew white noise) + let fine = max(1.0 - smoothstep(0.7, 1.5, r0 * size / px), 1.0 - smoothstep(1.0, 2.5, cell / px)); + if (fine > 0.0) { + let rr = 1.6 * r0 * size / cell; + (*a).avg = (*a).avg + fine * occ * min(3.14159 * rr * rr, 1.0); + if (fine > 0.99) { + return; + } + } + let turn = 0.61 + layer * 1.37; + let g2 = rain_turn(p.q, turn) / cell + vec2(layer * 17.3, layer * 5.1); + let c = floor(g2); + let timing = rain_hash(c + vec2(3.7, 9.2 + layer)); + let life = (9.0 + layer * 4.0) * (1.0 + timing.y); + let cycle = t / life + timing.x; + let ph = fract(cycle); + let arrival = c + floor(cycle) * vec2(17.0, 43.0); + let h = rain_hash(arrival); + // (a share of cells rising with the wetness: a drop fades in over a small rise of it) + let shown = clamp((occ - h.x) * 20.0, 0.0, 1.0) * smoothstep(0.0, 0.03, ph) * (1.0 - smoothstep(0.9, 1.0, ph)) * (1.0 - fine); + if (shown <= 0.0) { + return; + } + // (`r0` the layer's smallest drop, the largest twice that: rain on glass sits as drops of + // half a millimetre to four across - drawn up to a share of the cell they made drops of a + // centimetre and more, few and far between) + let radius = r0 * (1.0 + h.y * h.y) * mix(0.6, 1.0, smoothstep(0.0, 0.2, ph)) * size; + // (anywhere in the cell the largest still fits in - on the glass it is never smaller + // than in the projection - and the same place whatever its size: the size follows the + // wetness, which changes across the glass) + let room = min(r0 * 3.0 / cell, 0.45); + let centre = c + vec2(room) + rain_hash(arrival + 9.1) * (1.0 - 2.0 * room); + let dq = rain_turn((g2 - centre) * cell, -turn); + if (length(dq) > radius * 1.3) { + return; + } + var d = p.m * dq; + // No drop is a circle: its rim wanders where the glass held it as it spread, and its + // weight draws it a little fuller below than above. + let h3 = rain_hash(arrival + 23.9); + let dl = max(length(d), 1e-7); + let u = d / dl; + let c2 = u.x * u.x - u.y * u.y; + let s2 = 2.0 * u.x * u.y; + let c3 = u.x * (4.0 * u.x * u.x - 3.0); + let s3 = u.y * (3.0 - 4.0 * u.y * u.y); + let p2 = h3 * 2.0 - 1.0; + let wave = (s2 * p2.x + c2 * p2.y) * 0.7 + 0.45 * (s3 * p2.y - c3 * p2.x); + d = d / (1.0 + (0.03 + 0.05 * h.y) * wave); + d.y = d.y * select(1.06, 0.94, d.y > 0.0); + let dome = glass_dome(d, radius, px); + drop_take(a, vec4(dome.xy, dome.z * shown, dome.w), radius, px); +} + +// A runner's sideways wander as it goes down (m): a smooth random path of its own. +fn glass_meander(s: f32, seed: vec2, amp: f32) -> f32 { + let w = rain_patches(vec2(s * 9.0 + seed.x, seed.y)); + return amp * ((w.x - 0.5) * 1.5 + (w.y - 0.5) * 0.5); +} + +// The runners in a lattice of lanes (`qr`: the projection turned so they run down +y, `mr` +// taking its offsets onto the glass): now and then a drop grown heavy breaks loose and +// slides a hand's breadth or two down, in fits and starts, wandering a little from side to +// side, and stops again. It sweeps a narrow clear track through the small drops, which +// fill in again as the rain falls on it; behind it lies a short wet trail that drains +// within a second, and a few beads it left. One chance a cell of 4.5 cm x 1.2 m; a pixel +// looks at its own cell and the one above, whose drop may have slid into it. +fn glass_runners(a: ptr, qr: vec2, mr: mat2x2, seed: f32, wet: f32, heavy: f32, blow: f32, size: f32, t: f32, px: f32) { + // (lanes of 4.5 cm and cells 1.2 m tall, few of them running at once: with lanes of 2 cm + // and cells of 0.8 m nearly every lane ran in a downpour, and their tracks cut the glass + // into wide clear stripes, #4153) + let lane_w = 0.045; + let seg_h = 1.2; + let lane = floor(qr.x / lane_w); + let seg0 = floor(qr.y / seg_h); + for (var k = 0; k < 2; k = k + 1) { + let seg = seg0 - f32(k); + let key = vec2(lane * 1.7 + seed * 101.0, seg * 2.3 + seed * 37.0); + let h1 = rain_hash(key + vec2(3.0, 11.0)); + if (h1.x >= wet * (0.15 + 0.15 * heavy + 0.1 * blow)) { + continue; + } + let h2 = rain_hash(key + vec2(8.1, 5.1)); + // (it gathers a while, runs, and its trail fills in with new rain) + // (a drop grown heavy on upright glass runs off at some ten to twenty centimetres a + // second, most of the way down the pane) + let sit = 0.6 + 2.4 * h2.y; + let v = (0.08 + 0.16 * h1.y * h1.y) * (1.0 + 0.8 * blow) * (1.0 + 0.4 * heavy); + let run_len = 0.12 + 0.4 * h2.x; + let run_t = run_len / v; + let refill = mix(3.0, 1.5, wet); + let period = sit + run_t + refill; + let cycle = t / period + h2.x; + let tau = fract(cycle) * period; + let h3 = rain_hash(key + vec2(1.3, 29.7) + floor(cycle) * vec2(13.0, 41.0)); + // stick and slip: v s - v P / 2 pi sin(2 pi s / P) halts once a pulse P + let pulse = 0.3 + 0.4 * h3.x; + let st = clamp(tau - sit, 0.0, run_t * 1.05); + let travel = min(v * st - v * pulse * 0.1591549 * sin(6.283185 * st / pulse), run_len); + let vis = smoothstep(0.0, 0.6, tau) * (1.0 - smoothstep(period - 1.0, period, tau)); + let y0 = (seg + 0.02 + 0.32 * h3.x) * seg_h; + let x0 = (lane + 0.3 + 0.4 * h3.y) * lane_w; + let wseed = h3 * 57.0; + let amp = 0.002 + 0.002 * h2.y; + if (abs(qr.x - x0) > lane_w * 0.5 + amp * 1.5 || qr.y < y0 - 0.01 || qr.y > y0 + run_len + 0.01) { + continue; + } + // (a downpour's runners are heavier; a drop gathers before it goes) + let rh = size * (0.0012 + 0.0008 * h1.y) * (1.0 + 0.3 * heavy) * mix(0.6, 1.0, smoothstep(0.0, sit, tau)); + var head_d = mr * vec2(qr.x - (x0 + glass_meander(travel, wseed, amp)), qr.y - (y0 + travel)); + // (drawn out a little behind, full in front) + head_d.y = head_d.y * select(0.8, 1.0, head_d.y > 0.0); + let head = glass_dome(head_d, rh, px); + // (once stopped it sits at the end of its run and is taken into the new rain) + let head_vis = vis * (1.0 - smoothstep(sit + run_t, sit + run_t + refill * 0.8, tau)); + drop_take(a, vec4(head.xy, head.z * head_vis, head.w), rh, px); + let along = qr.y - y0; + if (along > 0.0 && along < travel - rh * 0.5) { + let dxq = qr.x - (x0 + glass_meander(along, wseed, amp)); + let dx = (mr * vec2(dxq, 0.0)).x; + // how long ago the head passed here + let age = max(tau - sit - along / v, 0.0); + let hw = rh * 0.9; + let cleared = (1.0 - smoothstep(hw * 0.6, hw * 1.1, abs(dx))) * (1.0 - smoothstep(refill * 0.4, refill, age)) * vis; + (*a).track = max((*a).track, cleared); + // the thin wet trail it draws, draining within a second: a faint lens, no strip + let tw = rh * 0.45 * exp(-age * 2.0); + let trail = glass_dome(vec2(dx, 0.0), max(tw, 1e-5), px); + let trail_cover = trail.z * 0.35 * (1.0 - smoothstep(0.2, 1.0, age)) * vis; + drop_take(a, vec4(trail.xy * 0.4, trail_cover, trail.w), tw, px); + // ... and a few beads, left behind where the trail broke + let bc = floor(along / 0.009); + let bh = rain_hash(vec2(lane * 3.1 + bc, seg * 1.9 + 41.0 + seed * 7.0)); + if (bh.x < 0.3) { + let bcen = vec2((bh.y - 0.5) * hw * 0.8, ((bc + 0.5) * 0.009 - along) * (mr * vec2(0.0, 1.0)).y); + let br = 0.0004 + 0.0005 * bh.y; + let bead = glass_dome(vec2(dx, 0.0) - bcen, br, px); + let bead_cover = bead.z * smoothstep(0.4, 1.0, age) * (1.0 - smoothstep(refill * 0.5, refill, age)) * vis; + drop_take(a, vec4(bead.xy, bead_cover, bead.w), br, px); + } + } + } +} + +// The drops on one projection of the pane (`w` its share, see `glass_water`). +fn glass_drops(a: ptr, b: PaneBase, p: PaneProj, w: f32, wet: f32, heavy: f32, bank: f32, size: f32, world: vec3, t: f32) { + // --- the airstream: a drop's drag grows with the speed squared, and at some 40 km/h it + // matches its weight. Along the glass the air drives the water back; where it meets the + // glass head on (the windscreen) it parts, up and out. The runners go where weight and + // air take them together; the drops that sit hold on. + var flow = vec2(0.0, 1.0); + var blow = 0.0; + if (camera.wind.w > 0.5 && near_player_vehicle(world) > 0.5) { + let air = -camera.wind.xyz; + var aw = vec2(dot(air, p.side_w), dot(air, p.down_w)); + aw.y = aw.y - abs(dot(air, b.out)) * 0.6; + let v2 = dot(aw, aw); + blow = clamp(v2 / 130.0, 0.0, 3.0); + flow = flow + aw / max(sqrt(v2), 1e-4) * blow; + } + if (p.steep) { + // The runners' lanes are laid along the way the water runs, in sixteenths of a turn + // (turned freely, a degree moved every lane a metre off by its width). Between two + // such ways the two lattices cross-fade, so a change of speed fades the runners + // over instead of jumping them. (`flow` is on the glass; the lanes in the + // projection, whose down is the glass's down.) + let fstep = 0.3926991; + let fa = atan2(flow.x, flow.y) / fstep; + let f0 = floor(fa); + let fw = smoothstep(0.35, 0.65, fa - f0); + for (var k = 0; k < 2; k = k + 1) { + let wk = select(1.0 - fw, fw, k == 1) * w; + if (wk < 0.01) { + continue; + } + let ang = (f0 + f32(k)) * fstep; + let cs = vec2(cos(ang), sin(ang)); + let mr = p.m * mat2x2(vec2(cs.x, -cs.y), vec2(cs.y, cs.x)); + glass_runners(a, rain_turn(p.q, ang), mr, f0 + f32(k), wet * wk, heavy, blow, size, t, b.px_area); + } + } + // --- the drops that sit: four sizes, a great many small ones and fewer large ones (radius + // 1 to 2, 1.6 to 3.2, 2.4 to 4.8 and 3.4 to 6.8 mm: smaller ones, true to a drizzle's, + // were under a pixel from the driver's seat and drew the windscreen as an even grain), + // all fewer in the runners' fresh + // tracks and under the bank + let room = (1.0 - (*a).track) * (1.0 - bank) * w; + for (var layer = 0; layer < 4; layer = layer + 1) { + let fl = f32(layer); + var cell = 0.0068; + var r0 = 0.001; + var occ = 0.85 * smoothstep(0.02, 0.25, wet); + if (layer == 1) { + cell = 0.0108; + r0 = 0.0016; + occ = 0.75 * smoothstep(0.05, 0.4, wet); + } else if (layer == 2) { + cell = 0.016; + r0 = 0.0024; + occ = 0.6 * smoothstep(0.15, 0.6, wet); + } else if (layer == 3) { + cell = 0.023; + r0 = 0.0034; + occ = 0.4 * smoothstep(0.35, 0.9, wet); + } + glass_bead(a, p, fl, cell, occ * room, r0, size, t, b.px_area); + } +} + +// The rain on a pane at a pixel (see the head of this file). `water` is the pane's +// wetness (0..1; below 0 a blade has just wiped it, above 1 the bank a blade pushed), +// `t` the animation clock, `outside_in` true for the eye in the bus. +fn glass_water(world: vec3, local: vec3, n: vec3, water: f32, t: f32, outside_in: bool) -> GlassWater { + let b = pane_base(world, local, n, outside_in); + let wdx = dpdx(water); + let wdy = dpdy(water); + var g: GlassWater; + g.n = b.out; + g.out = b.out; + g.cover = 0.0; + g.mist = 0.0; + g.veil = 0.0; + g.rim = 0.0; + g.size_px = 0.0; + let wet = clamp(water, 0.0, 1.0); + let wiped = clamp(-water * 25.0, 0.0, 1.0); + let bank = clamp((water - 1.0) * 0.18, 0.0, 1.0); + if (!b.ok || (wet <= 0.01 && wiped <= 0.01 && bank <= 0.0)) { + return g; + } + // Which way the pane is laid flat: by the larger of its normal's parts across and along + // the vehicle, the two cross-faded over a band round 45 degrees (a windscreen's curved + // corner), each drop of either set coming or going whole; a pane facing up is a roof's. + let an = abs(b.nl); + let roof = an.z > max(an.x, an.y) * 2.0; + let w_front = select(smoothstep(-0.12, 0.12, an.y - an.x), 1.0, roof); + let main_axis = select(select(1, 0, w_front >= 0.5), 2, roof); + let p = pane_proj(b, main_axis); + // the wetness's gradient on the glass (from its screen derivatives) + let jd = p.dqx.x * p.dqy.y - p.dqx.y * p.dqy.x; + var grad = vec2(0.0); + if (abs(jd) > 1e-14) { + grad = vec2(wdx * p.dqy.y - wdy * p.dqx.y, wdy * p.dqx.x - wdx * p.dqy.x) / jd; + } + if (wiped > 0.01) { + // Just wiped: fine streaks along the blade's sweep (the age gradient follows it) + // bend the view for a moment, without bringing the drops back. + var along = vec2(0.0, 1.0); + if (length(grad) > 0.01) { + along = normalize(grad); + } + let across = vec2(-along.y, along.x); + let streak = rain_patches(vec2(dot(p.q, across) * 600.0, dot(p.q, along) * 4.0)); + g.cover = wiped * (0.012 + 0.018 * streak.x); + g.veil = wiped * 0.06; + g.size_px = 4.0; + g.n = normalize(b.out + (p.side_w * across.x + p.down_w * across.y) * (streak.y - 0.5) * wiped * 0.003); + return g; + } + let heavy = smoothstep(0.55, 1.0, wet); + // (a drizzle leaves beads, a downpour full drops; on an upright side pane, which the rain + // meets edge on and the airstream sweeps, they stay smaller than on a raked windscreen) + let size = mix(0.85, 1.1, smoothstep(0.1, 0.8, wet)) * mix(0.8, 1.0, smoothstep(0.0, 0.4, abs(b.out.z))); + var acc: DropAcc; + acc.cover = 0.0; + acc.slope = vec2(0.0); + acc.rim = 0.0; + acc.size_px = 0.0; + acc.track = 0.0; + acc.avg = 0.0; + // the bank a blade pushed: its ridge bends the view + if (bank > 0.0) { + acc.cover = bank; + acc.slope = clamp(-0.00005 * grad, vec2(-0.15), vec2(0.15)) * bank; + acc.size_px = 8.0; + } + let w_main = select(select(1.0 - w_front, w_front, main_axis == 0), 1.0, roof); + glass_drops(&acc, b, p, w_main, wet, heavy, bank, size, world, t); + var side_w = p.side_w; + var down_w = p.down_w; + if (w_main < 0.99) { + let p2 = pane_proj(b, 1 - main_axis); + glass_drops(&acc, b, p2, 1.0 - w_main, wet, heavy, bank, size, world, t); + } + // --- the mist: droplets of a millimetre and less, too many to draw one by one far off + var grain = 0.0; + { + let mg = rain_turn(p.q, 0.33) / 0.0024; + let mc = floor(mg); + let mh = rain_hash(mc + 71.0); + let mr = 0.1 + 0.16 * mh.y; + let at = mc + vec2(mr) + rain_hash(mc + 5.3) * (1.0 - 2.0 * mr); + grain = step(mh.x, wet * 0.3) * (1.0 - smoothstep(mr * 0.6, mr, length(mg - at))); + } + // (seen from further than a millimetre a pixel: their average) + let mist = mix(wet * 0.3 * 0.12, grain, smoothstep(0.0015, 0.0006, b.px)); + g.mist = clamp((mist + 0.6 * acc.avg) * (1.0 - acc.track), 0.0, 1.0); + // The connected water between the drops scatters some of the view into a soft haze + // (the veil, drawn from the picture's blurred levels), the same on every pane as wet. + // A runner's fresh track is a clear sheet of water, sharper than the rest. + let film = smoothstep(0.03, 0.4, wet) * (1.0 - 0.3 * acc.track); + // (by the air's temperature, `camera.lod.w`: on cold glass the water spreads into a film + // and a fine mist of droplets that scatter the view - near freezing the sleet's slush on + // top - while in a warm summer rain it beads up and runs off, the glass between the drops + // nearly clear) + let cold = 1.0 - smoothstep(2.0, 24.0, camera.lod.w); + // (light: a strong veil hid the drops behind a uniform fog) + g.veil = film * mix(0.12, 0.25, heavy) * mix(0.7, 1.2, cold); + g.cover = acc.cover; + g.rim = acc.rim; + g.size_px = acc.size_px; + let slope = acc.slope; + let nz = sqrt(max(1.0 - dot(slope, slope), 0.02)); + g.n = normalize(b.out * nz + side_w * slope.x + down_w * slope.y); + return g; +} + +// The picture behind the glass (`glass_mips.rs`, pre-exposed radiance) at `uv`, blurred to +// level `lod`: five reads round the point a texel of that level apart, so the small levels' +// texels do not show as blocks when they are spread over many pixels. +fn glass_blur(uv: vec2, lod: f32) -> vec3 { + let dims = vec2(textureDimensions(mx_tex2d[mx_mat.env])); + let o = exp2(lod) * 0.75 / dims; + let c = clamp(uv, vec2(0.001), vec2(0.999)); + var s = textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], c, lod).rgb * 2.0; + s = s + textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], clamp(c + vec2(o.x, o.y * 0.5), vec2(0.001), vec2(0.999)), lod).rgb; + s = s + textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], clamp(c + vec2(-o.x * 0.5, o.y), vec2(0.001), vec2(0.999)), lod).rgb; + s = s + textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], clamp(c + vec2(-o.x, -o.y * 0.5), vec2(0.001), vec2(0.999)), lod).rgb; + s = s + textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], clamp(c + vec2(o.x * 0.5, -o.y), vec2(0.001), vec2(0.999)), lod).rgb; + return s / 6.0; +} + +// The snow a wiped pane holds while it snows (see enhanced/07_glass.wgsl `glass_snow`): +// `defrost` how far the windscreen's defroster has cleared it (0..0.85), `fz` the height on +// the glass in the bus's frame (-1 its bottom, 1 its top), for the drift along the bottom. +fn glass_snow_with(in: FsIn, cover: f32, defrost: f32, fz: f32) -> vec4 { + if (cover <= 0.0) { + return vec4(1.0, 1.0, 1.0, 0.0); + } + // (laid out on the glass as the drops are, `pane_proj`: the film's own coordinates + // drew the crystals and the drifts out long on the windscreen) + let b = pane_base(in.world, in.local, in.normal, false); + let an = abs(b.nl); + let axis = select(select(1, 0, an.y >= an.x), 2, an.z > max(an.x, an.y) * 2.0); + let m = pane_proj(b, axis).q; + let t = camera.post.y; + let front = material.wipe_bounds.z > 0.0; + let heat = select(0.15, 0.45 + 0.55 * clamp(defrost / 0.85, 0.0, 1.0), front); + var flakes = 0.0; + var melt_water = 0.0; + for (var layer = 0; layer < 2; layer = layer + 1) { + let fl = f32(layer); + let cell = select(0.012, 0.022, layer == 1); + let p = m / cell + fl * 37.0; + let c = floor(p); + let tm = rain_hash(c + vec2(5.0, 1.0 + fl)); + let life = mix(40.0, 7.0, heat) * (0.6 + 0.8 * tm.y); + let cycle = t / life + tm.x; + let ph = fract(cycle); + let arrival = c + floor(cycle) * vec2(19.0, 47.0); + let h = rain_hash(arrival); + let h2 = rain_hash(arrival + vec2(91.0, 13.0)); + // (a crystal shows once the cover passes its own threshold: they come one by one) + let shown = clamp((cover * select(1.15, 0.85, layer == 1) - h2.y) * 12.0, 0.0, 1.0) * smoothstep(0.0, 0.02, ph); + // the second half of its while it melts: it rounds off, shrinks and goes clear + let melt = smoothstep(0.45, 0.95, ph); + let d = p - (c + 0.25 + 0.5 * h); + let dl = length(d); + let r = (0.16 + 0.2 * h2.x) * (1.0 - 0.5 * melt); + // six arms, the rim reaching out along them + let arm = pow(abs(cos(3.0 * atan2(d.y, d.x) + h.x * 6.283185)), 4.0); + let rr = r * (0.55 + 0.45 * mix(arm, 1.0, melt)); + let edge = 1.0 - smoothstep(rr * 0.7, rr, dl); + flakes = max(flakes, shown * edge * (0.6 + 0.4 * h.x) * (1.0 - melt)); + melt_water = max(melt_water, shown * edge * melt * (1.0 - smoothstep(0.92, 1.0, ph))); + } + // settled snow is never even: a smooth noise of a few centimetres and a finer one break + // up where the layer closes and give the bank and the drifts their ragged edges + let lumps = snow_noise(m / 0.045) * 0.65 + snow_noise(m / 0.012 + 7.0) * 0.35; + var drift = 0.0; + if (front) { + // (by the height in the bus's own frame, not by the wiper mask's `wipe_uv`: a + // windscreen's film is several slots - each wiper's field and the glass round them - + // each with its own mask and its own 0 .. 1, and a bank laid along their edges drew + // seams down the middle of the windscreen and round the wipers' arcs) + if (camera.inside_c.w > 0.5) { + let low = 1.0 - (fz * 0.5 + 0.5); + drift = smoothstep(0.5, 0.75, low + 0.12 * (lumps - 0.5)) * smoothstep(0.1, 0.6, cover); + } + } + let c = cover * (0.7 + 0.6 * lumps) * (1.0 - 0.3 * heat) + drift * 0.9; + let sheet = smoothstep(0.5, 1.2, c) * 0.75 + smoothstep(1.0, 1.7, c) * 0.22; + let white = mix(vec3(0.9, 0.92, 0.96), vec3(0.97, 0.98, 1.0), smoothstep(1.0, 1.8, c)); + let solid = max(flakes * 0.92, sheet); + // (the melt water: a faint clear bead, the street a shade darker through it) + let wet = melt_water * 0.16 * (1.0 - solid); + let alpha = clamp(solid + wet, 0.0, 0.97); + let col = (white * solid + vec3(0.5, 0.55, 0.6) * wet) / max(solid + wet, 1e-4); + return vec4(col, alpha); +} + +// The rain on a pane that has no film of its own to carry it (`glass_film`): the windows of +// the traffic's cars and buses, seen from the street. OMSI gives only some buses a rain film, +// and only the player's own wets it, so every other window stayed dry and clear in a downpour. +// The same drops and runners (`glass_water`), as wet as the roads (`camera.shadow.w`); none +// on the player's own bus, whose films carry its rain. +fn pane_rain(world: vec3, local: vec3, n: vec3) -> GlassWater { + let wet = clamp(camera.shadow.w * 1.3, 0.0, 1.0); + let own = near_player_vehicle(world) > 0.5; + let far = distance(world, camera.cam_pos.xyz) > 80.0; + let w = select(wet, 0.0, own || far); + return glass_water(world, local, n, w, camera.post.y, false); +} + +// The pane's colour `rgb` and cover `a` under that rain (`vn` towards the eye): the drops, +// small lenses darker than the glass round them with the sky mirrored on their domes +// (`refl`, what the dome mirrors), and between them the wet film, a little milky +// (`haze`, the daylight it scatters) and less see-through. +fn pane_rain_compose(g: GlassWater, rgb: vec3, a: f32, vn: vec3, refl: vec3, haze: vec3) -> vec4 { + let cosv = clamp(abs(dot(g.n, vn)), 0.0, 1.0); + let f = 0.02 + 0.98 * pow(1.0 - cosv, 5.0); + let drop = mix(rgb * 0.7, refl, clamp(f * 3.0, 0.15, 0.8)); + var c = mix(rgb, drop, g.cover * 0.85); + let film = clamp(g.veil * 0.35 + g.mist * 0.2, 0.0, 0.5); + c = mix(c, haze, film); + let a2 = clamp(a + (1.0 - a) * (g.cover * 0.5 + film), a, 1.0); + return vec4(c, a2); +} + +@fragment +fn fs_main(in: FsIn) -> @location(0) vec4 { + var unused = 0.0; + return shade_vanilla(in, &unused, camera.cam_pos.xyz); +} + +// Shared with Enhanced and the wheel splash mask: pools spread as the road soaks. +fn road_puddle_coverage(world: vec3, normal: vec3, wet: f32) -> f32 { + let xy = world_pattern_xy(world); + let pn = vnoise_f(xy, 0.35, vec2(17.3, -9.1)) * 0.6 + + vnoise_f(xy, 1.6, vec2(-4.0, 8.0)) * 0.3 + + vnoise_f(xy, 5.0, vec2(2.7, 11.3)) * 0.1; + // The pools spread from the lowest spots as the road soaks, but they stay pools: a road + // wet through has standing water on about a fifth of it (PUDDLE_SPREAD in enhanced.wgsl, + // the same in `omsi-app/src/puddles.rs`) and wet asphalt between. + let threshold = 1.0 - wet * PUDDLE_SPREAD; + return smoothstep(threshold - 0.02, threshold + 0.02, pn) * smoothstep(0.75, 0.95, normal.z); +} + +@fragment +fn fs_vanilla_reflections(in: FsIn) -> EnhancedOut { + var weight = 0.0; + let c = shade_vanilla(in, &weight, camera.cam_pos.xyz); + let coverage = select(c.a, 0.0, in.params2.w > 1.5); + var out: EnhancedOut; + out.color = c; + out.mask = vec4(0.0, weight * 0.49, weight, coverage); + return out; +} + +fn shade_vanilla(in: FsIn, puddle_weight: ptr, eye: vec3) -> vec4 { + // (the pane's water, read once for the uses below) + let film_water = window_wetness(in); + if (material.emissive.w > 1.5) { + // a pane's film of water: drops, not the sliding texture (`glass_film_classic`) + return glass_film_classic(in, film_water); + } + var duv = tex_address(in.uv); + if (material.extra.x > 0.5) { + // terrain: uv is tile space; the ground texture repeats extra.z times per tile + duv = in.uv * material.extra.z; + } + var tex = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv); + if (is_snow_pane()) { + // (as the enhanced picture lays it, `glass_snow_with`: no cabin air here, so no + // defroster, and the height on the glass by the bus's level frame) + let fz = clamp((in.world.z - camera.inside_a.z - camera.inside_c.z) / max(camera.inside_b.w, 0.1), -1.0, 1.0); + tex = glass_snow_with(in, film_water, 0.0, fz); + } + // The texture coordinates without the [texcoordtransX/Y] offset: in Omsi.exe's + // fixed-function pipeline the texture transform is the diffuse stage's alone, the + // transmap, night map and light map stay in place under a scrolling roller blind. + let buv = tex_address(in.uv - in.params.zw); + if (material.extra.x > 0.5 && material.extra.y > 0.0) { + // the ground texture's detail texture, repeated finer than the texture itself and + // modulated over it as the original's terrain pass does. The stock detail maps are + // bright (noise_low averages 242, gras_det 179), so they are meant to be multiplied + // in plainly: doubling like a grey-centred D3D detail map blows the ground out. + let det = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], in.uv * material.extra.y, camera.lod.x); + tex = vec4(clamp(tex.rgb * det.rgb, vec3(0.0), vec3(1.0)), tex.a); + } + if (material.params.z > 0.5) { + // [matl_transmap]: alpha comes from a separate map, its alpha channel (a map without one + // is opaque, as D3D samples it: the WH UK AI cars' paint layer has a black 24-bit + // `transmap_null.tga`, read as luminance the paint was invisible); + // for terrain the map is the per-tile surface mask in tile space + let tm = sample_transmap(buv); + tex.a = select(1.0, tm.a, material.params.w > 0.5); + if (material.extra.x > 0.5 && material.params.x > 1.5) { + // A painted ground layer. The brush mask is coarse (0.6-3 m per texel) and + // binary; the loader smooths it into a soft ramp around a smooth curve + // (`smooth_paint_mask` in scene.rs). Sharpen only that coverage ramp: + // diffuse/detail mip colours change with viewing angle, and including + // their luminance made covered ground fade into lower layers at a slant. + tex.a = smoothstep(0.32, 0.68, tex.a); + } + } + // One night-map read supplies both coverage and lighting. Keep the tile map + // in its north-up UVs; vehicle maps use the unscrolled material UVs. + var night_sample = vec4(0.0); + if (material.extra.w > 0.5) { + let nuv = select(buv, vec2(in.uv.x, 1.0 - in.uv.y), material.extra.x > 0.5); + night_sample = sample_nightmap(nuv); + } + tex.a = night_coverage(tex.a, night_sample.a) * tree_card_fade(in.world); + let mode = material.params.x; + // Mip-filtered alpha is the fraction of the pixel covered by leaves or fence wires. + // Tighten the transition around the cutout edge before MSAA turns it into sample + // coverage. The depth prepass leaves these draws out so its binary cutoff cannot hide + // the scene behind samples that the colour pass leaves open. + if (ALPHA_TEST && mode > 0.5 && mode < 1.5) { + if (ALPHA_TO_COVERAGE) { + let aa = max(fwidth(tex.a) * 0.5, 1.0 / 255.0); + // (not `ALPHA_REF - aa`: a layer whose clear glass is alpha 128 kept a third of + // its samples there, a moire of the layer's paint over every window) + if (tex.a < ALPHA_REF) { + discard; + } + tex.a = smoothstep(ALPHA_REF - aa, ALPHA_REF + aa, tex.a); + } else if (tex.a < ALPHA_REF) { + discard; + } + } + // (a blended slot that keeps Omsi.exe's alpha test, `MaterialExtra::alpha_cut`: a + // livery's clear glass is cut away, its tinted glass blended) + tex.a = select(tex.a, 0.0, mode > 2.5 && tex.a < ALPHA_REF); + let n = safe_normal(in.normal); + let ndl = max(dot(n, camera.sun_dir.xyz), 0.0); + // three lights like the original: direct sun (A), light from above (B), ambient (C) + let from_above = 0.5 + 0.5 * n.z; + let shadow = sun_shadow(in.world, n, mode > 0.5 && mode < 1.5); + // screen-space ambient occlusion darkens the indirect light (sky and ambient) in + // corners, under the bus, between the seats - not the sun, which the shadow map handles + var ao = 1.0; + // (not on a blended surface: the AO is the opaque depth's, and a translucent door + // showed the shade of what stood behind it) + if (camera.clouds.w > 0.5 && mode < 1.5) { + ao = ao_at(in.clip.xy, in.world); + } + var diffuse = camera.sun_color.rgb * camera.sun_dir.w * ndl * shadow + (camera.sky_color.rgb * from_above * (0.6 + 0.4 * shadow) + camera.ambient.xyz) * ao; + var albedo = tex.rgb; + if (camera.flags.x > 0.5 && (material.extra.x > 0.5 || in.params2.w > 0.5)) { + // detail texturing (setting): procedural grain on the ground and the roads, fading out with distance + let dist0 = distance(in.world, camera.cam_pos.xyz); + let k = clamp(1.0 - (dist0 - 25.0) / 120.0, 0.0, 1.0); + let nz = detail_noise(world_pattern_xy(in.world), k); + albedo = albedo * (1.0 + (nz - 0.5) * 0.42 * k); + } + // ([nomaplighting]: params.y 0.25 - not lit by the map's lamps) + // (a light-mapped road or plate takes the map's lamps only in Vanilla+: as OMSI 2 shows + // it, the vanilla picture lights it from the tile light map alone) + let lm_only = light_map_mapped(material.params) && camera.sky_color.w > 0.5; + // (and a [tree]'s leaf cards, params.y 0.15: OMSI 2 leaves a tree dark even right under + // a street lamp, where the lamp's 40 m core lit the crown up yellow-green) + let tree_unlamped = camera.sky_color.w > 0.5 && material.params.y > 0.1 && material.params.y < 0.2; + let map_lamps = select(1.0, 0.0, (material.params.y > 0.2 && material.params.y < 0.3) || lm_only || tree_unlamped); + let lamp_light = point_lights(in.world, n, map_lamps); + // The headlight is lit at the vertices: see `classic_spot`. + var light = diffuse + lamp_light + in.spot_diffuse + in.spot_ambient; + // D3D lights the material's diffuse colour with the sun, the light from above and the + // lamps, and its ambient colour with the ambient light (C) and the headlight's ambient + // light. Omsi.exe makes every o3d slot's ambient white (0x7c62f8), so a white sign + // texture on a green material shows white in the shade, not green. + let ambient_light = camera.ambient.xyz * ao + in.spot_ambient; + let mat_light = material.color.rgb * (light - ambient_light) + material.ambient.rgb * ambient_light; + let light_mapped = material.params2.x > 0.5 && material.extra.x < 0.5; + // The low-range Vanilla+ target has no exposure/tonemapping. Saturate the + // diffuse light before modulating the texture, as the classic path does: + // overlapping lamps must not clip a coloured texture into a white patch. + // The light is OMSI's - the envir.cfg's sun, sky and ambient and its lamps - and those + // numbers are what Direct3D multiplies into the gamma-encoded texture: it is laid on the + // encoded texture here too, as in the classic picture below. Multiplied in linear light, + // a light L showed as L^(1/2.2): the night's 0.06 as 0.28, every night, dusk and shade + // in Vanilla+ several times as bright as in OMSI 2 (#300, #1612). + var lit = srgb_decode(srgb_encode(albedo) * clamp(mat_light, vec3(0.0), vec3(1.0))); + // The vanilla picture: Omsi.exe's texture stages multiply the gamma-encoded texture by + // the vertex light (clamped at 1); here the texture is sampled linear and the target + // encodes again, so multiplied here a light L showed as L^(1/2.2) - a night at 0.06 + // looked like 0.28, a late dusk (#300). So the product is made on the encoded texture + // and decoded again, with the light map laid on encoded as well. (Through the sRGB curve + // itself: taken as a power of 2.2, t v^2.2, the curve's linear foot below 0.0031 put a + // night wall at a quarter of OMSI 2's - a texture of 0.66 under a light of 0.05 came out + // at 2 of 255 instead of 8.) + let classic = camera.sky_color.w > 0.5; + // (the terrain's night map is its tile light map: light, not a glow - see below) + let terrain_map = material.params.y < 0.5 + && material.extra.x > 0.5 + && material.extra.w > 0.5 + && material.extra.w < 1.5; + let terrain_night = classic && terrain_map; + if (classic && material.params.y < 0.5) { + var v = clamp(material.emissive.rgb + mat_light + material.color.rgb * interior_lamps(in.world, n, in.params2.z), vec3(0.0), vec3(1.0)); + if (light_mapped) { + let lm = srgb_encode(textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], buv, camera.lod.x).rgb) * clamp(in.params2.x, 0.0, 1.0); + v = v + lm * (vec3(1.0) - v); + } + if (terrain_night) { + // the terrain's tile light map lights the ground as the lamps' own light: added + // to the vertex light before the texture is multiplied in. Laid over the lit + // ground instead, as a night map glows, its faint fringe (0.01, linear) put + // one beige veil over cobbles and grass alike, a whole car park the colour of + // sand where OMSI 2 shows it dark grey. + let nm = srgb_encode(night_sample.rgb); + v = min(v + nm * camera.sun_color.w * clamp(in.params2.y, 0.0, 1.0), vec3(1.0)); + } + if (lm_only) { + // a road, a plate or a [LightMapMapping] object: the same tile light map, the + // same way as the ground beside it (Omsi.exe lights both from it alone - its + // `[maplight]`s only bake the map, 0x7903e0). Added after the texture in linear + // light instead, the pools that lay bright on the verges hardly showed on the + // asphalt between them: the street lamps lit everything but the road (#847). + let lm = srgb_encode(light_map_at(in.world)); + v = min(v + lm * camera.sun_color.w, vec3(1.0)); + } + lit = srgb_decode(srgb_encode(albedo) * v); + } else if (light_mapped) { + // [matl_lightmap], as Omsi.exe's texture stages have it (0x7fe4d3..0x7fe604): the + // light map is laid onto the vertex light with D3DTOP_ADDSMOOTH (light + map x (1 - + // light)) before the texture is multiplied in - a lit saloon glows at night and + // hardly shows in daylight. The vertex light is D3D's: the material's emissive and + // its colour times every light - the saloon lamps (`[interiorlight]`, D3D lights + // too, 0x5fa8f0) among them - clamped at 1. (Added once more after the map, the + // saloon lamps lit a cabin twice over, flat white where the map was full; and the + // material's colour took the map down with it.) + let lm = srgb_encode(textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], buv, camera.lod.x).rgb) * clamp(in.params2.x, 0.0, 1.0); + let v = clamp(material.emissive.rgb + mat_light + material.color.rgb * interior_lamps(in.world, n, in.params2.z), vec3(0.0), vec3(1.0)); + lit = srgb_decode(srgb_encode(albedo) * (v + lm * (vec3(1.0) - v))); + } + // the D3D material's own highlight (specular colour and power of the o3d file or a + // [matl_allcolor]), lit at the vertices (see `vertex_specular`) and added after the + // texture as D3D's specular is; the sun's not in its shadow + let specular = in.spec_sun * shadow + in.spec_sky; + if (classic) { + // D3D adds its vertex specular after the encoded texture stages. Adding + // it in linear light encoded it again at the target and washed out dusk. + lit = srgb_decode(min(srgb_encode(lit) + specular, vec3(1.0))); + } else { + lit = lit + specular; + } + if (material.params.y > 0.5) { + lit = tex.rgb * material.color.rgb; + } + if ((!light_mapped && !classic) || material.params.y > 0.5) { + lit = lit + tex.rgb * material.emissive.rgb; + } + // [interiorlight]: the saloon lamps on the meshes and passengers they illuminate (in + // a light-mapped material's vertex light already, above) + if (!light_mapped && !classic) { + lit = lit + tex.rgb * interior_lamps(in.world, n, in.params2.z); + } + // (Vanilla+: the map's lamps light the ground, as they light the roads) + if (material.extra.w > 0.5 && !terrain_map) { + // [matl_nightmap]: self-illumination that fades in with the night + // terrain: the tile light map in tile space (north at the top row) + // a [matl_item] night map is switched by its variable (warning lamps, displays): + // it glows whenever that is on, by day as well; the others fade in with the night + let night = select(rain_lit_windows(in.local), 1.0, material.extra.w > 1.5); + lit = lit + night_sample.rgb * night * select(clamp(in.params2.y, 0.0, 1.0), 1.0, material.extra.w > 1.5); + } + if (material.params2.y > 0.0) { + // [matl_envmap]: sphere map reflection, masked by the diffuse alpha like the original + let vdir = normalize(in.world - eye); + var env_uv = in.env_uv; + if (material.bump.y > 0.5) { + env_uv = env_uv + bump_offset(duv); + } + let env = textureSample(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], env_uv); + let diffuse_a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv).a; + if (material.params.x < 1.5) { + // rain: a painted body goes darker and glossier when it is wet, so the bus + // stands out against a grey street instead of fading into it + let env_night = select(1.0 - 0.85 * clamp(camera.sun_color.w, 0.0, 1.0), 1.0, camera.sky_color.w > 0.5); + let env_light = clamp(camera.sun_color.r * camera.sun_dir.w + camera.sky_color.r + camera.ambient.r, 0.05, 1.0) * env_night; + let wet = camera.shadow.w * weather_outside_n(in.world, n, false, in.params2.w); + lit = lit * (1.0 - 0.30 * wet); + // the water film mirrors the (overcast) sky a little, mostly at grazing + // angles; kept faint - a strong rim read as a white outline round the bus + let facing = clamp(abs(dot(vdir, n)), 0.0, 1.0); + let sheen = wet * min(material.params2.y, 1.0) * (0.05 + 0.22 * pow(1.0 - facing, 5.0)); + lit = mix(lit, camera.sky_color.rgb * env_light, sheen); + } + // Omsi.exe's environment stage (0x7fd6c4 at 0x7ff626, fixed function), for paint + // and glass alike: the sphere map's colour as it is, over what the stages before + // made of the lit texture - D3DTOP_LERP by the texture factor when the material has + // neither a [matl_transmap] nor a [matl_envmap_mask], D3DTOP_BLENDCURRENTALPHA when + // it has one - and the alpha left as the stages before made it (ALPHAARG1 CURRENT, + // SELECTARG1, 0x7ff98a): a clear pane shows its reflection as faintly as it shows + // itself. (A glass path of our own - a quarter reflection at least, a Fresnel rim + // and the pane made opaque where it reflected - mirrored the street in every + // window far more than the original does.) The factor is [matl_envmap]'s times + // the ambient light plus `g` (the light the vehicle stands in: the lamps of the + // tile's light map and the sky), each at most 1, packed into a D3DCOLOR without + // saturation (0x7ff8ed: a factor over 1 spills its bits into the next channel, as + // there). The alpha it blends by is the mask's, or the diffuse texture's times `g` + // (0x7feacc, 0x7ff092) - never the diffuse alpha of a material without one of + // them: taken as a reflection mask, a body whose texture carries an alpha channel + // for other purposes was mirrored (dark) where that alpha was high. + // `g` (0x861ca0, set per vehicle at 0x7d8735): the mean of the light the tile's + // light map throws on it plus the day's light A (weather +0xac = the mean of + // lightcolor A, 0x75333f - by it the stars fade), at most 1 + let g = clamp(dot(lamp_light, vec3(1.0 / 3.0)) + dot(camera.sun_color.rgb, vec3(1.0 / 3.0)), 0.0, 1.0); + var kk = vec3(0.0); + if (has_transmap_declared() || has_env_mask()) { + let a = select(diffuse_a, textureSampleBias(mx_tex2d[mx_mat.envmask], mx_samplers[mx_mat.sampler], duv, camera.lod.x).a, has_env_mask()); + kk = vec3(a * g); + } else { + kk = omsi_texture_factor(material.params2.y, camera.ambient.rgb + vec3(g)); + } + // The lerp is made on the encoded values, as the stage makes it, like the texture x + // light product above: made on linear ones it showed the reflection about twice as + // bright over a dark surface - since the nights got dark (#300) the instrument glass + // of the MAN NL/NG (Fenster.tga, factor 0.5, the sky at the sphere map's bottom) lay + // milky white over the unlit gauges. (Vanilla+ as well: its linear lerp laid the + // sphere map as a grey sheen over every dark window band and chassis, #780.) + // The sphere map's colour as it is, as the stage takes it: the night already weakens + // the reflection through the factor (`kk`, the ambient light and `g`). Darkened once + // more by that light, as a photograph lit by the night, the reflection went twice + // and the paint and the windows lost their shine at dusk and by night, which they + // keep in OMSI (#2284). + lit = srgb_decode(mix(srgb_encode(lit), srgb_encode(env.rgb), kk * camera.cam_pos.w)); + } + // wet road: a surface whose texture carries [moisture] darkens under rain and starts + // to mirror the sky, strongest where you look along it (the Fresnel sheen that makes a + // wet street read as wet) + let outside = weather_outside_n(in.world, n, material.extra.x > 0.5, in.params2.w); + let wet = camera.shadow.w * material.params2.z * outside * (1.0 - clamp(camera.ambient.w, 0.0, 1.0)); + if (wet > 0.0) { + let vdir = normalize(in.world - eye); + let facing = clamp(-dot(vdir, n), 0.0, 1.0); + let fresnel = pow(1.0 - facing, 4.0); + let puddle = road_puddle_coverage(in.world, n, wet); + let water = 0.02 + 0.98 * pow(1.0 - facing, 5.0); + let weight = clamp(mix(fresnel * wet * 0.85, water * wet, puddle), 0.0, 0.9); + let sheen = camera.sky_color.rgb * 0.5 + camera.sun_color.rgb * camera.sun_dir.w * 0.35; + if (classic) { + // Vanilla blends encoded weather colours, but asphalt darkening + // must stay in linear light to avoid turning the road black. + lit = srgb_decode(mix(srgb_encode(lit * mix(1.0, 0.75, wet)), sheen, weight)); + } else { + lit = mix(lit * mix(1.0, 0.55, wet), sheen, weight); + } + *puddle_weight = weight * puddle; + } + // snow: the ground, the roads and every upward-facing surface whiten under it + // (not on a shadow blob: whitened, it lit the snow under the bus instead of shading it) + // (not in vanilla: OMSI 2 shows snow only through the season's WinterSnow textures) + // (nor on a texture that is the season's snow picture: the map's own WinterSnow + // textures show the snow as OMSI 2 does, and whitened over, the snowy grass and the + // grey road went one flat white, the lane markings left standing in it, #879) + let snow_ok = outside * select(1.0, 0.0, in.params2.w > 1.5 || camera.sky_color.w > 0.5 || material.ambient.w > 0.5); + // a carriageway (a [moisture] texture that is not the terrain) under snow that builds + // up: its own cover, the ruts of the lanes and the tyres' tracks (road_snow.wgsl) + let carriageway = material.extra.x < 0.5 && material.params2.z > 0.0 && road_snow_dynamic(); + var rs = vec3(0.0); + if (carriageway && snow_ok > 0.0) { + rs = road_snow(in.world); + } + // a vehicle's part: the snow its own roof has gathered, where that is kept (another + // player's bus keeps the weather's) + let vehicle = vehicle_snow_kept(in.params2.w); + var on_vehicle = 0.0; + if (vehicle && snow_ok > 0.0) { + on_vehicle = vehicle_snow(in.params2.w, in.local); + } + let snow = select(select(camera.ambient.w, rs.x, carriageway), on_vehicle, vehicle) * snow_ok; + if (snow > 0.0 || rs.y > 0.0) { + let up = clamp(n.z, 0.0, 1.0); + let ground = select(0.0, 1.0, material.extra.x > 0.5 || material.params2.z > 0.0); + // (a road kept clear - "snow on road" off - stays asphalt, #1362; built-up snow + // brings its own cover) + let cleared = select(1.0, 0.0, !carriageway && camera.post.z > 0.5 && material.extra.x < 0.5 && material.params2.z > 0.0); + // only surfaces that really face up get a cover; a soft threshold keeps the snow + // off the sides and off the grazing rims that showed as a white outline + let cover = cleared * snow * clamp(max(ground, smoothstep(0.78, 0.95, up) * 0.8), 0.0, 1.0); + let light = camera.sun_color.rgb * camera.sun_dir.w * ndl * shadow * 0.6 + camera.sky_color.rgb * 0.7 + camera.ambient.xyz; + let white = vec3(0.92, 0.94, 0.98) * light * ao; + // (a vehicle's gathered snow lies thick enough to hide the paint: the ground's + // dusting lets the texture show through) + lit = mix(lit, white, min(cover * select(0.55 + 0.35 * tex.a, 1.2, vehicle), 1.0)); + // the slush in the ruts and the tracks: wet, grey, darker than the snow beside it + lit = mix(lit, lit * 0.6 + white * 0.12, rs.y * snow_ok); + } + let dist = distance(in.world, camera.cam_pos.xyz); + let f = 1.0 - exp(-fog_distance(in.world) * camera.fog.w); + *puddle_weight *= 1.0 - clamp(f, 0.0, 1.0); + var rgb = mix(lit, camera.fog.xyz, clamp(f, 0.0, 1.0)); + if (classic) { + // D3D's fixed-function fog blends the encoded vertex fog colour too. + // Treating that colour as linear raised a mid-grey fog from 128 to 188. + rgb = srgb_decode(mix(srgb_encode(lit), camera.fog.xyz, clamp(f, 0.0, 1.0))); + } + if (camera.flags.z > 0.0) { + // Never taken: flags.z (the old enhanced look's aerial perspective) is always 0 + // now - the enhanced path has its own fragment shader (enhanced.wgsl). The branch + // stays because Metal's fast-math contracts the fog mix above differently without + // it, and the vanilla picture is to stay what it was to the last code value. + let vdir = normalize(in.world - camera.cam_pos.xyz); + let towards_sun = clamp(dot(vdir, camera.sun_dir.xyz), 0.0, 1.0); + let k = (1.0 - exp(-dist * 0.00045)) * camera.flags.z * (0.55 + 0.45 * clamp(camera.sun_dir.w, 0.0, 1.0)); + let scatter = mix(camera.sky_color.rgb * 1.4 + camera.ambient.rgb * 0.5, camera.sun_color.rgb * camera.sun_dir.w + camera.sky_color.rgb, towards_sun * towards_sun); + rgb = mix(rgb, scatter, clamp(k * 0.6, 0.0, 0.5)); + } + // (a NaN anywhere above - a zero-length vector normalised, 0 x infinity - was a black + // patch on Windows, e.g. an EN92's headlights while off, and invisible on the Mac) + rgb = finite_or(rgb, finite_or(albedo * material.color.rgb * diffuse, albedo)); + var a = tex.a * material.color.a; + if (mode < 0.5) { + a = 1.0; + } + if (!is_snow_pane()) { + a = a * clamp(film_water, 0.0, 1.0); + } + if (mode > 1.5 && min(material.emissive.r, min(material.emissive.g, material.emissive.b)) > 0.99 && material.emissive.w < 1.5) { + a = encoded_blend_alpha(rgb, a, light); + } + if (material.emissive.w > 0.5 && material.emissive.w < 1.5) { + // a pane in the rain without a film of its own (`pane_rain`): the traffic's windows + let g = pane_rain(in.world, in.local, in.normal); + if (g.cover > 0.001 || g.veil > 0.001 || g.mist > 0.001) { + let vn = normalize(camera.cam_pos.xyz - in.world); + let o = pane_rain_compose(g, rgb, a, vn, rain_env_vanilla(reflect(-vn, g.n)), rain_env_vanilla(vec3(0.0, 0.0, 0.5)) * 0.9); + rgb = o.rgb; + a = o.a; + } + } + return vec4(rgb, a); +} + +// What lies under a self-lit layer, for `encoded_blend_alpha`: a surface of this encoded +// brightness lit by the light at the layer (the road's asphalt under the KVB Citaro's +// light cone is 0.44 - 0.49 encoded). +const BLEND_GROUND_ENCODED: f32 = 0.45; + +// A self-lit blended layer (emissive white: a light cone laid on the road, a glow) as +// Omsi.exe blends it: Direct3D 9 mixes the gamma-encoded colours, the sRGB target here mixes +// linear ones, and a faint layer came out far brighter - the KVB Citaro's `lichtkegel.o3d` +// (alpha 0.14 on average) a flat beige sheet over the road where OMSI 2 shows a soft pool, +// 120 of 255 against its 85. The target cannot be read, so what is under the layer is taken +// to be ground lit by the light here (`light`, the vertex light the layer would have): +// the alpha is the one that gives Omsi.exe's encoded mix over it, never more than the +// layer's own. +fn encoded_blend_alpha(rgb: vec3, a: f32, light: vec3) -> f32 { + let w = vec3(0.2126, 0.7152, 0.0722); + let s = max(rgb, vec3(0.0)); + if (a <= 0.0) { + return a; + } + let d_enc = clamp(light, vec3(0.0), vec3(1.0)) * BLEND_GROUND_ENCODED; + let d = dot(srgb_decode(d_enc), w); + let over = dot(srgb_decode(srgb_encode(s) * a + d_enc * (1.0 - a)), w); + let span = dot(s, w) - d; + if (span < 1e-4) { + return a; + } + return clamp((over - d) / span, 0.0, a); +} + +// The rain film on a pane in the classic pictures: the drops, the runners and the blur of the +// wet glass as the enhanced picture draws them (`glass_water`, enhanced/07_glass.wgsl +// `glass_film`), lit by the classic picture's own sky (`rain_env_vanilla`). Without the +// cabin's air there is no condensation behind them. +fn glass_film_classic(in: FsIn, water: f32) -> vec4 { + let v = camera.cam_pos.xyz - in.world; + let dist = length(v); + let vn = v / max(dist, 1e-4); + let in_cab = inside_vehicle(camera.cam_pos.xyz) * near_player_vehicle(in.world) > 0.5; + let g = glass_water(in.world, in.local, in.normal, water, camera.post.y, in_cab); + if (g.cover <= 0.001 && g.mist <= 0.001 && g.veil <= 0.001) { + return vec4(0.0); + } + let has_picture = camera.flags.z < -0.5; + let dims = vec2(textureDimensions(mx_tex2d[mx_mat.env])); + let uv0 = in.clip.xy / dims; + let mist_col = rain_env_vanilla(vec3(0.0, 0.0, 0.5)) * 0.9; + // the view through the wet glass between the drops, softened by the film of water + let veil_lod = log2(max(dims.y * mix(0.002, 0.006, clamp(g.veil / 0.3, 0.0, 1.0)), 1.0)); + var behind = mist_col; + if (has_picture) { + behind = finite_or(glass_blur(uv0, veil_lod), mist_col); + } + // a drop: a small lens, the street small and upside down in it, darker at its rim + var drop_col = behind; + var a_drop = 0.0; + if (g.cover > 0.001) { + // (bent by the dome, the way out of the drop is looked up where it meets the street a + // few metres on - not a fixed share of the screen aside, which from the driver's seat + // landed on the dark dashboard and the pillars and drew every drop as a black speck: + // the classic pictures keep no depth to tell those from the street) + let tilt = g.n - g.out * dot(g.n, g.out); + let thr = normalize(-vn - tilt * 0.9); + var seen = behind; + let cp = camera.view_proj * vec4(in.world + thr * 6.0, 1.0); + if (has_picture && cp.w > 0.05) { + let ndc = cp.xy / cp.w; + let uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + let inside = smoothstep(0.0, 0.06, min(min(uv.x, 1.0 - uv.x), min(uv.y, 1.0 - uv.y))); + let far = finite_or(glass_blur(clamp(uv, vec2(0.001), vec2(0.999)), 0.8 + 1.5 * g.mist), behind); + seen = mix(behind, far, inside); + } + let rim = smoothstep(0.55, 1.0, g.rim); + let facing = dot(g.out, vn) > 0.0; + let cosv = clamp(abs(dot(g.n, vn)), 0.0, 1.0); + let f = select(0.02, 0.02 + 0.98 * pow(1.0 - cosv, 5.0), facing); + var c = seen * (1.0 - 0.45 * rim) * (1.0 - f) + rain_env_vanilla(reflect(-vn, g.n)) * f; + if (facing) { + let r = reflect(-vn, g.n); + c = c + camera.sun_color.rgb * camera.sun_dir.w * pow(max(dot(r, camera.sun_dir.xyz), 0.0), 900.0) * f * 60.0; + } + let detail = smoothstep(0.5, 1.6, g.size_px); + drop_col = mix(behind * 0.93, c, detail); + a_drop = g.cover * mix(select(0.15, 0.5, has_picture), 0.95, detail) * (1.0 - smoothstep(5.0, 15.0, dist)); + } + let a_mist = g.mist * 0.5; + var a_veil = 0.0; + if (g.veil > 0.001 && has_picture) { + a_veil = g.veil * (1.0 - smoothstep(25.0, 60.0, dist)); + } + let a_under = a_veil + a_mist * (1.0 - a_veil); + let under = (behind * a_veil + mix(mist_col, behind, 0.9) * a_mist * (1.0 - a_veil)) / max(a_under, 1e-4); + let a = a_drop + a_under * (1.0 - a_drop); + if (a <= 1e-4) { + return vec4(0.0); + } + let col = (drop_col * a_drop + under * a_under * (1.0 - a_drop)) / a; + return vec4(min(col, vec3(1.5)), a); +} + +// Snow on the carriageways: how far it has built up, the ruts the traffic keeps in it and +// the fresh tracks the tyres press into it (see `Renderer::set_snow_track_rect`). +// +// The field is a square of `place.z` metres that wraps around the world (a torus): texel +// (i, j) holds the world's point (x, y) where floor(x / texel) and floor(y / texel) are i and +// j modulo its size, so the app only rewrites the tiles the camera moves into. It is kept +// tile after tile (`TRACK_TILE` texels a side), each row after row, a texel an RGBA8 word: +// r: the ruts of the lanes' wheel tracks (0..1) +// g: a tyre has pressed the snow here (how much of the texel it covered) +// b, a: how much snow had fallen when a tyre last ran here (16 bits, see `state.y`; for +// a rut no tyre has run in yet, a moment as long ago as its lane's traffic makes +// likely): the track and the rut fill as more falls + +struct SnowTrack { + // xy: the render origin modulo the field's side (m), z: the side (m), w: 1 while the + // field holds the area around the camera + place: vec4, + // x: how far the snow covers the roads (0..1; below 0 the weather's "snow on road" + // decides, as before), y: the snow fallen so far (thousandths of a full cover, modulo + // 65536), z: how deep the lanes' ruts show (0..1), w: how far it thaws to slush (0..1; + // Enhanced alone, 0 on the other paths) + state: vec4, +}; + +@group(0) @binding(20) var snow_track_px: array; +@group(0) @binding(21) var snow_track: SnowTrack; + +const TRACK_TEXELS: i32 = 2048; +const TRACK_TILE: i32 = 256; + +// One texel's rut and fresh track, each filled by the snow fallen since a tyre last ran +// over it. +fn snow_track_texel(p: vec2) -> vec2 { + let q = ((p % TRACK_TEXELS) + TRACK_TEXELS) % TRACK_TEXELS; + let tile = (q.y / TRACK_TILE) * (TRACK_TEXELS / TRACK_TILE) + q.x / TRACK_TILE; + let i = (tile * TRACK_TILE + q.y % TRACK_TILE) * TRACK_TILE + q.x % TRACK_TILE; + let t = unpack4x8unorm(snow_track_px[i]); + let then = round(t.b * 255.0) * 256.0 + round(t.a * 255.0); + let since = (snow_track.state.y - then + 65536.0) % 65536.0; + // (a track begins to blur after 8 % of a cover has fallen on it and is gone at 28 %; a + // rut, worn deeper by the traffic, begins to fill at 15 % and is gone at 52 % - in a + // heavy snowfall (Starker Schneefall) one or two minutes, and four or seven, without a + // car: a driver who waits that long at a stop sees it happen) + let fresh = t.g * (1.0 - smoothstep(80.0, 280.0, since)); + let rut = t.r * (1.0 - smoothstep(150.0, 520.0, since)); + return vec2(rut, fresh); +} + +// The rut (x) and the fresh track (y) at a point of the render frame, blended between the +// four texels around it (each decoded first: the fill time does not blend). +// +// Faded out from 75 m off and not read beyond 90: the tiles the field takes as the camera +// moves lie 96 m off and more, and hold what they held before until their ruts are drawn +// a few frames later (see `SnowTracks::update`) - and a rut that far is a pixel or two. +fn snow_track_at(world: vec2) -> vec2 { + let fade = 1.0 - smoothstep(75.0, 90.0, distance(world, camera.cam_pos.xy)); + if (snow_track.place.w < 0.5 || fade <= 0.0) { + return vec2(0.0); + } + let q = (world + snow_track.place.xy) * (f32(TRACK_TEXELS) / snow_track.place.z) - 0.5; + let b = floor(q); + let f = q - b; + let i = vec2(b); + let a00 = snow_track_texel(i); + let a10 = snow_track_texel(i + vec2(1, 0)); + let a01 = snow_track_texel(i + vec2(0, 1)); + let a11 = snow_track_texel(i + vec2(1, 1)); + return mix(mix(a00, a10, f.x), mix(a01, a11, f.x), f.y) * fade; +} + +// Whether a part's surface code carries its roof's own snow (`vehicle_snow`) rather than +// leaving it to the weather's (a roof the roads' snow does not keep: another player's bus). +fn vehicle_snow_kept(code: f32) -> bool { + return code < -10000.0 && road_snow_dynamic(); +} + +// The snow on a vehicle's part (`code`: its instance's surface code, whose ten thousands +// carry how much snow its roof has gathered, 1..41 for 0..1, see upload.rs `roof_code`), +// at `local`, the point in the part's own mesh: patches at first, a closed layer as it +// goes on, laid out on the vehicle so that they ride with it. +fn vehicle_snow(code: f32, local: vec3) -> f32 { + let amount = (floor(-code / 10000.0) - 1.0) / 40.0; + let level = amount * 1.3 - 0.12; + // (bare, or closed over whatever the patches: no noise to sample) + if (amount <= 0.0) { + return 0.0; + } + if (level >= 1.08) { + return 1.0; + } + let p = local.xy; + let p2 = vec2(p.x * 0.8 - p.y * 0.6, p.x * 0.6 + p.y * 0.8); + let patches = vnoise_f(p, 0.9, vec2(4.3, 1.9)) * 0.65 + vnoise_f(p2, 3.1, vec2(8.1, 6.7)) * 0.35; + return smoothstep(patches - 0.3, patches + 0.08, level); +} + +// Whether the roads' snow is the built-up kind (`state.x` at or above 0) rather than the +// weather's on/off "snow on road". +fn road_snow_dynamic() -> bool { + return snow_track.state.x >= 0.0; +} + +// The snow on a carriageway at `world` (render frame): x the cover (0..1), y the slush in +// the ruts (0..1: the wheels keep it wet and grey), z a fresh tyre track (0..1). +fn road_snow(world: vec3) -> vec3 { + let base = clamp(snow_track.state.x, 0.0, 1.0); + if (base <= 0.0) { + return vec3(0.0); + } + // the map's own coordinates (modulo the pattern's period): the patches stay put + let m = world.xy + camera.world_origin.xy; + // It does not settle evenly: first a dusting in patches a stride or two across and in + // the grain of the asphalt, which close up as it goes on falling. + // (three octaves, the finer ones turned against the coarse: a single lattice's cells + // showed as square blots where the cover's edge ran through them) + // (once the cover has closed - its level over the patches' highest - every pixel of the + // road paid for three octaves of noise that changed nothing) + let m2 = vec2(m.x * 0.8 - m.y * 0.6, m.x * 0.6 + m.y * 0.8); + let level = base * 1.35 - 0.15; + var cover = 1.0; + if (level < 1.1) { + let m3 = vec2(m.x * 0.28 + m.y * 0.96, m.y * 0.28 - m.x * 0.96); + let patches = vnoise_f(m, 0.45, vec2(3.1, 7.7)) * 0.55 + vnoise_f(m2, 1.3, vec2(11.3, 2.9)) * 0.3 + vnoise_f(m3, 3.7, vec2(5.9, 13.1)) * 0.15; + cover = smoothstep(patches - 0.35, patches + 0.1, level); + } + let tracks = snow_track_at(world.xy); + // The ruts: the wheels of the traffic keep two strips of each lane down to slush, the + // more of it the more snow there is to churn; with a mere dusting they show the asphalt. + let rut = tracks.x * snow_track.state.z; + let slush = rut * smoothstep(0.15, 0.7, base); + cover = cover * (1.0 - rut * 0.85); + // A fresh track: the tread pressed the snow flat and grey. Its edge sharpened from the + // texels' blend (a soft ramp over a whole texel read as a blur), and the pressed snow + // grainy - the tread's blocks, as fine as the eye can still tell apart. + let edge = smoothstep(0.2, 0.75, tracks.y); + var track = 0.0; + if (edge > 0.0) { + track = edge * (0.75 + 0.25 * vnoise_f(m2, 14.0, vec2(1.7, 9.3))); + } + cover = cover * (1.0 - track * 0.6); + var wet = max(slush, track * 0.5 * base); + // Thawing (rain on it, or a wet road, while no fresh snow falls): what is left goes grey + // and soaked, and it breaks up - the thin patches first, in the grain of a smooth noise + // a few strides across - into slush over the wet asphalt. + let thaw = clamp(snow_track.state.w, 0.0, 1.0); + if (thaw > 0.0 && cover > 0.0) { + let n = vnoise_f(m, 1.1, vec2(6.1, 2.3)) * 0.6 + vnoise_f(m2, 4.3, vec2(9.7, 4.1)) * 0.4; + let bare = smoothstep(n - 0.06, n + 0.06, thaw * 0.6 - 0.08 + 0.3 * (1.0 - base)); + let left = cover * (1.0 - bare); + wet = max(wet, (cover - left) * 0.7 + left * thaw * 0.8); + cover = left * (1.0 - 0.55 * thaw); + } + return vec3(cover, wet, track); +} + +// Enhanced graphics: what the enhanced main pass, the sky and the coronas share - the +// light of the physically based sky (see atmosphere.rs), in its units (1 = 10 000 lux), +// and the air between the camera and what it sees. The scene is drawn pre-exposed: +// radiance times `enh.exposure.x`, so that the half-float target keeps its precision by +// night as well as by day. +struct Enhanced { + // x pre-exposure, y the level unlit things are drawn at, z a lit window's radiance + // (pre-exposed), w how bright a light's corona is drawn + exposure: vec4, + // rgb irradiance of the sun after the clouds, w its angular radius (rad) + sun: vec4, + // irradiance from the sky and the ground: order-2 spherical harmonics, rgb + sh: array, 9>, + // rgb radiance of the ground, w the sky table's scale + ground: vec4, + // x weather fog extinction (1/m) at its base, y its height falloff (1/m), z the base + // height (render-origin relative), w clear-air extinction (1/m) at the ground + fog: vec4, + // rgb fog radiance from the light around it (the sun's part is added by angle), + // w the table scale the reflection probe was drawn with + fog_color: vec4, + // x wet roads, y snow cover, z rain, w cloud cover in front of the sun + weather: vec4, + // x mip levels of the probe, y illuminance of a light's core (maplight colour 1), + // z cabin light illuminance, w how much of the sun the clouds let through + lights: vec4, + // rgb the sun disc's irradiance before the clouds, w frame time (s) + sun_disc: vec4, + // x which term the main pass shows alone (OMSI_DEBUG_ENHANCED, 0 = the picture), + // y the puddles' F0, z the envmap photo's strength, w the tone curve's contrast + debug: vec4, + // xyz where the sky cube is drawn from, relative to the camera + eye: vec4, + // x how bright an LED panel's dots burn (0 = off), y whether the LED panels' `\S:n` + // masks keep their mip chain (0: at full resolution, the dots stay visible when small), z 1 + // when lights glare and glow in the night air (the settings' `light_glow`) + led: vec4, + // xyz towards the moon, w its angular radius (rad) + moon: vec4, + // rgb the moon disc's irradiance before the clouds, w how much of the starry sky shows + moon_disc: vec4, + // rgb the sun's irradiance at 1400, 2100 and 2800 m (the cumulus layer) and 7000 m + // (the high thin layer), through the atmosphere from up there + cloud_sun: array, 4>, + // rgb the moonlight on a surface facing the moon (after the clouds), w 1 while the + // shadow maps are the moon's + moon_light: vec4, + // the condensation on the player's bus's panes (optical depths): windscreen, sides, + // rear, and how far the defroster has cleared the windscreen (0..1; omsi-app + // condensation.rs) + condensation: vec4, + // x the cumulus layer's base, y its top (m over the ground), z the altocumulus cover, + // w the storm's activity + layers: vec4, + // the lightning of this frame: x the light it throws on a surface facing it (1 = 10 000 + // lux), yz towards it (horizontal unit vector), w its elevation (rad) + flash: vec4, + // xyz towards the flash (unit vector), w how bright its channel is + flash2: vec4, + // x a number the channel's shape is drawn from + flash3: vec4, + // the clouds' shadow field (cloud_field.rs): xy its middle in cloud space, z one over its + // width, w 1 when there is one + cloud_f1: vec4, + // xy what takes a world point to cloud space, z the height of the plane it is taken on, + // w the share of the sun the main pass has taken off already for the clouds over the camera + cloud_f2: vec4, + // the player's bus's pitch and roll: sin, cos of each (its panes' condensation sits on + // the glass on a slope, `pane_local`) + pane_tilt: vec4, + // Slots of the weather overhaul, one owner each (zero until it fills them): + // the volumetric clouds, the volumetric fog, the precipitation, the bus's panes, the + // surfaces' PBR and the ray tracing, and two spare. + clouds_ext: vec4, + clouds_ext2: vec4, + vol_fog: vec4, + vol_fog2: vec4, + precip_ext: vec4, + glass_ext: vec4, + // (pbr_ext: x the share of the sun's light that still comes as a beam - the rest the + // clouds scatter, `sun_scattered` - y 1 when x is set) + pbr_ext: vec4, + rt_ext: vec4, +}; +@group(0) @binding(11) var enh: Enhanced; +@group(0) @binding(13) var s_lin: sampler; +@group(0) @binding(14) var t_sky_lut: texture_2d; + +const PI: f32 = 3.14159265; + +// Irradiance from the sky and the ground on a surface facing n. +fn sh_irradiance(n: vec3) -> vec3 { + let c = enh.sh; + let e = c[0].rgb * 0.282095 + + c[1].rgb * (0.488603 * n.y) + c[2].rgb * (0.488603 * n.z) + c[3].rgb * (0.488603 * n.x) + + c[4].rgb * (1.092548 * n.x * n.y) + c[5].rgb * (1.092548 * n.y * n.z) + + c[6].rgb * (0.315392 * (3.0 * n.z * n.z - 1.0)) + c[7].rgb * (1.092548 * n.x * n.z) + + c[8].rgb * (0.546274 * (n.x * n.x - n.y * n.y)); + return max(e, vec3(0.0)); +} + +// The lightning's light on a surface facing n: half of it from the cloud overhead and +// round it (a hemisphere), half along the way to the flash itself. +fn flash_irradiance(n: vec3) -> vec3 { + if (enh.flash.x <= 0.0) { + return vec3(0.0); + } + return vec3(0.80, 0.90, 1.0) * enh.flash.x * (0.5 * (0.5 + 0.5 * n.z) + 0.5 * max(dot(n, enh.flash2.xyz), 0.0)); +} + +// Sky radiance towards d (unscaled: times enh.ground.w is the radiance). The table runs +// over the azimuth from the sun (0..π) and the elevation (denser at the horizon). +// The sky table's texture: the table (32 x 48) in its corner and the clouds' shadow field +// (192 x 192) beside it, one texel clear (cloud_field.rs `SKY_TEX_W`, `FIELD_X0`). +const SKY_TEX: vec2 = vec2(225.0, 192.0); +const SKY_TABLE: vec2 = vec2(32.0, 48.0); +const FIELD_ORIGIN: f32 = 33.0; +const FIELD_N: f32 = 192.0; + +fn sky_table_raw(d: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let ls = length(s.xy); + let ld = length(d.xy); + var az = 0.0; + if (ls > 1e-4 && ld > 1e-4) { + az = acos(clamp(dot(s.xy / ls, d.xy / ld), -1.0, 1.0)); + } + let el = asin(clamp(d.z, -1.0, 1.0)); + let v = 0.5 + 0.5 * sign(el) * sqrt(min(abs(el) / 1.5707963, 1.0)); + // (kept a half texel inside the table: its neighbours in the texture are not the sky) + let tx = clamp(vec2(az / PI, v) * SKY_TABLE, vec2(0.5), SKY_TABLE - vec2(0.5)); + return textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).rgb; +} + +// The share of the sun that reaches the point p through the clouds, as against what the main +// pass's sun (`enh.sun`) already has for the camera's own place: the cumulus layer's shadow +// field read where the sun's way through p meets the layer's middle. 1 where there is no +// field, beyond its edge and where the sun is low (the camera's own factor stands there). +fn cloud_shadow_ratio(p: vec3) -> f32 { + let s = camera.sun_dir.xyz; + if (enh.cloud_f1.w < 0.5 || s.z < 0.06) { + return 1.0; + } + let cs = p.xy + s.xy / s.z * (enh.cloud_f2.z - p.z) + enh.cloud_f2.xy; + let uv = (cs - enh.cloud_f1.xy) * enh.cloud_f1.z + vec2(0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + let w = 1.0 - smoothstep(0.36, 0.48, edge); + if (w <= 0.0) { + return 1.0; + } + let tx = vec2(FIELD_ORIGIN, 0.0) + clamp(uv * FIELD_N, vec2(0.5), vec2(FIELD_N - 0.5)); + let f = textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).r; + let ratio = min(f / max(enh.cloud_f2.w, 0.02), 6.0); + return mix(1.0, ratio, w); +} + +fn sky_table(d: vec3) -> vec3 { + return sky_table_raw(d) * enh.ground.w; +} + +// Henyey-Greenstein phase function. +fn hg_phase(c: f32, g: f32) -> f32 { + let g2 = g * g; + return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * c, 1e-4), 1.5)); +} + +// Optical depth of an exponentially thinning layer (extinction sigma at height 0, falling +// off with k per metre) along a straight path of length dist from height h0 to h1. +fn layer_depth(sigma: f32, k: f32, h0: f32, h1: f32, dist: f32) -> f32 { + if (sigma <= 0.0) { + return 0.0; + } + let a = max(h0, 0.0); + let b = max(h1, 0.0); + let dh = b - a; + if (abs(k * dh) < 1e-3) { + return sigma * dist * exp(-k * 0.5 * (a + b)); + } + return sigma * dist * (exp(-k * a) - exp(-k * b)) / (k * dh); +} + +// The air between the camera and a point dist metres away in direction dir (from the +// camera), at heights h0 (camera) and h1 (point) above the fog's base: rgb the light it +// scatters towards the camera (radiance), a what it lets through of the point. +fn air(dir: vec3, dist: f32, h0: f32, h1: f32) -> vec4 { + return air_of(dir, dist, h0, h1, 1.0); +} + +// The same with the clear air's share scaled (0 for the sky, whose table holds it already). +fn air_of(dir: vec3, dist: f32, h0: f32, h1: f32, clear: f32) -> vec4 { + let tau_fog = layer_depth(enh.fog.x, enh.fog.y, h0, h1, dist); + let tau_air = layer_depth(enh.fog.w * clear, 1.0 / 1500.0, h0, h1, dist); + let tau = tau_fog + tau_air; + let t = exp(-tau); + if (tau < 1e-5) { + return vec4(0.0, 0.0, 0.0, 1.0); + } + // clear air takes on the sky's own colour at the horizon in this direction (which + // already holds the glow round the sun); a weather fog glows with the light around it + // and brighter towards the sun + let horizon = sky_table(normalize(vec3(dir.x, dir.y, max(dir.z, 0.0) * 0.3 + 0.03))); + let fog_in = enh.fog_color.rgb + enh.sun.rgb * hg_phase(dot(dir, camera.sun_dir.xyz), 0.55) * 0.9; + let inscatter = mix(horizon, fog_in, tau_fog / tau); + return vec4(inscatter * (1.0 - t), t); +} + +// The water normal shared by shading and scene reflections. The integer hash and the +// 1000 m period match shader.wgsl, keeping the rings fixed through floating-origin moves. +fn puddle_hash(c: vec2) -> f32 { + let cells = 8000.0; + let w = c - cells * floor(c / cells); + var v = vec2(w) * 1664525u + vec2(1013904223u); + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + v.x = v.x + v.y * 1664525u; + v.y = v.y + v.x * 1664525u; + v = v ^ (v >> vec2(16u)); + return f32(v.x >> 8u) / 16777215.0; +} + +// The rings the rain makes on standing water (Enhanced): xy the water's slope (a horizontal +// offset to its normal), z how much it is stirred (0..1, for its roughness as well). +// +// A falling drop sends out a short train of capillary waves: two or three rings close +// together, running out at a few decimetres a second and dying away within a hand's +// breadth. Three lattices of cells of 18 to 27 cm, turned against each other so that no grid +// shows, each take a drop now and then - the harder it rains the more often, and in more +// of them - every drop at a new place in its cell. A ring is a wave packet on its circle +// (a cosine under a Gaussian), its slope worked out exactly, and it stays inside its cell +// (no ring is cut off at a cell's edge). +fn puddle_ripple(pattern_xy: vec2, time: f32, rain: f32, coverage: f32) -> vec3 { + if (rain <= 0.001 || coverage <= 0.0) { + return vec3(0.0); + } + var slope = vec2(0.0); + var stir = 0.0; + let rate = 0.7 + 1.6 * rain; + let amp = min(1.0, 0.45 + rain) * coverage; + for (var i = 0; i < 3; i = i + 1) { + let fi = f32(i); + let size = 0.18 + 0.045 * fi; + let cs = vec2(cos(fi * 1.93), sin(fi * 1.93)); + let turned = vec2(pattern_xy.x * cs.x - pattern_xy.y * cs.y, pattern_xy.x * cs.y + pattern_xy.y * cs.x); + let q = turned / size + vec2(fi * 17.0, fi * 5.0); + let cell = floor(q); + let seed = puddle_hash(cell + vec2(fi * 311.0, 0.0)); + let tt = time * rate * (0.8 + 0.4 * seed) + seed * 7.0; + let n = floor(tt); + let age = tt - n; + let h = puddle_hash(cell + vec2(n - 97.0 * floor(n / 97.0) + 401.0, fi * 13.0 + 7.0)); + let hit = step(fract(h * 31.7), 0.3 + 0.65 * rain); + let centre = vec2(0.3) + 0.4 * vec2(h, fract(h * 13.7)); + let local = fract(q) - centre; + let r = length(local); + let radius = 0.05 + 0.24 * sqrt(age); + let d = r - radius; + let w = 0.045; + let k = 6.2831853 / 0.07; + let env = exp(-(d * d) / (w * w)); + let a = (1.0 - age) * (1.0 - age) * hit; + // the height is a * env * cos(k d): its slope along the radius + let dh = a * env * (-2.0 * d / (w * w) * cos(k * d) - k * sin(k * d)); + slope = slope - local / max(r, 1e-4) * dh / k; + stir = stir + a * env; + } + return vec3(slope * 0.03 * amp, clamp(stir * amp, 0.0, 1.0)); +} + +// The rings as a picture whose pixel covers `fp` metres of the water sees them: their +// slopes are a few centimetres long, and a pixel (or a puddle ray standing for several) +// wider than half of that lands on a ring's crest one frame and its trough the next - the +// water's picture trembled and broke into blocks. Faded out there, the rings leave their +// stir (the roughness) and the reflection keeps still. +fn puddle_ripple_seen(pattern_xy: vec2, time: f32, rain: f32, coverage: f32, fp: f32) -> vec3 { + let fade = 1.0 - smoothstep(0.012, 0.035, fp); + let r = puddle_ripple(pattern_xy, time, rain, coverage); + return vec3(r.xy * fade, r.z); +} + +// The classic rings (Vanilla+'s puddle reflections): one lattice of 12.5 cm cells. +fn puddle_ripple_classic(pattern_xy: vec2, time: f32, rain: f32, coverage: f32) -> vec3 { + let cell = floor(pattern_xy * 8.0); + let seed = puddle_hash(cell); + let phase = fract(time * (0.8 + seed * 0.9) + seed * 13.0); + let local = fract(pattern_xy * 8.0) - vec2(0.5); + let ring = abs(length(local) - phase * 0.4); + let hit = step(1.0 - clamp(0.25 + 0.6 * rain, 0.0, 0.9), fract(seed * 31.7)); + let strength = (1.0 - smoothstep(0.0, 0.06, ring)) * (1.0 - phase) * rain * coverage * hit; + // Shallow rain rings disturb the image gently; steep normals break neighbouring + // reflection rays apart and make otherwise still puddles look like rough waves. + let bump = normalize(local + vec2(1e-5, 0.0)) * strength * 0.018; + return vec3(bump, strength); +} + +// `beam_shadow.wgsl` for the shaders without the lamp shadow tiles: nothing stands in a beam. +fn beam_tile(li: u32, l: PointLight) -> u32 { + return 0xffffffffu; +} + +fn beam_reaches(k: u32, x: vec3) -> f32 { + return 1.0; +} + +// Enhanced graphics: the lamps as the scene and the sky share them - a headlamp's beam +// and the light the weather's fog scatters from the lamps towards the camera (needs the +// point lights, their grid and `camera.light_grid`). + +// A headlamp's intensity towards `t` (from the lamp) by the angles of a road lamp, not +// around its axis: wide across, brightest just under the lamp's horizon where it reaches +// far down the road, weak straight down, and with a low beam a sharp cut-off above it. +// `dir` is the lamp's axis in its vehicle's floor: its rise tilts the horizon with the +// vehicle, up a ramp and down (#1897). +fn headlamp(t: vec3, dir: vec3, low: bool) -> f32 { + let fwd = normalize(dir.xy + vec2(1e-6, 0.0)); + let ahead = dot(t.xy, fwd); + if (ahead <= 0.0) { + return 0.0; + } + let across = abs(t.x * fwd.y - t.y * fwd.x) / ahead; + let wide = 0.12 * smoothstep(1.0, 0.45, across) + 0.88 * exp(-across * across / 0.06); + let rise = t.z / max(length(t.xy), 1e-3); + let tilt = dir.z / max(length(dir.xy), 1e-3); + // (the tangent of the angle under that horizon) + let drop = (tilt - rise) / max(1.0 + rise * tilt, 1e-3); + // full out to where the road is 0.06 under the lamp's horizon, then less as the cube of + // the drop and a little more: the road is lit evenly from the bumper on, a little + // brighter as far as the beam reaches, and not as one hot pool where its axis lands + var up = min(1.0, pow(0.06 / max(abs(drop), 1e-4), 3.4)); + if (low) { + up = up * smoothstep(-0.012, 0.025, drop); + return wide * up; + } + // a full beam reaches far: a narrow, bright core along the lamp's horizon + let hot = exp(-across * across / 0.012 - drop * drop / 0.0004); + return wide * up + 6.0 * hot; +} + +// The lamps' light the weather's fog scatters towards the camera (radiance, not +// pre-exposed): single scattering along the view ray from `start` to `len` metres in +// direction `d` - the glow round a street lamp in the mist, its cone under it, a bus's +// beams reaching ahead into the fog or the falling snow. The droplets scatter strongly +// forward (fog and cloud droplets of some ten micrometres: g about 0.8), so the glow is +// brightest looking towards a lamp and a cone shows faintly from the side. +// +// Each lamp is taken once, over the whole stretch of the ray within its reach, in the grid +// cell the ray's point nearest to it lies in (the ray's cells are walked through; every +// cell lists the lamps reaching into it). Along a straight ray past a point source, with +// t - t0 = h tan(phi) (h the ray's distance from the lamp, t0 where it passes nearest), +// the inverse square cancels against the path element: dt / r^2 = dphi / h, and what is +// left is the phase function over the angle, cos(theta) = -sin(phi) - a smooth integral +// taken with five Gauss-Legendre nodes, at each of which a spot's or a headlamp's beam is +// asked how much it sends that way. The fog's extinction dims the light on its way from +// the lamp and to the camera (taken at the nearest point). A beam's light, which reaches +// only part of the way, is summed along the ray instead, its steps staggered by `jitter`. +// The droplets' phase function: a strong forward peak and the back-scattered light a +// fog's lidar ratio of some 18 sr asks for (0.055 per steradian straight back) - a single +// Henyey-Greenstein lobe of g 0.8 gave a tenth of it, and a bus's own headlights lit no +// wall of fog in front of the driver. Two lobes, 0.9 of g 0.85 and 0.1 of g -0.5. +fn fog_phase(c: f32) -> f32 { + return 0.9 * hg_phase(c, 0.85) + 0.1 * hg_phase(c, -0.5); +} +const AIRLIGHT_CELLS: u32 = 16u; + +// The clear night air's own haze, which lights a lamp's halo and a headlamp's beam as the fog's +// droplets do, only fainter: the lowest hundred metres of a city's air hold its dust, exhaust +// and humidity at several times the column's average aerosol extinction (`enh.fog.w`), 1-3e-4 +// per metre (a visibility of 15-40 km). A lamp then has a soft glow round it and a low beam +// a faint cone, as in any night photograph, instead of a lit disc on a black ground. +const GROUND_HAZE_GAIN: f32 = 8.0; + +// `droplets`: how much of the weather's extinction scatters like fog (see `FogLampUniform`). +fn lamp_airlight(c: vec3, d: vec3, start: f32, len: f32, jitter: f32, droplets: f32) -> vec3 { + var sum = vec3(0.0); + let sigma0 = enh.fog.x * droplets + enh.fog.w * GROUND_HAZE_GAIN * enh.led.z; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (sigma0 < 4e-5 || cell <= 0.0 || side == 0u || len <= start) { + return sum; + } + // (past a few optical depths nothing comes back) + let end = min(len, start + 4.0 / sigma0); + let gx = array(-0.9061798, -0.5384693, 0.0, 0.5384693, 0.9061798); + let gw = array(0.2369269, 0.4786287, 0.5688889, 0.4786287, 0.2369269); + // the walk through the grid's cells along the ray's plan + let o = (c.xy - camera.light_grid.xy) / cell; + let dd = d.xy / cell; + var ix = i32(floor(o.x + dd.x * start)); + var iy = i32(floor(o.y + dd.y * start)); + let sx = select(-1, 1, dd.x >= 0.0); + let sy = select(-1, 1, dd.y >= 0.0); + let inv_x = select(1e9, 1.0 / abs(dd.x), abs(dd.x) > 1e-7); + let inv_y = select(1e9, 1.0 / abs(dd.y), abs(dd.y) > 1e-7); + var tx = select((f32(ix) - o.x) / dd.x, (f32(ix + 1) - o.x) / dd.x, dd.x >= 0.0); + var ty = select((f32(iy) - o.y) / dd.y, (f32(iy + 1) - o.y) / dd.y, dd.y >= 0.0); + if (abs(dd.x) <= 1e-7) { tx = 1e9; } + if (abs(dd.y) <= 1e-7) { ty = 1e9; } + var t = start; + for (var k = 0u; k < AIRLIGHT_CELLS; k = k + 1u) { + if (t >= end) { + break; + } + let t_out = min(min(tx, ty), end); + if (ix >= 0 && iy >= 0 && ix < i32(side) && iy < i32(side)) { + let base = (u32(iy) * side + u32(ix)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let to_l = l.pos.xyz - c; + let t0 = dot(to_l, d); + // the ray's point nearest to the lamp: taken in this cell only + let tc = clamp(t0, start, end); + if (tc < t || tc > t_out) { + continue; + } + let range = l.extra.w; + let h = length(to_l - d * t0); + if (h >= range) { + continue; + } + // A beam (a headlamp, a spot) is lit in the weather's fog only: its cone is a sliver of + // sixteen jittered steps at half size, which the fog's density hides and the clear + // air's haze shows as shimmer and soap. The lamps' halo alone has the ground haze. + let beam_lamp = l.extra.z != 0.0 || l.dir.w > -1.5; + let fog_sigma = enh.fog.x * droplets; + if (beam_lamp && enh.fog.x < 2e-4) { + continue; + } + let s0 = select(sigma0, fog_sigma, beam_lamp); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + // (inside its core a lamp is as bright as at the core's edge) + let hh = max(h, select(core * 0.7, 0.4, l.extra.z != 0.0)); + let w = sqrt(range * range - h * h); + let ta = max(start, t0 - w); + let tb = min(end, t0 + w); + if (tb <= ta) { + continue; + } + var acc = 0.0; + var half = 0.0; + if (l.extra.z != 0.0 || l.dir.w > -1.5) { + // a beam (a headlamp, a spot): lit only where its cone or cut-off lets + // it - a sliver of the angles the lamp is seen under, which the five + // nodes missed. Sixteen even steps over that angle instead (dphi = + // h dt / r^2: the inverse square is in the step). (Sixteen even steps + // along the way put the few next to the lamp, where nearly all of its + // light is, a metre or more apart: the pixels' staggered steps came + // out as a coarse checker in the fog round every headlamp.) + let pa = atan((ta - t0) / hh); + let dphi = (atan((tb - t0) / hh) - pa) / 16.0; + let tile_k = beam_tile(li, l); + for (var q = 0u; q < 16u; q = q + 1u) { + let tq = t0 + hh * tan(pa + (f32(q) + jitter) * dphi); + let to = l.pos.xyz - (c + d * tq); + let ld = to * inverseSqrt(max(dot(to, to), 1e-6)); + var beam = 0.0; + if (l.extra.z != 0.0) { + beam = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0); + } else { + beam = smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } + // (the map is looked at only where the beam shines at all, and only for + // the few lamps that have a tile: no shadows, no tile, no tap) + var reach = 1.0; + if (beam > 0.002 && tile_k < 44u) { + reach = beam_reaches(tile_k, c + d * tq); + } + acc = acc + beam * reach * fog_phase(dot(ld, d)) * dphi; + } + half = 1.0; + } else { + let pa = atan((ta - t0) / hh); + let pb = atan((tb - t0) / hh); + half = 0.5 * (pb - pa); + let mid = 0.5 * (pa + pb); + let tile_p = beam_tile(li, l); + for (var q = 0u; q < 5u; q = q + 1u) { + let phi = mid + half * gx[q]; + let tq = t0 + hh * tan(phi); + let ld = normalize(l.pos.xyz - (c + d * tq)); + var beam = 1.0; + if (l.dir.z < -0.5) { + // (a lamp in a housing: see `lamp_light`) + beam = 0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z); + } + // (a lamp with a shadow map: what stands between it and the air + // keeps its light out of that air, as the headlamps' beams) + var reach = 1.0; + if (beam > 0.002 && tile_p < 44u) { + reach = beam_reaches(tile_p, c + d * tq); + } + acc = acc + gw[q] * beam * reach * fog_phase(-sin(phi)); + } + } + // a lamp's irradiance is core^2 / r^2 of its colour's (a headlamp's 1 / r^2) + let strength = select(core * core, 1.0, l.extra.z != 0.0); + let xc = c + d * tc; + let sigma = s0 * exp(-enh.fog.y * max(xc.z - enh.fog.z, 0.0)); + let dl = distance(xc, l.pos.xyz); + let atten = exp(-layer_depth(s0, enh.fog.y, c.z - enh.fog.z, xc.z - enh.fog.z, tc - start) - sigma * dl); + sum = sum + l.color.rgb * (l.color.w * strength * acc * half / hh * sigma * atten); + } + } + t = t_out; + if (tx < ty) { + tx = tx + inv_x; + ix = ix + sx; + } else { + ty = ty + inv_y; + iy = iy + sy; + } + } + return sum * enh.lights.y; +} + +// Enhanced: the light a raindrop or a snowflake sends towards the eye - what it scatters of +// the sky's light, the sun's and the lamps' round it, the drop's strongly forward (a +// streak flashes against a lamp seen through the rain, and is next to invisible in the +// dark between the lamps), the flake's nearly every way. (Drawn at the display's level +// whatever the light, the flakes of a snowfall at night shone white in the dark, far from +// any lamp.) +fn precip_light(x: vec3, to_eye: vec3, snow: bool) -> vec3 { + // the sky's and the ground's light round it, and the sun's on a small sphere + var e = enh.fog_color.rgb * (PI / 0.9) + enh.sun.rgb * 0.25; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell > 0.0 && side > 0u) { + let f = (x.xy - camera.light_grid.xy) / cell; + let gx = i32(floor(f.x)); + let gy = i32(floor(f.y)); + if (gx >= 0 && gy >= 0 && gx < i32(side) && gy < i32(side)) { + let base = (u32(gy) * side + u32(gx)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let dl = l.pos.xyz - x; + let dist2 = dot(dl, dl); + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let ld = dl * inverseSqrt(max(dist2, 1e-6)); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var k = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + if (l.extra.z != 0.0) { + k = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + k = k * smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } else if (l.dir.z < -0.5) { + k = k * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + // (the scattering towards the eye relative to an even one: a drop's light + // goes on forwards, a flake's every way. The angle is the one between the + // light's way from the lamp, -ld, and on to the eye: taken against -to_eye + // it put the forward peak behind the drop, and the drops in a bus's own + // beams, seen from behind the lamps, shone a hundred times too bright as + // white streaks down the road ahead) + let c = dot(-ld, to_eye); + let lobe = select(fog_phase(c), 0.7 * hg_phase(c, 0.3) + 0.3 / (4.0 * PI), snow) * 4.0 * PI; + e = e + l.color.rgb * l.color.w * enh.lights.y * k * lobe; + } + } + } + return e / PI; +} + + +// Enhanced graphics: the main pass's own lighting model, the usual metal/roughness one: +// GGX (Trowbridge-Reitz) microfacets with height-correlated Smith visibility and Schlick's +// Fresnel (F0 4 % for a dielectric, its colour for a metal), their multiple scattering given +// back (Fdez-Aguera), and Lambert diffuse with the share the specular part leaves it, so that +// nothing sends out more light than falls on it. Lit by the sun (soft shadows whose penumbra +// grows with the distance to the blocker; what the clouds scatter of it as a shadowless light +// of the sky's kind), the sky and the ground (spherical harmonics, occluded by the SSAO or +// the traced occlusion), a reflection probe of the sky for the reflections (the split sum +// with Karis' analytic DFG, occluded by the AO as Lagarde has it and by the horizon of a +// normal map), point and spot lights falling off with the square of the distance, and the +// air in between. Roughness is widened by the normal's spread across the pixel (specular +// antialiasing) and held off zero for the sun's disc. OMSI's material data +// decides the surface: [matl_envmap] factor x mask is how much it reflects and how smooth +// it is, the o3d specular power how rough a surface without one is, [matl_bumpmap] bends +// the normal. Everything is drawn pre-exposed into the high-range target. + +// Only painted terrain may skip empty brush-mask pixels. +override TERRAIN_PAINT: bool = false; + +@group(0) @binding(12) var t_probe: texture_cube; + +fn d_ggx(nh: f32, a: f32) -> f32 { + let a2 = a * a; + let d = nh * nh * (a2 - 1.0) + 1.0; + return a2 / (PI * d * d); +} + +// The microfacets of a film of water over a road: the slopes of a water surface are +// Gaussian (Cox and Munk 1954), the Beckmann distribution. Its tail falls off as +// exp(-tan^2 / a^2), where GGX's falls as a^2 / tan^4: under GGX a headlamp - a hundred +// thousand candela towards the road - kept a highlight brighter than the lit road some ten +// degrees off its mirror direction, and its reflection ran as one white line from the lamp +// down to the camera. +fn d_beckmann(nh: f32, a: f32) -> f32 { + let c2 = max(nh * nh, 1e-4); + let a2 = a * a; + return exp(-(1.0 - c2) / (c2 * a2)) / (PI * a2 * c2 * c2); +} + +// Height-correlated Smith visibility (G / (4 n.l n.v)). +fn v_smith(nv: f32, nl: f32, a: f32) -> f32 { + let a2 = a * a; + let gv = nl * sqrt(nv * nv * (1.0 - a2) + a2); + let gl = nv * sqrt(nl * nl * (1.0 - a2) + a2); + return 0.5 / max(gv + gl, 1e-5); +} + +// A diffuse surface's albedo under a film of water (n = 1.33; Lekner and Dorf 1988): the +// film lets in 1 - 0.066 of diffuse light, and of what the surface scatters back up only +// 1 - 0.472 leaves through the film's top, the rest returns to the surface. +fn wet_albedo(a: vec3) -> vec3 { + return 0.934 * a * 0.528 / (vec3(1.0) - 0.472 * a); +} + +fn f_schlick(f0: vec3, c: f32) -> vec3 { + let f = pow(1.0 - clamp(c, 0.0, 1.0), 5.0); + return f0 + (vec3(1.0) - f0) * f; +} + +// The split-sum's integral of the GGX lobe over the hemisphere for a white and a black F0 +// (Karis' analytic fit of the DFG table): the reflectance is f0 * x + y. +fn dfg_ab(rough: f32, nv: f32) -> vec2 { + let c0 = vec4(-1.0, -0.0275, -0.572, 0.022); + let c1 = vec4(1.0, 0.0425, 1.04, -0.04); + let r = c0 * rough + c1; + let a004 = min(r.x * r.x, pow(2.0, -9.28 * nv)) * r.x + r.y; + return vec2(-1.04, 1.04) * a004 + r.zw; +} + +// The split-sum environment term, single scattering only. +fn env_brdf(f0: vec3, rough: f32, nv: f32) -> vec3 { + let ab = dfg_ab(rough, nv); + return f0 * ab.x + vec3(ab.y); +} + +// What a surface reflects specularly towards the eye of light from every direction, with the +// light its microfacets pass on to each other before it leaves (Fdez-Aguera 2019, after +// Kulla and Conty): rgb that reflectance (the probe's weight; one minus it is what is left +// for the diffuse part, so the two never add up to more than came in), w the factor by which +// the single-scattering lobe of a direct light falls short of it. Without the multiple +// scattering a rough metal lost up to half its light and went dark grey. +fn spec_ms(f0: vec3, rough: f32, nv: f32) -> vec4 { + let ab = dfg_ab(rough, nv); + let ess = clamp(ab.x + ab.y, 0.05, 1.0); + let fss = f0 * ab.x + vec3(ab.y); + let ems = 1.0 - ess; + let favg = f0 + (vec3(1.0) - f0) / 21.0; + let fms = fss * favg / (vec3(1.0) - ems * favg); + let comp = 1.0 + dot(f0, vec3(0.2126, 0.7152, 0.0722)) * (1.0 / ess - 1.0); + return vec4(min(fss + fms * ems, vec3(1.0)), comp); +} + +// Specular antialiasing (Tokuyoshi and Kaplanyan 2019): the spread of the normal across the +// pixel widens the lobe, so that a mirror-smooth finish on a curved, faceted or normal-mapped +// surface does not sparkle and crawl where it is smaller than a pixel. Returns the +// perceptual roughness. +fn rough_aa(rough: f32, n: vec3) -> f32 { + let dx = dpdx(n); + let dy = dpdy(n); + let variance = 0.25 * (dot(dx, dx) + dot(dy, dy)); + let kernel = min(2.0 * variance, 0.18); + let a = rough * rough; + return sqrt(sqrt(clamp(a * a + kernel, 0.0, 1.0))); +} + +// Horizon occlusion (Jimenez et al. 2016): a normal map can turn a reflection below the +// surface the geometry really has; that part of the lobe sees the surface itself, not the sky. +fn horizon_occlusion(r: vec3, geo_n: vec3) -> f32 { + let h = clamp(1.0 + 1.3 * dot(r, geo_n), 0.0, 1.0); + return h * h; +} + +// The sun's light through the clouds that is no longer a beam (`enh.pbr_ext.x` the beam's +// share, lighting/enhanced.rs `sun_directness`): what a veil or a thin deck scatters round the +// sun lies on the street as a bright dome overhead with a glow towards the sun, casting no +// shadow. It is the flux the beam would have brought to the ground (its share on a horizontal +// surface), spread so: a cloudy day's light is flat, not a weaker sun with sharp shadows. +fn sun_scattered(n: vec3, e: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let dome = 0.5 + 0.5 * n.z; + let lobe = (1.0 + dot(n, s)) / (1.0 + max(s.z, 0.0)); + return e * max(s.z, 0.0) * mix(dome, lobe, 0.4); +} + +// The beam's share of the sun's light (1 under a clear sky; 0 while the pass has not set it). +fn sun_beam_share() -> f32 { + return select(1.0, clamp(enh.pbr_ext.x, 0.0, 1.0), enh.pbr_ext.y > 0.5); +} + +// Ambient occlusion that lets bright surfaces bounce some light back into their own +// corners (Jimenez' multi-bounce fit), so white walls do not get grey creases. +fn ao_bounce(ao: f32, albedo: vec3) -> vec3 { + let a = 2.0404 * albedo - vec3(0.3324); + let b = -4.7951 * albedo + vec3(0.6417); + let c = 2.7552 * albedo + vec3(0.6903); + return max(vec3(ao), ((a * ao + b) * ao + c) * ao); +} + +// World direction to the probe's cube coordinates (and back: the swap is its own inverse). +fn to_cube(d: vec3) -> vec3 { + return vec3(d.x, d.z, d.y); +} + +// What a raindrop on a pane shows (`glass_film`): the sky probe that way, blurred a little +// by the drop's small lens, and low down the street's light in place of the probe's +// horizon (see the reflections in `shade_enhanced`). +fn rain_env_enhanced(d: vec3, lod: f32) -> vec3 { + let e = textureSampleLevel(t_probe, s_lin, to_cube(d), lod).rgb * enh.fog_color.w; + let surround = enh.fog_color.rgb * (0.25 / 0.9); + return mix(surround, e, smoothstep(-0.05, 0.35, d.z)); +} + +// A fixed, deterministic PCF kernel (shader.wgsl's `shadow_tent`). The old PCSS blocker +// search was unstable for alpha-tested foliage: a few leaves entering or leaving its +// 12-sample search changed the penumbra radius, producing checkerboard patches and +// camera-driven strips. The filter is fixed in shadow-map space, so the only thing that +// can change is the actual caster. `thin`: foliage, whose normals OMSI points up for even +// lighting - no receiver plane can be taken from them, a leaf compares at its own depth. +fn sun_shadow_soft(world_in: vec3, n: vec3, thin: bool) -> f32 { + if (camera.shadow.x < 0.5) { + return 1.0; + } + // (half a metre towards the sun for a leaf, as in `sun_shadow`) + let world = world_in + select(vec3(0.0), camera.sun_dir.xyz * 0.5, thin); + let ndl = clamp(dot(n, camera.sun_dir.xyz), 0.0, 1.0); + // (a veil of high cloud spreads the sun into an aureole a few degrees wide: the light + // comes from a larger source, and the shadow's edge widens with it) + // (the tent's four gathers step apart for it: see `shader.wgsl`'s `shadow_tent_near`) + let widen = 1.0 + 3.0 * enh.cloud_sun[1].w; + let close = shadow_close(world, n, ndl, thin); + if (close.y >= 0.999) { + return close.x; + } + let near_lp = camera.light_view_proj * vec4(world + shadow_push_near(n, ndl), 1.0); + let near_uv = vec2(near_lp.x * 0.5 + 0.5, 0.5 - near_lp.y * 0.5); + let near_edge = max(abs(near_uv.x - 0.5), abs(near_uv.y - 0.5)); + let near_valid = near_edge < 0.48 && near_lp.z >= 0.0 && near_lp.z <= 1.0; + var near_slope = shadow_receiver_slope(camera.light_view_proj, n); + var far_slope = shadow_receiver_slope(camera.light_view_proj_far, n); + if (thin) { + near_slope = vec2(0.0); + far_slope = vec2(0.0); + } + // Blend cascades by radial distance, not by the near map's projected square. The + // projected-edge test made the blend factor change when the camera moved sideways or + // turned, even for a stationary receiver; that reads as a full shadow shimmer at the + // cascade boundary. The light boxes still validate coverage above, while this gives + // the overlap a camera-centred, continuous transition. + let radial = distance(world, camera.cam_pos.xyz); + let near_weight = select( + 0.0, + 1.0 - smoothstep(camera.shadow.z * 0.62, camera.shadow.z * 0.92, radial), + near_valid, + ); + // Each cascade is filtered only where it counts: sampling both everywhere (32 compares + // a pixel) halved the enhanced picture's frame rate against shadows off. + var near_value = 1.0; + if (near_weight > 0.001) { + near_value = shadow_pcf_near(near_uv, near_lp.z, near_slope, widen); + } + near_value = mix(near_value, close.x, close.y); + if (near_weight >= 0.999) { + return near_value; + } + let flp = camera.light_view_proj_far * vec4(world + shadow_push_far(n, ndl), 1.0); + let fuv = vec2(flp.x * 0.5 + 0.5, 0.5 - flp.y * 0.5); + let far_valid = fuv.x >= 0.0 && fuv.x <= 1.0 && fuv.y >= 0.0 && fuv.y <= 1.0 && flp.z >= 0.0 && flp.z <= 1.0; + var far_safe = 1.0; + if (far_valid) { + let far_value = shadow_pcf_far(fuv, flp.z, far_slope, widen); + let far_edge = max(abs(fuv.x - 0.5), abs(fuv.y - 0.5)); + far_safe = mix(1.0, far_value, clamp((0.5 - far_edge) * 12.0, 0.0, 1.0)); + } + return mix(far_safe, near_value, near_weight); +} + +// Enhanced+: the solid casters' shadow where no traced one is there for a surface. The close +// and near maps hold only the cut-out casters then (`shadow_plan`), and such a surface - a +// pane, the edge of a step or a handrail thinner than a pixel of the depth prepass - lay in +// the sun under a roof: bright specks and stair-stepped lines along the edges, flickering +// as the camera moved and the traced texel was found or not. The far map keeps them all. +fn sun_shadow_far(world: vec3, n: vec3) -> f32 { + if (camera.shadow.x < 0.5) { + return 1.0; + } + let ndl = clamp(dot(n, camera.sun_dir.xyz), 0.0, 1.0); + let flp = camera.light_view_proj_far * vec4(world + shadow_push_far(n, ndl), 1.0); + let fuv = vec2(flp.x * 0.5 + 0.5, 0.5 - flp.y * 0.5); + if (fuv.x < 0.0 || fuv.x > 1.0 || fuv.y < 0.0 || fuv.y > 1.0 || flp.z < 0.0 || flp.z > 1.0) { + return 1.0; + } + return shadow_pcf_far(fuv, flp.z, shadow_receiver_slope(camera.light_view_proj_far, n), 1.0); +} + +// The sun's shadow at a point by one compare in the finest cascade that holds it (the close +// one, else the near one; lit beyond): for glass (see fs_enhanced). +fn sun_shadow_hard(world: vec3, n: vec3) -> f32 { + if (camera.shadow.x < 0.5) { + return 1.0; + } + let ndl = clamp(dot(n, camera.sun_dir.xyz), 0.0, 1.0); + let range = camera.flags.w; + if (range > 0.0 && distance(world, camera.cam_pos.xyz) < range * 0.75) { + let lp = camera.light_view_proj_close * vec4(world + shadow_push_close(n, ndl), 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (max(abs(uv.x - 0.5), abs(uv.y - 0.5)) < 0.48 && lp.z >= 0.0 && lp.z <= 1.0) { + let scale = select(1.0, camera.post.w, camera.post.w > 0.0); + let a = vec2(uv.x * 0.5 * scale + 0.5, uv.y * scale); + return textureSampleCompareLevel(t_shadow, s_shadow, a, lp.z - SHADOW_BIAS_CLOSE / SHADOW_DEPTH_RANGE); + } + } + let lp = camera.light_view_proj * vec4(world + shadow_push_near(n, ndl), 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (max(abs(uv.x - 0.5), abs(uv.y - 0.5)) < 0.48 && lp.z >= 0.0 && lp.z <= 1.0) { + return textureSampleCompareLevel(t_shadow, s_shadow, vec2(uv.x * 0.5, uv.y), lp.z - SHADOW_BIAS_NEAR / SHADOW_DEPTH_RANGE); + } + return 1.0; +} + +// What a surface reflects and scatters: diffuse albedo, specular colour at normal +// incidence, perceptual roughness. +struct Surface { + albedo: vec3, + f0: vec3, + rough: f32, + // what the specular reflection leaves the diffuse part (`spec_ms`), and the factor + // that gives the specular lobe back the light of its multiple scattering + kd: vec3, + comp: f32, +}; + +// How much of lamp `li` reaches the point (1 for a lamp without a shadow map): its map is +// one of the tiles under the far shadow map (lib.rs `LampShadow`), which the light's record +// names (`light_marks`): looking down from a street lamp's head, or along the road from a +// vehicle's headlamps; a few taps of it soften the edge, as the lamp's glowing bowl does. +// (the player's headlamps - marked so - share one map from between them along the road, +// `passes::headlamp_shadow`; it is read once for the pair, `own_shadow`) +var own_shadow: f32; +fn lamp_shadow_at(li: u32, p: vec3, n: vec3, thin: bool) -> f32 { + let marks = light_marks(lights[li]); + let own = marks.x > 0.5; + if (marks.z < 0.5) { + return 1.0; + } + var k = u32(marks.z - 0.5); + if (own && own_shadow >= 0.0) { + return own_shadow; + } + let to_lamp = p - lights[li].pos.xyz; + // a lamp that shines every way has a block of six tiles, one a direction (+x -x +y -y +z -z, + // lib.rs `CUBE_SLOTS`): the one the lit point lies in + if (k >= 44u) { + let a = abs(to_lamp); + var face = select(5u, 4u, to_lamp.z > 0.0); + if (a.x >= a.y && a.x >= a.z) { + face = select(1u, 0u, to_lamp.x > 0.0); + } else if (a.y >= a.z) { + face = select(3u, 2u, to_lamp.y > 0.0); + } + k = k + face; + } + let d = length(to_lamp); + // (off the surface by a texel or so of the map there; a leaf card towards the lamp) + let off = select(n * (0.03 + 0.012 * d), normalize(lights[li].pos.xyz - p) * 0.3, thin); + let q = camera.lamp_view_proj[k] * vec4(p + off, 1.0); + if (q.w <= 0.0) { + return 1.0; + } + let ndc = q.xyz / q.w; + if (abs(ndc.x) >= 1.0 || abs(ndc.y) >= 1.0 || ndc.z >= 1.0 || ndc.z <= 0.0) { + return 1.0; + } + + let tuv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + // (the far map's texture: its width, its height with the tiles under it; the tile's + // texels in the atlas's terms, kept a texel off its edges) + let dims = vec2(1.0 / camera.shadow.y, camera.lamp_atlas.z); + let tile = camera.lamp_atlas.x; + let cols = camera.lamp_atlas.y; + let tx = clamp(tuv * tile, vec2(1.5), vec2(tile - 1.5)); + let base = vec2(f32(k % u32(cols)) * tile, dims.x + f32(k / u32(cols)) * tile) + tx; + // (nine taps; a saloon's lamp - tiles 28 on - four: its tile's texels are three centimetres + // and every pixel of a saloon takes a handful of lamps) + // (two loops of fixed bounds: one bounded by the tile's kind was not unrolled) + let saloon = k >= 28u && k < 44u; + let zr = ndc.z - 0.00002; + var sum = 0.0; + var taps = 9.0; + if (saloon) { + for (var y = 0; y <= 1; y = y + 1) { + for (var x = 0; x <= 1; x = x + 1) { + let a = (base + (vec2(f32(x), f32(y)) - vec2(0.5)) * 1.25) / dims; + sum = sum + textureSampleCompareLevel(t_shadow_far, s_shadow, a, zr); + } + } + taps = 4.0; + } else { + for (var y = -1; y <= 1; y = y + 1) { + for (var x = -1; x <= 1; x = x + 1) { + let a = (base + vec2(f32(x), f32(y)) * 1.25) / dims; + sum = sum + textureSampleCompareLevel(t_shadow_far, s_shadow, a, zr); + } + } + } + let lit = sum / taps; + if (own) { + own_shadow = lit; + } + return lit; +} + +const CABIN_FILL: f32 = 0.2; + +// How much of the player's saloon lamps' light reaches a point past what stands in it, 1 where +// nothing does: each lamp that has a shadow map (`camera.cabin_lamps`: the first sixteen, by +// their records in the light buffer, -1 for none) weighs by what it would give the point +// unshadowed. The saloon's meshes are lit by the sets of lamps their models name and by light +// maps made for the lamps; this is what lets a handrail or a seat shade what it stands over +// in both. +fn cabin_visibility(p: vec3, n: vec3) -> f32 { + var open_light = 0.0; + var seen_light = 0.0; + for (var i = 0u; i < 16u; i = i + 1u) { + let at = camera.cabin_lamps[i / 4u][i % 4u]; + if (at < 0.0) { + break; + } + let li = u32(at); + let l = lights[li]; + let d = l.pos.xyz - p; + let dist2 = max(dot(d, d), 1e-4); + let ndl = dot(n, d * inverseSqrt(dist2)); + if (ndl <= 0.0 || l.color.w <= 0.0) { + continue; + } + let core = max(l.extra.y, 0.01); + let share = (l.color.r + l.color.g + l.color.b) * l.color.w * core * core / dist2 * ndl; + open_light = open_light + share; + seen_light = seen_light + share * lamp_shadow_at(li, p, n, false); + } + // (the light a closed room's lining sends back where the lamps do not reach: a saloon's + // walls, ceiling and seats, a third reflecting, lit by the lamps again and again - about + // a fifth of what the lit parts have) + let direct = clamp(seen_light / max(open_light, 1e-6), 0.0, 1.0); + return select(1.0, mix(CABIN_FILL, 1.0, direct), open_light > 1e-4); +} + +// A light cookie layer's texels a side (lib.rs `cookies::COOKIE_SIZE`). +const COOKIE_SIZE: u32 = 32u; + +// The enhanced path's marks on a light (lib.rs `prepare_lights`, carried in `pos.w` below +// zero, in steps of 32 for its tile and the low bits below): x 1 for one of the player's +// headlamps, y 1 + the layer of its beam's picture (0: none), z 1 + its shadow map's tile +// (0: none, see `LAMP_MARK`). +fn light_marks(l: PointLight) -> vec3 { + let m = max(-l.pos.w, 0.0); + let tile = floor(m / 32.0); + let rest = m - tile * 32.0; + let own = select(0.0, 1.0, rest > 15.5); + return vec3(own, rest - own * 16.0, tile); +} + +// A light cookie's texel (x, y) of the layer whose records start at `base`. +fn cookie_texel(base: u32, x: u32, y: u32) -> vec3 { + let i = min(y, COOKIE_SIZE - 1u) * COOKIE_SIZE + min(x, COOKIE_SIZE - 1u); + let rec = lights[base + i / 4u]; + let k = i % 4u; + return select(select(rec.pos.xyz, rec.color.xyz, k == 1u), select(rec.dir.xyz, rec.extra.xyz, k == 3u), k >= 2u); +} + +// What a lamp with a picture of its beam (`[spotlight_cookie]`) sends towards `t` (unit, +// from the lamp): the picture's light there, as the beam would show on a wall square to +// the lamp - the picture's right towards the lamp's right as seen from behind it, its top +// up - and nothing outside the field it covers (`camera.cookies`: x, y its half angles' +// tangents, z where its layer starts in the light buffer, four linear texels a record), +// filtered between its four nearest texels. +fn cookie_light(t: vec3, l: PointLight) -> vec3 { + let f = l.dir.xyz; + let ahead = dot(t, f); + let rc = cross(f, vec3(0.0, 0.0, 1.0)); + let r = select(vec3(1.0, 0.0, 0.0), normalize(rc), dot(rc, rc) > 1e-8); + let layer = camera.cookies[min(u32(light_marks(l).y - 0.5), 7u)]; + let q = vec2(dot(t, r), dot(t, cross(r, f))) / (max(ahead, 1e-3) * max(layer.xy, vec2(1e-3))); + let st = clamp(vec2(q.x * 0.5 + 0.5, 0.5 - q.y * 0.5) * f32(COOKIE_SIZE) - vec2(0.5), vec2(0.0), vec2(f32(COOKIE_SIZE) - 1.0)); + let c0 = vec2(st); + let w = st - floor(st); + let base = u32(layer.z); + let top = mix(cookie_texel(base, c0.x, c0.y), cookie_texel(base, c0.x + 1u, c0.y), w.x); + let bottom = mix(cookie_texel(base, c0.x, c0.y + 1u), cookie_texel(base, c0.x + 1u, c0.y + 1u), w.x); + return select(vec3(0.0), mix(top, bottom, w.y), ahead > 1e-3 && all(abs(q) < vec2(1.0))); +} + +// The radiance of the street round the point as the lamps light it (`lamp_light` leaves it +// here): what a reflection pointing at the street and the walls beside it sees at night. +var lamp_ground: vec3; + +// The point and spot lights of the pixel's grid cell: diffuse and specular. +// `thin`: foliage, lit from whichever side the lamp is on (see the sun below). +// `film`: a wet road's film of water - x how much of the surface it is (0: none), y how +// rough it is, z the share of it that mirrors - with which the lamps are reflected as the +// sky is (`refl_rough`, `wet_share` in fs_enhanced), not by the dry surface's own lobe. +fn lamp_light(p: vec3, n: vec3, v: vec3, sf: Surface, thin: bool, shadows: bool, film: vec3, back: bool) -> vec3 { + var sum = vec3(0.0); + lamp_ground = vec3(0.0); + own_shadow = -1.0; + // the lamps' light on the ground round the point (a horizontal surface's, unshadowed: + // the ground the point looks down at is wider than its own shadow) + var ground_e = vec3(0.0); + + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell <= 0.0 || side == 0u) { + return sum; + } + let f = (p.xy - camera.light_grid.xy) / cell; + let x = i32(floor(f.x)); + let y = i32(floor(f.y)); + if (x < 0 || y < 0 || x >= i32(side) || y >= i32(side)) { + return sum; + } + let a = max(sf.rough * sf.rough, 0.02); + let a_film = max(film.y * film.y, 0.02); + let nv = max(dot(n, v), 1e-4); + let facing = select(1.0, 0.0, back); + let base = (u32(y) * side + u32(x)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let d = l.pos.xyz - p; + let dist2 = dot(d, d); + // (pos.w is 0 on a spot light, which the vanilla shader is to pass by) + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let dist = sqrt(dist2); + let ld = d / max(dist, 1e-3); + // inverse-square beyond the core with a soft knee at it, not flat within it; windowed to zero at + // the range so the grid cut-off does not show + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var e = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + // (a lamp's picture of its beam: its colour that way, see `cookie_light`) + var tint = vec3(1.0); + if (l.extra.z != 0.0) { + e = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + let cd = dot(-ld, l.dir.xyz); + if (light_marks(l).y > 0.5) { + tint = cookie_light(-ld, l); + e = e * step(1e-4, max(tint.r, max(tint.g, tint.b))); + } else { + e = e * smoothstep(l.dir.w, l.extra.x, cd); + } + } else if (l.dir.z < -0.5) { + // a lamp in a housing (a street lamp's head, a platform's light): its reflector + // sends the light down and out, its housing keeps it from the sky - a few per + // cent above its horizon, what the bowl and the pole scatter (the upward light + // ratio of road lighting, EN 13201 / CIE 115). Shining evenly every way, every + // lamp lit the crowns of the trees and the upper floors over it as brightly + // as the street. + e = e * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + if (e <= 0.0 || (!(l.extra.z == 0.0 && l.dir.w < -1.5 && l.dir.z < -0.5) && own_vehicle_blocks(p, l.pos.xyz))) { + continue; + } + var irr = l.color.rgb * tint * l.color.w * enh.lights.y * e; + let nl = dot(n, ld); + ground_e = ground_e + irr * max(ld.z, 0.0); + // Ground bounce is unshadowed. A lamp behind an ordinary surface contributes + // no direct light, so it must not sample its shadow map before being rejected. + if (!thin && nl <= 0.0) { + continue; + } + // the lamps' own shadow maps (the few lighting the view most, see `lamp_shadow_at`) + if (shadows) { + irr = irr * lamp_shadow_at(li, p, n, thin); + } + if (thin) { + // a headlamp skims the grass: it lights the tips, not a crown's every side + let wrap = select(0.45 + 0.25 * nl, 0.15 + 0.6 * max(nl, 0.0), l.extra.z != 0.0); + sum = sum + irr * wrap * sf.albedo / PI; + continue; + } + let h = normalize(ld + v); + let nh = max(dot(n, h), 0.0); + let fr = f_schlick(sf.f0, dot(v, h)); + var spec = d_ggx(nh, a) * v_smith(nv, nl, a) * fr; + if (film.x > 0.0) { + spec = mix(spec, d_beckmann(nh, a_film) * v_smith(nv, nl, a_film) * fr * film.z, film.x); + } + spec = spec * facing * sf.comp; + sum = sum + irr * nl * (sf.albedo / PI * sf.kd + spec); + } + // What the lit ground throws back up: a diffuse reflector of the street's albedo (asphalt + // and paving about 0.18, under water darker, fresh snow 0.75), seen by a surface over the + // lower half of its view, (1 - n.z) / 2 of it - a wall half, the underside of a shelter's + // roof all, the ground itself nothing. Without it the lamps lit only what faces them, and + // a facade or a bus's flank beside a lit street stood black. + let snow = clamp(enh.weather.y, 0.0, 1.0); + let rho = mix(0.18, 0.75, snow) * mix(1.0, 0.6, clamp(enh.weather.x, 0.0, 1.0) * (1.0 - snow)); + let seen = select((1.0 - clamp(n.z, -1.0, 1.0)) * 0.5, 0.5, thin); + sum = sum + ground_e * rho * seen * sf.albedo / PI; + lamp_ground = ground_e * rho / PI; + return sum; +} + +// The relief a rough surface has under its microfacets - asphalt's grit and chippings, a +// paving stone's dressing, a cobble's dome (slopes of a quarter and more, at millimetres to +// centimetres) - shadows and masks itself (Smith's function for that slope spread, +// height-correlated) towards a light and an eye low over it. GGX's own roughness is the +// grain under that; on its own it let a low sun's grazing glint off every rough road and +// wall shine white towards the camera, where a real road keeps it dull. The spread grows +// with the rougher surface, and with the patch the pixel covers: farther off, the road's +// waves and ruts are under the pixel too. A smooth surface is left as it is. +fn relief_masking(nl: f32, nv: f32, rough: f32, footprint: f32) -> f32 { + let s2 = 0.0625 * smoothstep(0.45, 0.85, rough) + 0.02 * smoothstep(0.01, 0.12, footprint) * smoothstep(0.45, 0.7, rough); + if (s2 <= 0.0) { + return 1.0; + } + // (Smith's Lambda for a slope variance s2: (sqrt(1 + s2 tan^2) - 1) / 2) + let ml = clamp(nl, 1e-3, 1.0); + let mv = clamp(nv, 1e-3, 1.0); + let ll = 0.5 * (sqrt(1.0 + s2 * (1.0 - ml * ml) / (ml * ml)) - 1.0); + let lv = 0.5 * (sqrt(1.0 + s2 * (1.0 - mv * mv) / (mv * mv)) - 1.0); + return 1.0 / (1.0 + ll + lv); +} + +// The light inside a cab relative to the average light outside: a bus's big windows let in +// most of the sky, and the dashboard lies right under the windscreen. +const CAB_AMBIENT: f32 = 1.15; + +// How far the puddle threshold drops with the wetness: see the puddle mask in `shade_enhanced`. +const PUDDLE_SPREAD: f32 = 0.37; + +/// The mip level a pixel's footprint asks for, in levels of the texture whose size is +/// `texels` (the usual `log2` of the larger derivative, held at 0 and up). An LED panel is +/// sampled with this, held at `enh.led.y` (`Lighting::led_mips`): 0 point-samples it, which +/// is the sharpest and shimmers worst - a regular dot grid is the worst case for a point +/// sample - and every level the chain is allowed to take is a 2x2 average that a point +/// sample of the level below does not have. (The derivatives have to be taken in uniform +/// control flow: the panels are per draw, so a call inside the material's branch is not.) +fn led_lod(uv: vec2, texels: vec2) -> f32 { + let dx = dpdx(uv) * texels; + let dy = dpdy(uv) * texels; + return max(0.5 * log2(max(dot(dx, dx), dot(dy, dy))), 0.0); +} + +// A tangent-space normal `tn` (a PBR normal map's) turned into the world about the +// surface normal `n`, with the tangent frame taken from how the position and the uv change +// across the pixel (no tangents in OMSI's meshes). `tn.y` down the texture, as Direct3D's +// normal maps have it. +fn perturb_normal(n: vec3, p: vec3, uv: vec2, tn: vec3) -> vec3 { + let dp1 = dpdx(p); + let dp2 = dpdy(p); + let duv1 = dpdx(uv); + let duv2 = dpdy(uv); + let dp2perp = cross(dp2, n); + let dp1perp = cross(n, dp1); + let t = dp2perp * duv1.x + dp1perp * duv2.x; + let b = dp2perp * duv1.y + dp1perp * duv2.y; + let m = max(dot(t, t), dot(b, b)); + if (m < 1e-20) { + return n; + } + let k = inverseSqrt(m); + return safe_normal(t * k * tn.x + b * k * tn.y + n * max(tn.z, 0.05)); +} + +// The enhanced pass's two targets: the picture, and the screen mask (r: 1 on the bus's own +// screens, carried by the coverage of what is drawn over them; g: 1 on an LED panel's own +// dots, 0.25 on other screens, see MASK_FORMAT; b is wet puddles' reflected-light weight). +struct EnhancedOut { + @location(0) color: vec4, + @location(1) mask: vec4, + //RT @location(2) gbuf: vec4, + //RT @location(3) aux: vec4, +}; + +// Enhanced+ (the window's picture, camera.clouds.w 2): the surface the traced reflections +// start from - its normal and how much of the reflection lands on the screen (w), its +// distance from the eye and its roughness, all times that weight (see GBUF_FORMAT). The +// probe's reflection is left out of the colour there: the traced one is added in its place. +var rt_gbuf: vec4; +var rt_aux: vec4; + +fn enhanced_surface(in: FsIn) -> EnhancedOut { + rt_gbuf = vec4(0.0); + rt_aux = vec4(0.0); + var puddle_weight = vec2(0.0); + let c = shade_enhanced(in, &puddle_weight, false, camera.cam_pos.xyz); + let screen = material.flags.x > 0.5; + // an LED panel's dots stay in the glow's source (`post.wgsl`), the other screens' + // letters stay out of it + let led = select(0.0, 1.0, material.emissive.w < -1.5); + var out: EnhancedOut; + out.color = c; + // Non-LED screens carry g = r / 4. The ratio survives a clear pane's coverage + // blending, so a faded screen marker cannot be mistaken for condensation. + // Water keeps its occluded sky weight in g and reflection weight in b. + // A vehicle's shadow is light blocked from the road, not a new dry surface. Its + // colour still blends normally, but it must preserve the road's reflection mask. + // A transparent screen layer must leave the masks underneath intact. Otherwise + // unused LED colour layers make the whole panel's background bloom as lit dots. + let coverage = select(c.a, 0.0, in.params2.w > 1.5); + // (r under 0.5: how much light the player's bus's misted glass scatters there, for the + // tone mapping's blur - post.wgsl `misted`. The mask is blended by the coverage, so the + // share is divided by it to land as MIST_MASK x the share over what lies behind; + // a misted pane's coverage is at least half its share, see `shade_enhanced`) + let mist = select(0.0, glass_fog * MIST_MASK / max(coverage, 1e-3), glass_fog > 0.001); + let screen_code = select(0.25, 1.0, led > 0.5); + out.mask = vec4(select(min(mist, 0.49), 1.0, screen), select(max(led, puddle_weight.y * 0.49), screen_code, screen), puddle_weight.x, coverage); + //RT out.gbuf = rt_gbuf; + //RT out.aux = rt_aux; + return out; +} + +@fragment +fn fs_enhanced(in: FsIn) -> EnhancedOut { + return enhanced_surface(in); +} + +// A headset uses mapped shadows, not screen-space ray reflections. Its colour +// pass needs only colour and the screen mask, even on an Enhanced+ renderer. +struct EnhancedColorOut { + @location(0) color: vec4, + @location(1) mask: vec4, +}; + +@fragment +fn fs_enhanced_color(in: FsIn) -> EnhancedColorOut { + let surface = enhanced_surface(in); + return EnhancedColorOut(surface.color, surface.mask); +} + +// A self-lit picture (a display, a light-mapped surface lit fully) at its own colour after +// the tone curve (post.wgsl `natural_tone`): it bleaches what is brighter than its knee - +// a display's yellow-green text came out olive - and gives the middle tones the contrast +// of `enh.debug.w` about mid grey. So the colour is kept under the knee and the contrast +// undone in advance (with the small black offset the text has always been drawn with). +// A display's own brightness for the light round it: as a bus's screens dim at night, to +// 15 % of the day's, and never lifted over their own colour by the dark-adapted metering. +fn display_dim(lift: f32) -> f32 { + let night = clamp(camera.sun_color.w, 0.0, 1.0); + return mix(lift, min(lift, 1.0) * 0.15, night); +} + +fn display_level(t: vec3) -> vec3 { + let peak = max(t.r, max(t.g, t.b)); + let tk = t * min(1.0, 0.64 / max(peak, 1e-3)); + let c = max(enh.debug.w, 1.0); + let x = 0.18 * pow(tk / 0.18 + vec3(1e-7), vec3(1.0 / c)); + return x + 0.04 * smoothstep(vec3(0.0), vec3(0.08), x); +} + +// [matl_glow] (see MaterialExtra::glow): the material is its own light. `buv` is where its +// mask is read (the light map's own coordinate, the slot it rides in) and `col` the colour +// the light is drawn in - the material's own, so a destination panel keeps the colour its +// display draws. The mask is a greyscale picture of how much shines where (white full, black +// none). The strength is the mod's own (the .cfg value x0.25, on the scale of the LED +// panels' `Led glow`) and is held against the metering as an LED panel's dots are; the +// glare round it comes from how bright it is, as every light's does (post.wgsl). +fn matl_glow_light(buv: vec2, col: vec3) -> vec3 { + let gm = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], buv, camera.lod.x); + return col * dot(gm.rgb, vec3(0.299, 0.587, 0.114)) * material.glow.x * max(enh.exposure.z * 2.0, 0.8); +} + +// How much of the light crossing the player's bus's pane its condensation scatters (0..1, +// 07_glass.wgsl `glass_condensation`), for the screen mask. +var glass_fog: f32; +// The screen mask's r for a pane scattering all the light (post.wgsl `MIST_MASK`). +const MIST_MASK: f32 = 0.24; +// Heading, pitch and roll: with the heading alone the film slid along the glass on a hill (#3958). +fn pane_local(world: vec3) -> vec3 { + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let v = vec3(d.x * ch - d.y * sh, d.x * sh + d.y * ch, d.z); + let t = enh.pane_tilt; + let p = vec3(v.x, v.y * t.y + v.z * t.x, v.z * t.y - v.y * t.x); + let b = vec3(p.x * t.w - p.z * t.z, p.y, p.z * t.w + p.x * t.z); + return b - camera.inside_c.xyz; +} + +fn shade_enhanced(in: FsIn, puddle_weight: ptr>, capture: bool, eye: vec3) -> vec4 { + // (the pane's water, read once for the uses below) + let film_water = window_wetness(in); + if (material.emissive.w > 1.5) { + // a pane's film of water: drops laid out on the glass, each a lens that mirrors the + // sky probe and shows the street upside down through itself, and the haze of the wet + // glass between them (07_glass.wgsl `glass_film`) + return glass_film(in, film_water); + } + // --- the surface's texture and alpha, exactly as the vanilla pass reads them + let terrain = material.extra.x > 0.5; + var duv = tex_address(in.uv); + if (terrain) { + duv = in.uv * material.extra.z; + } + // (without the [texcoordtransX/Y] offset: the transmap, night map and light map stay + // in place, see fs_main) + let buv = tex_address(in.uv - in.params.zw); + let msk_lod = led_lod(buv, vec2(textureDimensions(mx_tex2d[mx_mat.trans]))); + // Empty paint also needs no tiled diffuse or detail samples. Its brush mask + // replaces diffuse alpha, so coverage can be checked before those reads. + if (TERRAIN_PAINT && material.params.x > 1.5 && material.params.z > 0.5 + && material.params.w > 0.5 && enh.debug.x <= 0.5 && material.ambient.w <= 1.5) { + var coverage = sample_transmap(buv).a; + if (material.emissive.w < -1.5 && enh.led.y < msk_lod) { + coverage = textureSampleLevel(mx_tex2d[mx_mat.trans], mx_samplers[mx_mat.sampler], buv, enh.led.y).a; + } + coverage = smoothstep(0.32, 0.68, coverage); + if (coverage * material.color.a * in.params.x == 0.0) { + discard; + } + } + // An LED panel is sampled at the level its screen footprint asks for, held at + // `enh.led.y` (`Led mip strength`): its dots keep their gaps much further out than the + // full chain allows, and the shimmer is a fraction of a full-resolution sample's. The + // levels are worked out here and not inside the branch: derivatives are undefined in + // non-uniform control flow, and which of the two samples runs is per draw. When the + // setting does not bite, the plain (anisotropic) sample of the hardware is the better + // one and stays. + let pic_lod = led_lod(duv, vec2(textureDimensions(mx_tex2d[mx_mat.diffuse]))); + let led_pic = material.emissive.w < -1.5 && enh.led.y < pic_lod; + // The painted ground's albedo comes from the picture `fs_ground` laid (the base's and its + // layers', the frame's `camera.lod.y`): the terrain's base is lit once for all of them. + // (A condition of the draw alone, so the texture reads below stay in uniform control flow; + // `Renderer::plan_ground` has seen to it that every draw this holds for is in that picture.) + let from_ground = camera.lod.y > 0.5 && terrain && !TERRAIN_PAINT && !capture && material.params.x < 0.5 && material.params.z < 0.5; + var tex = vec4(1.0); + if (from_ground) { + tex = vec4(textureLoad(t_ao, vec2(in.clip.xy), 0).rgb, 1.0); + } else { + tex = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv); + if (is_snow_pane()) { + tex = glass_snow(in, film_water); + } + if (led_pic) { + tex = diffuse_border(textureSampleLevel(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, enh.led.y), duv); + } + } + let diffuse_a = tex.a; + if (terrain && !from_ground && material.extra.y > 0.0) { + let det = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], in.uv * material.extra.y, camera.lod.x); + tex = vec4(clamp(tex.rgb * det.rgb, vec3(0.0), vec3(1.0)), tex.a); + } + if (material.params.z > 0.5) { + // (an LED panel's `\S:n` mask is taken the same way: the dots stay dots when the + // panel is small, without the full-resolution shimmer) + var tm = sample_transmap(buv); + if (material.emissive.w < -1.5 && enh.led.y < msk_lod) { + tm = textureSampleLevel(mx_tex2d[mx_mat.trans], mx_samplers[mx_mat.sampler], buv, enh.led.y); + } + tex.a = select(1.0, tm.a, material.params.w > 0.5); + if (terrain && material.params.x > 1.5) { + // Coverage belongs to the brush mask, not the angle-dependent diffuse mip. + tex.a = smoothstep(0.32, 0.68, tex.a); + } + } + // One night-map read supplies both coverage and lighting. Keep the tile map + // in its north-up UVs; vehicle maps use the unscrolled material UVs. + var night_sample = vec4(0.0); + if (material.extra.w > 0.5) { + let nuv = select(buv, vec2(in.uv.x, 1.0 - in.uv.y), terrain); + night_sample = sample_nightmap(nuv); + } + tex.a = night_coverage(tex.a, night_sample.a) * tree_card_fade(in.world); + let mode = material.params.x; + // Keep the filtered fractional coverage, but tighten its transition around the cutout + // edge before MSAA turns it into sample coverage. The MSAA depth prepass skips these + // draws so uncovered samples keep the depth and colour of the scene behind them. + if ((ALPHA_TEST || capture) && mode > 0.5 && mode < 1.5) { + if (ALPHA_TO_COVERAGE) { + let aa = max(fwidth(tex.a) * 0.5, 1.0 / 255.0); + // (not `ALPHA_REF - aa`: a layer whose clear glass is alpha 128 kept a third of + // its samples there, a moire of the layer's paint over every window) + if (tex.a < ALPHA_REF) { + discard; + } + tex.a = smoothstep(ALPHA_REF - aa, ALPHA_REF + aa, tex.a); + } else if (tex.a < ALPHA_REF) { + discard; + } + } + // (a blended slot that keeps Omsi.exe's alpha test, `MaterialExtra::alpha_cut`: a + // livery's clear glass is cut away, its tinted glass blended) + tex.a = select(tex.a, 0.0, mode > 2.5 && tex.a < ALPHA_REF); + var alpha = tex.a * material.color.a; + if (mode < 0.5) { + alpha = 1.0; + } + if (!is_snow_pane()) { + alpha = alpha * clamp(film_water, 0.0, 1.0); + } + // Sparse brush masks still cover the whole tile mesh. Empty pixels contribute + // neither colour nor reflection coverage, so avoid lighting them. Keep fractional + // edges, debug views, and water (whose Fresnel can raise zero alpha) unchanged. + if (TERRAIN_PAINT && alpha == 0.0 && enh.debug.x <= 0.5 && material.ambient.w <= 1.5) { + discard; + } + let pre = enh.exposure.x; + let to_cam = eye - in.world; + let dist = length(to_cam); + let v = to_cam / max(dist, 1e-4); + let h_cam = camera.cam_pos.z - enh.fog.z; + let h_pt = in.world.z - enh.fog.z; + // (no fog inside the cab: only the part of the way outside the bus is misty) + // (the lamps' light in the fog is added over the whole picture afterwards: fog_lamps.wgsl) + let aer = air(-v, fog_distance(in.world), h_cam, h_pt); + if (in.params2.w > 1.5) { + // A vehicle's shadow blob is no surface: it is the sky light the body keeps off the + // road, a layer that only darkens what lies under it (as OMSI blends it). Shaded as + // a black surface it took the sky, the wet road's sheen and the lamps on top and + // hardly darkened anything. The air in front of it stays (the road's own fog, under + // the blob, is darkened with it as in the original). + return vec4(aer.rgb * pre, alpha * aer.a); + } + if (material.params.y > 0.5) { + // unlit (mirror glass, script and text textures): shown at their own brightness, + // under the tone curve's knee (`display_level`), and `exposure.y` undoes the + // metering (see ExposureLog in lib.rs) + let t = tex.rgb * material.color.rgb; + // A mirror (params.y 0.9) is no display: its picture is the street drawn a moment + // ago, dark at night. Brightened like a display by the metering (up to 1.6 in the + // dark) it showed a street far brighter than the one through the windscreen. + let lift = select(display_dim(enh.exposure.y), min(enh.exposure.y, 1.0), material.params.y < 0.95); + // (no [matl_glow] here: an unlit slot is drawn at its own brightness already, and + // reading the light map's slot in this branch failed Metal's shader compiler) + let c = display_level(t) * lift; + return vec4(c * aer.a + aer.rgb * pre, alpha); + } + let outside = weather_outside_n(in.world, safe_normal(in.normal), terrain, in.params2.w); + // the normal as the content gives it: never turned towards the viewer (Direct3D does + // not either, and OMSI's foliage points every leaf's normal up so the whole crown is lit + // evenly - turned round, the crown went dark above the horizon line) + var n = safe_normal(in.normal); + // the map's water (`MaterialExtra::water`): small waves running over it ripple its + // normal - fading with the distance, where they would only flicker - so that what it + // mirrors breaks up as on a lake instead of standing in it as in a pane of glass (#841) + let is_water = material.ambient.w > 1.5; + if (is_water) { + n = normalize(n + vec3(water_ripple(world_pattern_xy(in.world), camera.post.y) * clamp(1.0 - dist / 250.0, 0.2, 1.0), 0.0)); + } + // Leaves and fences transmit light. A terrain road-cut mask only removes ground: + // its remaining pixels must shade like the uncut ground on terrain-mapped splines. + // (people's cut-out hair and clothes are bodies: material flag 8) + let thin = !terrain && mode > 0.5 && mode < 1.5 && (u32(material.params2.w + 0.5) & 8u) == 0u; + let has_env = material.params2.y > 0.0; + // A blended transmap body is a masked paint surface, not glass. Traffic cars often + // use this material layout for their body; depth-disabled blends remain glass. + // Window assets are not consistent about carrying an envmap. The reliable signal + // is an explicitly named window, or a depth-disabled blended layer with env/transmap + // data that identifies a pane rather than a dirt/text overlay. This keeps bus + // panes on the reflection/transmission path after the material-depth repair. + // Painted terrain also blends a transmap without writing depth. It is never glass: + // Fresnel opacity on its empty mask pixels darkens every lower layer at grazing angles. + // A script's screen is never a pane, though it is laid out as one - blended, not writing + // depth, its letters a `\S:n` transparency map: the EMT Citaro's Krueger matrix + // (Mallorca) was taken for glass, which gives no light of its own, and its letters stayed + // grey at night while its light map lit them in Vanilla+ (#2927). + let glass = !terrain && mode > 1.5 && (material.bump.z > 0.5 || material.emissive.w > 0.5) && + (has_env || material.params.z > 0.5 || material.emissive.w > 0.5) && material.flags.x < 0.5; + // An envmap on opaque vehicle paint is legacy material data, not a request to make + // the whole body behave like glass. Keep the diffuse/sun response, but use the + // ordinary rough dielectric path for the body. + // Foliage and other alpha-tested assets are diffuse silhouettes, not polished surfaces. + // Letting the generic probe term reflect them creates white sparkles at grazing angles; + // the photographed envmap is reserved for materials that explicitly request it. + // (opaque materials reflect as well - chrome handrails, bumpers and wheel trims are + // opaque with a sphere map, and left out they showed no reflection at all in the + // enhanced picture, #266 - but through the clear-coat path below: metal only where a + // mask of its own says so) + // (not the water: its sphere map is OMSI's stand-in for the sky it mirrors, which the + // probe holds itself - drawn as paint's photo, it lay on the water as green specks) + // (a body painted through a [matl_transmap] too - most mod buses' and cars' paint, + // the W123's: its alpha is the transmap's, the envmap's mask the texture's own, as in + // the vanilla picture; left out, their paint showed no reflection at all while their + // windows did) + let reflective_env = has_env && !thin && !is_water; + // see-through glass is seen from either side: from inside the bus its normal points + // away (the vanilla pass takes the angle either way round too); taken as it is, the + // grazing Fresnel turned the whole windscreen into a milky mirror + var geo_n = n; + if (glass && dot(n, v) < 0.0) { + n = -n; + geo_n = n; + } + var face_n = n; + var face_v = 0.0; + var face_w = 1.0; + if (reflective_env && !glass && !terrain) { + let c = cross(dpdx(in.world), dpdy(in.world)); + if (dot(c, c) > 1e-14) { + let face = normalize(c) * select(-1.0, 1.0, dot(c, v) >= 0.0); + face_n = face; + face_v = dot(face, v); + face_w = smoothstep(0.5, 0.9, dot(n, face)); + } + } + if (reflective_env && material.bump.y > 0.5) { + // [matl_bumpmap]: the height map's slope bends the normal (tangent frame from the + // screen-space derivatives of position and texture coordinate) + let slope = bump_offset(duv); + let dp1 = dpdx(in.world); + let dp2 = dpdy(in.world); + let du1 = dpdx(duv); + let du2 = dpdy(duv); + let dp2p = cross(dp2, n); + let dp1p = cross(n, dp1); + let t = dp2p * du1.x + dp1p * du2.x; + let b = dp2p * du1.y + dp1p * du2.y; + let inv = inverseSqrt(max(max(dot(t, t), dot(b, b)), 1e-12)); + n = normalize(n - (t * inv * slope.x + b * inv * slope.y) * 0.6); + } + var albedo = select(tex.rgb * material.color.rgb, tex.rgb, from_ground); + // OMSI materials have separate diffuse and ambient colours. Some interiors have + // black diffuse but white ambient: using diffuse for both made them pitch black. + // Keep the direct response, and weather both colours with the same surface effects. + // A slot without a texture (ambient.w -1) takes its diffuse colour for both: Omsi.exe's + // white ambient of every o3d slot under a strong sky turned a coloured model white (#1737). + var ambient_albedo = select(tex.rgb * material.ambient.rgb, albedo, material.ambient.w < -0.5 || from_ground); + var detail_factor = 1.0; + if (camera.flags.x > 0.5 && (terrain || in.params2.w > 0.5)) { + let k = clamp(1.0 - (dist - 25.0) / 120.0, 0.0, 1.0); + let pattern_xy = world_pattern_xy(in.world); + detail_factor = 1.0 + (detail_noise(pattern_xy, k) - 0.5) * 0.42 * k; + albedo = albedo * detail_factor; + ambient_albedo = ambient_albedo * detail_factor; + } + // --- the material in physical terms + var refl = 0.0; + if (reflective_env) { + // (with a mask of its own or a [matl_transmap] the share is the mask's alone, as + // Omsi.exe's stage takes it - the factor counts only where there is none) + let by_mask = material.params.z > 0.5 || (u32(material.params2.w + 0.5) & 1u) != 0u; + refl = clamp(select(min(material.params2.y, 1.0), 1.0, by_mask) * reflection_mask(duv, diffuse_a), 0.0, 1.0); + } + var metal = 0.0; + var f0 = vec3(0.04); + var rough = 0.8; + let probe_only = camera.clouds.w < 1.5; + if (terrain) { + rough = 0.92; + f0 = vec3(0.03); + } else if (glass) { + // OMSI's window materials are deliberately very transparent. Raise the base + // dielectric reflection slightly so the outside scene remains readable through + // the pane instead of leaving a flat pale surface at normal incidence. + rough = 0.04; + // the pane's [matl_envmap] factor says how much it mirrors (its alpha is its + // transparency, never a mask): from glass's own 4 % up to 12 % for a factor of 1 + // (0.4 on the Scania's panes). Up to 26 % as before, every window of every bus + // was a mirror - far more than the original's panes reflect (issue #176). + // ... measured against the vanilla picture: Omsi.exe lays the sphere map over the + // pane by its factor and the pane shows that as faintly as it shows itself - the + // share it mirrors is the pane's alpha times the factor (0.25 .. 0.5 on the stock + // windows), at every angle, with no Fresnel term. Taken as the reflectance + // averaged over the angles (Schlick's mean, f0 + (1 - f0) / 21, as for the paint), + // the pane mirrors as much as there and rises towards grazing as glass does; 4 to + // 12 % at the normal, and three quarters of that, left the windows showing the + // saloon where the vanilla picture shows the street. + let share = clamp(alpha * min(material.params2.y, 1.0), 0.0, 1.0) * camera.cam_pos.w; + f0 = vec3(select(clamp((share - 1.0 / 21.0) * 21.0 / 20.0, 0.04, 0.9), 0.04, probe_only)); + } else if (reflective_env) { + // Paint reflects its few per cent through a smooth clear coat; much more than a few + // per cent is polished metal - but only where the model says so with a mask of its + // own ([matl_envmap_mask]). Nearly every car body carries `[matl_envmap] … 1` with + // no mask, which OMSI takes as "reflect the sphere map fully" and not as chrome: + // read as metalness it made a Golf's bonnet a mirror, in which the envmap photo's + // trees stood as contour lines across the paint at close range. + // + // The paint itself is a clear coat: a lacquer of refractive index 1.5 (4 % at normal + // incidence, Fresnel's 100 % at grazing) polished smooth, which mirrors the street + // as sharply as the windows do. How much of the sphere map OMSI lays over a + // material says how glossy it is: the stock bodies carry 1 or 10, the cabin's + // panels, frames and plastic trim 0.05 .. 0.2 - satin, a blurred sheen; the mask + // (the texture's alpha) says where. (Roughness + // 0.22 for every body, against the photo's contour lines on a car's bonnet, left + // the paint matte beside its sharp windows.) + let masked = (u32(material.params2.w + 0.5) & 1u) != 0u; + let metal_ok = (u32(material.params2.w + 0.5) & 4u) != 0u; + metal = select(0.0, smoothstep(0.3, 0.85, refl), masked || metal_ok); + // The coat is as smooth as lets it mirror, averaged over the angles, the share + // Omsi.exe lays over it: a polished 4 % coat mirrors 8.7 % on average (Fresnel's + // rise at grazing), a rough one less (2.5 % at 0.8, its grazing light scattered and + // shadowed by its own roughness). So a share of 8.7 % and more is smooth lacquer, the + // stock bodies' few per cent - the MAN NL's 15 of 255 - a satin one (taken as rough + // up to a share of a half they came out matte, #2067; smooth from 4 %, a body meant + // to mirror barely shone like glass against the light, #2474), and where the mask + // says nothing reflects - a tyre or a seal - the rough rubber or plastic it is. + // Between those and chrome, the share says how much the paint mirrors, not how + // sharply: Omsi.exe lays a soft sphere map over it, a blurred sheen of the sky. Taken + // as polished glass from 8.7 % on (0.2.42), the many mod bodies whose texture alpha + // holds a tenth to a half mirrored the grey sky like chrome - silver buses and AI + // cars that glowed (#2563, #2301). Only a share near the whole is a sharp mirror. + let coat_rough = max(clamp(0.06 + (0.087 - refl) * 11.9, 0.06, 0.8), mix(0.3, 0.06, smoothstep(0.5, 0.95, refl))); + // Where the model says how much it mirrors - a [matl_envmap_mask], or the texture's + // alpha under a [matl_transmap] (most mod bodies) - Omsi.exe lays the sphere map + // over the paint by that share at every angle (shader.wgsl's environment stage): + // OMSI has no Fresnel term, so the share is the reflectance averaged over the angles + // the surface is seen at. A Fresnel reflectance with that average (Schlick's, whose + // hemispherical mean is f0 + (1 - f0) / 21) mirrors as much as the vanilla picture + // and rises towards grazing as a real coat does. (A plain 4 % coat left those + // bodies far fainter than in the vanilla picture.) A body with neither keeps the + // lacquer's 4 %: there Omsi.exe's lerp by the factor alone made every Golf a mirror. + let authored = masked || material.params.z > 0.5; + let coat = select(0.04, clamp((refl - 1.0 / 21.0) * 21.0 / 20.0, 0.04, 0.95), authored); + f0 = mix(vec3(coat), mix(albedo, vec3(1.0), 0.4) * refl, metal); + rough = mix(coat_rough, 0.14, metal); + } else if (!thin && material.specular.w > 0.0 && dot(material.specular.rgb, vec3(1.0)) > 0.05) { + // the o3d material's Blinn-Phong power as GGX roughness + rough = clamp(sqrt(sqrt(2.0 / (material.specular.w + 2.0))), 0.4, 0.9); + } else if (thin) { + rough = 0.7; + } + if (is_water) { + // water: a dielectric of 2 % at normal incidence, nearly a mirror where it is seen + // flat, smooth but for its waves + f0 = vec3(0.02); + rough = 0.06; + metal = 0.0; + } + // --- a PBR set beside the diffuse texture (`foo_n.png`, `foo_r` / `_m` / `_ao` or + // `foo_orm`: see omsi_texture::pbr): the normal map bends the normal, the packed map + // gives the occlusion, roughness and metalness in place of the guesses above + var pbr_ao = 1.0; + if (material.pbr.x > 0.5 && !terrain) { + var tn = textureSampleBias(mx_tex2d[mx_mat.pbr_normal], mx_samplers[mx_mat.sampler], duv, camera.lod.x).xyz * 2.0 - vec3(1.0); + // (an OpenGL-style map, green up: `_gl` in its name) + if (material.pbr.x > 1.5) { + tn.y = -tn.y; + } + n = perturb_normal(n, in.world, duv, tn); + } + if (material.pbr.y + material.pbr.z + material.pbr.w > 0.5 && !terrain) { + let orm = textureSampleBias(mx_tex2d[mx_mat.pbr_orm], mx_samplers[mx_mat.sampler], duv, camera.lod.x).rgb; + if (material.pbr.y > 0.5) { + pbr_ao = orm.r; + } + if (material.pbr.z > 0.5) { + rough = clamp(orm.g, 0.03, 1.0); + } + if (material.pbr.w > 0.5) { + metal = orm.b; + f0 = mix(vec3(0.04), albedo, metal); + } + } + // rain: roads with [moisture] turn dark and smooth, everything outside a little glossier + // (not under snow: a snowy road took the rain's gloss and the snow on it shone like + // plastic in every headlight) + let dry_snow = 1.0 - clamp(enh.weather.y, 0.0, 1.0); + let wet_road = camera.shadow.w * material.params2.z * outside * dry_snow; + let wet_any = camera.shadow.w * outside * select(0.35, 0.0, glass) * dry_snow; + var puddle = 0.0; + if (wet_road > 0.0) { + albedo = albedo * mix(1.0, 0.5, wet_road); + ambient_albedo = ambient_albedo * mix(1.0, 0.5, wet_road); + rough = mix(rough, 0.12, wet_road); + f0 = mix(f0, vec3(0.02), wet_road); + // Puddles: standing water pools in low, flat spots rather than spreading evenly + // over the whole carriageway the way the sheen above does. A world-space mask at a + // frequency of its own (unrelated to the road's detail noise, so the two do not + // look tied together) picks out patches that grow with the wetness and vanish again + // as the road dries; a puddle goes glass-flat and mirrors what is above it. While it + // is actually raining rather than merely wet, and never while it is snow settling + // instead (`enh.weather.z` is fed by any precipitation, `.y` singles snow back out), + // concentric rings cross a puddle where drops land, fading as they widen - the other + // half of the wheel splashes in `puddles.rs`. + let pattern_xy = world_pattern_xy(in.world); + // (the pools: see `road_puddle_coverage`, shared with the classic picture) + puddle = road_puddle_coverage(in.world, n, wet_road); + if (puddle > 0.001) { + // A drop is a few millimetres across and its ring dies away within a hand's + // breadth, so the shared ripple grid is 12.5 cm wide and a ring grows + // to RIPPLE_MAX of a cell, about 5 cm: at 2 m cells with rings a metre and a half + // across, every drop looked like a puddle of its own. Cells run at their own pace + // and only some of them carry a drop at a time, so the surface reads as many small + // impacts rather than one pulsing pattern. + let raining = enh.weather.z * (1.0 - enh.weather.y); + // (faded out where the pixel is wider than half a ring's wave: past a few + // metres they only made the water shimmer) + let ripple_fp = max(length(dpdx(in.world)), length(dpdy(in.world))); + let ripple = puddle_ripple_seen(pattern_xy, camera.post.y, raining, puddle, ripple_fp); + // Standing water hides most of the fine asphalt grain. Keep dry and damp + // asphalt's detail, but let the reflected image read across a filled pool. + albedo = albedo * (1.0 - 0.68 * puddle) / mix(1.0, detail_factor, puddle * 0.8); + ambient_albedo = ambient_albedo * (1.0 - 0.68 * puddle) / mix(1.0, detail_factor, puddle * 0.8); + rough = clamp(mix(rough, 0.03, puddle) - ripple.z * 0.12, 0.02, 1.0); + f0 = mix(f0, vec3(enh.debug.y), puddle); + n = normalize(mix(n, geo_n, puddle) + vec3(ripple.xy, 0.0)); + } + } else if (wet_any > 0.0) { + // (a body's paint wears a film of water as smooth as glass: the street and the sky + // mirror in a wet bus as sharply as in its windows) + // (Lagarde's wet surfaces: the water stands on what faces up and runs off a wall, + // so a wall only darkens where a ledge or a step goes glossy) + let up = smoothstep(0.1, 0.9, geo_n.z); + // (the rougher, the more porous - soil, plaster, unglazed stone - and the more water + // it takes in; a smooth, sealed surface keeps its colour under the film) + let porous = smoothstep(0.25, 0.7, rough); + if (!terrain) { + rough = mix(rough, select(mix(rough * 0.75, min(rough, 0.2), up), min(rough, 0.04), reflective_env), select(wet_any, min(wet_any * 2.6, 1.0), reflective_env)); + } + // Soaked by the rain, a porous surface - soil, a paving stone, plaster, bark - + // turns darker and deeper in colour: the light that enters the water film and is + // scattered back by the surface under it is partly reflected down again at the + // film's top (total internal reflection), and meets the surface once more, which + // absorbs a share of it each time (Lekner and Dorf, "Why some things are darker + // when wet", Applied Optics 1988). Painted metal, glass and leaves shed the water. + let soak = camera.shadow.w * outside * dry_snow * select(0.75, 1.0, terrain) * mix(0.3, 1.0, porous) + * mix(0.45, 1.0, clamp(n.z, 0.0, 1.0)) * select(1.0, 0.0, reflective_env || glass || is_water || thin || metal > 0.5); + albedo = mix(albedo, wet_albedo(albedo), soak); + ambient_albedo = mix(ambient_albedo, wet_albedo(ambient_albedo), soak); + } + // snow lies on what faces up + // (not on a shadow blob: whitened, it lit the snow under the bus instead of shading it) + // (nor on a texture that is the season's snow picture, which shows the map's own snow + // as OMSI 2 does: see the vanilla shader, #879) + let snow_ok = outside * select(1.0, 0.0, in.params2.w > 1.5 || material.ambient.w > 0.5); + // a carriageway under snow that builds up: its own cover, ruts and tracks (road_snow.wgsl) + let carriageway = !terrain && material.params2.z > 0.0 && road_snow_dynamic(); + var rs = vec3(0.0); + if (carriageway && snow_ok > 0.0) { + rs = road_snow(in.world); + } + // a vehicle's part: the snow its own roof has gathered, where that is kept (another + // player's bus keeps the weather's) + let vehicle = vehicle_snow_kept(in.params2.w); + var on_vehicle = 0.0; + if (vehicle && snow_ok > 0.0) { + on_vehicle = vehicle_snow(in.params2.w, in.local); + } + let snow = select(select(enh.weather.y, rs.x, carriageway), on_vehicle, vehicle) * snow_ok; + if (rs.y > 0.0) { + // the slush in the ruts and the tracks: wet and grey, darker than the snow, glossy + let slush = rs.y * snow_ok; + albedo = mix(albedo, albedo * 0.55 + vec3(0.08), slush); + ambient_albedo = mix(ambient_albedo, ambient_albedo * 0.55 + vec3(0.08), slush); + rough = mix(rough, 0.35, slush); + } + if (snow > 0.0) { + let up = clamp(n.z, 0.0, 1.0); + let ground = select(0.0, 1.0, terrain || material.params2.z > 0.0); + // (a road kept clear - "snow on road" off - stays asphalt: whitened, it turned the + // roads white exactly when the weather says they are cleared, #1362; built-up snow + // brings its own cover) + let cleared = select(1.0, 0.0, !carriageway && camera.post.z > 0.5 && !terrain && material.params2.z > 0.0); + // (a vehicle's gathered snow lies thick enough to hide the paint) + let cover = min(cleared * snow * clamp(max(ground, smoothstep(0.78, 0.95, up) * 0.8), 0.0, 1.0) * select(0.55 + 0.35 * tex.a, 1.2, vehicle), 1.0); + albedo = mix(albedo, vec3(0.82, 0.84, 0.88), cover); + ambient_albedo = mix(ambient_albedo, vec3(0.82, 0.84, 0.88), cover); + // fresh snow is all but matte: it scatters the light and shows no highlight + rough = mix(rough, 0.95, cover); + f0 = mix(f0, vec3(0.02), cover); + metal = metal * (1.0 - cover); + } + // specular antialiasing: where the normal turns quickly across a pixel (a low-poly + // bonnet close up, a curved body far away) the surface cannot reflect sharper than that + // spread, or the interpolated normals show as bands in a mirror-like finish + if (reflective_env && !glass) { + let dndx = dpdx(n); + let dndy = dpdy(n); + let spread = min((dot(dndx, dndx) + dot(dndy, dndy)) * 2.0, 0.4); + rough = sqrt(min(rough * rough + spread, 1.0)); + } else if (!thin && !glass) { + rough = rough_aa(rough, n); + } + let env_share = select(1.0, camera.cam_pos.w, reflective_env && !glass); + var sf: Surface; + sf.albedo = albedo * (1.0 - metal); + ambient_albedo = ambient_albedo * (1.0 - metal); + sf.f0 = f0; + sf.rough = rough; + let nv = clamp(mix(face_v, dot(n, v), face_w), 1e-4, 1.0); + // the specular reflectance over the hemisphere, its multiple scattering included: one + // minus it is the share the diffuse part gets, so a surface never sends out more than falls + // on it (and a rough metal is not darker than its colour) + let spec_e = spec_ms(f0, rough, nv); + sf.kd = vec3(1.0) - spec_e.rgb; + sf.comp = spec_e.w; + // (how wide a patch of the surface the pixel covers, m: see `relief_masking`) + let relief_footprint = length(dpdx(in.world)) + length(dpdy(in.world)); + // The same depth-aware traced sample feeds the sun, AO and the debug view. Repeating + // rt_at here and inside ao_gi_at overflowed the optimizer's stack in the DX12 FXC + // fallback (used when dxcompiler.dll cannot be loaded); DXC compiles either form. + // Read it once after the early material returns, with the same taps and their order, + // so that the fallback can compile fs_enhanced too. + let surface_rt = rt_at(in.clip.xy, in.world); + // --- the sun + let s = camera.sun_dir.xyz; + let nl = dot(n, s); + var direct = vec3(0.0); + if (enh.lights.w > 0.0 && max(enh.sun.r, enh.sun.g) > 1e-5) { + var shadow = 0.0; + // (Enhanced+ without a traced shadow for the surface: the far map's as well, below - + // one call of it for both cases: two, each inlined, made the scene shader too big for + // Apple's M4 compiler, whose service crashed on every scene pipeline) + var far = false; + if (glass && nl > 0.0) { + // a pane lets nearly all of it through: the sun on it is its glint, for which one + // compare says enough (the soft filter over a cab's windscreen, doors and side + // windows was a millisecond of the frame) + shadow = sun_shadow_hard(in.world, n); + far = camera.clouds.w > 1.5; + } else if (nl > 0.0 || thin) { + // Enhanced+: the traced shadow where there is one for this surface + // (whose cut-out leaves and fences the shadow map holds alone: see `render_inner`) + let traced = surface_rt; + shadow = sun_shadow_soft(in.world, n, thin); + if (traced.w > 0.5 && traced.z >= 0.0) { + shadow = shadow * traced.z; + } else { + far = camera.clouds.w > 1.5 && traced.w < 0.5; + } + } + if (far) { + shadow = shadow * sun_shadow_far(in.world, n); + } + // (only the beam casts the shadow: what the clouds scatter of it is the sky's, below) + let e_sun = enh.sun.rgb * (shadow * cloud_shadow_ratio(in.world) * sun_beam_share()); + if (thin) { + // foliage: a crown of leaves facing every way, whose normals OMSI points up + // only to light it evenly - lit by the sun from any side (the shadow map + // darkens its far side), a little through the leaves as well. A crown is + // hundreds of leaves at every angle: on average about half of the sun falls on + // them square on, whatever the sun's height (with the up-pointing normals alone a + // low sun left every tree dull and dark while the walls beside it glowed). Seen + // against the sun a leaf glows with what comes through it - yellow-green, the + // light having passed the leaf's colour twice. + let through = pow(clamp(dot(-v, s), 0.0, 1.0), 3.0); + let leaf = sf.albedo / PI; + direct = e_sun * (leaf * (0.42 + 0.3 * max(nl, 0.0) + 0.08 * max(-nl, 0.0)) + + leaf * min(sf.albedo * 2.2, vec3(1.0)) * through * 0.45); + } else if (nl > 0.0) { + // the sun is a disc, not a point: no highlight sharper than it + let a = max(rough * rough, 0.012); + let h = normalize(s + v); + var spec = d_ggx(max(dot(n, h), 0.0), a) * v_smith(nv, nl, a) * f_schlick(f0, dot(v, h)); + // (a rough, unpolished surface's own relief hides its glint from a low sun: see + // `relief_masking`; glass, paint, chrome, water and a wet film keep theirs) + if (!glass && !reflective_env && !is_water && metal < 0.5) { + spec = spec * relief_masking(nl, nv, rough, relief_footprint); + } + // Optional road glare: only the specular sun highlight on terrain or roads. + // Diffuse sunlight, wet reflections and vehicle paint remain unchanged. + if ((terrain || material.params2.z > 0.0) && !is_water) { + spec = spec * camera.lod.z; + } + spec = select(spec, vec3(0.0), dot(geo_n, v) < 0.0 && !is_water); + direct = e_sun * nl * (sf.albedo / PI * sf.kd + spec * sf.comp); + } + } + // --- the moon: by night a directional light as the sun is, with its shadow when the + // maps are drawn along it + let em = enh.moon_light.rgb; + if (max(em.r, em.g) > 1e-9) { + let m = enh.moon.xyz; + let nlm = dot(n, m); + if (nlm > 0.0 || thin) { + var ms = 1.0; + if (enh.moon_light.w > 0.5) { + ms = sun_shadow_soft(in.world, n, thin); + } + let leaf = sf.albedo / PI; + if (thin) { + direct = direct + em * ms * leaf * (0.42 + 0.3 * max(nlm, 0.0)); + } else { + direct = direct + em * ms * nlm * leaf; + } + } + } + // --- sky and ground + var ao = 1.0; + let screen_ao = camera.clouds.w > 0.5 && !capture; + var bounce = vec3(0.0); + if (screen_ao) { +//VK ao = ao_traced_at(in.clip.xy, in.world, surface_rt); + let ag = ao_gi_at(in.clip.xy, in.world, surface_rt); + ao = ag.x; + bounce = ag.yzw; + } + // AO is generated from the opaque depth buffer. A transparent bus pane therefore + // samples the seats/dashboard behind it and makes their dark outlines crawl across the + // glass as the camera moves. The pane has its own transmission/reflection path; it must + // not inherit occlusion belonging to geometry on the far side of the window. + // (nor any other blended surface: a van's translucent door showed the shade of what + // stood behind it) + if (glass || mode > 1.5) { + ao = 1.0; + } + ao = ao * pbr_ao; + let fr = f_schlick(f0, nv); + // inside the player's vehicle the light comes in through the windows and off the + // cabin's own walls: less of it, and neither as blue nor as directional as the sky's + let in_cab = 1.0 - outside; + // The cab's light is one even ambient already (cab_e below); the screen-space occlusion + // on top of it went black in the hollow under the windscreen - the steering wheel and + // the dashboard stood dark beside a brightly lit cash desk. Inside the cab it is taken + // at a third of its strength. + ao = mix(ao, 1.0 - (1.0 - ao) * 0.35, in_cab); + let avg_e = enh.fog_color.rgb * (PI / 0.9); + let cab_e = vec3(dot(avg_e, vec3(0.2126, 0.7152, 0.0722))) * vec3(1.0, 0.98, 0.95); + // (the sun the clouds scatter: shadowless, a light of the sky's kind) + var sky_e = sh_irradiance(n); + let beam = sun_beam_share(); + if (beam < 0.999 && enh.lights.w > 0.0) { + sky_e = sky_e + sun_scattered(n, enh.sun.rgb * cloud_shadow_ratio(in.world) * (1.0 - beam)); + } + var e_amb = mix(sky_e, cab_e * CAB_AMBIENT, 0.6 * in_cab) * ao_bounce(ao, ambient_albedo) + + flash_irradiance(n) * ao * (1.0 - 0.7 * in_cab); +//VK if (screen_ao && in_cab < 1.0) { +//VK e_amb = e_amb + bounce_at(in.clip.xy, in.world) * mix(1.0, ao, 0.5) * (1.0 - in_cab); +//VK } + e_amb = e_amb + bounce * mix(1.0, ao, 0.5) * (1.0 - in_cab); + var ambient = e_amb * ambient_albedo / PI * (vec3(1.0) - spec_e.rgb * env_share); + // --- reflections: the sky probe, as sharp as the surface is smooth + var r = reflect(-v, normalize(mix(face_n, n, face_w))); + let bend_n = normalize(mix(face_n, geo_n, face_w)); + let horizon = horizon_occlusion(r, bend_n); + // a reflection pointing into the surface would show the probe's ground: bend it up + let below = dot(r, bend_n); + if (below < 0.0) { + r = normalize(r - bend_n * below * 1.02); + } + // A wet road, a wet pavement is no mirror: a soft, dim sheen of what stands round it, a + // puddle a blurred picture of it (panes, envmapped paint and still water keep their own + // smoothness). Its reflection is taken this rough, at this share. + let wet_only = !(reflective_env || glass || is_water || ((material.pbr.z > 0.5 || material.pbr.w > 0.5) && !terrain)); + let refl_rough = select(rough, max(rough, mix(0.2, 0.16, puddle)), wet_only); + let wet_share = select(1.0, mix(0.6, 0.7, puddle), wet_only); + let lod = refl_rough * (enh.lights.x - 1.0); + var env = textureSampleLevel(t_probe, s_lin, to_cube(r), lod).rgb * enh.fog_color.w; + // the probe holds only the sky: in a street the low sky is hidden behind houses and + // trees, which reflect about as much light as a quarter-white wall (without this every + // surface wore a milky sheen of the bright horizon, strongest against a low sun) + let surround = enh.fog_color.rgb * (0.25 / 0.9); + let open = smoothstep(-0.05, 0.35, r.z); + env = mix(surround, env, mix(open, 1.0, select(0.25, 0.5, reflective_env && !(glass && probe_only)))); + // the cabin reflects the cabin, not the sky - and so does the bus's own glass seen + // from the driver's seat + let cab_view = max(in_cab, near_player_vehicle(in.world) * inside_vehicle(camera.cam_pos.xyz)); + // From inside the player bus the pane is near the cabin, but it must still show the + // outside sky/street. Using the opaque-surface cabin weight here made every window a + // flat pale patch and hid the useful reflection while driving. + // A pane is the boundary between the cabin and the outside. Mixing the cabin + // irradiance into its reflection made every windscreen look like a pale grey sheet + // from the driver's seat; the interior is already behind the alpha-blended pane. + let cabin_reflection = select(0.85, 0.0, glass); + env = mix(env, cab_e * 0.35 / PI, cabin_reflection * cab_view); + // ... but the inner face of the bus's own glass cannot mirror the sky, which lies + // behind it: it mirrors the cab, far darker than the street seen through it. Taken as + // the sky, the doors (seen at a grazing angle from the driver's seat) went a milky + // grey sheet in fog and snow, when the probe is bright all round. + let own_pane = select(0.0, near_player_vehicle(in.world) * inside_vehicle(camera.cam_pos.xyz), glass); + if (reflective_env) { + // OMSI's photographed environment gives the reflection its structure (trees, + // houses, the street), the probe its light + // A pane looks it up by the reflection's direction in the world, not in the + // camera's frame as Direct3D's sphere map does: taken from the camera, what a + // standing bus's windows mirrored changed whenever the view turned, trees sliding + // in from nowhere over the street seen through them. Height gives the photo's rows + // (sky, the horizon's trees and houses, the ground), the compass direction a + // gentle drift across it that stays put in the world. + let az = atan2(r.y, r.x); + var env_uv = vec2(0.5 + 0.3 * sin(az), 0.5 + 0.45 * clamp(r.z, -1.0, 1.0)); + // The paint reads the photo as Omsi.exe's environment stage lays it on: Direct3D's + // sphere map of the reflection in the camera's frame (`sphere_map_uv`, 0x7ff670 sets + // D3DTSS_TCI_SPHEREMAP and no texture matrix), so the picture on a body turns with + // the camera's yaw and pitch as it does in OMSI. (A pane keeps the world's: through + // it the street itself is seen, and the photo turning over it read as a smear.) + if (!glass) { + env_uv = in.env_uv; + } + if (material.bump.y > 0.5) { + env_uv = env_uv + bump_offset(duv); + } + // (with the mip level its footprint needs on top of the blur: a fixed level showed + // the photo's trees as contour lines across a car's curved bonnet close up, and + // paint takes it as blurred as the vanilla path does) + let photo = textureSampleBias(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], env_uv, max(rough * 16.0, select(2.0, 0.0, glass))).rgb; + let photo_avg = textureSampleLevel(mx_tex2d[mx_mat.env], mx_samplers[mx_mat.sampler], vec2(0.5, 0.5), 12.0).rgb; + let lum_avg = max(dot(photo_avg, vec3(0.2126, 0.7152, 0.0722)), 0.02); + // (a tint, not a picture: an unbounded ratio drew the photo's trees as bands) + // (the photo's own contrast, as the vanilla picture shows it, held only off black + // and off a blinding white; clamped to 0.35 .. 2 and laid on at two thirds, the + // windows mirrored a flat grey where the vanilla ones mirror trees and sky) + let ratio = clamp(photo / lum_avg, vec3(0.12), vec3(select(3.5, 1.0, glass && probe_only))); + let band = 1.0 - smoothstep(0.25, 0.7, abs(r.z)); + // Only a smooth surface mirrors the photo; a satin one a quarter of its contrast. + // (A car's bonnet is a handful of triangles: the photo's mip level by its footprint + // above keeps its trees from turning into contour lines across it close up.) + let sharpness = 1.0 - smoothstep(0.05, 0.25, rough); + // ... and only as far as the reflection is of the outside at all: the driver's own + // windscreen reflects the cab, and the photo's trees drawn over that stood as + // contour lines across everything seen through it (a car's bonnet close up) + let outside_env = 1.0 - cab_view; + // ... and not in a fog: there is nothing sharp out there to mirror. The photo's + // trees stood as flat grey silhouettes on every pane in fog, in front of the real + // (fogged) trees behind the glass - outlines of trees that are not there + let clear_air = exp(-enh.fog.x * 150.0); + env = env * mix(vec3(1.0), ratio, band * mix(0.25, 1.0, sharpness) * outside_env * clear_air * enh.debug.z); + } + // what the SSAO darkens, it also keeps reflections out of + let spec_occ = clamp(pow(nv + ao, exp2(-16.0 * rough - 1.0)) - 1.0 + ao, 0.0, 1.0); + // (a PBR set's roughness or metalness map says how it reflects: the probe, as for an envmap) + let pbr_reflects = (material.pbr.z > 0.5 || material.pbr.w > 0.5) && !terrain; + // (a wet road mirrors the sky probe as well; and what reflects nothing keeps the light + // the Fresnel term took off its ambient above - at a grazing angle that term is near 1, + // and the far road and ground went dark with no reflection in its place, #374) + // Every solid surface reflects its few per cent: a dielectric's 4 % at normal incidence + // rising towards grazing, by its roughness and the light its microfacets pass on (the + // diffuse part took that share off above). Leaves and fences are left out: alpha-tested + // silhouettes, whose grazing sheen was white sparkle. A wet road's film reflects at its + // own share. + let reflects = !thin; + var refl_f = spec_e.rgb * spec_occ * horizon * select(1.0, mix(1.0, wet_share, wet_road), wet_only); + if (!reflects) { + ambient = e_amb * ambient_albedo / PI; + } + if (glass) { + // Transparent bus panes need a readable outside reflection from the driver's + // viewpoint; opaque paint must never receive this boost. + refl_f = refl_f * (1.0 - 0.85 * own_pane); + } + refl_f = refl_f * env_share; + var reflection = select(vec3(0.0), env * refl_f, reflects); + // Enhanced+: traced instead (rough surfaces keep the probe, which is as good as a + // ray there): the windows, the chrome and the paint's clear coat mirror the real street + // round them - the coat as sharply as the glass, where it is polished (`coat_rough`) + // (a dry plain surface - plaster, plastic, a satin wall - is traced up to a lesser + // roughness: its few per cent of a blurred street are as good from the probe, and the rays + // are spent where the reflection is seen; between the two the traced one fades in) + let trace_top = select(0.75, 0.5, wet_only && wet_road <= 0.0); + let trace_k = 1.0 - smoothstep(trace_top - 0.15, trace_top, refl_rough); + // (not the player's own panes seen from inside: their faint reflection of the cab is the + // glass's own, and the street behind them - a wet road through the windscreen - keeps + // its traced one, see below) + let traced = camera.clouds.w > 1.5 && reflects && trace_k > 0.0 && !capture && !(glass && own_pane > 0.5); + if (traced) { + var w = dot(refl_f, vec3(0.2126, 0.7152, 0.0722)) * aer.a * trace_k; + if (glass) { + // A pane mirrors what the rays find as glass does: 4 % at the normal, Fresnel's + // rise towards grazing (a tinted one a little more against what little comes + // through it). The share above is the vanilla picture's, which lays a dim photo + // over the pane; the traced street at that share - a fifth to a half - turned + // every window into a mirror of the bright sky. + let f0_glass = vec3(mix(0.04, 0.07, clamp(alpha * 1.5, 0.0, 1.0))); + w = dot(spec_ms(f0_glass, rough, nv).rgb, vec3(0.2126, 0.7152, 0.0722)) * spec_occ * horizon * env_share * aer.a * trace_k; + w = w * smoothstep(0.0, 0.05, alpha); + } else if (mode > 1.5) { + // (a blended layer reflects only where it is there: a painted ground's brush mask) + w = w * clamp(alpha, 0.0, 1.0); + } + let rough_t = refl_rough; + if (w > 0.002) { + reflection = reflection * (1.0 - trace_k); + rt_gbuf = vec4(n * w, w); + rt_aux = vec4(dist * w, rough_t * w, 0.0, w); + if (glass) { + // A pane takes the pixel's surface over (coverage 1, its weight in the + // normal's length, rt_reflect.wgsl): blended over the seats behind it by its + // own few per cent, the saloon's surfaces had weighed nine tenths - the rays + // left from a point between the pane and the seats along a normal halfway + // between theirs, and the window wore white blotches of the sky with the + // seats' outlines. + rt_gbuf = vec4(n * w, 1.0); + rt_aux = vec4(dist, rough_t, 0.0, 1.0); + } + } + } + // --- the lamps, the cabin light and what glows by itself + // ([nomaplighting] objects are not lit by the map's lamps; light-mapped roads are, with + // the tile light map on top) + // (no shadows inside the player's own vehicle, whose cab the depth hardly shows, nor in + // the probe's capture) + let film = select(vec3(0.0), vec3(wet_road, refl_rough, wet_share), wet_only && wet_road > 0.0); + // A clear pane scatters nothing: what lights it shows only in what it mirrors (the + // lamps' glints, the sky, the street) and in the little its tint takes from the daylight + // through it. Lit as a grey Lambertian layer, every lamp and the cab's own lamps laid a + // milky veil over the windows at night, over everything seen through them. + var sf_lit = sf; + if (glass) { + sf_lit.albedo = vec3(0.0); + } + if ((terrain || material.params2.z > 0.0) && !is_water) { + sf_lit.f0 = sf_lit.f0 * camera.lod.z; + } + let lamps = lamp_light(in.world, n, v, sf_lit, thin, !capture, film, dot(geo_n, v) < 0.0 && !is_water) * select(1.0, 0.0, material.params.y > 0.2 && material.params.y < 0.3); + // [interiorlight]: OMSI adds its lamps' light to the lit meshes whatever the daylight, + // so a switched-on saloon is brighter by day as well and only stands out more at night. + // Taken as a lamp against the daylight exposure it vanished by day altogether. + // (in the picture's own terms, as the vanilla pass adds it: scaled with the metering it + // grew with the night and whitened the saloon) + // (the lamps' light does not reach into the gaps under the seats and round the + // handrails either: without the ambient occlusion on it they glowed through there) + // A sphere-mapped pane or body mirrors the street round it: at night that is lit by the + // lamps, not by the sky the probe holds (dark then). The street's radiance under them + // (`lamp_ground`) is laid into the reflection where it points at the street and the + // walls: a bus's windows and paint under a street lamp show the lit street, the ones on + // an unlit road stay dark. (Not through the photo's structure: its bright rows are the + // day's sky, which the lamps do not light.) + if ((reflective_env || glass) && !traced) { + let lit_round = lamp_ground * (1.0 - open); + reflection = reflection + lit_round * refl_f * (1.0 - cab_view); + } + // (in the player's saloon: what its lamps' light meets on the way, see `cabin_visibility`) + var cabin_vis = 1.0; + if (in_cab > 0.5 && camera.lamp_atlas.w > 0.5) { + cabin_vis = cabin_visibility(in.world, n); + } + let cabin_light = interior_lamps(in.world, n, in.params2.z) * cabin_vis; + let cabin = sf_lit.albedo * cabin_light * mix(1.0, ao, 0.85); + var rgb = (direct + ambient + lamps) * pre + cabin; + // A material's own emissive colour ([matl_allcolor], an .x's emissive) is the texture at + // full brightness in Omsi.exe: shown at the screen's white, not scaled with the eye's + // night adaptation - a texture lit that way by [matl_allcolor] glared at several times + // white at night (#1228, #1236). (The night maps of lit windows keep their light.) + // (not a pane's: glass gives off no light of its own, see `sf_lit`) + var emit = select(tex.rgb * material.emissive.rgb * clamp(enh.exposure.z * 2.0, 0.8, 1.0), vec3(0.0), glass); + // (the tile light map on the splines and [LightMapMapping] objects is the vanilla + // path's: here the map's lamps light them, tinted from that map, as they light every + // other surface - added on top it lit the roads twice, with a hard edge where a road + // met a square that is an object) + if (material.extra.w > 0.5) { + let switched = material.extra.w > 1.5; + let night = select(rain_lit_windows(in.local), 1.0, switched); + // (a switched one is the display's own state: not dimmed with the instance's night + // lighting, which is 0 by day and left the Procity's pressure screen black) + let nm = night_sample.rgb * night * select(clamp(in.params2.y, 0.0, 1.0), 1.0, switched); + // (The ground gets no light from the tile's light map here: it is the lamps' pools as + // OMSI bakes them, a `[maplight]`'s colour times (radius / distance)^2 out to sixteen + // radii, taken through every wall and roof, with no shadow of anything and with a + // tail past where the lamp itself reaches. The lamps are lights of their own in this + // picture - the same inverse square, cut off where their reach ends, shadowed by the + // maps of `LampShadow` - and what the map added three times over was a snow-covered + // lawn in a courtyard lit orange by floodlights across a building, or the ground of a + // whole street glowing with one lamp's tail.) + if (!terrain) { + // lit windows and signs; a switched lamp or display holds up against daylight + // as the self-illuminated materials do + // (a window lit from inside shows some 80 cd/m² - a room's 300 lux off its + // walls and through a curtain - an illuminated sign more: over the dark street + // round it, a little over the screen's white, so that it keeps its colour) + emit = emit + nm * select(min(enh.exposure.z * 3.6, 1.2), mix(max(enh.exposure.z * 2.0, 0.8), 0.8, near_player_vehicle(in.world) * inside_vehicle(camera.cam_pos.xyz) * (1.0 - outside)), switched); + } + } + if (material.params2.x > 0.5 && !terrain && !glass) { + // [matl_lightmap]: laid onto the light with ADDSMOOTH in Omsi.exe (see the vanilla + // shader), so it adds what the surface's own light leaves: little by day, fully at + // night, and less where the saloon lamps light the surface already. (As an emission + // at 0.6 of the texture by day and on top of the lamps at night, a switched-on + // cabin's light-mapped parts were flat white.) + let lm = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], buv, camera.lod.x).rgb * clamp(in.params2.x, 0.0, 1.0); + if (material.emissive.w < -1.5) { + let night = clamp(camera.sun_color.w, 0.0, 1.0); + let left = (vec3(1.0) - clamp(cabin_light, vec3(0.0), vec3(1.0))) * (0.12 + 0.88 * night); + emit = emit + tex.rgb * lm * left * max(enh.exposure.z * 2.0, 0.6); + } else { + // (By day as by night: ADDSMOOTH lifts the surface to its texture's colour by the + // map whatever light it has, and what the light already gives - the day's, the + // saloon lamps' - is taken off below. Lifted by an eighth of that by day, a + // display in the cab's shade was far darker than in Vanilla+, #2051.) + // ... and as there it lifts the surface to its texture's own colour at the + // most, shown as a display is (see the unlit path): taken as a light of the + // night's level on top, a white light map (`weiss.bmp`, laid on a display so + // it shows at night) went past the tone curve's knee and bleached its colours - + // the Procity's red and blue gauges pink and lavender (#827). (An LED panel's + // light map stays as it was: its dots are meant to burn above their colour.) + // The map's script variable controls its backlight. Dimming every light-mapped + // surface as a cab screen hid instrument backlights even with the lights on. + // (the lift is the saloon lamps' light: where their light does not reach for a + // handrail or a seat standing in it, the map does not lift the surface either) + emit = emit + max(display_level(tex.rgb) * enh.exposure.y - rgb, vec3(0.0)) * lm * cabin_vis; + } + } + if (material.emissive.w < -1.5) { + // an LED panel (see MaterialExtra::led): the lit dots - the alpha the `\S:n` script + // texture carries, in the colour of the panel's own texture - are the panel's own + // light, drawn as bright as the settings ask for (`Led glow`, 16 levels, 0 = off). + // The glow takes them where it leaves every other screen out of its source + // (`post.wgsl`) and blooms a halo around the panel. (Kept at their own brightness + // however the metering treats the scene, as a display's text is.) Its light is its + // white light map's, so it goes out with that map's variable (the busbar, the + // lights) as the Omsi.exe stage does. + let lm_gate = select(1.0, clamp(in.params2.x, 0.0, 1.0), material.params2.x > 0.5); + // (in the cab - a dashboard's LCD lit by a white map reads as a panel - it dims at night; + // not a page's destination sign (-3), which is read from the street through the windscreen) + let cab_dim = select(1.0 - outside, 0.0, material.emissive.w < -2.5); + // (`material.glow.y`: the share of it the modeller gives the panel, `[led_glow_effect]`) + emit = emit + tex.rgb * enh.led.x * material.glow.y * alpha * lm_gate * max(enh.exposure.z * 2.0, 0.8) * mix(1.0, display_dim(1.0), cab_dim); + } else if (material.emissive.w < -0.5) { + // a display's text (see MaterialExtra::display) + emit = emit + tex.rgb * 0.35 * max(enh.exposure.z * 2.0, 0.8) * display_dim(1.0); + } + if (material.glow.x > 0.0) { + // [matl_glow] (see `matl_glow_light`): the material is its own light, drawn in HDR. + // The classic picture does not know the keyword (`params2.x` is off, see + // `add_material_extra`). + emit = emit + matl_glow_light(buv, tex.rgb); + } + rgb = rgb + emit; + if (enh.debug.x > 0.5) { + // OMSI_DEBUG_ENHANCED: one term alone, as it lands on the screen + let dm = i32(enh.debug.x); + var dc = vec3(0.0); + switch dm { + case 1: { + let tr = surface_rt; + let sm = sun_shadow_soft(in.world, n, thin); + dc = select(vec3(sm), vec3(tr.z * sm, tr.z * sm, tr.z * 0.6 + 0.4), tr.w > 0.5 && tr.z >= 0.0); + } + case 2: { dc = vec3(ao); } + case 3: { dc = n * 0.5 + vec3(0.5); } + case 4: { dc = vec3(aer.a); } + case 5: { dc = e_amb * pre * 0.1; } + case 6: { dc = reflection * pre; } + case 7: { dc = sf.albedo; } + case 8: { dc = direct * pre; } + case 9: { dc = aer.rgb * pre; } + case 11: { dc = vec3(fract(dist / 10.0), dist / 1000.0, in.clip.z * 100.0); } + case 12: { dc = vec3(mode * 0.5, f32(terrain), in.params2.w); } + case 13: { dc = vec3(in_cab, ao, spec_occ); } + case 14: { dc = (ambient + direct) * pre; } + case 15: { dc = lamps * pre; } + case 16: { dc = emit; } + case 17: { dc = vec3(rough, f0.g * 10.0, metal); } + default: { dc = vec3(alpha, f32(glass), f32(has_env)); } + } + return vec4(dc, 1.0); + } + if (glass) { + // see-through glass: the reflection is added on top of what shows through, so + // the blend keeps it where the glass itself is faint - but not where the texture + // is not there at all: Omsi.exe leaves the alpha as the texture has it, so a + // see-through part of a blended layer (the clear ground of a sticker on the + // cab's wall, #861) shows no reflection; made up to a quarter opaque by it, the + // whole rectangle of the sticker mirrored the sky + let cover = smoothstep(0.0, 0.05, alpha); + // (or, from inside the player's bus, the lit cabin it mirrors: `glass_reflection`) + let refl_rgb = glass_reflection(in.world, n, v, reflection * pre) * cover; + let rl = dot(refl_rgb, vec3(0.2126, 0.7152, 0.0722)); + // (a pane passes most light: a reflection making it up to 60 % opaque laid a grey + // veil over the destination display behind the windscreen and the saloon) + var a2 = clamp(alpha + (1.0 - alpha) * clamp(rl * 0.25 + fr.g, 0.0, 0.25) * (1.0 - 0.85 * own_pane) * cover, alpha, 1.0); + var c = (rgb * alpha + refl_rgb) / max(a2, 1e-3); + // the rain on a pane without a film of its own (`pane_rain`): the traffic's windows + { + let pr = pane_rain(in.world, in.local, in.normal); + if ((pr.cover > 0.001 || pr.veil > 0.001 || pr.mist > 0.001) && cover > 0.0) { + let o = pane_rain_compose(pr, c, a2, v, rain_env_enhanced(reflect(-v, pr.n), 1.0) * pre, sh_irradiance(pr.out) / PI * 0.9 * pre); + c = o.rgb; + a2 = o.a; + } + } + // the condensation on the player's bus's panes (omsi-app condensation.rs): a film of + // droplets, each many wavelengths wide, takes twice its shadow out of the light + // (the extinction paradox): half of what it scatters is diffracted a degree or two + // forward - what lies behind goes soft, in the tone mapping (post.wgsl `misted`) - + // and half is refracted and reflected every way, a milky veil lit by the street + // through the glass and, the part the droplets send back, by the cabin + let fog = glass_condensation(in.world, n) * cover; + glass_fog = fog; + if (fog > 0.001) { + // (of the widely scattered half, some 30 % goes back: a fully misted pane sends + // some 15 % of the light back, Briscoe and Galvin 1991) + let back = 0.3; + let lit_street = avg_e / PI * pre; + let lit_cabin = cab_e * CAB_AMBIENT / PI * pre + cabin_light; + let milky = lit_street * (1.0 - back) + lit_cabin * back; + let veil = 0.5 * fog; + let a3 = a2 + (1.0 - a2) * veil; + c = (c * a2 * (1.0 - veil) + milky * veil) / max(a3, 1e-3); + a2 = a3; + } + return vec4(c * aer.a + aer.rgb * pre, a2); + } + rgb = rgb + reflection * pre; + // The later screen-space pass replaces only this fraction of the sky reflection. + // A miss adds zero, so the existing sky, Fresnel and fog stay the fallback. Colour + // and coverage are resolved together, including terrain painting and glass over roads. + if (!glass && !reflective_env) { + // (a pool mirrors by its Fresnel term and its share of the road; so does the sheen of a wet + // road, at the Fresnel term of water a little under full - the lamps' and the cars' + // streaks down a wet street at night, which come from the light's own brightness and so + // need no more than that share - and still water as a whole) + let fresnel = 0.02 + 0.98 * pow(1.0 - clamp(nv, 0.0, 1.0), 5.0); + let pool = puddle * env_brdf(f0, rough, nv).g * select(wet_road, 1.0, pbr_reflects) * wet_share * aer.a; + let sheen = select(0.8 * smoothstep(0.55, 0.95, wet_road), 1.0, is_water) * fresnel * aer.a; + let weight = clamp(max(pool, sheen), 0.0, 1.0); + *puddle_weight = vec2(weight, weight * spec_occ); + } + // water hides what lies under it as far as it reflects (Fresnel): see-through from + // above, a mirror of the sky towards the horizon + let a_out = select(alpha, clamp(alpha + (1.0 - alpha) * fr.g, alpha, 1.0), is_water); + return vec4(rgb * aer.a + aer.rgb * pre, a_out); +} + +// Small waves on the water at map point `p` (m) and time `t` (s): the slope of four wave +// trains of 1.3 to 4.7 m running different ways. +fn water_ripple(p: vec2, t: f32) -> vec2 { + var g = vec2(0.0); + let dirs = array, 4>(vec2(0.8, 0.6), vec2(-0.45, 0.89), vec2(0.96, -0.28), vec2(-0.7, -0.71)); + let lens = array(4.7, 2.9, 1.9, 1.3); + for (var i = 0; i < 4; i = i + 1) { + let k = 6.2831853 / lens[i]; + // deep-water waves: their speed goes with the square root of their length + let w = sqrt(9.81 * k); + g = g + dirs[i] * cos(dot(p, dirs[i]) * k - w * t) * 0.045; + } + return g; +} + +// Shade the complete local vehicle from the reflected eye. Main-camera ambient +// occlusion is not applicable to this view beneath the road. +@fragment +fn fs_puddle_vehicle(input: FsIn) -> @location(0) vec4 { + // One reflected camera for the complete vehicle, including its transparent panes. + let plane = vehicle_reflection.plane; + let height = dot(plane.xyz, input.world) - plane.w; + if (height < 0.0 || material.emissive.w > 1.5) { discard; } + var unused = vec2(0.0); + let eye = camera.cam_pos.xyz - 2.0 * plane.xyz * (dot(plane.xyz, camera.cam_pos.xyz) - plane.w); + if (camera.post.x < 0.5) { + var unused_vanilla = 0.0; + return shade_vanilla(input, &unused_vanilla, eye); + } + return shade_enhanced(input, &unused, true, eye); +} + +@fragment +fn fs_puddle_chassis() -> @location(0) vec4 { + if (camera.post.x < 0.5) { return vec4(camera.ambient.rgb * 0.025, 1.0); } + return vec4(sh_irradiance(vec3(0.0, 0.0, -1.0)) * enh.exposure.x * 0.025, 1.0); +} + +// The painted ground's albedo (`Renderer::encode_ground`): the terrain's base and its paint +// layers laid over each other into one picture of what the surface is made of - texture, +// detail and tint, blended by each layer's coverage - which the main pass then lights once +// (`from_ground` in `shade_enhanced`) instead of lighting every layer in full and blending +// the lit colours. The base writes it, the layers blend into it (the pipeline's blend: the +// coverage over what is there; the alpha channel is left as the base wrote it). +@fragment +fn fs_ground(in: FsIn) -> @location(0) vec4 { + let duv = in.uv * material.extra.z; + let buv = tex_address(in.uv - in.params.zw); + let mode = material.params.x; + // (a brush mask that covers nothing here: the layer's texture need not be read) + if (TERRAIN_PAINT && mode > 1.5 && material.params.z > 0.5 && material.params.w > 0.5) { + let cover = smoothstep(0.32, 0.68, sample_transmap(buv).a); + if (cover * material.color.a * in.params.x == 0.0) { + discard; + } + } + var tex = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], duv, camera.lod.x), duv); + if (material.extra.y > 0.0) { + let det = textureSampleBias(mx_tex2d[mx_mat.light], mx_samplers[mx_mat.sampler], in.uv * material.extra.y, camera.lod.x); + tex = vec4(clamp(tex.rgb * det.rgb, vec3(0.0), vec3(1.0)), tex.a); + } + var cover = tex.a; + if (material.params.z > 0.5) { + cover = select(1.0, sample_transmap(buv).a, material.params.w > 0.5); + if (mode > 1.5) { + cover = smoothstep(0.32, 0.68, cover); + } + } + var alpha = cover * material.color.a; + if (mode < 0.5) { + alpha = 1.0; + } + alpha = alpha * clamp(in.params.x, 0.0, 1.0); + if (TERRAIN_PAINT && alpha == 0.0) { + discard; + } + return vec4(tex.rgb * material.color.rgb, alpha); +} + +// The bus's windows in the enhanced picture: the rain on their outer face, the snow that +// settles there and the condensation on their inner face. (The drops and the snow are the classic pictures' too: scene/08_rain_glass.wgsl.) + +// The pane at a pixel, in the vehicle's own frame (the film's vertices as its mesh has them, +// `FsIn.local`): the drops are laid out there, so they stay on the glass however the body +// rolls and pitches and on a door that swings open. The modellers' texture coordinates of +// a film are no measure of the glass: on the windscreen of the NL202 they run half as fast +// again one way as the other and at sixty degrees to each other, from triangle to triangle +// anew, and every drop drawn in them came out a slanting streak. So a pane is laid flat by +// the axes of the vehicle (`pane_proj`): the windscreen and the rear window onto its +// across and up, the side windows onto its along and up, a roof light onto its plan. A +// raked or curved pane is foreshortened in that projection; a drop is drawn round all the +// same, its offsets taken back onto the glass (`m`) before its shape is worked out. The +// drops' grid alone stays in the projection: on a pane at an angle to it a cell covers +// more glass, and the drops are a little fewer there. + +// (The drops on a pane, the runners, the blur's picture and the pane's own frame - +// `glass_water`, `glass_blur` - are the classic pictures' too: scene/08_rain_glass.wgsl.) + +// The rain film on a pane (the enhanced pass's `emissive.w` 2 layer), drawn over the +// clean picture of the frame: the drops, each a small lens that shows the street behind +// it upside down, a shade darker at its rim where the light is bent away, with the sky's +// glint on it, and between them the soft blur of the wet glass. +fn glass_film(in: FsIn, water: f32) -> vec4 { + let v = camera.cam_pos.xyz - in.world; + let dist = length(v); + let vn = v / max(dist, 1e-4); + let in_cab = inside_vehicle(camera.cam_pos.xyz) * near_player_vehicle(in.world) > 0.5; + let g = glass_water(in.world, in.local, in.normal, water, camera.post.y, in_cab); + if (g.cover <= 0.001 && g.mist <= 0.001 && g.veil <= 0.001) { + return vec4(0.0); + } + let pre = enh.exposure.x; + let has_picture = camera.flags.z < -0.5; + let dims = vec2(textureDimensions(mx_tex2d[mx_mat.env])); + let uv0 = in.clip.xy / dims; + let mist_col = sh_irradiance(g.out) / PI * 0.9 * pre; + // the view through the wet glass between the drops: softened by the film of water + // (a running film scatters the light by a fraction of a degree: some 0.7 % of the + // picture's height in a downpour, a third of that in a drizzle) + let veil_lod = log2(max(dims.y * mix(0.002, 0.006, clamp(g.veil / 0.3, 0.0, 1.0)), 1.0)); + var behind = mist_col; + if (has_picture) { + behind = finite_or(glass_blur(uv0, veil_lod), mist_col); + } + // --- a drop: a small lens. Through it the street shows small and upside down (each + // point of the drop looks out along its own bent way, `tilt` across the screen), the + // more bent the further out on it; at its rim the light is bent so far that little of + // it reaches the eye, a darker ring. + var drop_col = behind; + var a_drop = 0.0; + if (g.cover > 0.001) { + let tilt = g.n - g.out * dot(g.n, g.out); + let right = camera.cam_right.xyz; + let up = camera.cam_up.xyz; + // (a drop is a wide lens: from its rim it looks out some 30 degrees aside, the sky + // in the bottom of a drop against a wall) + let o = vec2(dot(tilt, right), -dot(tilt, up)) * 0.3; + var seen = behind; + if (has_picture) { + var uv = clamp(uv0 - o, vec2(0.001), vec2(0.999)); + // (only what lies beyond the glass: where the bent way lands on the cab's own + // dashboard or pillar, in front of the pane, the drop shows what is straight + // behind it instead) + if (camera.clouds.w > 0.5 && camera.clouds.w < 1.5) { + let asz = vec2(textureDimensions(t_ao)); + let z = textureLoad(t_ao, min(vec2(uv * asz), vec2(asz) - vec2(1)), 0).g; + let zg = (camera.view_proj * vec4(in.world, 1.0)).w; + let beyond = select(smoothstep(zg + 0.05, zg + 0.4, z), 1.0, z <= 0.0); + uv = mix(uv0, uv, beyond); + } + seen = finite_or(glass_blur(uv, 0.8 + 1.5 * g.mist), behind); + } + let rim = smoothstep(0.55, 1.0, g.rim); + let facing = dot(g.out, vn) > 0.0; + let cosv = clamp(abs(dot(g.n, vn)), 0.0, 1.0); + let f = select(0.02, 0.02 + 0.98 * pow(1.0 - cosv, 5.0), facing); + let mirrored = rain_env_enhanced(reflect(-vn, g.n), 1.0) * pre; + var c = seen * (1.0 - 0.45 * rim) * (1.0 - f) + mirrored * f; + // the sun: a pinpoint where the dome mirrors it + if (facing) { + let r = reflect(-vn, g.n); + c = c + enh.sun.rgb / PI * pre * pow(max(dot(r, camera.sun_dir.xyz), 0.0), 900.0) * f * 60.0; + } + // A drop of a pixel or less is no lens one can see: its many ways average to the + // view behind it, a little dimmer for its rim - a faint grain, not a dark speck. + let detail = smoothstep(0.5, 1.6, g.size_px); + drop_col = mix(behind * 0.93, c, detail); + a_drop = g.cover * mix(select(0.15, 0.5, has_picture), 0.95, detail); + } + // Drops a few pixels across are a pane's sparkle close up; seen from the street they + // fade out over the first fifteen metres. The haze stays further. + let aer = air(-vn, fog_distance(in.world), camera.cam_pos.z - enh.fog.z, in.world.z - enh.fog.z); + a_drop = a_drop * (1.0 - smoothstep(5.0, 15.0, dist)); + // the fine mist of droplets: a faint grey scatter of the light about + let a_mist = g.mist * 0.5; + var a_veil = 0.0; + if (g.veil > 0.001 && has_picture) { + a_veil = g.veil * (1.0 - smoothstep(25.0, 60.0, dist)); + } + let a_under = a_veil + a_mist * (1.0 - a_veil); + let under = (behind * a_veil + mix(mist_col, behind, 0.9) * a_mist * (1.0 - a_veil)) / max(a_under, 1e-4); + var a = a_drop + a_under * (1.0 - a_drop); + if (a <= 1e-4) { + return vec4(0.0); + } + let col = (drop_col * aer.a * a_drop + under * a_under * (1.0 - a_drop)) / a; + // From inside, the rain is seen through the condensation on the glass's inner face + // (drawn with the pane before this film): a misted pane shows the drops behind it as + // soft shadows, not sharp lenses. + if (in_cab) { + a = a * (1.0 - 0.5 * glass_condensation(in.world, g.out)); + } + return vec4(col, a); +} + +// The snow a wiped pane holds while it snows (`is_snow_pane`; the mask's cover: 0 clear +// glass, up to 1 a pane closed by snow, above 1 the bank a blade pushed to the end of its +// sweep, below 0 glass a blade has just cleared). Crystals land one by one and stick, hold +// a while and melt into a little water - soon on the windscreen, whose glass the warm air +// of the defroster heats, slowly on a side window. As the cover grows they close into a +// milky layer, and it lies deepest along the windscreen's bottom edge and in its lower +// corners, where the blades and the airstream do not reach. +fn glass_snow(in: FsIn, cover: f32) -> vec4 { + // (the windscreen's defroster from the cabin's air, the height on the glass in the bus's + // own frame with the body's tilt: see `glass_snow_with`, which the classic pictures + // share) + let l = pane_local(in.world); + let fz = clamp(l.z / max(camera.inside_b.w, 0.1), -1.0, 1.0); + return glass_snow_with(in, cover, enh.condensation.w, fz); +} + +// A direction in the frame of the bus the camera is in (`pane_local` without the shift). +fn pane_dir(d: vec3) -> vec3 { + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + let v = vec3(d.x * ch - d.y * sh, d.x * sh + d.y * ch, d.z); + let t = enh.pane_tilt; + let p = vec3(v.x, v.y * t.y + v.z * t.x, v.z * t.y - v.y * t.x); + return vec3(p.x * t.w - p.z * t.z, p.y, p.z * t.w + p.x * t.z); +} + +// How close the edge of the pane at `world` (normal `n`) is: 1 against it, falling to 0 +// some 25 cm in; -1 where it cannot be told. A pane's edge is where its frame begins - the +// rubber, the pillar, the trim, the dashboard under the windscreen: opaque and in the depth +// prepass, lying on the glass's own plane, where the glass is not. So points on the pane's +// plane round the pixel, in eight ways out to 26 cm, are looked up in the prepass's depth +// (the ambient occlusion's texture keeps it): where an opaque surface lies there on the +// plane - within a centimetre or two of it, not a wiper's arm a hand's breadth outside - the +// pane has ended. The nearest such end in each way, averaged over the ways: in a corner +// two ways find it close, along an edge one, in the middle of a pane none. +fn glass_frame_near(world: vec3, n: vec3) -> f32 { + if (camera.clouds.w < 0.5 || camera.clouds.w > 1.5) { + return -1.0; + } + let size = vec2(textureDimensions(t_ao)); + let nn = safe_normal(n); + let up0 = vec3(0.0, 0.0, 1.0) - nn * nn.z; + let a = select(vec3(1.0, 0.0, 0.0), normalize(up0), dot(up0, up0) > 0.04); + let b = cross(nn, a); + var sum = 0.0; + for (var i = 0; i < 8; i = i + 1) { + let ang = f32(i) * 0.7853982 + 0.2; + let dir = a * cos(ang) + b * sin(ang); + var near = 0.0; + for (var k = 0; k < 6; k = k + 1) { + let dist = 0.03 + 0.046 * f32(k); + let c = camera.view_proj * vec4(world + dir * dist, 1.0); + if (c.w <= 0.05) { + break; + } + let uv = vec2(c.x / c.w * 0.5 + 0.5, 0.5 - c.y / c.w * 0.5); + if (any(uv < vec2(0.0)) || any(uv > vec2(1.0))) { + break; + } + let z = textureLoad(t_ao, min(vec2(uv * size), vec2(size) - vec2(1)), 0).g; + if (z > 0.0 && abs(z - c.w) < 0.015 + 0.006 * c.w) { + near = 1.0 - (dist - 0.03) / 0.26; + break; + } + } + sum = sum + near; + } + return clamp(sum / 3.0, 0.0, 1.0); +} + +// How much of the light crossing the player's bus's pane at `world` (normal `n`) its +// condensation scatters (0..1). One cabin air mists all the glass much alike: each +// window's film (enh.condensation: the optical depths of the windscreen's, the side +// windows' and the rear window's, omsi-weather condensation.rs) is taken two thirds from +// their mean. The film starts where the glass is coldest and the air stillest, in a pane's +// corners and along its frame (and low down), and grows inward as it thickens, its front +// wandering with the glass's own patchiness, until it closes over the pane. A heavy film +// gathers into drops that trickle down and leave clear tracks; on the windscreen the +// defroster's warm air clears it from the bottom up. +fn glass_condensation(world: vec3, n: vec3) -> f32 { + if (camera.inside_c.w < 0.5) { + return 0.0; + } + let l = pane_local(world); + let h = camera.inside_b.yzw; + if (any(abs(l) >= h + vec3(0.25))) { + return 0.0; + } + let nl = safe_normal(pane_dir(n)); + let gap = h - abs(l); + // (the panes in the body's skin only, by the way they face: not the instruments' glass + // behind the windscreen or a partition in the saloon) + var own = -1.0; + var front = false; + if (abs(nl.y) > 0.55 && gap.y < 0.45) { + front = l.y > 0.0; + own = select(enh.condensation.z, enh.condensation.x, front); + } else if (abs(nl.x) > 0.5 && gap.x < 0.35) { + own = enh.condensation.y; + } + if (own < 0.0) { + return 0.0; + } + let depth = mix((enh.condensation.x + enh.condensation.y + enh.condensation.z) / 3.0, own, 0.35); + if (depth <= 0.001) { + return 0.0; + } + // the pane's own frame in metres: across, and up the glass + let up0 = vec3(0.0, 0.0, 1.0) - nl * nl.z; + let up = select(vec3(1.0, 0.0, 0.0), normalize(up0), dot(up0, up0) > 0.04); + let s = vec2(dot(l, cross(up, nl)), dot(l, up)); + let fz = clamp(l.z / max(h.z, 0.1), -1.0, 1.0); + let low = 1.0 - clamp(fz * 0.5 + 0.5, 0.0, 1.0); + let edge_seen = glass_frame_near(world, n); + let edge = select(edge_seen, 0.15 + 0.3 * low, edge_seen < 0.0); + let n1 = snow_noise(s * 3.0 + vec2(11.0, 3.0)); + let n2 = snow_noise(s * 9.0 + vec2(3.0, 17.0)); + let patchy = n1 * 0.7 + n2 * 0.3; + // (the front: into the corners and along the frame at first, the glass's patchiness + // breaking its line, over the whole pane at a depth of two; a soft front, the film + // thinning out over a few centimetres) + let grow = 1.0 - exp(-depth * 1.3); + let potential = 0.45 * edge + 0.15 * low + 0.45 * patchy; + let front_line = 1.0 - grow * 1.3; + let covered = smoothstep(front_line - 0.18, front_line + 0.18, potential); + var amount = covered * (1.0 - exp(-depth * (0.9 + 0.5 * patchy))); + // the fine grain of the droplets themselves + amount = amount * (0.92 + 0.08 * snow_noise(s * 140.0)); + if (depth > 1.4) { + // trickles: drops grown heavy run down a few centimetres a minute, each clearing a + // narrow track below where it started + let lane = floor(s.x / 0.03); + let h1 = rain_hash(vec2(lane, 71.0)); + if (h1.x < clamp((depth - 1.4) * 0.35, 0.0, 0.6)) { + let h2 = rain_hash(vec2(lane, 13.0)); + let x0 = (lane + 0.3 + 0.4 * h2.x) * 0.03 + 0.003 * sin(s.y * 40.0 + h2.y * 6.283185); + let period = 90.0 + 120.0 * h1.y; + let tau = fract(camera.post.y / period + h2.y) * period; + let start = h.z * (0.75 - 0.9 * h2.x); + let end = start - min(tau * 0.004, 0.6); + let fade = smoothstep(0.0, 5.0, tau) * (1.0 - smoothstep(period - 10.0, period, tau)); + let dx = abs(s.x - x0); + let in_track = step(end, s.y) * step(s.y, start) * (1.0 - smoothstep(0.0012, 0.0025, dx)); + let head = 1.0 - smoothstep(0.0018, 0.0028, length(vec2(dx, s.y - end))); + amount = amount * (1.0 - 0.8 * max(in_track, head) * fade); + } + } + if (front && enh.condensation.w > 0.02) { + // the defroster's warm air clears the windscreen from its bottom edge up, first in + // the middle over its outlets + let u = clamp((fz + 0.35) / 1.2, 0.0, 1.0); + let fx = l.x / max(h.x, 0.1); + let reach = enh.condensation.w / 0.85 * 1.15 - 0.2 * fx * fx + 0.06 * (n1 - 0.5); + amount = amount * smoothstep(reach - 0.12, reach, u); + } + return clamp(amount, 0.0, 1.0); +} + +// The reflection a pane adds over what shows through it (pre-exposed `reflection`): the +// street and the sky it mirrors, seen from outside or on another vehicle; none on the inner +// face of the player's own bus's glass. (A box-projected cube of the cabin was mirrored +// there; it lagged behind the camera, shook with the head and showed a blurred picture, and +// was taken out on the user's word, 2026-11-22.) +fn glass_reflection(world: vec3, n: vec3, v: vec3, reflection: vec3) -> vec3 { + let inside = inside_vehicle(camera.cam_pos.xyz) * near_player_vehicle(world); + return reflection * (1.0 - step(0.5, inside)); +} + +// Temporal upscaling: the depth prepass that also writes each pixel's motion, appended to the +// scene module for this prepass only, so the scene module others compile stays as it is. + +struct Motion { + vp: mat4x4, + // last frame's, for last frame's model matrices (relative to last frame's render origin) + vp_prev: mat4x4, + // last frame's, relative to this frame's render origin: the sky, and the entries without + // a matrix of last frame + vp_prev_here: mat4x4, + vp_inv: mat4x4, + // xy: the render size in pixels, z: 1 when `prev_models` holds last frame's matrices, + // w: how many entries it holds + params: vec4, + // xyz: last frame's render origin minus this one's, w: the most an object may move in a + // frame and still be the same object (`MAX_FRAME_JUMP`) + origin_delta: vec4, +}; +@group(3) @binding(0) var motion: Motion; +@group(3) @binding(1) var prev_models: array>; + +struct MotionOut { + @builtin(position) @invariant clip: vec4, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + @location(5) cur: vec4, + @location(6) prev: vec4, + @location(7) world: vec3, +}; +// (the fragment side of MotionOut, without the invariant: see DepthIn) +struct MotionIn { + @builtin(position) clip: vec4, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, + @location(5) cur: vec4, + @location(6) prev: vec4, + @location(7) world: vec3, +}; + +@vertex +fn vs_motion(in: VsIn) -> MotionOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let local = vec4(in.pos, 1.0); + let wp = m * local; + var out: MotionOut; + let swayed = wp + vec4(tree_sway(in.pos, m), 0.0); + out.clip = scene_clip(e, swayed, (m * vec4(in.normal, 0.0)).xyz); + out.world = swayed.xyz; + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + out.cur = motion.vp * wp; + if (motion.params.z > 0.5 && f32(e) < motion.params.w) { + let k = e * 4u; + // Drop the affine row's draw-order and depth-normal metadata, as model_matrix does. + let pm = mat4x4(vec4(prev_models[k].xyz, 0.0), vec4(prev_models[k + 1u].xyz, 0.0), vec4(prev_models[k + 2u].xyz, 0.0), prev_models[k + 3u]); + // (an entry handed over to another object since: its old matrix is not this one's) + let jump = pm[3].xyz + motion.origin_delta.xyz - m[3].xyz; + if (dot(jump, jump) <= motion.origin_delta.w * motion.origin_delta.w) { + out.prev = motion.vp_prev * (pm * local); + } else { + out.prev = motion.vp_prev_here * wp; + } + } else { + out.prev = motion.vp_prev_here * wp; + } + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +// From this pixel to where the same point was last frame, in pixels (x right, y down). +fn motion_pixels(cur: vec4, prev: vec4) -> vec4 { + if (prev.w <= 1e-4 || cur.w <= 1e-4) { + return vec4(0.0); + } + let d = (prev.xy / prev.w - cur.xy / cur.w) * vec2(0.5, -0.5) * motion.params.xy; + return vec4(d, 0.0, 0.0); +} + +@fragment +fn fs_motion(in: MotionIn) -> @location(0) vec4 { + return motion_pixels(in.cur, in.prev); +} + +@fragment +fn fs_motion_test(in: MotionIn) -> @location(0) vec4 { + cutout_coverage(in.uv, in.params, camera.lod.x, tree_card_fade(in.world)); + return motion_pixels(in.cur, in.prev); +} + +@fragment +fn fs_motion_transmap(in: MotionIn) -> @location(0) vec4 { + transmap_coverage(in.uv, in.params, camera.lod.x); + return motion_pixels(in.cur, in.prev); +} + +struct SkyMotionOut { + @builtin(position) clip: vec4, + @location(0) ndc: vec2, +}; + +@vertex +fn vs_motion_sky(@builtin(vertex_index) i: u32) -> SkyMotionOut { + let x = f32(i32(i & 1u) * 4 - 1); + let y = f32(i32(i >> 1u) * 4 - 1); + var out: SkyMotionOut; + out.clip = vec4(x, y, 0.0, 1.0); + out.ndc = vec2(x, y); + return out; +} + +@fragment +fn fs_motion_sky(in: SkyMotionOut) -> @location(0) vec4 { + let far = motion.vp_inv * vec4(in.ndc, 0.0, 1.0); + let wp = vec4(far.xyz / far.w, 1.0); + return motion_pixels(vec4(in.ndc, 0.0, 1.0), motion.vp_prev_here * wp); +} + +// The transparency mask (DLSS's bias-current-colour hint, FSR 3's reactive mask): where glass +// and the rain on it lie, the upscaler leans on this frame, since the history behind the pane +// smeared its reflections. +const MASK_RAIN: f32 = 0.5; +const MASK_SCREEN: f32 = 0.8; +// FSR 3 gives up the history faster than DLSS for the same mask: at full strength the view +// through the windscreen went soft, so it takes the panes at this share of it. +const FSR_GLASS_SHARE: f32 = 0.4; + +struct MaskOut { + @builtin(position) @invariant clip: vec4, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, +}; +struct MaskIn { + @builtin(position) clip: vec4, + @location(2) uv: vec2, + @location(3) @interpolate(flat) params: vec4, +}; + +@vertex +fn vs_mask(in: VsIn) -> MaskOut { + let e = draw_list[in.inst]; + let m = model_matrix(e); + let wp = m * vec4(in.pos, 1.0) + vec4(tree_sway(in.pos, m), 0.0); + var out: MaskOut; + out.clip = scene_clip(e, wp, (m * vec4(in.normal, 0.0)).xyz); + let pr = inst_params[e * 2u]; + out.uv = in.uv + pr.zw; + out.params = pr; + if (pr.y < 0.5) { + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + } + return out; +} + +fn glass_mask(in: MaskIn) -> f32 { + let a = diffuse_border(textureSampleBias(mx_tex2d[mx_mat.diffuse], mx_samplers[mx_mat.sampler], tex_address(in.uv), camera.lod.x), in.uv).a + * material.color.a * in.params.x; + return clamp(a, 0.0, 1.0); +} + +@fragment +fn fs_glass_mask(in: MaskIn) -> @location(0) vec4 { + return vec4(glass_mask(in)); +} + +@fragment +fn fs_glass_mask_fsr(in: MaskIn) -> @location(0) vec4 { + return vec4(glass_mask(in) * FSR_GLASS_SHARE); +} + +@fragment +fn fs_rain_mask(in: MaskIn) -> @location(0) vec4 { + return vec4(MASK_RAIN); +} + +// The bus's own screens (IBIS, matrix displays, the dashboard's LCDs): their picture changes +// without any motion, so the history behind them is useless and swam over what passes them. +@fragment +fn fs_screen_mask(in: MaskIn) -> @location(0) vec4 { + return vec4(MASK_SCREEN); +} diff --git a/crates/mx/tests/openomsi/texture_means.wgsl b/crates/mx/tests/openomsi/texture_means.wgsl new file mode 100644 index 0000000..1d2da31 --- /dev/null +++ b/crates/mx/tests/openomsi/texture_means.wgsl @@ -0,0 +1,55 @@ +// Enhanced+ (rt.rs, rt_tex.rs): each texture's mean colour (sampled 8 x 8 from a small level) +// and its small copy in the reflections' atlas, for the hits +@group(0) @binding(0) var avg_tex: texture_2d; +@group(0) @binding(1) var avg_samp: sampler; +struct AvgOut { + c: vec4, + tile: vec4, +}; +@group(0) @binding(2) var avg_out: AvgOut; +@group(0) @binding(3) var atlas: texture_storage_2d; +// xy the texture's tile's corner in the atlas (texels), z 1 where it has a tile +@group(0) @binding(4) var tile: vec4; +var avg_sum: array, 64>; + +// (the atlas is sampled as sRGB: filtered in linear light, stored with the texture's own +// precision in the darks) +fn srgb_encode(c: vec3) -> vec3 { + let x = clamp(c, vec3(0.0), vec3(1.0)); + return select(1.055 * pow(x, vec3(1.0 / 2.4)) - 0.055, x * 12.92, x <= vec3(0.0031308)); +} + +@compute @workgroup_size(8, 8) +fn cs_tex_avg(@builtin(local_invocation_id) lid: vec3, @builtin(local_invocation_index) li: u32) { + let levels = f32(textureNumLevels(avg_tex)); + let lod = max(levels - 4.0, 0.0); + let uv = (vec2(lid.xy) + vec2(0.5)) / 8.0; + avg_sum[li] = textureSampleLevel(avg_tex, avg_samp, uv, lod); + // The tile: 30 x 30 texels of the level nearest that size, inside a texel of border that + // repeats the opposite edge (filtering across a tile's edge wraps as the texture does). + if (tile.z > 0.5) { + let size = vec2(textureDimensions(avg_tex)); + let tlod = clamp(log2(max(size.x, size.y) / 30.0), 0.0, levels - 1.0); + for (var k = li; k < 1024u; k += 64u) { + let q = vec2(k % 32u, k / 32u); + let c = (vec2((q + vec2(29u)) % vec2(30u)) + vec2(0.5)) / 30.0; + let s = textureSampleLevel(avg_tex, avg_samp, c, tlod); + textureStore(atlas, vec2(tile.xy) + vec2(q), vec4(srgb_encode(s.rgb), s.a)); + } + } + workgroupBarrier(); + if (li == 0u) { + // (the colour weighed by the coverage: a cut-out texture's thrown-away texels are + // white or black, and its leaves' mean came out pale or dark with them; a solid + // texture's alpha - a reflection mask - hardly moves it) + var s = vec4(0.0); + var cw = 0.0; + for (var i = 0u; i < 64u; i++) { + let k = avg_sum[i].a + 0.02; + s += vec4(avg_sum[i].rgb * k, avg_sum[i].a); + cw += k; + } + avg_out.c = vec4(s.rgb / cw, s.a / 64.0); + avg_out.tile = tile; + } +} diff --git a/crates/mx/tests/openomsi/upscale.wgsl b/crates/mx/tests/openomsi/upscale.wgsl new file mode 100644 index 0000000..dc72385 --- /dev/null +++ b/crates/mx/tests/openomsi/upscale.wgsl @@ -0,0 +1,222 @@ +// Render scale: the 3D picture, drawn smaller than the window, scaled up to it. A +// Catmull-Rom filter (nine bilinear taps) keeps edges and texture detail far better than a +// plain bilinear stretch; its overshoot is clamped to the neighbouring texels so that +// edges do not ring, and a contrast-adaptive sharpening pass (after AMD's CAS) brings back +// what the smaller picture lost, most where the picture is flat and least on hard edges. +struct Params { + // xy: size of the source picture, z: sharpening 0..1, w: 1 = the picture at the window's + // own size smoothed by FXAA instead (the plain graphics without multisampling); 2 = a + // temporal upscaler's result at the window's size, copied as it is but brought back to + // linear light (it hands back the sRGB-encoded numbers it read, which the window's sRGB + // target would encode once more) + src: vec4, +}; +@group(0) @binding(0) var p: Params; +@group(0) @binding(1) var t_src: texture_2d; +@group(0) @binding(2) var s_src: sampler; + +struct VsOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +}; + +@vertex +fn vs_main(@builtin(vertex_index) i: u32) -> VsOut { + let x = f32(i32(i & 1u) * 4 - 1); + let y = f32(i32(i >> 1u) * 4 - 1); + var out: VsOut; + out.clip = vec4(x, y, 0.0, 1.0); + out.uv = vec2((x + 1.0) * 0.5, (1.0 - y) * 0.5); + return out; +} + +fn tap(uv: vec2) -> vec3 { + return textureSampleLevel(t_src, s_src, uv, 0.0).rgb; +} + +fn catmull_rom(uv: vec2, size: vec2) -> vec3 { + let pos = uv * size; + let t1 = floor(pos - 0.5) + 0.5; + let f = pos - t1; + 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); + // the two middle taps become one bilinear tap between them + let w12 = w1 + w2; + let p0 = (t1 - 1.0) / size; + let p3 = (t1 + 2.0) / size; + let p12 = (t1 + w2 / w12) / size; + var c = tap(vec2(p0.x, p0.y)) * w0.x * w0.y; + c = c + tap(vec2(p12.x, p0.y)) * w12.x * w0.y; + c = c + tap(vec2(p3.x, p0.y)) * w3.x * w0.y; + c = c + tap(vec2(p0.x, p12.y)) * w0.x * w12.y; + c = c + tap(vec2(p12.x, p12.y)) * w12.x * w12.y; + c = c + tap(vec2(p3.x, p12.y)) * w3.x * w12.y; + c = c + tap(vec2(p0.x, p3.y)) * w0.x * w3.y; + c = c + tap(vec2(p12.x, p3.y)) * w12.x * w3.y; + c = c + tap(vec2(p3.x, p3.y)) * w3.x * w3.y; + return c; +} + +// FXAA as the Enhanced post pass does it (after Lottes' FXAA 3.11), on a picture with +// linear values: the luma is taken of their square roots, near enough to the gamma curve. +fn luma(c: vec3) -> f32 { + return dot(sqrt(max(c, vec3(0.0))), vec3(0.299, 0.587, 0.114)); +} + +fn lum_at(uv: vec2) -> f32 { + return luma(tap(uv)); +} + +fn fxaa(uv: vec2, texel: vec2) -> vec3 { + let rgbm = tap(uv); + let m = luma(rgbm); + let n = lum_at(uv + vec2(0.0, -texel.y)); + let s = lum_at(uv + vec2(0.0, texel.y)); + let e = lum_at(uv + vec2(texel.x, 0.0)); + let w = lum_at(uv + vec2(-texel.x, 0.0)); + let hi = max(m, max(max(n, s), max(e, w))); + let lo = min(m, min(min(n, s), min(e, w))); + let range = hi - lo; + if (range < max(0.0312, hi * 0.125)) { + return rgbm; + } + let nw = lum_at(uv + vec2(-texel.x, -texel.y)); + let ne = lum_at(uv + vec2(texel.x, -texel.y)); + let sw = lum_at(uv + vec2(-texel.x, texel.y)); + let se = lum_at(uv + vec2(texel.x, texel.y)); + let avg = (2.0 * (n + s + e + w) + nw + ne + sw + se) / 12.0; + let sub = smoothstep(0.0, 1.0, clamp(abs(avg - m) / range, 0.0, 1.0)); + let blend_sub = sub * sub * 0.75; + let horz = abs(nw + sw - 2.0 * w) + abs(n + s - 2.0 * m) * 2.0 + abs(ne + se - 2.0 * e); + let vert = abs(nw + ne - 2.0 * n) + abs(w + e - 2.0 * m) * 2.0 + abs(sw + se - 2.0 * s); + let is_h = horz >= vert; + var stp = select(texel.x, texel.y, is_h); + let l1 = select(w, n, is_h); + let l2 = select(e, s, is_h); + let g1 = abs(l1 - m); + let g2 = abs(l2 - m); + let neg = g1 >= g2; + let grad = max(g1, g2) * 0.25; + let edge_l = 0.5 * (m + select(l2, l1, neg)); + if (neg) { + stp = -stp; + } + var cuv = uv; + if (is_h) { + cuv.y = cuv.y + stp * 0.5; + } else { + cuv.x = cuv.x + stp * 0.5; + } + let dir = select(vec2(0.0, texel.y), vec2(texel.x, 0.0), is_h); + let steps = array(1.0, 1.0, 1.0, 1.0, 1.0, 1.5, 2.0, 2.0, 2.0, 2.0, 4.0, 8.0); + var p_uv = cuv + dir; + var n_uv = cuv - dir; + var p_end = lum_at(p_uv) - edge_l; + var n_end = lum_at(n_uv) - edge_l; + var p_done = abs(p_end) >= grad; + var n_done = abs(n_end) >= grad; + for (var i = 1; i < 12; i = i + 1) { + if (p_done && n_done) { + break; + } + if (!p_done) { + p_uv = p_uv + dir * steps[i]; + p_end = lum_at(p_uv) - edge_l; + p_done = abs(p_end) >= grad; + } + if (!n_done) { + n_uv = n_uv - dir * steps[i]; + n_end = lum_at(n_uv) - edge_l; + n_done = abs(n_end) >= grad; + } + } + var dp: f32; + var dn: f32; + if (is_h) { + dp = p_uv.x - uv.x; + dn = uv.x - n_uv.x; + } else { + dp = p_uv.y - uv.y; + dn = uv.y - n_uv.y; + } + let near_neg = dn <= dp; + let end_l = select(p_end, n_end, near_neg); + let span = dp + dn; + var blend_edge = 0.0; + if ((m - edge_l < 0.0) != (end_l < 0.0)) { + blend_edge = 0.5 - min(dp, dn) / span; + } + let blend = max(blend_edge, blend_sub); + var fuv = uv; + if (is_h) { + fuv.y = fuv.y + blend * stp; + } else { + fuv.x = fuv.x + blend * stp; + } + return tap(fuv); +} + +@fragment +fn fs_copy(in: VsOut) -> @location(0) vec4 { + // Present classic lighting without metering, grading, or a second AA/upscale pass. + return textureLoad(t_src, vec2(in.clip.xy), 0); +} + +@fragment +fn fs_panel(in: VsOut) -> @location(0) vec4 { + // Triple screen: one panel's picture 1:1 at its place in the window (src.z: its left + // edge in window pixels). + return textureLoad(t_src, vec2(in.clip.xy) - vec2(i32(p.src.z), 0), 0); +} + +@fragment +fn fs_main(in: VsOut) -> @location(0) vec4 { + let size = p.src.xy; + if (p.src.w > 1.5) { + var c = max(tap(in.uv), vec3(0.0)); + // (a light contrast-adaptive sharpening, on the sRGB-encoded numbers as AMD's CAS wants) + if (p.src.z > 0.0) { + let px = 1.0 / size; + let n = tap(in.uv - vec2(0.0, px.y)); + let s = tap(in.uv + vec2(0.0, px.y)); + let w = tap(in.uv - vec2(px.x, 0.0)); + let e = tap(in.uv + vec2(px.x, 0.0)); + let mn = min(c, min(min(n, s), min(w, e))); + let mx = max(c, max(max(n, s), max(w, e))); + let amp = sqrt(clamp(min(mn, vec3(1.0) - mx) / max(mx, vec3(1e-4)), vec3(0.0), vec3(1.0))); + let wgt = amp * (-1.0 / mix(8.0, 5.0, p.src.z)); + c = clamp((c + (n + s + w + e) * wgt) / (vec3(1.0) + 4.0 * wgt), vec3(0.0), vec3(1.0)); + } + let lin = select(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, c <= vec3(0.04045)); + return vec4(lin, 1.0); + } + if (p.src.w > 0.5) { + return vec4(fxaa(in.uv, 1.0 / size), 1.0); + } + let px = 1.0 / size; + // the four texels around the point bound the filtered value (no ringing) + let base = (floor(in.uv * size - 0.5) + 0.5) * px; + let a = tap(base); + let b = tap(base + vec2(px.x, 0.0)); + let c = tap(base + vec2(0.0, px.y)); + let d = tap(base + px); + let lo = min(min(a, b), min(c, d)); + let hi = max(max(a, b), max(c, d)); + var col = clamp(catmull_rom(in.uv, size), lo, hi); + // contrast-adaptive sharpening on the source's texel grid + if (p.src.z > 0.0) { + let n = tap(in.uv - vec2(0.0, px.y)); + let s = tap(in.uv + vec2(0.0, px.y)); + let w = tap(in.uv - vec2(px.x, 0.0)); + let e = tap(in.uv + vec2(px.x, 0.0)); + let mn = min(col, min(min(n, s), min(w, e))); + let mx = max(col, max(max(n, s), max(w, e))); + let amp = sqrt(clamp(min(mn, vec3(1.0) - mx) / max(mx, vec3(1e-4)), vec3(0.0), vec3(1.0))); + let peak = -1.0 / mix(8.0, 5.0, p.src.z); + let wgt = amp * peak; + col = clamp((col + (n + s + w + e) * wgt) / (vec3(1.0) + 4.0 * wgt), vec3(0.0), vec3(1.0)); + } + return vec4(col, 1.0); +} diff --git a/crates/mx/tests/openomsi/volumetric_fog.wgsl b/crates/mx/tests/openomsi/volumetric_fog.wgsl new file mode 100644 index 0000000..74a2f35 --- /dev/null +++ b/crates/mx/tests/openomsi/volumetric_fog.wgsl @@ -0,0 +1,1247 @@ +// Enhanced graphics: the light the air scatters towards the camera that the main pass +// leaves out - the lamps' in the weather's fog, rain or falling snow (`lamp_airlight` in +// lamp_air.wgsl) and the sun's shafts between the shadows (`sun_shafts`) - added onto the +// drawn picture before its glow and its metering. Once per pixel over the depth prepass: worked out in +// the main pass it was paid again for every layer drawn over a pixel (painted ground, +// decals), several milliseconds a frame in a foggy night. +struct Camera { + view_proj: mat4x4, + cam_pos: vec4, + // (kept in lockstep with `CameraUniform` in lib.rs, as sky.wgsl's) + world_origin: vec4, + sun_dir: vec4, + ambient: vec4, + fog: vec4, + sun_color: vec4, + sky_color: vec4, + light_grid: vec4, + sky: vec4, + cam_right: vec4, + cam_up: vec4, + clouds: vec4, + light_view_proj: mat4x4, + light_view_proj_far: mat4x4, + shadow: vec4, + post: vec4, + inside_a: vec4, + inside_b: vec4, + inside_c: vec4, + flags: vec4, + light_view_proj_close: mat4x4, + wind: vec4, + lamp_view_proj: array, 56>, + lamp_atlas: vec4, + tree_wind: vec4, + inside2_a: vec4, + inside2_b: vec4, + inside2_c: vec4, + cookies: array, 8>, + cabin_lamps: array, 4>, + // x: the textures' mip bias (FSR 1: negative, see `CameraUniform::lod`) + lod: vec4, + // (the classic picture's headlight, `CameraUniform::spot`: unread here) + spot: array, 4>, +}; +@group(0) @binding(0) var camera: Camera; + +struct FogLampParams { + // clip space (reversed Z) back to the render-origin relative world + inv_view_proj: mat4x4, + // xy the picture's size in pixels, z 1: the sun's glare is added (2: it is all that is + // added, the half-size result holds only the sun's row), w the share of the weather's + // extinction that is mist and fog (not rain) + size: vec4, +}; +@group(1) @binding(0) var fp: FogLampParams; +@group(1) @binding(1) var t_depth: texture_depth_2d; +// the half-size result (rgb pre-exposed light, a the distance it was worked out to) +@group(1) @binding(2) var t_fog: texture_2d; + +struct FogVsOut { + @builtin(position) clip: vec4, +}; + +@vertex +fn vs_fog_lamps(@builtin(vertex_index) i: u32) -> FogVsOut { + let x = f32(i32(i & 1u) * 4 - 1); + let y = f32(i32(i >> 1u) * 4 - 1); + var out: FogVsOut; + out.clip = vec4(x, y, 0.0, 1.0); + return out; +} + +// The camera, the direction through a full-size pixel position and the distance to what +// the prepass holds there (3 km for the sky). +fn pixel_ray(at: vec2) -> vec4 { + let dims = vec2(textureDimensions(t_depth)); + let px = clamp(vec2(at), vec2(0), dims - vec2(1)); + let d = textureLoad(t_depth, px, 0); + let ndc = vec2(at.x / fp.size.x * 2.0 - 1.0, 1.0 - at.y / fp.size.y * 2.0); + let c = camera.cam_pos.xyz; + let mid = fp.inv_view_proj * vec4(ndc, 0.5, 1.0); + let dir = normalize(mid.xyz / mid.w - c); + var len = 3000.0; + if (d > 0.0) { + let h = fp.inv_view_proj * vec4(ndc, d, 1.0); + len = distance(h.xyz / h.w, c); + } + return vec4(dir, len); +} + +// The sun's shadow maps (shader.wgsl's bindings and constants). +@group(0) @binding(5) var t_shadow: texture_depth_2d; +@group(0) @binding(6) var s_shadow: sampler_comparison; +@group(0) @binding(7) var t_shadow_far: texture_depth_2d; +const SHAFT_DEPTH_RANGE: f32 = 2199.0; +const SHAFT_STEPS: u32 = 16u; +// how far the shafts are followed in the dense steps (the near cascade's reach, a little less) +const SHAFT_NEAR: f32 = 180.0; +// and, past it, in a few sparse ones to the far map's reach (the beams of a misty avenue, or +// a low sun between the blocks, reach farther than the first hundred metres) +const SHAFT_FAR_STEPS: u32 = 4u; +const SHAFT_REACH: f32 = 420.0; +// how far the sky's gaps are followed (the haze beyond that is the table's, lit as a whole) and in +// how many steps growing by a fixed ratio +const SKY_SHAFT_REACH: f32 = 7000.0; +const SKY_SHAFT_STEPS: u32 = 8u; + +// Whether the sun reaches a point in the air (1) or a house or a crown stands between (0). +fn sun_reaches(x: vec3) -> f32 { + let lp = camera.light_view_proj * vec4(x, 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (max(abs(uv.x - 0.5), abs(uv.y - 0.5)) < 0.48 && lp.z >= 0.0 && lp.z <= 1.0) { + return textureSampleCompareLevel(t_shadow, s_shadow, vec2(uv.x * 0.5, uv.y), lp.z - 0.15 / SHAFT_DEPTH_RANGE); + } + let fp2 = camera.light_view_proj_far * vec4(x, 1.0); + let fuv = vec2(fp2.x * 0.5 + 0.5, 0.5 - fp2.y * 0.5); + if (fuv.x < 0.0 || fuv.x > 1.0 || fuv.y < 0.0 || fuv.y > 1.0 || fp2.z < 0.0 || fp2.z > 1.0) { + return 1.0; + } + // (the far map takes the top of its texture, see shader.wgsl `shadow_pcf_far`) + return textureSampleCompareLevel(t_shadow_far, s_shadow, vec2(fuv.x, fuv.y * (1.0 / (camera.shadow.y * camera.lamp_atlas.z))), fp2.z - 0.6 / SHAFT_DEPTH_RANGE); +} + +fn sun_reaches_close(x: vec3) -> f32 { + let lp = camera.light_view_proj_close * vec4(x, 1.0); + let uv = vec2(lp.x * 0.5 + 0.5, 0.5 - lp.y * 0.5); + if (camera.flags.w <= 0.0 || max(abs(uv.x - 0.5), abs(uv.y - 0.5)) >= 0.48 || lp.z < 0.0 || lp.z > 1.0) { + return sun_reaches(x); + } + let s = select(1.0, camera.post.w, camera.post.w > 0.0); + return textureSampleCompareLevel(t_shadow, s_shadow, vec2(0.5 + uv.x * s * 0.5, uv.y * s), lp.z - 0.05 / SHAFT_DEPTH_RANGE); +} + +// Shafts of sunlight - crepuscular rays: the air between the camera and what it sees +// scatters the sun towards the eye wherever the sun reaches it, and not in the shadow of a +// house or a tree. The picture's air (`air` in enhanced_common.wgsl) holds that light as +// if the sun reached the air everywhere; along the first stretch of the ray, which the +// shadow maps cover, what lies in shadow is taken out again here (a negative radiance): +// lit and dark shafts through a hazy evening, a misty morning wood, a dusty street. The +// air scatters the way `air` has it - the weather's fog with g 0.55, the clear air's haze +// and dust forward with g 0.7 (its Rayleigh part is small near the ground). +fn sun_shafts(c: vec3, d: vec3, len: f32, jitter: f32) -> vec3 { + let s = camera.sun_dir.xyz; + let e_sun = enh.sun.rgb; + // (the clouds' shadow field: the shafts through a broken sky, followed to kilometres) + let sky_gaps = enh.cloud_f1.w > 0.5 && s.z >= 0.06; + let shadows = camera.shadow.x > 0.5; + // (with the volumetric fog on, its march has the shadows in the air already: + // volumetric_fog.wgsl, enh.vol_fog.x) + if (enh.vol_fog.x > 0.5 || (!shadows && !sky_gaps) || s.z <= 0.0 || max(e_sun.r, e_sun.g) < 1e-4) { + return vec3(0.0); + } + let end = min(len, SHAFT_NEAR); + let dt = end / f32(SHAFT_STEPS); + let far_len = max(min(len, SHAFT_REACH) - SHAFT_NEAR, 0.0); + let dt_far = far_len / f32(SHAFT_FAR_STEPS); + let cos_t = dot(s, d); + let p_fog = hg_phase(cos_t, 0.55) * 0.9; + let p_air = hg_phase(cos_t, 0.7); + let h0 = c.z - enh.fog.z; + // the clouds' part reaches on, out to the haze's own horizon: from the sparse steps' + // end, in steps growing by a fixed ratio + let sky_end = select(SHAFT_REACH, min(len, SKY_SHAFT_REACH), sky_gaps); + // (the most the shadows could take out along the way, on the screen: where that is + // too little to see - most of the picture, looking away from the sun - nothing is done) + let most = (enh.fog.x * p_fog + enh.fog.w * p_air) * max(e_sun.r, e_sun.g) * max(end, select(0.0, sky_end, sky_gaps)) * enh.exposure.x; + if (most < 0.004) { + return vec3(0.0); + } + var shade = vec3(0.0); + for (var i = 0u; i < SHAFT_STEPS + SHAFT_FAR_STEPS; i = i + 1u) { + let far = i >= SHAFT_STEPS; + if (far && far_len <= 0.0) { + break; + } + let t = select((f32(i) + jitter) * dt, SHAFT_NEAR + (f32(i - SHAFT_STEPS) + jitter) * dt_far, far); + let w = select(dt, dt_far, far); + let x = c + d * t; + var lit = 1.0; + if (shadows) { + lit = sun_reaches(x); + } + if (sky_gaps) { + lit = lit * cloud_shadow_ratio(x); + } + // (a point the cloud lets more sun through than the camera's own place gets adds light) + if (lit >= 0.999 && lit <= 1.001) { + continue; + } + let h = max(x.z - enh.fog.z, 0.0); + let s_fog = enh.fog.x * exp(-enh.fog.y * h); + let s_air = enh.fog.w * exp(-h / 1500.0); + let tau = layer_depth(enh.fog.x, enh.fog.y, h0, h, t) + layer_depth(enh.fog.w, 1.0 / 1500.0, h0, h, t); + shade = shade + vec3((1.0 - lit) * (s_fog * p_fog + s_air * p_air) * exp(-tau) * w); + } + // the part beyond the shadow maps: only the clouds' shadow is known there + if (sky_gaps && sky_end > SHAFT_REACH) { + let r = pow(sky_end / SHAFT_REACH, 1.0 / f32(SKY_SHAFT_STEPS)); + var t0 = SHAFT_REACH; + for (var i = 0u; i < SKY_SHAFT_STEPS; i = i + 1u) { + let t1 = t0 * r; + let t = t0 + (t1 - t0) * jitter; + let x = c + d * t; + let lit = cloud_shadow_ratio(x); + if (lit < 0.999 || lit > 1.001) { + let h = max(x.z - enh.fog.z, 0.0); + let s_fog = enh.fog.x * exp(-enh.fog.y * h); + let s_air = enh.fog.w * exp(-h / 1500.0); + let tau = layer_depth(enh.fog.x, enh.fog.y, h0, h, t) + layer_depth(enh.fog.w, 1.0 / 1500.0, h0, h, t); + shade = shade + vec3((1.0 - lit) * (s_fog * p_fog + s_air * p_air) * exp(-tau) * (t1 - t0)); + } + t0 = t1; + } + } + return -shade * e_sun; +} + +// at half size: one ray per four pixels +@fragment +fn fs_fog_lamps(in: FogVsOut) -> @location(0) vec4 { + // (the texture's last row: how much of the sun is seen, worked out once for the frame + // in its first texel) + // (t_fog is not this pass's target: the row is the one under the half picture) + if (i32(in.clip.y) >= i32(ceil(fp.size.y * 0.5))) { + var seen = 0.0; + if (i32(in.clip.x) == 0 && fp.size.z > 0.5 && camera.sun_dir.z > -0.02) { + seen = sun_seen(camera.cam_pos.xyz, camera.sun_dir.xyz); + } + return vec4(seen, 0.0, 0.0, 0.0); + } + let r = pixel_ray(floor(in.clip.xy) * 2.0 + vec2(0.5)); + let q = vec2(in.clip.xy) & vec2(1); + let ign = (f32(q.x * 2 + (q.x ^ q.y)) + 0.5) * 0.25; + // (the lamps' halo and cones only from the mist's and fog's droplets: fp.size.w) + let l = (lamp_airlight(camera.cam_pos.xyz, r.xyz, 0.0, r.w, ign, fp.size.w) + sun_shafts(camera.cam_pos.xyz, r.xyz, r.w, ign)) * enh.exposure.x; + return vec4(clamp(l, vec3(-4000.0), vec3(4000.0)), r.w); +} + +// How much of the sun's disc is seen (0..1): houses, trees and the bus in front of it +// are in the depth prepass (the clouds and the fog are in `enh.sun` already). +fn sun_seen(c: vec3, s: vec3) -> f32 { + let r = enh.sun.w; + let up0 = select(vec3(0.0, 0.0, 1.0), vec3(1.0, 0.0, 0.0), abs(s.z) > 0.9); + let a = normalize(cross(s, up0)); + let b = cross(s, a); + var seen = 0.0; + var n = 0.0; + for (var k = 0; k < 13; k = k + 1) { + var o = vec2(0.0); + if (k > 0) { + let ang = f32(k) * 2.3999632; + o = vec2(cos(ang), sin(ang)) * sqrt(f32(k) / 12.0) * 0.9; + } + let dir = normalize(s + (a * o.x + b * o.y) * r); + let clip = camera.view_proj * vec4(c + dir * 1000.0, 1.0); + let ndc = clip.xy / max(clip.w, 1e-6); + n = n + 1.0; + if (clip.w <= 0.0 || abs(ndc.x) > 1.0 || abs(ndc.y) > 1.0) { + // Beyond the picture's edge the prepass knows nothing: whether the eye stands in + // the shadow of anything the sun's shadow maps hold (without shadows: seen). + // What stood at the edge was taken before - a house or a pole reaching the edge + // as the camera turned put out the whole veil at once, and sky put it back, a + // sheet of light over the picture switched off and on. + if (camera.shadow.x > 0.5) { + seen = seen + sun_reaches_close(c + dir * 0.3); + } else { + seen = seen + 1.0; + } + continue; + } + let px = vec2((ndc.x * 0.5 + 0.5) * fp.size.x, (0.5 - ndc.y * 0.5) * fp.size.y); + let dims = vec2(textureDimensions(t_depth)); + let q = clamp(vec2(px), vec2(0), dims - vec2(1)); + seen = seen + select(0.0, 1.0, textureLoad(t_depth, q, 0) <= 0.0); + } + return seen / n; +} + +// Glare: the light a lens scatters round a bright source - the sun seen directly washes out +// what is right beside it. The picture is a camera's, and the player compares it with +// photographs: a good lens' stray light falls off as the near term of the CIE's glare +// function, 10/theta^3 per unit of the source's illuminance (theta in degrees, CIE +// 146:2002), a glow of a few degrees. The eye's own share - the wide veil of 5/theta^2 and +// more that the vitreous and the eye's wall add, its ciliary streaks and its lenticular +// halo - was drawn as well and made a white blot ten degrees round the sun of a clear day, +// "the sun is too large" (#2400): a photograph shows none of it. +fn sun_glare(dir: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + if (max(enh.sun.r, enh.sun.g) < 1e-5 || s.z < -0.02) { + return vec3(0.0); + } + let cos_t = clamp(dot(dir, s), -1.0, 1.0); + // (cos 100 degrees: past it there is no veil, and the arc cosine is not needed) + if (cos_t < -0.17364818) { + return vec3(0.0); + } + let theta = max(degrees(acos(cos_t)), 0.25); + let seen = textureLoad(t_fog, vec2(0, i32(textureDimensions(t_fog).y) - 1), 0).r; + if (seen <= 0.0) { + return vec3(0.0); + } + return enh.sun.rgb * seen * (10.0 / (theta * theta * theta)); +} + +// at full size, added onto the picture: the four nearest half-size rays, each as far as +// it was worked out to a distance like this pixel's (the light in front of a near pole +// is not the light in front of the houses behind it) +@fragment +fn fs_fog_composite(in: FogVsOut) -> @location(0) vec4 { + let ray = pixel_ray(in.clip.xy); + var air_light = vec3(0.0); + if (fp.size.z < 1.5) { + air_light = gathered_air_light(in.clip.xy, ray.w); + } + // the eye's glare from the sun, on top of everything (fp.size.z: on) + var glare = vec3(0.0); + if (fp.size.z > 0.5) { + glare = sun_glare(ray.xyz) * enh.exposure.x; + } + return vec4(air_light + min(glare, vec3(4000.0)), 0.0); +} + +fn gathered_air_light(at: vec2, len: f32) -> vec3 { + let hp = at * 0.5 - vec2(0.5); + let base = vec2(floor(hp)); + let f = hp - floor(hp); + // (the last row is the sun's, see `fs_fog_lamps`) + let hd = vec2(textureDimensions(t_fog)) - vec2(1, 2); + // (not one of the sixteen half-size rays holds any light: no lamp's cone and no shaft + // here - most of a picture in clear air - and the weighted sum below would only add up + // zeros, so it is not worked out. All sixteen, the whole footprint of the tent: a lit + // ray at its edge still lights the pixel) + var lit = false; + for (var k = 0; k < 16; k = k + 1) { + let o = vec2(k & 3, k >> 2) - vec2(1); + lit = lit || any(textureLoad(t_fog, clamp(base + o, vec2(0), hd), 0).rgb != vec3(0.0)); + } + if (!lit) { + return vec3(0.0); + } + var sum = vec3(0.0); + var wsum = 0.0; + // (a twig or a wire none of the four rays met: the one nearest in distance) + var best = vec3(0.0); + var best_d = 1e9; + // (a tent over the 4 x 4 nearest: the edge of a headlight's beam in the haze, worked + // out at half size, showed its 2 x 2 blocks under a plain bilinear one) + for (var k = 0; k < 16; k = k + 1) { + let o = vec2(k & 3, k >> 2) - vec2(1); + let s = textureLoad(t_fog, clamp(base + o, vec2(0), hd), 0); + let dx = abs(f32(o.x) - f.x); + let dy = abs(f32(o.y) - f.y); + let bil = max(1.0 - dx * 0.5, 0.0) * max(1.0 - dy * 0.5, 0.0); + let dd = abs(s.a - len); + // (a Gaussian of the distance difference, not an exponential: a road's rows differ by + // a few per cent of its length from one half-size row to the next, and an exponential + // weighted every row differently - the offsets of the staggered steps, which cancel + // over the tent exactly when its weights are even, then came out as a stripe along + // every other row of a bright beam. A step in depth, a pole against what is behind it, + // still keeps the taps of the far side out.) + let tol = (dd / (0.05 * len + 0.5)) * 1.2; + let w = (bil + 1e-3) * exp(-tol * tol); + sum = sum + s.rgb * w; + wsum = wsum + w; + if (dd < best_d) { + best_d = dd; + best = s.rgb * min(len / max(s.a, 0.1), 1.0); + } + } + if (wsum < 1e-4) { + return best; + } + return sum / max(wsum, 1e-6); +} + + +// Enhanced graphics: what the enhanced main pass, the sky and the coronas share - the +// light of the physically based sky (see atmosphere.rs), in its units (1 = 10 000 lux), +// and the air between the camera and what it sees. The scene is drawn pre-exposed: +// radiance times `enh.exposure.x`, so that the half-float target keeps its precision by +// night as well as by day. +struct Enhanced { + // x pre-exposure, y the level unlit things are drawn at, z a lit window's radiance + // (pre-exposed), w how bright a light's corona is drawn + exposure: vec4, + // rgb irradiance of the sun after the clouds, w its angular radius (rad) + sun: vec4, + // irradiance from the sky and the ground: order-2 spherical harmonics, rgb + sh: array, 9>, + // rgb radiance of the ground, w the sky table's scale + ground: vec4, + // x weather fog extinction (1/m) at its base, y its height falloff (1/m), z the base + // height (render-origin relative), w clear-air extinction (1/m) at the ground + fog: vec4, + // rgb fog radiance from the light around it (the sun's part is added by angle), + // w the table scale the reflection probe was drawn with + fog_color: vec4, + // x wet roads, y snow cover, z rain, w cloud cover in front of the sun + weather: vec4, + // x mip levels of the probe, y illuminance of a light's core (maplight colour 1), + // z cabin light illuminance, w how much of the sun the clouds let through + lights: vec4, + // rgb the sun disc's irradiance before the clouds, w frame time (s) + sun_disc: vec4, + // x which term the main pass shows alone (OMSI_DEBUG_ENHANCED, 0 = the picture), + // y the puddles' F0, z the envmap photo's strength, w the tone curve's contrast + debug: vec4, + // xyz where the sky cube is drawn from, relative to the camera + eye: vec4, + // x how bright an LED panel's dots burn (0 = off), y whether the LED panels' `\S:n` + // masks keep their mip chain (0: at full resolution, the dots stay visible when small), z 1 + // when lights glare and glow in the night air (the settings' `light_glow`) + led: vec4, + // xyz towards the moon, w its angular radius (rad) + moon: vec4, + // rgb the moon disc's irradiance before the clouds, w how much of the starry sky shows + moon_disc: vec4, + // rgb the sun's irradiance at 1400, 2100 and 2800 m (the cumulus layer) and 7000 m + // (the high thin layer), through the atmosphere from up there + cloud_sun: array, 4>, + // rgb the moonlight on a surface facing the moon (after the clouds), w 1 while the + // shadow maps are the moon's + moon_light: vec4, + // the condensation on the player's bus's panes (optical depths): windscreen, sides, + // rear, and how far the defroster has cleared the windscreen (0..1; omsi-app + // condensation.rs) + condensation: vec4, + // x the cumulus layer's base, y its top (m over the ground), z the altocumulus cover, + // w the storm's activity + layers: vec4, + // the lightning of this frame: x the light it throws on a surface facing it (1 = 10 000 + // lux), yz towards it (horizontal unit vector), w its elevation (rad) + flash: vec4, + // xyz towards the flash (unit vector), w how bright its channel is + flash2: vec4, + // x a number the channel's shape is drawn from + flash3: vec4, + // the clouds' shadow field (cloud_field.rs): xy its middle in cloud space, z one over its + // width, w 1 when there is one + cloud_f1: vec4, + // xy what takes a world point to cloud space, z the height of the plane it is taken on, + // w the share of the sun the main pass has taken off already for the clouds over the camera + cloud_f2: vec4, + // the player's bus's pitch and roll: sin, cos of each (its panes' condensation sits on + // the glass on a slope, `pane_local`) + pane_tilt: vec4, + // Slots of the weather overhaul, one owner each (zero until it fills them): + // the volumetric clouds, the volumetric fog, the precipitation, the bus's panes, the + // surfaces' PBR and the ray tracing, and two spare. + clouds_ext: vec4, + clouds_ext2: vec4, + vol_fog: vec4, + vol_fog2: vec4, + precip_ext: vec4, + glass_ext: vec4, + // (pbr_ext: x the share of the sun's light that still comes as a beam - the rest the + // clouds scatter, `sun_scattered` - y 1 when x is set) + pbr_ext: vec4, + rt_ext: vec4, +}; +@group(0) @binding(11) var enh: Enhanced; +@group(0) @binding(13) var s_lin: sampler; +@group(0) @binding(14) var t_sky_lut: texture_2d; + +const PI: f32 = 3.14159265; + +// Irradiance from the sky and the ground on a surface facing n. +fn sh_irradiance(n: vec3) -> vec3 { + let c = enh.sh; + let e = c[0].rgb * 0.282095 + + c[1].rgb * (0.488603 * n.y) + c[2].rgb * (0.488603 * n.z) + c[3].rgb * (0.488603 * n.x) + + c[4].rgb * (1.092548 * n.x * n.y) + c[5].rgb * (1.092548 * n.y * n.z) + + c[6].rgb * (0.315392 * (3.0 * n.z * n.z - 1.0)) + c[7].rgb * (1.092548 * n.x * n.z) + + c[8].rgb * (0.546274 * (n.x * n.x - n.y * n.y)); + return max(e, vec3(0.0)); +} + +// The lightning's light on a surface facing n: half of it from the cloud overhead and +// round it (a hemisphere), half along the way to the flash itself. +fn flash_irradiance(n: vec3) -> vec3 { + if (enh.flash.x <= 0.0) { + return vec3(0.0); + } + return vec3(0.80, 0.90, 1.0) * enh.flash.x * (0.5 * (0.5 + 0.5 * n.z) + 0.5 * max(dot(n, enh.flash2.xyz), 0.0)); +} + +// Sky radiance towards d (unscaled: times enh.ground.w is the radiance). The table runs +// over the azimuth from the sun (0..π) and the elevation (denser at the horizon). +// The sky table's texture: the table (32 x 48) in its corner and the clouds' shadow field +// (192 x 192) beside it, one texel clear (cloud_field.rs `SKY_TEX_W`, `FIELD_X0`). +const SKY_TEX: vec2 = vec2(225.0, 192.0); +const SKY_TABLE: vec2 = vec2(32.0, 48.0); +const FIELD_ORIGIN: f32 = 33.0; +const FIELD_N: f32 = 192.0; + +fn sky_table_raw(d: vec3) -> vec3 { + let s = camera.sun_dir.xyz; + let ls = length(s.xy); + let ld = length(d.xy); + var az = 0.0; + if (ls > 1e-4 && ld > 1e-4) { + az = acos(clamp(dot(s.xy / ls, d.xy / ld), -1.0, 1.0)); + } + let el = asin(clamp(d.z, -1.0, 1.0)); + let v = 0.5 + 0.5 * sign(el) * sqrt(min(abs(el) / 1.5707963, 1.0)); + // (kept a half texel inside the table: its neighbours in the texture are not the sky) + let tx = clamp(vec2(az / PI, v) * SKY_TABLE, vec2(0.5), SKY_TABLE - vec2(0.5)); + return textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).rgb; +} + +// The share of the sun that reaches the point p through the clouds, as against what the main +// pass's sun (`enh.sun`) already has for the camera's own place: the cumulus layer's shadow +// field read where the sun's way through p meets the layer's middle. 1 where there is no +// field, beyond its edge and where the sun is low (the camera's own factor stands there). +fn cloud_shadow_ratio(p: vec3) -> f32 { + let s = camera.sun_dir.xyz; + if (enh.cloud_f1.w < 0.5 || s.z < 0.06) { + return 1.0; + } + let cs = p.xy + s.xy / s.z * (enh.cloud_f2.z - p.z) + enh.cloud_f2.xy; + let uv = (cs - enh.cloud_f1.xy) * enh.cloud_f1.z + vec2(0.5); + let edge = max(abs(uv.x - 0.5), abs(uv.y - 0.5)); + let w = 1.0 - smoothstep(0.36, 0.48, edge); + if (w <= 0.0) { + return 1.0; + } + let tx = vec2(FIELD_ORIGIN, 0.0) + clamp(uv * FIELD_N, vec2(0.5), vec2(FIELD_N - 0.5)); + let f = textureSampleLevel(t_sky_lut, s_lin, tx / SKY_TEX, 0.0).r; + let ratio = min(f / max(enh.cloud_f2.w, 0.02), 6.0); + return mix(1.0, ratio, w); +} + +fn sky_table(d: vec3) -> vec3 { + return sky_table_raw(d) * enh.ground.w; +} + +// Henyey-Greenstein phase function. +fn hg_phase(c: f32, g: f32) -> f32 { + let g2 = g * g; + return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * c, 1e-4), 1.5)); +} + +// Optical depth of an exponentially thinning layer (extinction sigma at height 0, falling +// off with k per metre) along a straight path of length dist from height h0 to h1. +fn layer_depth(sigma: f32, k: f32, h0: f32, h1: f32, dist: f32) -> f32 { + if (sigma <= 0.0) { + return 0.0; + } + let a = max(h0, 0.0); + let b = max(h1, 0.0); + let dh = b - a; + if (abs(k * dh) < 1e-3) { + return sigma * dist * exp(-k * 0.5 * (a + b)); + } + return sigma * dist * (exp(-k * a) - exp(-k * b)) / (k * dh); +} + +// The air between the camera and a point dist metres away in direction dir (from the +// camera), at heights h0 (camera) and h1 (point) above the fog's base: rgb the light it +// scatters towards the camera (radiance), a what it lets through of the point. +fn air(dir: vec3, dist: f32, h0: f32, h1: f32) -> vec4 { + return air_of(dir, dist, h0, h1, 1.0); +} + +// The same with the clear air's share scaled (0 for the sky, whose table holds it already). +fn air_of(dir: vec3, dist: f32, h0: f32, h1: f32, clear: f32) -> vec4 { + let tau_fog = layer_depth(enh.fog.x, enh.fog.y, h0, h1, dist); + let tau_air = layer_depth(enh.fog.w * clear, 1.0 / 1500.0, h0, h1, dist); + let tau = tau_fog + tau_air; + let t = exp(-tau); + if (tau < 1e-5) { + return vec4(0.0, 0.0, 0.0, 1.0); + } + // clear air takes on the sky's own colour at the horizon in this direction (which + // already holds the glow round the sun); a weather fog glows with the light around it + // and brighter towards the sun + let horizon = sky_table(normalize(vec3(dir.x, dir.y, max(dir.z, 0.0) * 0.3 + 0.03))); + let fog_in = enh.fog_color.rgb + enh.sun.rgb * hg_phase(dot(dir, camera.sun_dir.xyz), 0.55) * 0.9; + let inscatter = mix(horizon, fog_in, tau_fog / tau); + return vec4(inscatter * (1.0 - t), t); +} + +struct PointLight { + pos: vec4, + color: vec4, + dir: vec4, + extra: vec4, +}; +@group(0) @binding(3) var lights: array; +@group(0) @binding(4) var grid: array; +const CELL_CAP: u32 = 32u; + +// The shadows in a lamp's beam (the fog pass: its camera uniform has the lamp shadow tiles and +// the far shadow map's texture, see `fog_lamps.wgsl`). The other shaders that share +// `lamp_air.wgsl` take `beam_shadow_none.wgsl`'s: no map to look up, the beam goes on. + +// Which of the lamp shadow tiles (under the far shadow map, see `lamp_shadow_at` in the +// scene's lamps) belongs to lamp `li`: its record names it in `pos.w` (a multiple of 32 of the +// marks below zero, `light_marks`), or 0xffffffff for a lamp with none. +fn beam_tile(li: u32, l: PointLight) -> u32 { + let tile = floor(max(-l.pos.w, 0.0) / 32.0); + return select(0xffffffffu, u32(tile - 0.5), tile > 0.5); +} + +// How much of a beam reaches a point of the air, in tile `k` of its lamp's map: 0 where a +// pole, a car or a wall stands between the lamp and the point, so that the fog shows the +// shadow in its beam as it shows the sun's in a shaft. A tap of the hardware's filtered +// compare; off the tile, or without a map, the beam goes on. +fn beam_reaches(k: u32, x: vec3) -> f32 { + if (k >= 44u) { + return 1.0; + } + let q = camera.lamp_view_proj[k] * vec4(x, 1.0); + if (q.w <= 0.0) { + return 1.0; + } + let ndc = q.xyz / q.w; + if (abs(ndc.x) >= 1.0 || abs(ndc.y) >= 1.0 || ndc.z >= 1.0 || ndc.z <= 0.0) { + return 1.0; + } + let dims = vec2(1.0 / camera.shadow.y, camera.lamp_atlas.z); + let tile = camera.lamp_atlas.x; + let cols = u32(camera.lamp_atlas.y); + let tuv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + let tx = clamp(tuv * tile, vec2(1.5), vec2(tile - 1.5)); + let at = (vec2(f32(k % cols) * tile, dims.x + f32(k / cols) * tile) + tx) / dims; + // (a little more off the occluder than a surface takes: the air has no surface to + // acne, and the lamp's own housing must not shade its beam) + return textureSampleCompareLevel(t_shadow_far, s_shadow, at, ndc.z - 0.0002); +} + +// Enhanced graphics: the lamps as the scene and the sky share them - a headlamp's beam +// and the light the weather's fog scatters from the lamps towards the camera (needs the +// point lights, their grid and `camera.light_grid`). + +// A headlamp's intensity towards `t` (from the lamp) by the angles of a road lamp, not +// around its axis: wide across, brightest just under the lamp's horizon where it reaches +// far down the road, weak straight down, and with a low beam a sharp cut-off above it. +// `dir` is the lamp's axis in its vehicle's floor: its rise tilts the horizon with the +// vehicle, up a ramp and down (#1897). +fn headlamp(t: vec3, dir: vec3, low: bool) -> f32 { + let fwd = normalize(dir.xy + vec2(1e-6, 0.0)); + let ahead = dot(t.xy, fwd); + if (ahead <= 0.0) { + return 0.0; + } + let across = abs(t.x * fwd.y - t.y * fwd.x) / ahead; + let wide = 0.12 * smoothstep(1.0, 0.45, across) + 0.88 * exp(-across * across / 0.06); + let rise = t.z / max(length(t.xy), 1e-3); + let tilt = dir.z / max(length(dir.xy), 1e-3); + // (the tangent of the angle under that horizon) + let drop = (tilt - rise) / max(1.0 + rise * tilt, 1e-3); + // full out to where the road is 0.06 under the lamp's horizon, then less as the cube of + // the drop and a little more: the road is lit evenly from the bumper on, a little + // brighter as far as the beam reaches, and not as one hot pool where its axis lands + var up = min(1.0, pow(0.06 / max(abs(drop), 1e-4), 3.4)); + if (low) { + up = up * smoothstep(-0.012, 0.025, drop); + return wide * up; + } + // a full beam reaches far: a narrow, bright core along the lamp's horizon + let hot = exp(-across * across / 0.012 - drop * drop / 0.0004); + return wide * up + 6.0 * hot; +} + +// The lamps' light the weather's fog scatters towards the camera (radiance, not +// pre-exposed): single scattering along the view ray from `start` to `len` metres in +// direction `d` - the glow round a street lamp in the mist, its cone under it, a bus's +// beams reaching ahead into the fog or the falling snow. The droplets scatter strongly +// forward (fog and cloud droplets of some ten micrometres: g about 0.8), so the glow is +// brightest looking towards a lamp and a cone shows faintly from the side. +// +// Each lamp is taken once, over the whole stretch of the ray within its reach, in the grid +// cell the ray's point nearest to it lies in (the ray's cells are walked through; every +// cell lists the lamps reaching into it). Along a straight ray past a point source, with +// t - t0 = h tan(phi) (h the ray's distance from the lamp, t0 where it passes nearest), +// the inverse square cancels against the path element: dt / r^2 = dphi / h, and what is +// left is the phase function over the angle, cos(theta) = -sin(phi) - a smooth integral +// taken with five Gauss-Legendre nodes, at each of which a spot's or a headlamp's beam is +// asked how much it sends that way. The fog's extinction dims the light on its way from +// the lamp and to the camera (taken at the nearest point). A beam's light, which reaches +// only part of the way, is summed along the ray instead, its steps staggered by `jitter`. +// The droplets' phase function: a strong forward peak and the back-scattered light a +// fog's lidar ratio of some 18 sr asks for (0.055 per steradian straight back) - a single +// Henyey-Greenstein lobe of g 0.8 gave a tenth of it, and a bus's own headlights lit no +// wall of fog in front of the driver. Two lobes, 0.9 of g 0.85 and 0.1 of g -0.5. +fn fog_phase(c: f32) -> f32 { + return 0.9 * hg_phase(c, 0.85) + 0.1 * hg_phase(c, -0.5); +} +const AIRLIGHT_CELLS: u32 = 16u; + +// The clear night air's own haze, which lights a lamp's halo and a headlamp's beam as the fog's +// droplets do, only fainter: the lowest hundred metres of a city's air hold its dust, exhaust +// and humidity at several times the column's average aerosol extinction (`enh.fog.w`), 1-3e-4 +// per metre (a visibility of 15-40 km). A lamp then has a soft glow round it and a low beam +// a faint cone, as in any night photograph, instead of a lit disc on a black ground. +const GROUND_HAZE_GAIN: f32 = 8.0; + +// `droplets`: how much of the weather's extinction scatters like fog (see `FogLampUniform`). +fn lamp_airlight(c: vec3, d: vec3, start: f32, len: f32, jitter: f32, droplets: f32) -> vec3 { + var sum = vec3(0.0); + let sigma0 = enh.fog.x * droplets + enh.fog.w * GROUND_HAZE_GAIN * enh.led.z; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (sigma0 < 4e-5 || cell <= 0.0 || side == 0u || len <= start) { + return sum; + } + // (past a few optical depths nothing comes back) + let end = min(len, start + 4.0 / sigma0); + let gx = array(-0.9061798, -0.5384693, 0.0, 0.5384693, 0.9061798); + let gw = array(0.2369269, 0.4786287, 0.5688889, 0.4786287, 0.2369269); + // the walk through the grid's cells along the ray's plan + let o = (c.xy - camera.light_grid.xy) / cell; + let dd = d.xy / cell; + var ix = i32(floor(o.x + dd.x * start)); + var iy = i32(floor(o.y + dd.y * start)); + let sx = select(-1, 1, dd.x >= 0.0); + let sy = select(-1, 1, dd.y >= 0.0); + let inv_x = select(1e9, 1.0 / abs(dd.x), abs(dd.x) > 1e-7); + let inv_y = select(1e9, 1.0 / abs(dd.y), abs(dd.y) > 1e-7); + var tx = select((f32(ix) - o.x) / dd.x, (f32(ix + 1) - o.x) / dd.x, dd.x >= 0.0); + var ty = select((f32(iy) - o.y) / dd.y, (f32(iy + 1) - o.y) / dd.y, dd.y >= 0.0); + if (abs(dd.x) <= 1e-7) { tx = 1e9; } + if (abs(dd.y) <= 1e-7) { ty = 1e9; } + var t = start; + for (var k = 0u; k < AIRLIGHT_CELLS; k = k + 1u) { + if (t >= end) { + break; + } + let t_out = min(min(tx, ty), end); + if (ix >= 0 && iy >= 0 && ix < i32(side) && iy < i32(side)) { + let base = (u32(iy) * side + u32(ix)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let to_l = l.pos.xyz - c; + let t0 = dot(to_l, d); + // the ray's point nearest to the lamp: taken in this cell only + let tc = clamp(t0, start, end); + if (tc < t || tc > t_out) { + continue; + } + let range = l.extra.w; + let h = length(to_l - d * t0); + if (h >= range) { + continue; + } + // A beam (a headlamp, a spot) is lit in the weather's fog only: its cone is a sliver of + // sixteen jittered steps at half size, which the fog's density hides and the clear + // air's haze shows as shimmer and soap. The lamps' halo alone has the ground haze. + let beam_lamp = l.extra.z != 0.0 || l.dir.w > -1.5; + let fog_sigma = enh.fog.x * droplets; + if (beam_lamp && enh.fog.x < 2e-4) { + continue; + } + let s0 = select(sigma0, fog_sigma, beam_lamp); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + // (inside its core a lamp is as bright as at the core's edge) + let hh = max(h, select(core * 0.7, 0.4, l.extra.z != 0.0)); + let w = sqrt(range * range - h * h); + let ta = max(start, t0 - w); + let tb = min(end, t0 + w); + if (tb <= ta) { + continue; + } + var acc = 0.0; + var half = 0.0; + if (l.extra.z != 0.0 || l.dir.w > -1.5) { + // a beam (a headlamp, a spot): lit only where its cone or cut-off lets + // it - a sliver of the angles the lamp is seen under, which the five + // nodes missed. Sixteen even steps over that angle instead (dphi = + // h dt / r^2: the inverse square is in the step). (Sixteen even steps + // along the way put the few next to the lamp, where nearly all of its + // light is, a metre or more apart: the pixels' staggered steps came + // out as a coarse checker in the fog round every headlamp.) + let pa = atan((ta - t0) / hh); + let dphi = (atan((tb - t0) / hh) - pa) / 16.0; + let tile_k = beam_tile(li, l); + for (var q = 0u; q < 16u; q = q + 1u) { + let tq = t0 + hh * tan(pa + (f32(q) + jitter) * dphi); + let to = l.pos.xyz - (c + d * tq); + let ld = to * inverseSqrt(max(dot(to, to), 1e-6)); + var beam = 0.0; + if (l.extra.z != 0.0) { + beam = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0); + } else { + beam = smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } + // (the map is looked at only where the beam shines at all, and only for + // the few lamps that have a tile: no shadows, no tile, no tap) + var reach = 1.0; + if (beam > 0.002 && tile_k < 44u) { + reach = beam_reaches(tile_k, c + d * tq); + } + acc = acc + beam * reach * fog_phase(dot(ld, d)) * dphi; + } + half = 1.0; + } else { + let pa = atan((ta - t0) / hh); + let pb = atan((tb - t0) / hh); + half = 0.5 * (pb - pa); + let mid = 0.5 * (pa + pb); + let tile_p = beam_tile(li, l); + for (var q = 0u; q < 5u; q = q + 1u) { + let phi = mid + half * gx[q]; + let tq = t0 + hh * tan(phi); + let ld = normalize(l.pos.xyz - (c + d * tq)); + var beam = 1.0; + if (l.dir.z < -0.5) { + // (a lamp in a housing: see `lamp_light`) + beam = 0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z); + } + // (a lamp with a shadow map: what stands between it and the air + // keeps its light out of that air, as the headlamps' beams) + var reach = 1.0; + if (beam > 0.002 && tile_p < 44u) { + reach = beam_reaches(tile_p, c + d * tq); + } + acc = acc + gw[q] * beam * reach * fog_phase(-sin(phi)); + } + } + // a lamp's irradiance is core^2 / r^2 of its colour's (a headlamp's 1 / r^2) + let strength = select(core * core, 1.0, l.extra.z != 0.0); + let xc = c + d * tc; + let sigma = s0 * exp(-enh.fog.y * max(xc.z - enh.fog.z, 0.0)); + let dl = distance(xc, l.pos.xyz); + let atten = exp(-layer_depth(s0, enh.fog.y, c.z - enh.fog.z, xc.z - enh.fog.z, tc - start) - sigma * dl); + sum = sum + l.color.rgb * (l.color.w * strength * acc * half / hh * sigma * atten); + } + } + t = t_out; + if (tx < ty) { + tx = tx + inv_x; + ix = ix + sx; + } else { + ty = ty + inv_y; + iy = iy + sy; + } + } + return sum * enh.lights.y; +} + +// Enhanced: the light a raindrop or a snowflake sends towards the eye - what it scatters of +// the sky's light, the sun's and the lamps' round it, the drop's strongly forward (a +// streak flashes against a lamp seen through the rain, and is next to invisible in the +// dark between the lamps), the flake's nearly every way. (Drawn at the display's level +// whatever the light, the flakes of a snowfall at night shone white in the dark, far from +// any lamp.) +fn precip_light(x: vec3, to_eye: vec3, snow: bool) -> vec3 { + // the sky's and the ground's light round it, and the sun's on a small sphere + var e = enh.fog_color.rgb * (PI / 0.9) + enh.sun.rgb * 0.25; + let cell = camera.light_grid.z; + let side = u32(camera.light_grid.w); + if (cell > 0.0 && side > 0u) { + let f = (x.xy - camera.light_grid.xy) / cell; + let gx = i32(floor(f.x)); + let gy = i32(floor(f.y)); + if (gx >= 0 && gy >= 0 && gx < i32(side) && gy < i32(side)) { + let base = (u32(gy) * side + u32(gx)) * CELL_CAP; + for (var j = 0u; j < CELL_CAP; j = j + 1u) { + let li = grid[base + j]; + if (li == 0xffffffffu) { + break; + } + let l = lights[li]; + let dl = l.pos.xyz - x; + let dist2 = dot(dl, dl); + let range = l.extra.w; + if (dist2 >= range * range) { + continue; + } + let ld = dl * inverseSqrt(max(dist2, 1e-6)); + var core = l.extra.y; + if (core <= 0.0) { + core = range * 0.125; + } + let q = dist2 / (range * range); + let window = (1.0 - q * q) * (1.0 - q * q); + var k = core * core / sqrt(dist2 * dist2 + core * core * core * core) * window; + if (l.extra.z != 0.0) { + k = headlamp(-ld, l.dir.xyz, l.extra.z > 0.0) / max(dist2, 0.3) * window; + } else if (l.dir.w > -1.5) { + k = k * smoothstep(l.dir.w, l.extra.x, dot(-ld, l.dir.xyz)); + } else if (l.dir.z < -0.5) { + k = k * (0.05 + 0.95 * smoothstep(-0.1, 0.3, ld.z)); + } + // (the scattering towards the eye relative to an even one: a drop's light + // goes on forwards, a flake's every way. The angle is the one between the + // light's way from the lamp, -ld, and on to the eye: taken against -to_eye + // it put the forward peak behind the drop, and the drops in a bus's own + // beams, seen from behind the lamps, shone a hundred times too bright as + // white streaks down the road ahead) + let c = dot(-ld, to_eye); + let lobe = select(fog_phase(c), 0.7 * hg_phase(c, 0.3) + 0.3 / (4.0 * PI), snow) * 4.0 * PI; + e = e + l.color.rgb * l.color.w * enh.lights.y * k * lobe; + } + } + } + return e / PI; +} + + +// Enhanced graphics: the volumetric fog (the settings' `volumetric_fog`). The main pass lays +// an analytic air over every surface (`air` in enhanced_common.wgsl): a fog as even as a +// sheet, lit as if the sun reached all of it. Here the air between the camera and what the +// depth prepass holds is marched through instead, at half size: the weather's fog thicker +// and thinner in banks that drift with the wind, the sun's light only where the shadow maps +// and the clouds' shadow field let it in - shafts through the crowns and between the houses, +// beams under a broken sky - scattered strongly forward round the sun, as fog droplets do, +// and the sky's light from all round (`enh.fog_color`, from the sky's harmonics). Each frame +// starts its steps elsewhere and is blended into the frames before, followed to where they +// lie now (a jittered march and its history: no banding, little noise). +// +// Over the full picture the air the main pass laid on is then exchanged for the marched one, +// along the stretch that was marched: what the picture holds behind that air (its light less +// the analytic air's, over what that let through) times what the marched air lets through, +// plus the light the marched air scatters. Nothing is fogged twice, a pane or a blended layer +// in front keeps the fog the main pass gave it, and past the march's reach (and with the +// option off) the analytic fog stands as it always did. The sun's shafts that fog_lamps.wgsl +// cut into the analytic air (`sun_shafts`) are this march's then; the lamps' light in the air +// stays there (`lamp_airlight`, added over this). +// +// The module is fog_lamps.wgsl's (its camera, shadow look-ups and enhanced_common.wgsl) with +// this added; its own bindings are group 2. + +struct VolFogParams { + // clip space (reversed Z) back to the render-origin relative world + inv_view_proj: mat4x4, + // the last frame's view and projection, taken to this frame's render origin + prev_view_proj: mat4x4, + // xy the picture's size in pixels, zw the half-size result's + size: vec4, + // x the steps of a ray, y where in its step this frame's samples lie (0..1), z 1 when the + // last frame's result can be followed, w the exposure now over the last frame's + march: vec4, + // xyz the last frame's camera (this frame's render origin), w which pixel of each 2 x 2 + // block is marched this frame (0..3) + prev_cam: vec4, + // xyz the small noise's offset (m: the world origin and the drift, within its period) + detail: vec4, +}; +@group(2) @binding(0) var vf: VolFogParams; +@group(2) @binding(1) var vf_depth: texture_depth_2d; +// the half-size result: rgb the light the marched air scatters towards the camera +// (pre-exposed), a what it lets through; the march reads the last frame's, the composite +// this frame's +@group(2) @binding(2) var vf_air: texture_2d; +// the distance it was marched to (negative: the sky's) +@group(2) @binding(3) var vf_dist: texture_2d; +// the fog's density noise (vol_fog.rs `density_noise`), tiling +@group(2) @binding(4) var vf_noise: texture_3d; +@group(2) @binding(5) var vf_repeat: sampler; + +// The span of the noise texture in the world (m): the banks across and up, the small eddies +// across and up. The offsets the Rust side passes are taken within these periods. +const VF_BANKS: vec3 = vec3(260.0, 260.0, 70.0); +const VF_EDDIES: vec3 = vec3(52.0, 52.0, 26.0); + +struct VfVsOut { + @builtin(position) clip: vec4, +}; + +@vertex +fn vs_vol_fog(@builtin(vertex_index) i: u32) -> VfVsOut { + let x = f32(i32(i & 1u) * 4 - 1); + let y = f32(i32(i >> 1u) * 4 - 1); + var out: VfVsOut; + out.clip = vec4(x, y, 0.0, 1.0); + return out; +} + +// The direction through a full-size pixel position and the distance to what the prepass +// holds there (-1: the sky). +fn vf_pixel_ray(at: vec2) -> vec4 { + let dims = vec2(textureDimensions(vf_depth)); + let px = clamp(vec2(at), vec2(0), dims - vec2(1)); + let z = textureLoad(vf_depth, px, 0); + let ndc = vec2(at.x / vf.size.x * 2.0 - 1.0, 1.0 - at.y / vf.size.y * 2.0); + let c = camera.cam_pos.xyz; + let mid = vf.inv_view_proj * vec4(ndc, 0.5, 1.0); + let dir = normalize(mid.xyz / mid.w - c); + var len = -1.0; + if (z > 0.0) { + let h = vf.inv_view_proj * vec4(ndc, z, 1.0); + len = distance(h.xyz / h.w, c); + } + return vec4(dir, len); +} + +// A point in the player's vehicle box frame (the scene shader's `fn_box_local`). +fn vf_box_local(world: vec3) -> vec3 { + let d = world - camera.inside_a.xyz; + let sh = camera.inside_a.w; + let ch = camera.inside_b.x; + return vec3(d.x * ch - d.y * sh - camera.inside_c.x, d.x * sh + d.y * ch - camera.inside_c.y, d.z - camera.inside_c.z); +} + +// Where the ray's first `len` metres run through the player's vehicle (from, to; equal: not +// at all): there is no fog in the cab, and the main pass leaves that stretch out of its air +// (the scene shader's `fog_distance`, the same box and the same test). +fn vf_cab(c: vec3, d: vec3, len: f32) -> vec2 { + if (camera.inside_c.w < 0.5 || len <= 0.0) { + return vec2(0.0); + } + let o = vf_box_local(c); + let e = vf_box_local(c + d * len) - o; + let h = camera.inside_b.yzw; + var t0 = 0.0; + var t1 = 1.0; + for (var k = 0; k < 3; k = k + 1) { + if (abs(e[k]) < 1e-6) { + if (abs(o[k]) > h[k]) { + return vec2(0.0); + } + } else { + let a = (-h[k] - o[k]) / e[k]; + let b = (h[k] - o[k]) / e[k]; + t0 = max(t0, min(a, b)); + t1 = min(t1, max(a, b)); + } + } + if (t1 <= t0) { + return vec2(0.0); + } + return vec2(t0, t1) * len; +} + +// How much thicker or thinner than the weather's mean the fog is at x: banks a couple of +// hundred metres across, flatter than wide, with smaller eddies in them, both drifting with +// the wind (`enh.vol_fog2`, `vf.detail`). Its mean is 1: past the march the analytic fog +// goes on with the same amount. +fn vf_density(x: vec3) -> f32 { + let amp = enh.vol_fog.y; + if (amp <= 0.0) { + return 1.0; + } + let banks = textureSampleLevel(vf_noise, vf_repeat, (x + enh.vol_fog2.xyz) / VF_BANKS, 0.0).r; + let eddies = textureSampleLevel(vf_noise, vf_repeat, (x + vf.detail.xyz) / VF_EDDIES + vec3(0.37, 0.11, 0.73), 0.0).r; + let n = banks * 0.72 + eddies * 0.28; + return max(1.0 + amp * (n - 0.5) * 3.2, 0.0); +} + +// The fog droplets' phase function: most of their light goes on within a few tens of degrees +// of the way it came (a bright glow round the sun in the fog, a dim fog with the sun behind), +// a little is sent back (two Henyey-Greenstein lobes). +fn vf_phase(c: f32) -> f32 { + return mix(hg_phase(c, 0.7), hg_phase(c, -0.2), 0.15); +} + +// The air along d from c over [0, reach] (the cab's stretch `cab` left out): rgb the light +// it scatters towards the camera (radiance), a what it lets through. `clear` 0 for the sky, +// whose table holds the clear air already (its shadowed part is taken out all the same, as +// `sun_shafts` did). +fn vf_march(c: vec3, d: vec3, reach: f32, clear: f32, cab: vec2, jitter: f32) -> vec4 { + // the light that casts the shadow maps: the sun, or by night the moon (enh.moon_light.w) + let moon = enh.moon_light.w > 0.5; + let l_dir = select(camera.sun_dir.xyz, enh.moon.xyz, moon); + let e = select(enh.sun.rgb, enh.moon_light.rgb, moon); + let lit = max(e.r, max(e.g, e.b)) > 1e-7 && l_dir.z > -0.02; + let shadows = lit && camera.shadow.x > 0.5; + let gaps = lit && !moon && enh.cloud_f1.w > 0.5 && l_dir.z >= 0.06; + let cos_t = dot(d, l_dir); + let p_fog = vf_phase(cos_t) * 0.9; + let p_air = hg_phase(cos_t, 0.7); + // (the clear air takes the sky's colour at the horizon in this direction, as `air_of`) + let horizon = sky_table(normalize(vec3(d.x, d.y, max(d.z, 0.0) * 0.3 + 0.03))); + let ambient = enh.fog_color.rgb; + let steps = max(u32(vf.march.x), 1u); + var through = 1.0; + var light = vec3(0.0); + var t0 = 0.0; + for (var i = 0u; i < steps; i = i + 1u) { + // steps growing with the distance (squared): the near air, where the shafts and the + // banks are seen largest, sampled densest + let u = f32(i + 1u) / f32(steps); + let t1 = reach * u * u; + let t = mix(t0, t1, jitter); + let w = (t1 - t0) - max(min(t1, cab.y) - max(t0, cab.x), 0.0); + t0 = t1; + if (w <= 0.0) { + continue; + } + let x = c + d * t; + let h = max(x.z - enh.fog.z, 0.0); + let s_fog = enh.fog.x * exp(-enh.fog.y * h) * vf_density(x); + let s_air = enh.fog.w * exp(-h / 1500.0); + let s_ext = s_fog + s_air * clear; + var vis = 1.0; + if (shadows) { + vis = sun_reaches(x); + } + if (gaps) { + vis = vis * cloud_shadow_ratio(x); + } + // what a metre of this air sends towards the camera: the fog the sky's light and + // the sun where it reaches; the clear air its horizon's colour, less the sun it + // holds there where the sun does not reach + let src = s_fog * (ambient + e * (p_fog * vis)) + s_air * (horizon * clear - e * (p_air * (1.0 - vis))); + // (the step's light integrated over its own extinction: energy kept however long the + // step - Hillaire, "Physically based and unified volumetric rendering", 2015) + let step_t = exp(-s_ext * w); + let along = select(w, (1.0 - step_t) / max(s_ext, 1e-12), s_ext * w > 1e-5); + light = light + src * (through * along); + through = through * step_t; + if (through < 0.002) { + break; + } + } + return vec4(light, through); +} + +// The analytic air the main pass laid over [0, reach] of this ray (`air` for a surface, the +// sky's own `air_of` without the clear air for the sky), and the stretch's length outside +// the cab. +fn vf_analytic(c: vec3, d: vec3, reach: f32, sky: bool, cab: vec2) -> vec4 { + let h0 = c.z - enh.fog.z; + if (sky) { + return air_of(d, reach, h0, h0 + reach * max(d.z, 0.0), 0.0); + } + let p = c + d * reach; + let outside = max(reach - max(min(reach, cab.y) - cab.x, 0.0), 0.0); + return air(d, outside, h0, p.z - enh.fog.z); +} + +struct VfMarchOut { + @location(0) air: vec4, + @location(1) dist: f32, +}; + +// at half size: one ray per 2 x 2 block, through another of its pixels each frame +@fragment +fn fs_vol_march(in: VfVsOut) -> VfMarchOut { + let k = u32(vf.prev_cam.w); + let at = floor(in.clip.xy) * 2.0 + vec2(f32(k & 1u), f32(k >> 1u)) + vec2(0.5); + let r = vf_pixel_ray(at); + let c = camera.cam_pos.xyz; + let sky = r.w < 0.0; + let full = enh.vol_fog.z; + let reach = select(min(r.w, full), full, sky); + let cab = select(vf_cab(c, r.xyz, reach), vec2(0.0), sky); + let ign = fract(52.9829189 * fract(dot(in.clip.xy, vec2(0.06711056, 0.00583715)))); + let jitter = fract(ign + vf.march.y); + var cur = vf_march(c, r.xyz, reach, select(1.0, 0.0, sky), cab, jitter); + cur = vec4(min(cur.rgb * enh.exposure.x, vec3(60000.0)), cur.a); + var out: VfMarchOut; + out.dist = select(reach, -reach, sky); + out.air = cur; + if (vf.march.z < 0.5) { + return out; + } + // the last frames' result where this point lay then: the four half-size texels round it, + // those that were marched to the same distance (a pole that moved, a bus driving past: + // what was behind is not this) + let p = c + r.xyz * reach; + let prev = vf.prev_view_proj * vec4(p, 1.0); + if (prev.w <= 1e-4) { + return out; + } + let uv = vec2(prev.x / prev.w * 0.5 + 0.5, 0.5 - prev.y / prev.w * 0.5); + if (any(uv < vec2(0.0)) || any(uv > vec2(1.0))) { + return out; + } + let expect = select(min(distance(p, vf.prev_cam.xyz), full), -full, sky); + let tol = 0.06 * abs(expect) + 0.6; + let hp = uv * vf.size.zw - vec2(0.5); + let base = vec2(floor(hp)); + let f = hp - floor(hp); + let hd = vec2(vf.size.zw) - vec2(1); + var sum = vec4(0.0); + var wsum = 0.0; + for (var j = 0; j < 4; j = j + 1) { + let o = vec2(j & 1, j >> 1); + let q = clamp(base + o, vec2(0), hd); + let dd = abs(textureLoad(vf_dist, q, 0).r - expect); + if (dd > tol) { + continue; + } + let w = select(1.0 - f.x, f.x, o.x == 1) * select(1.0 - f.y, f.y, o.y == 1); + sum = sum + textureLoad(vf_air, q, 0) * w; + wsum = wsum + w; + } + if (wsum < 0.25) { + return out; + } + let hist = sum / wsum; + // (the exposure moved since: the history is taken to this frame's) + let held = vec4(hist.rgb * vf.march.w, hist.a); + out.air = mix(held, cur, 0.12); + return out; +} + +// The marched air at a full-size pixel: the four nearest half-size results, each as far as +// it was marched to a distance like this pixel's (the fog in front of a near pole is not the +// fog in front of the houses behind it, nor the sky's). +fn vf_gather(at: vec2, dist: f32) -> vec4 { + let hp = at * 0.5 - vec2(0.5); + let base = vec2(floor(hp)); + let f = hp - floor(hp); + let hd = vec2(vf.size.zw) - vec2(1); + var sum = vec4(0.0); + var wsum = 0.0; + var best = vec4(0.0, 0.0, 0.0, 1.0); + var best_d = 1e9; + for (var j = 0; j < 4; j = j + 1) { + let o = vec2(j & 1, j >> 1); + let q = clamp(base + o, vec2(0), hd); + let s = textureLoad(vf_air, q, 0); + let dd = abs(textureLoad(vf_dist, q, 0).r - dist); + let bil = select(1.0 - f.x, f.x, o.x == 1) * select(1.0 - f.y, f.y, o.y == 1); + let tol = dd / (0.05 * abs(dist) + 0.5); + let w = (bil + 1e-3) * exp(-tol * tol); + sum = sum + s * w; + wsum = wsum + w; + if (dd < best_d) { + best_d = dd; + best = s; + } + } + if (wsum < 1e-3) { + return best; + } + return sum / wsum; +} + +// at full size, over the picture (blended: the source plus the picture times the source's +// alpha): the analytic air exchanged for the marched one +@fragment +fn fs_vol_composite(in: VfVsOut) -> @location(0) vec4 { + let r = vf_pixel_ray(in.clip.xy); + let c = camera.cam_pos.xyz; + let sky = r.w < 0.0; + let full = enh.vol_fog.z; + let reach = select(min(r.w, full), full, sky); + let cab = select(vf_cab(c, r.xyz, reach), vec2(0.0), sky); + let a = vf_analytic(c, r.xyz, reach, sky, cab); + let v = vf_gather(in.clip.xy, select(reach, -reach, sky)); + // (where the analytic air let next to nothing through, what the picture holds there is + // that air itself: the ratio is kept within reason) + let ratio = clamp(v.a / max(a.a, 1e-4), 0.0, 4.0); + return vec4(v.rgb - a.rgb * (enh.exposure.x * ratio), ratio); +} diff --git a/crates/mx/tests/openomsi/xr_ui.wgsl b/crates/mx/tests/openomsi/xr_ui.wgsl new file mode 100644 index 0000000..0e13aac --- /dev/null +++ b/crates/mx/tests/openomsi/xr_ui.wgsl @@ -0,0 +1,39 @@ +// A textured UI quad projected into each headset eye from one place in space. +struct Quad { + top_left: vec4, + top_right: vec4, + bottom_right: vec4, + bottom_left: vec4, + opts: vec4, +}; + +@group(0) @binding(0) var q: Quad; +@group(0) @binding(1) var t_img: texture_2d; +@group(0) @binding(2) var s_img: sampler; + +struct VsOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +}; + +@vertex +fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut { + let indices = array(0u, 1u, 2u, 0u, 2u, 3u); + let corners = array, 4>(q.top_left, q.top_right, q.bottom_right, q.bottom_left); + let coords = array, 4>(vec2(0.0, 0.0), vec2(1.0, 0.0), + vec2(1.0, 1.0), vec2(0.0, 1.0)); + let index = indices[vid]; + var out: VsOut; + out.clip = corners[index]; + out.uv = coords[index]; + return out; +} + +@fragment +fn fs_main(in: VsOut) -> @location(0) vec4 { + let sample = textureSample(t_img, s_img, in.uv); + if (q.opts.x > 0.5) { + return sample; + } + return vec4(sample.rgb * sample.a, sample.a); +} diff --git a/crates/mx/tests/openomsi_shaders.rs b/crates/mx/tests/openomsi_shaders.rs index 185a791..6c111f0 100644 --- a/crates/mx/tests/openomsi_shaders.rs +++ b/crates/mx/tests/openomsi_shaders.rs @@ -1,18 +1,21 @@ //! openOMSI's own WGSL modules, as its renderer assembles them, compile through mX unchanged. //! -//! Needs the modules on disk: `python3 tools/openomsi_shaders.py `, -//! then `MX_OPENOMSI_SHADERS= cargo test -p mx --test openomsi_shaders`. Without the -//! variable the test says so and passes. +//! The modules are in `tests/openomsi` (see its README); `MX_OPENOMSI_SHADERS=` takes +//! another set (`python3 tools/openomsi_shaders.py `). use mx::*; #[test] fn every_openomsi_module_compiles_for_the_gpu() { - let Ok(dir) = std::env::var("MX_OPENOMSI_SHADERS") else { - eprintln!("skipped: set MX_OPENOMSI_SHADERS (see tools/openomsi_shaders.py)"); - return; - }; + let dir = std::env::var("MX_OPENOMSI_SHADERS").unwrap_or_else(|_| concat!(env!("CARGO_MANIFEST_DIR"), "/tests/openomsi").to_string()); let adapter = Instance::new().default_adapter().expect("a GPU mX can use"); + eprintln!("on {:?}", adapter.info()); + if adapter.is_bound_tier() { + // (these are the native renderer's modules - storage buffers, depth read by + // textureLoad; on OpenGL openOMSI writes variants of its own, `gl_backend()`) + eprintln!("skipped: the bound tier takes openOMSI's OpenGL variants, not these"); + return; + } let (device, _queue) = adapter.request_device(&Default::default()).unwrap(); let mut files: Vec<_> = std::fs::read_dir(&dir) .unwrap() diff --git a/docs/STATUS.md b/docs/STATUS.md index 5a92ac4..d127600 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -27,9 +27,10 @@ unless the row says otherwise. The no-op backend (`mx-noop`): written and compiled; openOMSI's dedicated server and its renderer tests open it. -OpenGL / OpenGL ES (`mx-gl`, the bound tier): written and compiled for macOS, Linux and -Windows, not yet run on a GPU; its shader lowering and GLSL output are unit-tested, the GLSL -compiled by `glslangValidator`. See [BOUND_TIER.md](BOUND_TIER.md#status-2026-11-17). +OpenGL / OpenGL ES (`mx-gl`, the bound tier): the 29 conformance tests pass on ANGLE over +Metal (OpenGL ES 3.0, the level ANGLE gives older chips; 2026-11-23), compute and the buffer +heap skipped there for want of ES 3.1. Not yet run on a desktop GL driver or on ANGLE over +Direct3D 11. See [BOUND_TIER.md](BOUND_TIER.md#status-2026-11-17). ## Test suites @@ -37,7 +38,7 @@ compiled by `glslangValidator`. See [BOUND_TIER.md](BOUND_TIER.md#status-2026-11 |-------|--------| | Conformance tests, 28 (`crates/mx/tests/conformance.rs`) | pass on Metal (2026-11-17), with and without the residency set and with direct heap textures, under Metal's API and shader validation; pass on MoltenVK (27; the dynamic-offset test is new since) | | Pixel parity with wgpu, 7 scenes and 21 of openOMSI's full-screen passes | identical bytes on Metal and on MoltenVK | -| openOMSI's 27 WGSL modules | compile for every backend; the HLSL has not been through DXC yet | +| openOMSI's 23 WGSL modules of its mX renderer (`crates/mx/tests/openomsi`, openOMSI 940ab2f97) | compile through DXC (shader model 6.8) on Direct3D 12 (WARP, in CI), on lavapipe and MoltenVK under the Khronos layer with no findings, and on Metal (2026-11-23) | | `wgpu-mx` through wgpu's API (`crates/wgpu-mx/tests`) | pass on Metal and MoltenVK | | Khronos validation layer with synchronization validation (MoltenVK) | no synchronization findings; two known reports, below (2026-11-17, all 27 tests) | | openOMSI's renderer tests on mX's native API (`omsi-render`, 2026-11-17) | 194 on the no-op device and 86 of 90 GPU tests on Metal pass; the 4 others fail the same way on wgpu (see openOMSI's `docs/MX_PORT.md`) |