From 224b83c6a6ab13fb3d5876630c93f9346c3db22f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:48:03 +0100 Subject: [PATCH] Shader packs, clean room 36: the hand A pack with gbuffers_hand (or textured_lit, textured, basic; spec 2.3) draws the first-person hand and held items after the opaque world, into its own buffers and the world's depth, without blending and with the entities' 0.1 alpha cut. The vertices are Horizon's hand geometry, read as entities are; `gl_ProjectionMatrix` is the hand's own projection (the hand's field of view and bob) with depth scaled by MC_HAND_DEPTH, while `gbufferProjection` stays the world's (5.2). Horizon's own hand draw is skipped only when the pack draws it. Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1; no other loader's code read. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 11 +- .../horizon-client/src/gfx/pack_entities.rs | 2 +- crates/horizon-client/src/gfx/pack_hand.rs | 169 ++++++++++++++++++ crates/horizon-client/src/gfx/pack_post.rs | 70 +++++++- crates/horizon-shaders/src/post.rs | 32 +++- crates/horizon-shaders/tests/real_packs.rs | 3 +- 6 files changed, 282 insertions(+), 5 deletions(-) create mode 100644 crates/horizon-client/src/gfx/pack_hand.rs diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index e2e71e036..9f048f19e 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -71,6 +71,7 @@ mod occlusion; mod pack_atlas; pub mod pack_draw; mod pack_entities; +mod pack_hand; mod pack_post; mod pack_sky; mod pack_timing; @@ -2825,6 +2826,7 @@ impl Renderer { .map(|t| t.create_view(&Default::default())), clouds: Some(&self.cloud_bindings), weather: true, + hand: true, }; pack_post::PackPost::new( &self.device, @@ -2851,6 +2853,7 @@ impl Renderer { entities: Some(pack_entities::inputs()), clouds: Some(pack_entities::cloud_inputs()), weather: Some(pack_weather::inputs()), + hand: Some(pack_hand::inputs()), } } @@ -3806,6 +3809,12 @@ impl Renderer { .as_ref() .and_then(|p| p.1.as_ref()) .is_some_and(|p| p.has_clouds()); + let pack_draws_hand = pack_post + && self + .pack_post + .as_ref() + .and_then(|p| p.1.as_ref()) + .is_some_and(|p| p.has_hand()); let pack_draws_weather = pack_post && self .pack_post @@ -4195,7 +4204,7 @@ impl Renderer { } else if scaled.is_some() { self.world_post.finish(&mut encoder, &view_target); } - if hand_quads > 0 { + if hand_quads > 0 && !pack_draws_hand { let attachments = [Some(wgpu::RenderPassColorAttachment { view: &view_target, resolve_target: None, diff --git a/crates/horizon-client/src/gfx/pack_entities.rs b/crates/horizon-client/src/gfx/pack_entities.rs index b06c45af6..ffc55149f 100644 --- a/crates/horizon-client/src/gfx/pack_entities.rs +++ b/crates/horizon-client/src/gfx/pack_entities.rs @@ -356,7 +356,7 @@ impl PackEntities { } /// Two triangles for each of `quads` quads, from vertex 0. -fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer { +pub(super) fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer { let indices: Vec = (0..quads) .flat_map(|q| [0, 1, 2, 0, 2, 3].map(|i| q * 4 + i)) .collect(); diff --git a/crates/horizon-client/src/gfx/pack_hand.rs b/crates/horizon-client/src/gfx/pack_hand.rs new file mode 100644 index 000000000..096cc5bcf --- /dev/null +++ b/crates/horizon-client/src/gfx/pack_hand.rs @@ -0,0 +1,169 @@ +//! The first-person hand and held items drawn by a shader pack's `gbuffers_hand` (spec 2.3): +//! `Frame::hand`'s entity vertices, read as entities are (`pack_entities::inputs`), with the +//! hand's own projection as `gl_ProjectionMatrix` (5.2: `gbufferProjection` stays the world's). + +use glam::Mat4; + +use super::Vertex; + +/// `MC_HAND_DEPTH`'s value (1.5): the hand's depth is scaled by it through its projection, so +/// that it sits in front of the world in the shared depth buffer. +const HAND_DEPTH: f32 = 0.125; + +/// `HzHand`: the hand's projection and its inverse. +const UNIFORM: u64 = 2 * 64; + +/// What `gbuffers_hand` reads: the entity inputs, and the hand's projection from set 1. +pub fn inputs() -> horizon_shaders::GbuffersInputs { + let mut inputs = super::pack_entities::inputs(); + inputs.declarations.push_str( + "layout(set = 1, binding = 1) uniform HzHand { mat4 hz_hand_projection; mat4 hz_hand_projection_inverse; };\n", + ); + inputs.body.push_str( + " hz_ProjectionMatrix = hz_hand_projection;\n \ + hz_ProjectionMatrixInverse = hz_hand_projection_inverse;\n \ + hz_ModelViewProjectionMatrix = hz_hand_projection * hz_ModelViewMatrix;\n", + ); + inputs +} + +/// The hand's projection in GL's conventions: `hud_fov` degrees, the view bob, depth scaled by +/// `MC_HAND_DEPTH`. +pub fn projection(hud_fov: f32, aspect: f32, far: f32, bob: Mat4) -> Mat4 { + Mat4::from_scale(glam::Vec3::new(1.0, 1.0, HAND_DEPTH)) + * Mat4::perspective_rh_gl(hud_fov.to_radians(), aspect, 0.05, far) + * bob +} + +/// The hand's vertices (also read at set 1 for normals and tangents), its uniform and quad +/// indices. +pub struct PackHand { + pub layout: wgpu::BindGroupLayout, + vertices: wgpu::Buffer, + uniform: wgpu::Buffer, + pub group: wgpu::BindGroup, + pub indices: wgpu::Buffer, + capacity: u32, + /// Quads uploaded this frame. + pub quads: u32, +} + +impl PackHand { + pub fn new(device: &wgpu::Device) -> Self { + let entry = |binding, ty| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Shader pack hand"), + entries: &[ + entry(0, wgpu::BufferBindingType::Storage { read_only: true }), + entry(1, wgpu::BufferBindingType::Uniform), + ], + }); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Shader pack hand"), + size: UNIFORM, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let capacity = 256; + let (vertices, group) = Self::vertex_buffer(device, &layout, &uniform, capacity); + Self { + indices: super::pack_entities::quad_indices(device, capacity), + layout, + vertices, + uniform, + group, + capacity, + quads: 0, + } + } + + fn vertex_buffer( + device: &wgpu::Device, + layout: &wgpu::BindGroupLayout, + uniform: &wgpu::Buffer, + quads: u32, + ) -> (wgpu::Buffer, wgpu::BindGroup) { + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Shader pack hand vertices"), + size: u64::from(quads) * 4 * std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::VERTEX + | wgpu::BufferUsages::STORAGE + | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Shader pack hand"), + layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: buffer.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: uniform.as_entire_binding(), + }, + ], + }); + (buffer, group) + } + + /// Uploads this frame's hand and its projection. + pub fn prepare( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + hand: &[Vertex], + projection: Mat4, + ) { + self.quads = (hand.len() / 4) as u32; + if self.quads == 0 { + return; + } + if self.quads > self.capacity { + self.capacity = self.quads.next_power_of_two(); + (self.vertices, self.group) = + Self::vertex_buffer(device, &self.layout, &self.uniform, self.capacity); + self.indices = super::pack_entities::quad_indices(device, self.capacity); + } + queue.write_buffer(&self.vertices, 0, bytemuck::cast_slice(hand)); + let matrices = [projection, projection.inverse()].map(|m| m.to_cols_array()); + queue.write_buffer(&self.uniform, 0, bytemuck::cast_slice(&matrices)); + } + + pub fn vertices(&self) -> wgpu::BufferSlice<'_> { + self.vertices.slice(..) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The hand's window depth lies within `MC_HAND_DEPTH` of the middle (packs tell the hand + /// apart by it), and x, y match the plain projection. + #[test] + fn hand_depth_is_scaled_around_the_middle() { + let p = projection(70.0, 16.0 / 9.0, 512.0, Mat4::IDENTITY); + let plain = Mat4::perspective_rh_gl(70f32.to_radians(), 16.0 / 9.0, 0.05, 512.0); + for z in [-0.06f32, -0.5, -3.0, -400.0] { + let v = glam::Vec4::new(0.1, -0.2, z, 1.0); + let (a, b) = (p * v, plain * v); + let window = (a.z / a.w) * 0.5 + 0.5; + assert!( + (window - 0.5).abs() <= HAND_DEPTH * 0.5 + 1e-6, + "{z}: {window}" + ); + assert!((a.x / a.w - b.x / b.w).abs() < 1e-6); + } + } +} diff --git a/crates/horizon-client/src/gfx/pack_post.rs b/crates/horizon-client/src/gfx/pack_post.rs index f6f87cbb8..57c24b1ed 100644 --- a/crates/horizon-client/src/gfx/pack_post.rs +++ b/crates/horizon-client/src/gfx/pack_post.rs @@ -208,6 +208,8 @@ pub(super) struct World<'a> { pub clouds: Option<&'a wgpu::BindGroupLayout>, /// The game can hand its rain and snow to the pack. pub weather: bool, + /// The game can hand its first-person hand to the pack. + pub hand: bool, } /// This frame's clouds, when the pack draws them: their vertices, uniform, quad indices and @@ -251,6 +253,9 @@ pub struct PackPost { weather: Option<[Pass; 2]>, weather_draw: Option, weather_generation: u64, + /// What draws the first-person hand (`gbuffers_hand` or its fallback), after the opaque + /// world, and its vertices. + hand: Option<(Pass, super::pack_hand::PackHand)>, /// A program after translucent terrain reads `depthtex1`: it is copied before water. depth1: bool, /// Buffers with mipmaps (filterable ones a program asks them for). @@ -997,6 +1002,18 @@ impl PackPost { ids: None, cull: false, }); + let hand_geometry = world.hand.then(|| super::pack_hand::PackHand::new(device)); + let hand = post.hand.zip(hand_geometry).and_then(|(p, geometry)| { + let g = Geometry { + buffers: &entity_buffers, + table: Some(&geometry.layout), + depth_write: true, + atlas: world.celestial.clone(), + ids: None, + cull: false, + }; + build(p, Some(&g)).map(|pass| (pass, geometry)) + }); let weather = post .weather .zip(weather_geometry.as_ref()) @@ -1041,6 +1058,9 @@ impl PackPost { if let Some(c) = &clouds { notes.push(format!("clouds draw with {}", c.name)); } + if let Some((h, _)) = &hand { + notes.push(format!("the hand draws with {}", h.name)); + } if let Some([w, _]) = &weather { notes.push(format!("rain and snow draw with {}", w.name)); } @@ -1071,6 +1091,7 @@ impl PackPost { .chain(&clouds) .chain(&water) .chain(weather.iter().take(1).flatten()) + .chain(hand.iter().map(|h| &h.0)) .find(touched) .map(|_| true) .or_else(|| { @@ -1088,6 +1109,7 @@ impl PackPost { || entities.is_some() || clouds.is_some() || weather.is_some() + || hand.is_some() || passes.iter().any(|p| { p.samplers .iter() @@ -1190,6 +1212,7 @@ impl PackPost { weather, weather_draw: None, weather_generation: 0, + hand, depth1, mipped, mips_valid: 0, @@ -1607,6 +1630,50 @@ impl PackPost { self.draw_terrain(device, queue, encoder, size, false, terrain); self.draw_entities(device, queue, encoder, size, false); self.draw_clouds(device, queue, encoder, size); + self.draw_hand(device, queue, encoder, size, frame); + } + + /// The first-person hand and held items, with `gbuffers_hand` at the hand's projection. + fn draw_hand( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + size: [u32; 2], + frame: &super::Frame, + ) { + let Some((mut pass, mut geometry)) = self.hand.take() else { + return; + }; + let projection = super::pack_hand::projection( + frame.hand_fov_degrees, + size[0] as f32 / size[1].max(1) as f32, + frame.depth_far, + frame.bob, + ); + geometry.prepare(device, queue, frame.hand, projection); + if geometry.quads > 0 { + let group = self.bind(device, queue, &mut pass, size); + { + let mut rp = self.begin(encoder, &pass); + rp.set_pipeline(&pass.pipeline); + rp.set_bind_group(0, &group, &[]); + rp.set_bind_group(1, &geometry.group, &[]); + if pass.draw { + self.draws.bind(&mut rp, "HAND_SOLID"); + } + rp.set_vertex_buffer(0, geometry.vertices()); + rp.set_index_buffer(geometry.indices.slice(..), wgpu::IndexFormat::Uint32); + rp.draw_indexed(0..geometry.quads * 6, 0, 0..1); + } + self.mips_valid &= !pass.written; + } + self.hand = Some((pass, geometry)); + } + + /// Whether the pack draws the first-person hand itself. + pub fn has_hand(&self) -> bool { + self.hand.is_some() } /// The clouds `set_clouds` gave for this frame, with `gbuffers_clouds`. @@ -2018,7 +2085,8 @@ impl PackPost { let mut terrain_drawn = self.terrain.is_none() && self.sky.is_none() && self.entities.is_none() - && self.clouds.is_none(); + && self.clouds.is_none() + && self.hand.is_none(); let late_entities = self.entities.as_ref().is_some_and(|e| { e.passes .iter() diff --git a/crates/horizon-shaders/src/post.rs b/crates/horizon-shaders/src/post.rs index 5a7ea1472..9beb7f06a 100644 --- a/crates/horizon-shaders/src/post.rs +++ b/crates/horizon-shaders/src/post.rs @@ -123,6 +123,14 @@ const BLOCK: [&str; 5] = [ /// `gbuffers_clouds`: no fallback, the game draws its clouds otherwise (OQ-3). const CLOUDS: [&str; 1] = ["gbuffers_clouds"]; +/// `gbuffers_hand` and its fallbacks (2.3). +const HAND: [&str; 4] = [ + "gbuffers_hand", + "gbuffers_textured_lit", + "gbuffers_textured", + "gbuffers_basic", +]; + /// `gbuffers_weather` and its fallbacks (2.3). const WEATHER: [&str; 4] = [ "gbuffers_weather", @@ -206,6 +214,8 @@ pub struct Post { pub clouds: Option, /// What draws rain and snow, after deferred. pub weather: Option, + /// What draws the first-person hand and held items. + pub hand: Option, /// Translucent entities draw after deferred (`separateEntityDraws`, 3.2). pub translucent_late: bool, /// Particles draw after deferred (`particles.ordering`, `particles.before.deferred`, 3.2). @@ -241,6 +251,8 @@ pub struct GameInputs { pub clouds: Option, /// Rain and snow. pub weather: Option, + /// The first-person hand and held items. + pub hand: Option, } /// Loads the post-processing programs of `folder` and, for the geometry `inputs` describes, the @@ -267,6 +279,7 @@ pub fn load_post( particles: None, clouds: None, weather: None, + hand: None, translucent_late: false, particles_late: false, custom: Custom::parse(properties), @@ -381,6 +394,15 @@ pub fn load_post( p.blend = blend(properties, &p.name).unwrap_or(Some(TRANSLUCENT_BLEND)); p }); + // The hand draws as entities do: no blending unless `blend.*` says otherwise (OQ-23). + let hand = inputs + .hand + .as_ref() + .and_then(|i| gbuffers(&HAND, Group::Gbuffers, i)) + .map(|mut p| { + p.blend = blend(properties, &p.name).flatten(); + 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). @@ -402,6 +424,7 @@ pub fn load_post( loader.post.particles = particles; loader.post.clouds = clouds; loader.post.weather = weather; + loader.post.hand = hand; let flag = |key: &str| properties.get(key).map(|v| v.trim() == "true"); loader.post.translucent_late = flag("separateEntityDraws").unwrap_or(false); // `after` when the pack has a deferred program, else `mixed`; ours are all translucent, so @@ -691,7 +714,8 @@ mod tests { celestial: Some(inputs.clone()), entities: Some(inputs.clone()), clouds: Some(inputs.clone()), - weather: Some(inputs), + weather: Some(inputs.clone()), + hand: Some(inputs), }; let post = load_post(&pack, "", &Properties::default(), ¯os, &inputs); let (terrain, water) = (post.terrain.unwrap(), post.water.unwrap()); @@ -741,6 +765,12 @@ mod tests { assert!(post.particles_late && !post.translucent_late); // gbuffers_clouds has no fallback (OQ-3): without it the game draws its clouds. assert!(post.clouds.is_none()); + // The hand falls back to gbuffers_textured and does not blend. + let hand = post.hand.as_ref().unwrap(); + assert_eq!( + (hand.name.as_str(), hand.group, hand.blend), + ("gbuffers_textured", Group::Gbuffers, None) + ); // Weather falls back to gbuffers_textured, after deferred, blended. let weather = post.weather.as_ref().unwrap(); assert_eq!( diff --git a/crates/horizon-shaders/tests/real_packs.rs b/crates/horizon-shaders/tests/real_packs.rs index 41323d440..747b732d7 100644 --- a/crates/horizon-shaders/tests/real_packs.rs +++ b/crates/horizon-shaders/tests/real_packs.rs @@ -175,7 +175,8 @@ fn real_packs_read() { celestial: Some(terrain.clone()), entities: Some(terrain.clone()), clouds: Some(terrain.clone()), - weather: Some(terrain), + weather: Some(terrain.clone()), + hand: Some(terrain), }; let post = load_post(&pack, &folder, &shaders, &Macros::standard(), &inputs); println!(