From 7d6583dc4d088d794398391aad4c0ced94009883 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 03:45:24 +0100 Subject: [PATCH] Shader packs, clean room 22: the sky (gbuffers_skybasic) The pack's gbuffers_skybasic (or gbuffers_basic) draws vanilla's sky geometry, as Horizon's own sky builds it: the disc at y 16, the sunset fan while the sun is low, the stars and the void disc, each with its render stage. One static vertex buffer; the frame's colours and rotations sit in a small uniform the vertex inputs read. The sky draws after the world copy and before terrain, at the far plane: only where nothing else drew, without writing depth. It blends with the translucent default unless blend. says otherwise. Horizon's world pass then skips its own sky disc, stars and void. The sun and moon stay Horizon's for now (gbuffers_skytextured is next): the pack's sky covers them. load_post takes the game's inputs per geometry (GameInputs); GbuffersInputs gains statements run after the pack's main. Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1, 2.1, 2.3, 5.4; no other loader's code read. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/game/shader_packs.rs | 4 +- crates/horizon-client/src/gfx.rs | 46 +++- crates/horizon-client/src/gfx/pack_atlas.rs | 1 + crates/horizon-client/src/gfx/pack_post.rs | 157 +++++++++--- crates/horizon-client/src/gfx/pack_sky.rs | 229 ++++++++++++++++++ crates/horizon-shaders/src/lib.rs | 3 +- crates/horizon-shaders/src/post.rs | 88 +++++-- crates/horizon-shaders/src/translate/mod.rs | 6 +- .../tests/packs/terrain-test/README.md | 4 +- .../shaders/gbuffers_skybasic.fsh | 15 ++ .../shaders/gbuffers_skybasic.vsh | 8 + crates/horizon-shaders/tests/real_packs.rs | 16 +- 12 files changed, 502 insertions(+), 75 deletions(-) create mode 100644 crates/horizon-client/src/gfx/pack_sky.rs create mode 100644 crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_skybasic.fsh create mode 100644 crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_skybasic.vsh diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs index d819eddef..360262640 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -42,8 +42,8 @@ impl Game<'_> { ); } let folder = dimension_folder(&pack, dimension); - let terrain = renderer.pack_terrain_inputs(); - let post = load_post(&pack, &folder, &properties, ¯os, terrain.as_ref()); + let inputs = renderer.pack_inputs(); + let post = load_post(&pack, &folder, &properties, ¯os, &inputs); if let Some((programs, notes)) = renderer.set_shader_pack(dimension, Some(post)) { for note in notes { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 354dc8d07..7444b136a 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -71,6 +71,7 @@ mod occlusion; mod pack_atlas; mod pack_draw; mod pack_post; +mod pack_sky; mod pack_timing; pub mod pack_uniforms; mod page_runs; @@ -88,6 +89,19 @@ const COMPLETE_COLUMN: u32 = (1 << (crate::chunk::HEIGHT / 16)) - 1; /// its fixed-point UVs (`terrain.wgsl`'s `terrain_uv`). /// The world pass again after occlusion culling's test: it loads both /// targets (phase 2 draws over phase 1, reading the test's results). +/// LevelRenderer: no sky inside lava or powder snow (sky fog ends within 2 blocks). +fn sky_open(frame: &Frame) -> bool { + match frame.fog { + Some(f) => f.sky_end > 2.0, + None => !frame.underwater, + } +} + +/// The Overworld-style sky (disc, sunset, stars, void) draws this frame. +fn sky_visible(frame: &Frame) -> bool { + !frame.title && frame.skybox && sky_open(frame) +} + fn world_pass_after_culling<'e>( encoder: &'e mut wgpu::CommandEncoder, view: &wgpu::TextureView, @@ -2777,6 +2791,7 @@ impl Renderer { terrain: self.pack_atlas.as_ref().map(|_| pack_post::Geometry { buffers: if flat { &buffers[..1] } else { &buffers }, table: self.flat.as_ref().filter(|_| flat).map(|f| &f.draw_layout), + depth_write: true, }), }; pack_post::PackPost::new( @@ -2794,9 +2809,16 @@ impl Renderer { self.pack_post = Some((dimension, post)); report } - /// What a shader pack's terrain program reads from Horizon's terrain vertices, in the - /// pack's block atlas (made here when missing); `None` when the atlas does not fit. - pub fn pack_terrain_inputs(&mut self) -> Option { + /// What a shader pack's gbuffers programs read from Horizon's geometry: the sky's, and + /// terrain's in the pack's block atlas (made here when missing; none when it does not fit). + pub fn pack_inputs(&mut self) -> horizon_shaders::GameInputs { + horizon_shaders::GameInputs { + terrain: self.pack_terrain_inputs(), + sky: Some(pack_sky::inputs()), + } + } + + fn pack_terrain_inputs(&mut self) -> Option { if self.pack_atlas.is_none() { let mut encoder = self.device.create_command_encoder(&Default::default()); let layers = self @@ -3711,6 +3733,12 @@ impl Renderer { let pack_post = !frame.title && self.pack_post.as_ref().is_some_and(|p| p.1.is_some()); // The pack's program reads the vertices this frame's draws bind. let pack_draws_terrain = pack_terrain && flat_frame == self.pack_terrain_flat; + let pack_draws_sky = pack_post + && self + .pack_post + .as_ref() + .and_then(|p| p.1.as_ref()) + .is_some_and(|p| p.has_sky()); let pack_draws_water = pack_draws_terrain && self .pack_post @@ -3770,13 +3798,9 @@ impl Renderer { ..Default::default() }); pass.set_bind_group(0, &self.group, &[]); - // LevelRenderer: no sky inside lava or powder snow (sky fog ends within 2 blocks). - let sky_visible = match frame.fog { - Some(f) => f.sky_end > 2.0, - None => !frame.underwater, - }; + let sky_visible = sky_open(frame); if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) { - if !frame.title && frame.skybox { + if !frame.title && frame.skybox && !pack_draws_sky { pass.set_pipeline(&self.sky); pass.draw(0..3, 0..1); } @@ -3796,11 +3820,11 @@ impl Renderer { } pass.set_bind_group(0, &self.group, &[]); } - if !frame.title && frame.stars.is_some() { + if !frame.title && frame.stars.is_some() && !pack_draws_sky { self.stars.draw(&mut pass); pass.set_bind_group(0, &self.group, &[]); } - if !frame.title && frame.dark_disc { + if !frame.title && frame.dark_disc && !pack_draws_sky { pass.set_pipeline(&self.dark_disc); pass.draw(0..3, 0..1); } diff --git a/crates/horizon-client/src/gfx/pack_atlas.rs b/crates/horizon-client/src/gfx/pack_atlas.rs index 011dff379..1a14a8da9 100644 --- a/crates/horizon-client/src/gfx/pack_atlas.rs +++ b/crates/horizon-client/src/gfx/pack_atlas.rs @@ -173,6 +173,7 @@ impl PackAtlas { .iter() .map(|&(n, v)| (n.to_owned(), v.to_owned())) .collect(), + after: String::new(), } } } diff --git a/crates/horizon-client/src/gfx/pack_post.rs b/crates/horizon-client/src/gfx/pack_post.rs index 08a2dedcc..2334b84c9 100644 --- a/crates/horizon-client/src/gfx/pack_post.rs +++ b/crates/horizon-client/src/gfx/pack_post.rs @@ -16,6 +16,7 @@ use std::collections::HashMap; use horizon_shaders::{Format, Group, Kind, Post, Val}; use super::pack_draw::DrawUniforms; +use super::pack_sky::PackSky; use super::pack_uniforms::{self, FrameUniforms, PackInputs}; const BUFFERS: usize = horizon_shaders::BUFFERS; @@ -120,6 +121,14 @@ fn share_samplers(module: &mut naga::Module, slot: &HashMap) { } } +/// The game's geometry a gbuffers pass draws. +#[derive(Clone, Copy, PartialEq)] +enum Gbuffers { + Sky, + Terrain, + Water, +} + struct Pass { name: String, group: Group, @@ -181,6 +190,8 @@ pub struct PackPost { terrain: Option, /// What draws translucent terrain (`gbuffers_water` or its fallback), after `deferred`. water: Option, + /// What draws the sky (`gbuffers_skybasic` or its fallback), before terrain, and its vertices. + sky: Option<(Pass, PackSky)>, /// A program after translucent terrain reads `depthtex1`: it is copied before water. depth1: bool, /// Buffers with mipmaps (filterable ones a program asks them for). @@ -481,6 +492,8 @@ fn attach( pub(super) struct Geometry<'a> { pub buffers: &'a [Option>], pub table: Option<&'a wgpu::BindGroupLayout>, + /// Writes depth (the sky does not). + pub depth_write: bool, } /// The pass of program `p`: a quad, or `geometry` drawn by the game. `None` (with a note) when @@ -664,9 +677,9 @@ fn build_pass( buffers: geometry.map_or(&[], |g| g.buffers), }, primitive: Default::default(), - depth_stencil: geometry.map(|_| wgpu::DepthStencilState { + depth_stencil: geometry.map(|g| wgpu::DepthStencilState { format: wgpu::TextureFormat::Depth32Float, - depth_write_enabled: Some(true), + depth_write_enabled: Some(g.depth_write), depth_compare: Some(wgpu::CompareFunction::LessEqual), stencil: Default::default(), bias: Default::default(), @@ -783,6 +796,15 @@ impl PackPost { .water .zip(world.terrain.as_ref()) .and_then(|(p, g)| build(p, Some(g))); + let sky = post.sky.and_then(|p| { + let sky = PackSky::new(device); + let geometry = Geometry { + buffers: &PackSky::buffers(), + table: Some(&sky.layout), + depth_write: false, + }; + Some((build(p, Some(&geometry))?, sky)) + }); // Developers' aid: `HORIZON_SHADER_PACK_SKIP=composite,final` leaves programs out. let skip = std::env::var("HORIZON_SHADER_PACK_SKIP").unwrap_or_default(); let passes: Vec = post @@ -797,6 +819,9 @@ impl PackPost { if let Some(w) = &water { notes.push(format!("translucent terrain draws with {}", w.name)); } + if let Some((s, _)) = &sky { + notes.push(format!("the sky draws with {}", s.name)); + } let depth1 = water.is_some() && passes .iter() @@ -810,8 +835,10 @@ impl PackPost { let bit = 1u16 << b; let touched = |p: &&Pass| (p.reads | p.flip | p.written) & bit != 0; // Gbuffers passes cover part of their targets: a clear is needed if they touch it. - let first = terrain + let first = sky .iter() + .map(|s| &s.0) + .chain(&terrain) .chain(&water) .find(touched) .map(|_| true) @@ -826,6 +853,7 @@ impl PackPost { // Terrain tests against the world's depth (entities...), so the blit copies it then. let blit_depth = terrain.is_some() || water.is_some() + || sky.is_some() || passes.iter().any(|p| { p.samplers .iter() @@ -920,6 +948,7 @@ impl PackPost { passes, terrain, water, + sky, depth1, mipped, mips_valid: 0, @@ -1084,25 +1113,34 @@ impl PackPost { group.clone() } - /// Terrain (or, `translucent`, translucent terrain) with the pack's program into the - /// buffers it writes, in place, tested against the world's depth; `draw` issues the - /// game's draws. - fn draw_terrain( + /// The sky, terrain or translucent terrain with the pack's program into the buffers it + /// writes, in place, tested against the world's depth; `draw` issues the game's terrain + /// draws (`true`: translucent), the sky draws itself. + #[allow(clippy::too_many_arguments)] + fn draw_gbuffers( &mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, size: [u32; 2], - translucent: bool, + frame: &super::Frame, + which: Gbuffers, draw: &mut dyn FnMut(&mut wgpu::RenderPass<'_>, bool), ) { - let slot = if translucent { - &mut self.water - } else { - &mut self.terrain - }; - let Some(mut pass) = slot.take() else { - return; + let translucent = which == Gbuffers::Water; + let (mut pass, sky) = match which { + Gbuffers::Sky => match self.sky.take() { + Some((pass, sky)) => (pass, Some(sky)), + None => return, + }, + Gbuffers::Terrain => match self.terrain.take() { + Some(pass) => (pass, None), + None => return, + }, + Gbuffers::Water => match self.water.take() { + Some(pass) => (pass, None), + None => return, + }, }; if translucent && let Some(t) = &self.targets @@ -1148,24 +1186,58 @@ impl PackPost { }); rp.set_pipeline(&pass.pipeline); rp.set_bind_group(0, &group, &[]); - if pass.draw { - let stage = if translucent { - "TERRAIN_TRANSLUCENT" - } else { - "TERRAIN_SOLID" - }; - self.draws.bind(&mut rp, stage); + let draws = pass.draw.then_some(&self.draws); + match &sky { + Some(sky) => sky.draw(queue, &mut rp, frame, &|rp, stage| { + if let Some(d) = draws { + d.bind(rp, stage); + } + }), + None => { + if let Some(d) = draws { + let stage = if translucent { + "TERRAIN_TRANSLUCENT" + } else { + "TERRAIN_SOLID" + }; + d.bind(&mut rp, stage); + } + draw(&mut rp, translucent); + } } - draw(&mut rp, translucent); } self.mips_valid &= !pass.written; - if translucent { - self.water = Some(pass); - } else { - self.terrain = Some(pass); + match (which, sky) { + (Gbuffers::Sky, Some(sky)) => self.sky = Some((pass, sky)), + (Gbuffers::Water, _) => self.water = Some(pass), + _ => self.terrain = Some(pass), } } + /// The sky, when it shows, then terrain. + fn draw_opaque( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + size: [u32; 2], + frame: &super::Frame, + terrain: &mut dyn FnMut(&mut wgpu::RenderPass<'_>, bool), + ) { + if super::sky_visible(frame) { + self.draw_gbuffers(device, queue, encoder, size, frame, Gbuffers::Sky, terrain); + } + self.draw_gbuffers( + device, + queue, + encoder, + size, + frame, + Gbuffers::Terrain, + terrain, + ); + } + /// Regenerates the mip chain of buffer `b`'s side that programs read. fn mipmap(&self, encoder: &mut wgpu::CommandEncoder, b: usize) { let (Some(targets), Some((pipeline, _))) = (&self.targets, self.down.get(&self.formats[b])) @@ -1197,6 +1269,11 @@ impl PackPost { self.terrain.is_some() } + /// Whether the pack draws the sky itself. + pub fn has_sky(&self) -> bool { + self.sky.is_some() + } + /// Whether the pack draws translucent terrain itself. pub fn has_water(&self) -> bool { self.water.is_some() @@ -1435,16 +1512,24 @@ impl PackPost { let mut passes = std::mem::take(&mut self.passes); let mut seen = (false, false); let mut shown = false; - let mut terrain_drawn = self.terrain.is_none(); + let mut terrain_drawn = self.terrain.is_none() && self.sky.is_none(); let mut water_drawn = self.water.is_none(); for pass in &mut passes { if !terrain_drawn && pass.group != Group::Prepare { terrain_drawn = true; - self.draw_terrain(device, queue, encoder, size, false, terrain); + self.draw_opaque(device, queue, encoder, size, frame, terrain); } if !water_drawn && matches!(pass.group, Group::Composite | Group::Final) { water_drawn = true; - self.draw_terrain(device, queue, encoder, size, true, terrain); + self.draw_gbuffers( + device, + queue, + encoder, + size, + frame, + Gbuffers::Water, + terrain, + ); } if pass.group == Group::Deferred && !seen.0 { seen.0 = true; @@ -1496,10 +1581,18 @@ impl PackPost { } self.passes = passes; if !terrain_drawn { - self.draw_terrain(device, queue, encoder, size, false, terrain); + self.draw_opaque(device, queue, encoder, size, frame, terrain); } if !water_drawn { - self.draw_terrain(device, queue, encoder, size, true, terrain); + self.draw_gbuffers( + device, + queue, + encoder, + size, + frame, + Gbuffers::Water, + terrain, + ); } let targets = self.targets.as_ref().expect("resized"); let view = |m: u16, i: usize, alt: bool| { diff --git a/crates/horizon-client/src/gfx/pack_sky.rs b/crates/horizon-client/src/gfx/pack_sky.rs new file mode 100644 index 000000000..cd99d03b9 --- /dev/null +++ b/crates/horizon-client/src/gfx/pack_sky.rs @@ -0,0 +1,229 @@ +//! The vanilla sky's geometry for a shader pack's `gbuffers_skybasic` (spec 2.3): the sky disc, +//! the sunset fan, the stars and the void disc, as Horizon's own sky draws them (terrain.wgsl, +//! stars.rs), built once into a vertex buffer. The frame's colours and rotations sit in a small +//! uniform (set 1) that the vertex inputs read. + +use std::ops::Range; + +use wgpu::util::DeviceExt; + +/// A sky vertex: a position and what it belongs to (`SKY`...). +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct Vertex { + pos: [f32; 3], + kind: u32, +} + +const SKY: u32 = 0; +const SUNSET_APEX: u32 = 1; +/// Rim of the sunset fan: `pos.xy` is (sin, cos) of its angle. +const SUNSET_RIM: u32 = 2; +const STAR: u32 = 3; +const VOID: u32 = 4; + +/// The frame's sky (std140). +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct Uniform { + /// Camera-relative world from star space. + stars: [[f32; 4]; 4], + /// Sky colour, alpha 1. + color: [f32; 4], + /// Sunset colour and alpha. + sunrise: [f32; 4], + /// cos and sin of the sunset fan's turn, star brightness. + sun: [f32; 4], +} + +pub(super) const ATTRIBUTES: [wgpu::VertexAttribute; 2] = + wgpu::vertex_attr_array![0 => Float32x3, 1 => Uint32]; + +/// What `gbuffers_skybasic` reads from these vertices. +pub fn inputs() -> horizon_shaders::GbuffersInputs { + let declarations = + "layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in uint hz_v_kind;\n\ + layout(set = 1, binding = 0) uniform HzSky { mat4 hz_sky_stars; vec4 hz_sky_color; \ + vec4 hz_sky_sunrise; vec4 hz_sky_sun; };\n" + .to_owned(); + let body = format!( + " vec3 hz_p = hz_v_pos;\n \ + hz_Color = hz_sky_color;\n \ + if (hz_v_kind == {SUNSET_APEX}u || hz_v_kind == {SUNSET_RIM}u) {{\n \ + vec3 hz_l = vec3(0.0, 100.0, 0.0);\n \ + hz_Color = hz_sky_sunrise;\n \ + if (hz_v_kind == {SUNSET_RIM}u) {{\n \ + hz_l = vec3(hz_v_pos.xy * 120.0, -hz_v_pos.y * 40.0 * hz_sky_sunrise.a);\n \ + hz_Color.a = 0.0;\n \ + }}\n \ + vec3 hz_r = vec3(hz_l.x * hz_sky_sun.x - hz_l.y * hz_sky_sun.y, hz_l.x * hz_sky_sun.y + hz_l.y * hz_sky_sun.x, hz_l.z);\n \ + hz_p = vec3(hz_r.x, -hz_r.z, hz_r.y);\n \ + }} else if (hz_v_kind == {STAR}u) {{\n \ + hz_p = (hz_sky_stars * vec4(hz_v_pos, 1.0)).xyz;\n \ + hz_Color = vec4(hz_sky_sun.z);\n \ + }} else if (hz_v_kind == {VOID}u) {{\n \ + hz_Color = vec4(0.0, 0.0, 0.0, 1.0);\n \ + }}\n \ + hz_Vertex = vec4(hz_p, 1.0);\n \ + hz_MultiTexCoord0 = vec4(0.0, 0.0, 0.0, 1.0);\n \ + hz_MultiTexCoord1 = vec4(0.0, 240.0, 0.0, 1.0);\n \ + hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \ + hz_Normal = vec3(0.0, 1.0, 0.0);\n" + ); + horizon_shaders::GbuffersInputs { + declarations, + body, + attributes: vec![ + ("vaPosition".into(), "hz_Vertex.xyz".into()), + ("vaColor".into(), "hz_Color".into()), + ("vaNormal".into(), "hz_Normal".into()), + ], + // At the far plane: the sky shows only where nothing else drew, and it writes no depth. + after: " gl_Position.z = gl_Position.w;\n".into(), + } +} + +/// A disc fan at height `y`, radius 512, as triangles (SkyRenderer's sky and void discs). +fn disc(y: f32, kind: u32, out: &mut Vec) { + let sign = y.signum(); + let rim = |i: i32| { + let a = (i as f32).to_radians(); + Vertex { + pos: [sign * 512.0 * a.cos(), y, 512.0 * a.sin()], + kind, + } + }; + let centre = Vertex { + pos: [0.0, y, 0.0], + kind, + }; + for i in (-180..180).step_by(45) { + out.extend([centre, rim(i), rim(i + 45)]); + } +} + +pub(super) struct PackSky { + vertices: wgpu::Buffer, + uniform: wgpu::Buffer, + pub layout: wgpu::BindGroupLayout, + group: wgpu::BindGroup, + /// Vertex ranges of the sky disc, the sunset fan, the stars and the void. + ranges: [Range; 4], +} + +impl PackSky { + pub fn new(device: &wgpu::Device) -> Self { + let mut v = Vec::new(); + disc(16.0, SKY, &mut v); + let sky = 0..v.len() as u32; + let apex = Vertex { + pos: [0.0; 3], + kind: SUNSET_APEX, + }; + let rim = |i: u32| { + let a = i as f32 * std::f32::consts::TAU / 16.0; + Vertex { + pos: [a.sin(), a.cos(), 0.0], + kind: SUNSET_RIM, + } + }; + for i in 0..16 { + v.extend([apex, rim(i), rim(i + 1)]); + } + let sunset = sky.end..v.len() as u32; + v.extend( + super::stars::star_triangles() + .into_iter() + .map(|pos| Vertex { pos, kind: STAR }), + ); + let stars = sunset.end..v.len() as u32; + disc(-4.0, VOID, &mut v); + let void = stars.end..v.len() as u32; + let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("Shader pack sky"), + contents: bytemuck::cast_slice(&v), + usage: wgpu::BufferUsages::VERTEX, + }); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Shader pack sky"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Shader pack sky"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }], + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Shader pack sky"), + layout: &layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: uniform.as_entire_binding(), + }], + }); + Self { + vertices, + uniform, + layout, + group, + ranges: [sky, sunset, stars, void], + } + } + + pub fn buffers() -> [Option>; 1] { + [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &ATTRIBUTES, + })] + } + + /// Draws the frame's sky, each part with its render stage: the disc, the sunset fan while + /// the sun is near the horizon, the stars and, with the camera low, the void. + pub fn draw( + &self, + queue: &wgpu::Queue, + pass: &mut wgpu::RenderPass<'_>, + frame: &super::Frame, + stage: &dyn Fn(&mut wgpu::RenderPass<'_>, &str), + ) { + let sun_angle = frame.sky.sun_angle.to_radians(); + // The fan turns to the other horizon in the afternoon (terrain.wgsl's sunrise_weight). + let flip = if sun_angle.sin() < 0.0 { 180f32 } else { 0.0 }; + let theta = (flip + 90.0).to_radians(); + let (rotation, brightness) = frame.stars.unwrap_or_default(); + let [r, g, b] = frame.sky.sky_color; + let uniform = Uniform { + stars: rotation.to_cols_array_2d(), + color: [r, g, b, 1.0], + sunrise: frame.sky.sunrise_color, + sun: [theta.cos(), theta.sin(), brightness.clamp(0.0, 1.0), 0.0], + }; + queue.write_buffer(&self.uniform, 0, bytemuck::bytes_of(&uniform)); + pass.set_bind_group(1, &self.group, &[]); + pass.set_vertex_buffer(0, self.vertices.slice(..)); + let [sky, sunset, stars, void] = self.ranges.clone(); + let parts = [ + ("SKY", sky, true), + ("SUNSET", sunset, frame.sky.sunrise_color[3] > 0.001), + ("STARS", stars, frame.stars.is_some()), + ("VOID", void, frame.dark_disc), + ]; + for (name, range, shown) in parts { + if shown { + stage(pass, name); + pass.draw(range, 0..1); + } + } + } +} diff --git a/crates/horizon-shaders/src/lib.rs b/crates/horizon-shaders/src/lib.rs index bed86758e..853f2f2ba 100644 --- a/crates/horizon-shaders/src/lib.rs +++ b/crates/horizon-shaders/src/lib.rs @@ -34,7 +34,8 @@ pub use macros::{MC_VERSION, Macros, RENDER_STAGES, render_stage}; pub use options::switches_on; pub use pack::{Pack, PackError}; pub use post::{ - Blend, Factor, Group, Post, PostProgram, TRANSLUCENT_BLEND, dimension_folder, load_post, + Blend, Factor, GameInputs, Group, Post, PostProgram, TRANSLUCENT_BLEND, dimension_folder, + load_post, }; pub use preprocess::{Diagnostic, Origin, Preprocessed, preprocess}; pub use properties::{Entry, Note, Properties}; diff --git a/crates/horizon-shaders/src/post.rs b/crates/horizon-shaders/src/post.rs index e155cefbe..56303e67b 100644 --- a/crates/horizon-shaders/src/post.rs +++ b/crates/horizon-shaders/src/post.rs @@ -93,6 +93,9 @@ const TERRAIN: [&str; 4] = [ "gbuffers_basic", ]; +/// `gbuffers_skybasic` and its fallback (2.3). +const SKY: [&str; 2] = ["gbuffers_skybasic", "gbuffers_basic"]; + const GROUPS: [(Group, &str); 4] = [ (Group::Prepare, "prepare"), (Group::Deferred, "deferred"), @@ -127,6 +130,8 @@ pub struct Post { pub terrain: Option, /// What draws translucent terrain (water, stained glass) after deferred. pub water: Option, + /// What draws the sky (disc, sunset, stars, void) before terrain. + pub sky: Option, /// The custom uniforms of `shaders.properties` (3.4). pub custom: Custom, pub config: Config, @@ -145,14 +150,22 @@ pub fn dimension_folder(pack: &Pack, id: i32) -> String { } } -/// Loads the post-processing programs of `folder` and, given the game's terrain vertices, the -/// program terrain draws with. +/// The game's geometry a pack may draw with its gbuffers programs: each kind's vertex inputs, +/// when the game can draw it with a pack. +#[derive(Clone, Debug, Default)] +pub struct GameInputs { + pub terrain: Option, + pub sky: Option, +} + +/// Loads the post-processing programs of `folder` and, for the geometry `inputs` describes, the +/// gbuffers programs it draws with. pub fn load_post( pack: &Pack, folder: &str, properties: &Properties, macros: &Macros, - terrain: Option<&GbuffersInputs>, + inputs: &GameInputs, ) -> Post { let mut post = Post { folder: folder.to_owned(), @@ -161,6 +174,7 @@ pub fn load_post( composite_pre: flips(properties, "composite_pre"), terrain: None, water: None, + sky: None, custom: Custom::parse(properties), config: Config::default(), notes: Vec::new(), @@ -191,17 +205,26 @@ pub fn load_post( } } } - if let Some(inputs) = terrain { - let mut gbuffers = |names: &[&str], group| { - names.iter().find_map(|name| { - loader.load(name.to_string(), group, |v, f| { - translate_gbuffers(v, f, Target::Buffers, inputs) - }) + let mut gbuffers = |names: &[&str], group, inputs: &GbuffersInputs| { + names.iter().find_map(|name| { + loader.load(name.to_string(), group, |v, f| { + translate_gbuffers(v, f, Target::Buffers, inputs) }) - }; - let terrain = gbuffers(&TERRAIN, Group::Gbuffers); + }) + }; + // The sky blends as vanilla draws its sunset fan and stars unless `blend.*` says otherwise. + let sky = inputs + .sky + .as_ref() + .and_then(|i| gbuffers(&SKY, Group::Gbuffers, i)); + let sky = sky.map(|mut p| { + p.blend = blend(properties, &p.name).unwrap_or(Some(TRANSLUCENT_BLEND)); + p + }); + if let Some(inputs) = &inputs.terrain { + let terrain = gbuffers(&TERRAIN, Group::Gbuffers, inputs); // gbuffers_water falls back to gbuffers_terrain's chain (2.3). - let water = gbuffers(&WATER, Group::Translucent); + let water = gbuffers(&WATER, Group::Translucent, inputs); loader.post.terrain = terrain; loader.post.water = water.map(|mut p| { p.blend = blend(properties, &p.name).unwrap_or(Some(TRANSLUCENT_BLEND)); @@ -211,6 +234,7 @@ pub fn load_post( p.blend = blend(properties, &p.name).flatten(); } } + loader.post.sky = sky; post.config = std::mem::take(&mut post.config).finish(); post } @@ -433,7 +457,13 @@ mod tests { ); assert_eq!(dimension_folder(&pack, 0), ""); assert_eq!(dimension_folder(&pack, -1), "world-1"); - let post = load_post(&pack, "", &properties, &Macros::standard(), None); + let post = load_post( + &pack, + "", + &properties, + &Macros::standard(), + &GameInputs::default(), + ); let names: Vec<&str> = post.programs.iter().map(|p| p.name.as_str()).collect(); assert_eq!(names, ["deferred", "composite", "composite2", "final"]); let p = &post.programs; @@ -454,14 +484,21 @@ mod tests { let mut macros = Macros::standard(); macros.define("HQ", ""); - let post = load_post(&pack, "world-1", &properties, ¯os, None); + let post = load_post( + &pack, + "world-1", + &properties, + ¯os, + &GameInputs::default(), + ); let names: Vec<&str> = post.programs.iter().map(|p| p.name.as_str()).collect(); assert_eq!(names, ["final"]); - let post = load_post(&pack, "", &properties, ¯os, None); + let post = load_post(&pack, "", &properties, ¯os, &GameInputs::default()); assert!(post.programs.iter().any(|p| p.name == "composite3")); } - /// Water falls back to the terrain chain and blends by default; `blend.*` overrides. + /// Water falls back to the terrain chain and blends by default, as the sky does; `blend.*` + /// overrides. #[test] fn water_falls_back_to_terrain_and_blends() { let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/packs/terrain-test"); @@ -470,12 +507,25 @@ mod tests { let inputs = crate::GbuffersInputs { declarations: "layout(location = 0) in vec3 hz_v_pos;".into(), body: " hz_Vertex = vec4(hz_v_pos, 1.0);\n hz_Color = vec4(1.0);\n".into(), - attributes: Vec::new(), + ..Default::default() }; - let post = load_post(&pack, "", &Properties::default(), ¯os, Some(&inputs)); + let inputs = GameInputs { + terrain: Some(inputs.clone()), + sky: Some(inputs), + }; + let post = load_post(&pack, "", &Properties::default(), ¯os, &inputs); let (terrain, water) = (post.terrain.unwrap(), post.water.unwrap()); assert_eq!((terrain.group, terrain.blend), (Group::Gbuffers, None)); assert_eq!(water.name, "gbuffers_terrain"); + let sky = post.sky.unwrap(); + assert_eq!( + (sky.name.as_str(), sky.group, sky.blend), + ( + "gbuffers_skybasic", + Group::Gbuffers, + Some(TRANSLUCENT_BLEND) + ) + ); assert_eq!( (water.group, water.blend), (Group::Translucent, Some(TRANSLUCENT_BLEND)) @@ -504,7 +554,7 @@ mod tests { &dimension_folder(&pack, 0), &properties, ¯os, - None, + &GameInputs::default(), ); assert!(post.notes.is_empty(), "{:?}", post.notes); let names: Vec<&str> = post.programs.iter().map(|p| p.name.as_str()).collect(); diff --git a/crates/horizon-shaders/src/translate/mod.rs b/crates/horizon-shaders/src/translate/mod.rs index fe736e4d8..35475ddab 100644 --- a/crates/horizon-shaders/src/translate/mod.rs +++ b/crates/horizon-shaders/src/translate/mod.rs @@ -109,6 +109,8 @@ pub struct GbuffersInputs { /// The value of each attribute a pack may declare (`mc_Entity`, `vaPosition`...), as a GLSL /// expression of the declared type's size; an attribute not listed reads zero. pub attributes: Vec<(String, String)>, + /// GLSL statements run last in `main`, with `gl_Position` in wgpu's clip space. + pub after: String, } /// Translates a composite-style program (`composite`, `deferred`, `final`...). @@ -292,7 +294,8 @@ fn translate( } write!( vertex_main, - " hz_main();\n gl_Position = vec4(gl_Position.x, {flip}gl_Position.y, (gl_Position.z + gl_Position.w) * 0.5, gl_Position.w);\n}}\n" + " hz_main();\n gl_Position = vec4(gl_Position.x, {flip}gl_Position.y, (gl_Position.z + gl_Position.w) * 0.5, gl_Position.w);\n{}}}\n", + gbuffers.map_or("", |g| &g.after) ) .unwrap(); let mut fragment_main = String::from("\nvoid main() {\n"); @@ -597,6 +600,7 @@ mod tests { hz_MultiTexCoord1 = vec4(240.0, 240.0, 0.0, 1.0);\n hz_Color = vec4(1.0);\n hz_Normal = vec3(0.0, 1.0, 0.0);\n" .into(), attributes: vec![("mc_midTexCoord".into(), "vec2(game_uv) / 32768.0".into())], + ..Default::default() }; let p = translate_gbuffers( &preprocess(&pack, "gbuffers_terrain.vsh", &m), diff --git a/crates/horizon-shaders/tests/packs/terrain-test/README.md b/crates/horizon-shaders/tests/packs/terrain-test/README.md index bb8ddd060..3fc37bf4d 100644 --- a/crates/horizon-shaders/tests/packs/terrain-test/README.md +++ b/crates/horizon-shaders/tests/packs/terrain-test/README.md @@ -3,6 +3,8 @@ Horizon's own shader pack for testing gbuffers terrain (written for Horizon, no other pack's code). `gbuffers_terrain` draws blocks from the atlas with their vertex colour and lightmap, tinted by the lightmap coordinate's sky light (cooler where the sky is hidden); `mc_midTexCoord` marks each -face's centre with a dot. `composite` puts the depth buffer's view-space distance into the blue +face's centre with a dot, and any stage but solid terrain (translucent terrain falls back to it) +is red. `gbuffers_skybasic` draws the sky in its vertex colour, a little greener, with magenta +stars and a dark red void. `composite` puts the depth buffer's view-space distance into the blue channel of the far half. Copy the folder into `shaderpacks/` and run the game with `HORIZON_SHADER_PACK=terrain-test`. diff --git a/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_skybasic.fsh b/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_skybasic.fsh new file mode 100644 index 000000000..8d62f3291 --- /dev/null +++ b/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_skybasic.fsh @@ -0,0 +1,15 @@ +#version 120 + +uniform int renderStage; + +varying vec4 glcolor; + +void main() { + vec4 color = glcolor; + // Stars magenta, the void dark red, the sky disc a little greener: each stage is told apart. + if (renderStage == MC_RENDER_STAGE_STARS) color.rgb = vec3(1.0, 0.0, 1.0); + if (renderStage == MC_RENDER_STAGE_VOID) color.rgb = vec3(0.3, 0.0, 0.0); + if (renderStage == MC_RENDER_STAGE_SKY) color.g = min(color.g + 0.2, 1.0); + /* DRAWBUFFERS:0 */ + gl_FragData[0] = color; +} diff --git a/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_skybasic.vsh b/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_skybasic.vsh new file mode 100644 index 000000000..7b3bd59ce --- /dev/null +++ b/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_skybasic.vsh @@ -0,0 +1,8 @@ +#version 120 + +varying vec4 glcolor; + +void main() { + gl_Position = ftransform(); + glcolor = gl_Color; +} diff --git a/crates/horizon-shaders/tests/real_packs.rs b/crates/horizon-shaders/tests/real_packs.rs index c5d4defac..a04a31b15 100644 --- a/crates/horizon-shaders/tests/real_packs.rs +++ b/crates/horizon-shaders/tests/real_packs.rs @@ -167,19 +167,19 @@ fn real_packs_read() { declarations: "layout(location = 0) in vec3 hz_v_pos;".into(), body: " hz_Vertex = vec4(hz_v_pos, 1.0);\n hz_Color = vec4(1.0);\n".into(), attributes: vec![("mc_Entity".into(), "vec4(-1.0)".into())], + ..Default::default() }; - let post = load_post( - &pack, - &folder, - &shaders, - &Macros::standard(), - Some(&terrain), - ); + let inputs = horizon_shaders::GameInputs { + terrain: Some(terrain.clone()), + sky: Some(terrain), + }; + let post = load_post(&pack, &folder, &shaders, &Macros::standard(), &inputs); println!( - " dimension {id} (folder `{folder}`): {} post programs, terrain {:?}, water {:?}, {} notes, {:.0} ms", + " dimension {id} (folder `{folder}`): {} post programs, terrain {:?}, water {:?}, sky {:?}, {} notes, {:.0} ms", post.programs.len(), post.terrain.as_ref().map(|t| &t.name), post.water.as_ref().map(|t| &t.name), + post.sky.as_ref().map(|t| &t.name), post.notes.len() + post.config.notes.len(), start.elapsed().as_secs_f64() * 1000.0 );