diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index f0987dddd..354dc8d07 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -69,6 +69,7 @@ pub mod lightning; mod lod; mod occlusion; mod pack_atlas; +mod pack_draw; mod pack_post; mod pack_timing; pub mod pack_uniforms; diff --git a/crates/horizon-client/src/gfx/pack_draw.rs b/crates/horizon-client/src/gfx/pack_draw.rs new file mode 100644 index 000000000..91c77a6bf --- /dev/null +++ b/crates/horizon-client/src/gfx/pack_draw.rs @@ -0,0 +1,67 @@ +//! The uniforms a shader pack's gbuffers programs read per draw (`HzDraw` at set 2, the +//! translator's `DRAW_UNIFORMS`): one slot per render stage of a uniform buffer, picked with a +//! dynamic offset at each draw. + +use horizon_shaders::{RENDER_STAGES, render_stage}; + +/// `HzDraw`'s size: `renderStage`, `entityId`, `blockEntityId`, a pad, `entityColor`. +const SIZE: u32 = 32; + +pub(super) struct DrawUniforms { + pub layout: wgpu::BindGroupLayout, + group: wgpu::BindGroup, + stride: u32, +} + +impl DrawUniforms { + pub fn new(device: &wgpu::Device) -> Self { + let stride = SIZE.max(device.limits().min_uniform_buffer_offset_alignment); + let mut contents = vec![0u8; stride as usize * RENDER_STAGES.len()]; + for (i, slot) in contents.chunks_mut(stride as usize).enumerate() { + slot[..4].copy_from_slice(&(i as i32).to_le_bytes()); + } + let buffer = wgpu::util::DeviceExt::create_buffer_init( + device, + &wgpu::util::BufferInitDescriptor { + label: Some("Shader pack draws"), + contents: &contents, + usage: wgpu::BufferUsages::UNIFORM, + }, + ); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Shader pack draws"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: wgpu::BufferSize::new(u64::from(SIZE)), + }, + count: None, + }], + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Shader pack draws"), + layout: &layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &buffer, + offset: 0, + size: wgpu::BufferSize::new(u64::from(SIZE)), + }), + }], + }); + Self { + layout, + group, + stride, + } + } + + /// Draws that follow read `renderStage` = `MC_RENDER_STAGE_`, other values zero. + pub fn bind(&self, pass: &mut wgpu::RenderPass<'_>, stage: &str) { + pass.set_bind_group(2, &self.group, &[self.stride * render_stage(stage)]); + } +} diff --git a/crates/horizon-client/src/gfx/pack_post.rs b/crates/horizon-client/src/gfx/pack_post.rs index 2f152b893..08a2dedcc 100644 --- a/crates/horizon-client/src/gfx/pack_post.rs +++ b/crates/horizon-client/src/gfx/pack_post.rs @@ -15,6 +15,7 @@ use std::collections::HashMap; use horizon_shaders::{Format, Group, Kind, Post, Val}; +use super::pack_draw::DrawUniforms; use super::pack_uniforms::{self, FrameUniforms, PackInputs}; const BUFFERS: usize = horizon_shaders::BUFFERS; @@ -139,6 +140,8 @@ struct Pass { written: u16, /// Buffers whose mip chain is regenerated right before it (6.1.7). mipmaps: u16, + /// Reads the per-draw block (`DrawUniforms`). + draw: bool, groups: HashMap, } @@ -186,6 +189,8 @@ pub struct PackPost { mips_valid: u16, /// The downsampling pipeline of each format with mipmaps. down: HashMap, + /// The per-draw uniforms of gbuffers programs. + draws: DrawUniforms, /// `HORIZON_SHADER_PACK_TIMING`: GPU time of each pass, in the log. timing: Option, /// `shaders.properties`' custom uniforms, after the frame's in `uniforms.values`. @@ -488,6 +493,7 @@ fn build_pass( notes: &mut Vec, geometry: Option<&Geometry<'_>>, custom: &[String], + draws: &wgpu::BindGroupLayout, ) -> Option { let features = device.features(); // The frame's uniforms, then the pack's custom ones. @@ -499,6 +505,7 @@ fn build_pass( }; let mask = |flips: &[(u32, bool)]| flips.iter().filter(|f| f.1).fold(0u16, |m, f| m | 1 << f.0); let interface = &p.program.interface; + let draw = interface.draw; let mut entries = vec![entry( 0, wgpu::BindingType::Buffer { @@ -632,7 +639,11 @@ fn build_pass( }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(&p.name), - bind_group_layouts: &[Some(&layout), geometry.and_then(|g| g.table)], + bind_group_layouts: &[ + Some(&layout), + geometry.and_then(|g| g.table), + draw.then_some(draws), + ], ..Default::default() }); let module = |mut m: naga::Module| { @@ -712,6 +723,7 @@ fn build_pass( reads, written, mipmaps: p.mipmaps, + draw, groups: HashMap::new(), }) } @@ -748,6 +760,7 @@ impl PackPost { let mask = |flips: &[(u32, bool)]| flips.iter().filter(|f| f.1).fold(0u16, |m, f| m | 1 << f.0); let mut used = 1u16; + let draws = DrawUniforms::new(device); let mut build = |p: horizon_shaders::PostProgram, geometry: Option<&Geometry<'_>>| { let pass = build_pass( device, @@ -757,6 +770,7 @@ impl PackPost { &mut notes, geometry, &custom_names, + &draws.layout, )?; used |= pass.reads | pass.written | pass.flip; Some(pass) @@ -910,6 +924,7 @@ impl PackPost { mipped, mips_valid: 0, down, + draws, timing: super::pack_timing::PassTiming::new(device, queue), custom, atlas: world.atlas.as_ref().map(|a| a.0.clone()), @@ -1133,6 +1148,14 @@ 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); + } draw(&mut rp, translucent); } self.mips_valid &= !pass.written; diff --git a/crates/horizon-shaders/src/lib.rs b/crates/horizon-shaders/src/lib.rs index f5819d435..bed86758e 100644 --- a/crates/horizon-shaders/src/lib.rs +++ b/crates/horizon-shaders/src/lib.rs @@ -30,7 +30,7 @@ pub use config::{BUFFERS, Buffer, Config, Format, Kind, buffer_index, draw_buffe pub use custom::{Custom, Val}; pub use discover::{Found, discover}; pub use lang::Lang; -pub use macros::{MC_VERSION, Macros, RENDER_STAGES}; +pub use macros::{MC_VERSION, Macros, RENDER_STAGES, render_stage}; pub use options::switches_on; pub use pack::{Pack, PackError}; pub use post::{ @@ -39,6 +39,6 @@ pub use post::{ pub use preprocess::{Diagnostic, Origin, Preprocessed, preprocess}; pub use properties::{Entry, Note, Properties}; pub use translate::{ - Error, GbuffersInputs, Interface, Program, Sampler, Target, Uniform, translate_composite, - translate_gbuffers, + DRAW_UNIFORMS, Error, GbuffersInputs, Interface, Program, Sampler, Target, Uniform, + translate_composite, translate_gbuffers, }; diff --git a/crates/horizon-shaders/src/macros.rs b/crates/horizon-shaders/src/macros.rs index d8a184f41..6c7fb2678 100644 --- a/crates/horizon-shaders/src/macros.rs +++ b/crates/horizon-shaders/src/macros.rs @@ -60,6 +60,14 @@ pub const RENDER_STAGES: [&str; 24] = [ "HAND_TRANSLUCENT", ]; +/// The value of `MC_RENDER_STAGE_` (OQ-7: its index in `RENDER_STAGES`). +pub fn render_stage(name: &str) -> u32 { + RENDER_STAGES + .iter() + .position(|s| *s == name) + .unwrap_or_else(|| panic!("no render stage {name}")) as u32 +} + impl Macros { /// The standard macros that need no renderer (spec 1.5.1): `MC_VERSION`, this system's /// `MC_OS_*`, the GL and GLSL versions Horizon's translation accepts, the render stages and diff --git a/crates/horizon-shaders/src/translate/mod.rs b/crates/horizon-shaders/src/translate/mod.rs index 83dcb3af9..fe736e4d8 100644 --- a/crates/horizon-shaders/src/translate/mod.rs +++ b/crates/horizon-shaders/src/translate/mod.rs @@ -45,8 +45,19 @@ pub struct Interface { pub samplers: Vec, /// The fragment stage's output locations. pub outputs: Vec, + /// A gbuffers program reads `DRAW_UNIFORMS`: the block at set 2, binding 0, set per draw. + pub draw: bool, } +/// The uniforms a gbuffers program reads per draw (5.3's "D"), in a block of their own +/// (`HzDraw`, std140: three ints, a pad, a vec4; 32 bytes) the game sets for each draw. +pub const DRAW_UNIFORMS: [(&str, &str); 4] = [ + ("renderStage", "int"), + ("entityId", "int"), + ("blockEntityId", "int"), + ("entityColor", "vec4"), +]; + #[derive(Clone, Debug, PartialEq)] pub struct Uniform { pub name: String, @@ -170,6 +181,17 @@ fn translate( samplers.insert(name.clone(), ty.clone()); } } + // Per-draw values move to their own block; another type than the documented one keeps + // the frame's block (and reads zero). + let mut draw = false; + if gbuffers.is_some() { + for (name, ty) in DRAW_UNIFORMS { + if uniforms.get(name).is_some_and(|t| t == ty) { + uniforms.remove(name); + draw = true; + } + } + } let samplers: Vec = samplers .into_iter() .enumerate() @@ -203,6 +225,12 @@ fn translate( .unwrap(); } h.push_str(" };\n"); + if draw { + h.push_str( + "layout(set = 2, binding = 0) uniform HzDraw { int renderStage; int entityId; \ + int blockEntityId; int hz_draw_pad; vec4 entityColor; };\n", + ); + } for s in &samplers { let (texture, sampler) = split_sampler(&s.ty); writeln!( @@ -327,6 +355,7 @@ fn translate( uniforms, samplers, outputs, + draw, }, }) } @@ -394,7 +423,11 @@ fn compile(stage: &Stage, text: &str, header_lines: usize) -> Result (u32, Vec<(String, u32)>) { for (_, var) in module.global_variables.iter() { - if var.space != naga::AddressSpace::Uniform { + let frame = var + .binding + .as_ref() + .is_some_and(|b| b.group == 0 && b.binding == 0); + if var.space != naga::AddressSpace::Uniform || !frame { continue; } if let naga::TypeInner::Struct { members, span } = &module.types[var.ty].inner { @@ -546,9 +579,9 @@ mod tests { light = (gl_TextureMatrix[1] * gl_MultiTexCoord1).xy;\n color = gl_Color;\n \ normal = normalize(gl_NormalMatrix * gl_Normal);\n id = mc_Entity.x + mc_midTexCoord.x;\n}\n"; let fsh = "#version 120\nuniform sampler2D texture;\nuniform sampler2D lightmap;\nuniform mat4 gbufferModelView;\n\ - varying vec2 uv;\nvarying vec2 light;\nvarying vec4 color;\nvarying vec3 normal;\nvarying float id;\n\ + uniform int renderStage;\nvarying vec2 uv;\nvarying vec2 light;\nvarying vec4 color;\nvarying vec3 normal;\nvarying float id;\n\ void main() {\n vec4 c = texture2D(texture, uv) * texture2D(lightmap, light) * color;\n \ - /* DRAWBUFFERS:02 */\n gl_FragData[0] = c * gl_FragCoord.z;\n \ + /* DRAWBUFFERS:02 */\n gl_FragData[0] = c * gl_FragCoord.z * float(renderStage);\n \ gl_FragData[1] = vec4(normal * 0.5 + 0.5, id);\n}\n"; let files: Vec<(String, &str)> = [("gbuffers_terrain.vsh", vsh), ("gbuffers_terrain.fsh", fsh)] @@ -586,6 +619,14 @@ mod tests { assert!(names.contains(&name), "{name} missing from {names:?}"); } assert_eq!(p.interface.outputs, vec![0, 1]); + // renderStage is set per draw, in its own block. + assert!(p.interface.draw && !names.contains(&"renderStage")); + let per_draw = p.fragment.global_variables.iter().any(|(_, v)| { + v.binding + .as_ref() + .is_some_and(|b| b.group == 2 && b.binding == 0) + }); + assert!(per_draw); let inputs: Vec<&str> = p.vertex.entry_points[0] .function .arguments diff --git a/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_terrain.fsh b/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_terrain.fsh index 902cf3525..8be409929 100644 --- a/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_terrain.fsh +++ b/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_terrain.fsh @@ -3,6 +3,7 @@ uniform sampler2D texture; uniform sampler2D lightmap; uniform ivec2 atlasSize; +uniform int renderStage; varying vec2 texcoord; varying vec2 lmcoord; @@ -17,6 +18,8 @@ void main() { color.rgb = mix(color.rgb * vec3(0.6, 0.7, 1.2), color.rgb, lmcoord.y); // A dot at the face's centre, one texel wide. if (length((texcoord - mid) * vec2(atlasSize)) < 1.0) color.rgb = vec3(1.0, 0.0, 1.0); + // Any other stage than solid terrain (translucent terrain falls back here): red. + if (renderStage != MC_RENDER_STAGE_TERRAIN_SOLID) color.rgb = vec3(1.0, 0.0, 0.0); /* DRAWBUFFERS:0 */ gl_FragData[0] = color; }