From 5dcbe222c94261c7291659a15a06549f46134014 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:00:44 +0100 Subject: [PATCH] Shader packs, clean room 37: shadow settings and the shadow camera The stage files' shadow constants (shadowMapResolution, shadowDistance, shadowDistanceRenderMul, shadowIntervalSize, sunPathRotation, shadowMapFov, shadowNearPlane, shadowFarPlane, shadowHardwareFiltering[0|1] and the shadowcolor0/1 Format, Clear and ClearColor) are read into Config::shadow (spec 6.3, 7.1). The shadow matrices are no longer a placeholder (OQ-6): the camera looks from the shadow light, sits 128 blocks toward it from a point that moves in steps of shadowIntervalSize along the shadow view's own axes, and projects orthographically over shadowDistance each side (or in perspective with shadowMapFov), between shadowNearPlane and shadowFarPlane. sunPathRotation turns the sun and moon's path about the world's X axis: sunPosition, moonPosition, shadowLightPosition and the shadow camera follow it, and so do the sun, moon and stars a pack's gbuffers_skytextured and gbuffers_skybasic draw. Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1, sections 6.3 and 7.1; no other loader's code read. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx/pack_post.rs | 6 +- crates/horizon-client/src/gfx/pack_sky.rs | 10 +- .../horizon-client/src/gfx/pack_uniforms.rs | 121 +++++++++++++--- crates/horizon-shaders/src/config.rs | 136 ++++++++++++++++++ crates/horizon-shaders/src/lib.rs | 2 +- 5 files changed, 252 insertions(+), 23 deletions(-) diff --git a/crates/horizon-client/src/gfx/pack_post.rs b/crates/horizon-client/src/gfx/pack_post.rs index 57c24b1ed..2be557c17 100644 --- a/crates/horizon-client/src/gfx/pack_post.rs +++ b/crates/horizon-client/src/gfx/pack_post.rs @@ -879,6 +879,7 @@ impl PackPost { }); let mut notes = post.notes; notes.extend(post.config.notes); + let shadow_config = post.config.shadow.clone(); let mut custom = post.custom; let custom_names: Vec = custom.uniforms().map(|u| u.0.to_owned()).collect(); // A first run finds the names neither the frame nor the pack defines. @@ -1279,6 +1280,7 @@ impl PackPost { uniforms: { let mut u = FrameUniforms::default(); u.atlas = world.atlas.map_or([0; 2], |a| a.1); + u.shadow = shadow_config; u }, } @@ -1495,7 +1497,9 @@ impl PackPost { let Some(mut sky) = self.sky.take() else { return; }; - let parts = sky.geometry.prepare(queue, frame); + let parts = sky + .geometry + .prepare(queue, frame, self.uniforms.shadow.sun_path_rotation); let mut groups = [None, None]; for (i, pass) in [&mut sky.basic, &mut sky.textured].into_iter().enumerate() { if let Some(pass) = pass { diff --git a/crates/horizon-client/src/gfx/pack_sky.rs b/crates/horizon-client/src/gfx/pack_sky.rs index 694f3096f..4823da4a4 100644 --- a/crates/horizon-client/src/gfx/pack_sky.rs +++ b/crates/horizon-client/src/gfx/pack_sky.rs @@ -255,8 +255,10 @@ impl PackSky { /// Writes the frame's sky and returns its draws in vanilla's order: the disc, the sunset /// fan while the sun is near the horizon, the sun and the moon, the stars and, with the - /// camera low, the void. - pub fn prepare(&self, queue: &wgpu::Queue, frame: &super::Frame) -> Vec { + /// camera low, the void. `tilt` is the pack's `sunPathRotation` (degrees): the sun, moon + /// and stars turn with it (7.1). + pub fn prepare(&self, queue: &wgpu::Queue, frame: &super::Frame, tilt: f32) -> Vec { + let turn = super::pack_uniforms::tilt_matrix(tilt); 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 }; @@ -264,7 +266,7 @@ impl PackSky { 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(), + stars: (turn * 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], @@ -281,7 +283,7 @@ impl PackSky { .clone() .flat_map(|q| [0, 1, 2, 0, 2, 3].map(|i| q[i])) .map(|v| Celestial { - pos: v.pos, + pos: turn.transform_vector3(v.pos.into()).into(), uv: v.uv, color: v.color, }) diff --git a/crates/horizon-client/src/gfx/pack_uniforms.rs b/crates/horizon-client/src/gfx/pack_uniforms.rs index efa8d2e2c..d1a85a1ba 100644 --- a/crates/horizon-client/src/gfx/pack_uniforms.rs +++ b/crates/horizon-client/src/gfx/pack_uniforms.rs @@ -3,7 +3,8 @@ //! Matrices follow GL's conventions (5.5): `gbufferProjection` maps view depth to clip z in //! [-w, w], and the depth buffers packs read hold GL window depth. -use glam::{Mat4, Vec3, Vec4}; +use glam::{DMat4, DVec3, Mat4, Vec3, Vec4}; +use horizon_shaders::Shadow; use super::Frame; @@ -172,6 +173,8 @@ pub struct FrameUniforms { previous: Option<(Vec3, Mat4, Mat4)>, wetness: f32, eye_smooth: [f32; 2], + /// The pack's shadow settings (7.1). + pub shadow: Shadow, } impl Default for FrameUniforms { @@ -185,14 +188,72 @@ impl Default for FrameUniforms { previous: None, wetness: 0.0, eye_smooth: [0.0; 2], + shadow: Shadow::default(), } } } -/// `(0, 100, 0)` on the frame the sky draws a body on: Y -90°, then X by its angle in degrees. -fn body(angle: f32) -> Vec3 { - (Mat4::from_rotation_y((-90.0f32).to_radians()) * Mat4::from_rotation_x(angle.to_radians())) - .transform_vector3(Vec3::new(0.0, 100.0, 0.0)) +/// `(0, 100, 0)` on the frame the sky draws a body on: Y -90°, then X by its angle in degrees; +/// `sunPathRotation` (`tilt`, degrees) then turns the path about the world's X axis (7.1, OQ-6). +fn body(angle: f32, tilt: f32) -> Vec3 { + (tilt_matrix(tilt) + * Mat4::from_rotation_y((-90.0f32).to_radians()) + * Mat4::from_rotation_x(angle.to_radians())) + .transform_vector3(Vec3::new(0.0, 100.0, 0.0)) +} + +/// `sunPathRotation`'s turn of the sky's bodies: `tilt` degrees about the world's X axis, so a +/// positive angle moves the noon sun toward +Z (south). +pub fn tilt_matrix(tilt: f32) -> Mat4 { + Mat4::from_rotation_x(tilt.to_radians()) +} + +/// The world direction of the shadow light (7.1): the sun by day, the moon by night. +fn shadow_light(frame: &Frame, shadow: &Shadow) -> Vec3 { + let sun_angle = (frame.sky.sun_angle / 360.0 + 0.25).rem_euclid(1.0); + let angle = if sun_angle < 0.5 { + frame.sky.sun_angle + } else { + frame.sky.moon_angle + }; + body(angle, shadow.sun_path_rotation).normalize() +} + +/// Distance from the snapped point to the shadow camera, toward the light: the middle of the +/// default near and far planes (OQ-6). +const SHADOW_EYE: f64 = 128.0; + +/// The shadow camera (7.1; OQ-6, impl-plan.md): its view (player space to shadow view space) +/// and GL projection. The camera looks from the light, world +Z up (+Y when the light is near +/// Z); the point it centres moves in steps of `shadowIntervalSize` along the shadow view's +/// own axes, and it sits `SHADOW_EYE` blocks toward the light from it. Orthographic over +/// `shadowDistance` each side, or perspective with `shadowMapFov`. +pub fn shadow_camera(light: Vec3, camera: DVec3, shadow: &Shadow) -> (Mat4, Mat4) { + let light = light.as_dvec3(); + let up = if light.z.abs() > 0.99 { + DVec3::Y + } else { + DVec3::Z + }; + let rotation = DMat4::look_to_rh(DVec3::ZERO, -light, up); + let at = rotation.transform_vector3(camera); + let step = f64::from(shadow.interval); + let snapped = if step > 0.0 { + (at / step).floor() * step + } else { + at + }; + let offset = at - snapped - DVec3::new(0.0, 0.0, SHADOW_EYE); + let view = (DMat4::from_translation(offset) * rotation).as_mat4(); + let (near, far) = (shadow.near, shadow.far); + let projection = match shadow.fov { + Some(fov) => Mat4::perspective_rh_gl(fov.to_radians(), 1.0, near, far), + None => { + let d = shadow.distance; + Mat4::orthographic_rh_gl(-d, d, -d, d, near, far) + } + }; + (view, projection) } /// `value` moved toward `target` with a half-life of `half_life` seconds over `dt` (5.6). @@ -223,8 +284,9 @@ impl FrameUniforms { let to_view = |v: Vec3| view.transform_vector3(v); let sun_angle = (frame.sky.sun_angle / 360.0 + 0.25).rem_euclid(1.0); let day = sun_angle < 0.5; - let sun = to_view(body(frame.sky.sun_angle)); - let moon = to_view(body(frame.sky.moon_angle)); + let tilt = self.shadow.sun_path_rotation; + let sun = to_view(body(frame.sky.sun_angle, tilt)); + let moon = to_view(body(frame.sky.moon_angle, tilt)); // Half-lives are given in ticks (7.2); smoothing runs per frame in seconds (OQ-26). let half_life = if inputs.rain > self.wetness { 600.0 @@ -250,14 +312,8 @@ impl FrameUniforms { } None => (frame.sky.fog_color, frame.distance * 0.9, frame.distance), }; - // The shadow camera (OQ-6, impl-plan.md): orthographic, `shadowDistance` (160) blocks - // each side, 100 blocks from the player toward the shadow light, world +z up. - let light = view - .inverse() - .transform_vector3(if day { sun } else { moon }) - .normalize(); - let shadow_view = Mat4::look_at_rh(light * 100.0, Vec3::ZERO, Vec3::Z); - let shadow_projection = Mat4::orthographic_rh_gl(-160.0, 160.0, -160.0, 160.0, 0.05, 256.0); + let light = shadow_light(frame, &self.shadow); + let (shadow_view, shadow_projection) = shadow_camera(light, frame.camera, &self.shadow); let day_time = inputs.day_time.rem_euclid(24000) as i32; let world_day = inputs.day_time.div_euclid(24000); let seconds = (now - self.start).as_secs_f32() % 3600.0; @@ -413,7 +469,38 @@ mod tests { #[test] fn noon_is_straight_up_and_the_sun_sets_in_the_west() { - assert!(body(0.0).abs_diff_eq(Vec3::new(0.0, 100.0, 0.0), 1e-3)); - assert!(body(90.0).abs_diff_eq(Vec3::new(-100.0, 0.0, 0.0), 1e-3)); + assert!(body(0.0, 0.0).abs_diff_eq(Vec3::new(0.0, 100.0, 0.0), 1e-3)); + assert!(body(90.0, 0.0).abs_diff_eq(Vec3::new(-100.0, 0.0, 0.0), 1e-3)); + // sunPathRotation tilts noon toward +Z and leaves sunset on the horizon. + assert!(body(0.0, 30.0).abs_diff_eq(Vec3::new(0.0, 86.60254, 50.0), 1e-3)); + assert!(body(90.0, 30.0).abs_diff_eq(Vec3::new(-100.0, 0.0, 0.0), 1e-3)); + } + + #[test] + fn the_shadow_camera_looks_down_from_the_light_in_steps() { + let shadow = Shadow::default(); + let mut camera = DVec3::new(1000.3, 70.0, -20.7); + // Noon: the light is straight up. + let (view, projection) = shadow_camera(Vec3::Y, camera, &shadow); + let at = |p: Vec3| view.transform_point3(p); + // Straight down: a block below the player is farther from the light. + assert!(at(Vec3::new(0.0, -1.0, 0.0)).z < at(Vec3::ZERO).z); + // The player is less than a step from the centre, 128 blocks from the light. + let centre = at(Vec3::ZERO); + assert!(centre.x.abs() <= 2.0 && centre.y.abs() <= 2.0, "{centre}"); + assert!((centre.z + 128.0).abs() < 1e-3, "{centre}"); + // Moving within a step keeps the world where it was in the map. + camera.x = 1000.6; + let (moved, _) = shadow_camera(Vec3::Y, camera, &shadow); + let world = Vec3::new(5.0, -3.0, 9.0); + let shift = Vec3::new(0.3, 0.0, 0.0); + assert!( + moved + .transform_point3(world - shift) + .abs_diff_eq(at(world), 1e-3) + ); + // shadowDistance blocks reach the map's edge. + let edge = projection.project_point3(Vec3::new(160.0, 0.0, -128.0)); + assert!((edge.x.abs() - 1.0).abs() < 1e-4, "{edge}"); } } diff --git a/crates/horizon-shaders/src/config.rs b/crates/horizon-shaders/src/config.rs index 0f21e4900..042840354 100644 --- a/crates/horizon-shaders/src/config.rs +++ b/crates/horizon-shaders/src/config.rs @@ -118,9 +118,55 @@ impl Default for Buffer { } } +/// The shadow map's settings (6.3, 7.1), from `const` lines of the stage files. +#[derive(Clone, Debug, PartialEq)] +pub struct Shadow { + /// `shadowMapResolution`: the map's side in pixels. + pub resolution: u32, + /// `shadowDistance`: half the side of the area the map covers, in blocks. + pub distance: f32, + /// `shadowDistanceRenderMul`: when > 0, geometry beyond `distance × mul` is not drawn. + pub render_mul: f32, + /// `shadowIntervalSize`: the shadow camera moves in steps of this many blocks (0: none). + pub interval: f32, + /// `sunPathRotation`, degrees. + pub sun_path_rotation: f32, + /// `shadowMapFov`: a perspective projection of this many degrees instead of orthographic. + pub fov: Option, + /// `shadowNearPlane`, `shadowFarPlane`. + pub near: f32, + pub far: f32, + /// `shadowHardwareFiltering(0|1)`: shadowtex0/1 sampled with depth comparison. + pub hardware_filtering: [bool; 2], + /// `shadowcolor0/1`: format, cleared every frame, clear colour (default white). + pub colors: [Buffer; 2], +} + +impl Default for Shadow { + fn default() -> Self { + let white = Buffer { + clear_color: Some([1.0; 4]), + ..Buffer::default() + }; + Self { + resolution: 1024, + distance: 160.0, + render_mul: -1.0, + interval: 2.0, + sun_path_rotation: 0.0, + fov: None, + near: 0.05, + far: 256.0, + hardware_filtering: [false; 2], + colors: [white.clone(), white], + } + } +} + #[derive(Clone, Debug, PartialEq)] pub struct Config { pub buffers: [Buffer; BUFFERS], + pub shadow: Shadow, /// Conflicting or unreadable settings, as `file:line: message`. pub notes: Vec, format_set: [bool; BUFFERS], @@ -133,6 +179,7 @@ impl Default for Config { fn default() -> Self { Self { buffers: std::array::from_fn(|_| Buffer::default()), + shadow: Shadow::default(), notes: Vec::new(), format_set: [false; BUFFERS], seen: Vec::new(), @@ -197,6 +244,9 @@ impl Config { } fn constant(&mut self, place: &str, ty: &str, name: &str, value: &str) { + if self.shadow_constant(ty, name, value) { + return; + } let settings = [ ("Format", "int"), ("ClearColor", "vec4"), @@ -243,6 +293,70 @@ impl Config { } } +impl Config { + /// A shadow setting of 6.3 or 7.1; true when `name` is one (read or not). + fn shadow_constant(&mut self, ty: &str, name: &str, value: &str) -> bool { + let s = &mut self.shadow; + let float = |v: &mut f32| { + if let Some(n) = number(value) { + *v = n; + } + }; + match name { + "shadowMapResolution" => { + if let Some(n) = number(value).filter(|n| *n >= 1.0) { + s.resolution = (n as u32).min(16384); + } + } + "shadowDistance" => float(&mut s.distance), + "shadowDistanceRenderMul" => float(&mut s.render_mul), + "shadowIntervalSize" => float(&mut s.interval), + "sunPathRotation" => float(&mut s.sun_path_rotation), + "shadowNearPlane" => float(&mut s.near), + "shadowFarPlane" => float(&mut s.far), + "shadowMapFov" => s.fov = number(value).filter(|f| *f > 0.0), + "shadowHardwareFiltering" => { + if let Some(b) = boolean(value) { + s.hardware_filtering = [b; 2]; + } + } + "shadowHardwareFiltering0" | "shadowHardwareFiltering1" => { + if let Some(b) = boolean(value) { + s.hardware_filtering[usize::from(name.ends_with('1'))] = b; + } + } + _ => { + let color = ["shadowcolor0", "shadowcolor1", "shadowcolor"] + .iter() + .find_map(|b| Some((b, name.strip_prefix(b)?))); + let Some((buffer, setting)) = color else { + return false; + }; + let b = &mut s.colors[usize::from(buffer.ends_with('1'))]; + match (setting, ty) { + ("Format", "int") => { + if let Some(f) = Format::parse(value) { + b.format = f; + } + } + ("Clear", "bool") => { + if let Some(v) = boolean(value) { + b.clear = v; + } + } + ("ClearColor", "vec4") => { + if let Some(c) = vec4(value) { + b.clear_color = Some(c); + } + } + _ => return false, + } + } + } + true + } +} + /// The buffers a fragment shader writes, from the last `DRAWBUFFERS` or `RENDERTARGETS` comment /// of its live code, or `None` without one (then it writes buffers 0 to 7). 6.1.4. pub fn draw_buffers(pp: &Preprocessed) -> Option> { @@ -402,6 +516,28 @@ mod tests { assert!(config.notes.is_empty(), "{:?}", config.notes); } + #[test] + fn shadow_settings() { + let mut c = Config::default(); + c.read(&stage( + "const int shadowMapResolution = 2048;\nconst float shadowDistance = 128.0f;\n\ + const float sunPathRotation = -40.0;\nconst bool shadowHardwareFiltering = true;\n\ + /* const int shadowcolor1Format = RGBA16F; */\nconst bool shadowcolor0Clear = false;\n", + )); + let s = c.finish().shadow; + assert_eq!( + (s.resolution, s.distance, s.sun_path_rotation), + (2048, 128.0, -40.0) + ); + assert_eq!( + (s.interval, s.fov, s.hardware_filtering), + (2.0, None, [true; 2]) + ); + assert!(!s.colors[0].clear && s.colors[1].clear); + assert_eq!(s.colors[1].format, Format::parse("RGBA16F").unwrap()); + assert_eq!(s.colors[1].clear_color, Some([1.0; 4])); + } + #[test] fn no_directive_and_conflicts() { let pp = stage("void main() {}\n"); diff --git a/crates/horizon-shaders/src/lib.rs b/crates/horizon-shaders/src/lib.rs index 426ee5b35..9411f506c 100644 --- a/crates/horizon-shaders/src/lib.rs +++ b/crates/horizon-shaders/src/lib.rs @@ -30,7 +30,7 @@ mod translate; pub use biomes::{category as biome_category, precipitation as biome_precipitation}; pub use block_ids::BlockIds; pub use condition::eval_condition; -pub use config::{BUFFERS, Buffer, Config, Format, Kind, buffer_index, draw_buffers}; +pub use config::{BUFFERS, Buffer, Config, Format, Kind, Shadow, buffer_index, draw_buffers}; pub use custom::{Custom, Val}; pub use discover::{Found, discover}; pub use lang::Lang;