From 17f0029d08f63ed2931f7af09cdf55f937a1e985 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:04:01 -0400 Subject: [PATCH] Fix vertical camera flip, breaking crack blending and cloud face culling --- .../horizon-client/examples/cloud_fixture.rs | 34 +++ crates/horizon-client/src/camera.rs | 28 +++ crates/horizon-client/src/clouds.rs | 81 +++++++ crates/horizon-client/src/entity.wgsl | 4 +- crates/horizon-client/src/game.rs | 143 ++++++----- crates/horizon-client/src/gfx.rs | 225 +++++++++++++----- crates/horizon-client/src/lib.rs | 1 + .../parity/VanillaCloudRenderOracle.java | 52 ++++ tools/test_cloud_render_parity.py | 31 +++ 9 files changed, 458 insertions(+), 141 deletions(-) create mode 100644 crates/horizon-client/examples/cloud_fixture.rs create mode 100644 crates/horizon-client/src/clouds.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCloudRenderOracle.java create mode 100644 tools/test_cloud_render_parity.py diff --git a/crates/horizon-client/examples/cloud_fixture.rs b/crates/horizon-client/examples/cloud_fixture.rs new file mode 100644 index 000000000..7c05f00af --- /dev/null +++ b/crates/horizon-client/examples/cloud_fixture.rs @@ -0,0 +1,34 @@ +//! CloudRenderer face selection and mesh traversal, without a GPU. +use horizon_client::clouds; +use std::{fmt::Write, fs}; +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let mut output = String::new(); + for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() { + let values: Vec = line + .split_whitespace() + .map(|v| v.parse().unwrap()) + .collect(); + let [kind, x, z, bottom, neighbors] = values.as_slice() else { + panic!("invalid case") + }; + write!(output, "{case}")?; + let mut cell = |x, z, neighbors| { + let empty = std::array::from_fn(|i| neighbors & (1 << i) != 0); + for (direction, inside) in clouds::faces(clouds::face_mask(x, z, *bottom as f32, empty)) + { + write!(output, " {x},{z},{direction},{}", u8::from(inside)).unwrap(); + } + }; + if *kind == 0 { + cell(*x, *z, *neighbors); + } else { + for (x, z) in clouds::cells(*x) { + cell(x, z, 0); + } + } + output.push_str("\n"); + } + fs::write(&args[2], output)?; + Ok(()) +} diff --git a/crates/horizon-client/src/camera.rs b/crates/horizon-client/src/camera.rs index 2fe6ae95e..f74f083cd 100644 --- a/crates/horizon-client/src/camera.rs +++ b/crates/horizon-client/src/camera.rs @@ -288,6 +288,13 @@ pub mod joml { } use joml::{Mat4, Quat}; +/// Camera-relative world view used by terrain, sky and the first-person hand. +pub fn view_matrix(yaw: f32, pitch: f32) -> glam::Mat4 { + // Vanilla uses the conjugate of Camera.rotation, not a world-up look-at. + let q = Quat::rotation_yxz(PI - yaw * DEG_TO_RAD, -pitch * DEG_TO_RAD, 0.0); + glam::Mat4::from_quat(glam::Quat::from_xyzw(-q.x, -q.y, -q.z, q.w)) +} + /// `CameraType`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum CameraType { @@ -763,6 +770,27 @@ pub fn bob_matrix(state: &BobState, damage_tilt_strength: f64, bob_view_option: mod tests { use super::*; #[test] + fn view_keeps_yaw_at_vertical_pitch_limits() { + for yaw in [0.0, 45.0, 90.0, 180.0, -90.0, 360.0] { + for pitch in [-90.0, -89.999, 0.0, 89.999, 90.0] { + let view = view_matrix(yaw, pitch); + let mut camera = Camera::default(); + camera.set_rotation(yaw, pitch); + for (world, expected) in [ + (camera.forwards, -glam::Vec3::Z), + (camera.up, glam::Vec3::Y), + (camera.left, -glam::Vec3::X), + ] { + let got = view.transform_vector3(glam::Vec3::from(world)); + assert!( + (got - expected).length() < 1e-5, + "yaw={yaw}, pitch={pitch}: {got:?} != {expected:?}" + ); + } + } + } + } + #[test] fn camera_eases_eye_height_and_fov() { let mut camera = Camera::default(); camera.tick(Some(1.62), 1.0); diff --git a/crates/horizon-client/src/clouds.rs b/crates/horizon-client/src/clouds.rs new file mode 100644 index 000000000..161edb168 --- /dev/null +++ b/crates/horizon-client/src/clouds.rs @@ -0,0 +1,81 @@ +//! Fancy cloud face selection (`CloudRenderer.buildExtrudedCell`). +/// Direction order is DOWN, UP, NORTH, SOUTH, WEST, EAST; inward faces use bits 6..12. +pub fn face_mask(x: i32, z: i32, bottom: f32, empty: [bool; 4]) -> u16 { + let mut mask = 0; + if bottom <= 0.0 { + mask |= 1 << 1; + } + if bottom + 4.0 >= 0.0 { + mask |= 1; + } + for (i, visible) in [z > 0, z < 0, x > 0, x < 0].into_iter().enumerate() { + if empty[i] && visible { + mask |= 1 << (i + 2); + } + } + if x.abs() <= 1 && z.abs() <= 1 { + mask |= 63 << 6; + } + mask +} + +/// Exterior faces first, then reversed interior faces, in vanilla emission order. +pub fn faces(mask: u16) -> impl Iterator { + [1, 0, 2, 3, 4, 5] + .into_iter() + .filter(move |d| mask & (1 << d) != 0) + .map(|d| (d, false)) + .chain( + (0..6) + .filter(move |d| mask & (1 << (d + 6)) != 0) + .map(|d| (d, true)), + ) +} + +/// CloudRenderer builds cells in expanding Manhattan rings, nearest first. +pub fn cells(radius: i32) -> impl Iterator { + (0..=2 * radius).flat_map(move |ring| { + (-ring..=ring).flat_map(move |x| { + let z = ring - x.abs(); + let visible = z <= radius && x * x + z * z <= radius * radius; + (visible && z != 0) + .then_some((x, -z)) + .into_iter() + .chain(visible.then_some((x, z))) + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn cells_are_nearest_first_and_unique() { + let cells: Vec<_> = cells(2).collect(); + assert_eq!(cells[0], (0, 0)); + assert_eq!(cells.len(), 13); + assert!( + cells + .windows(2) + .all(|w| w[0].0.abs() + w[0].1.abs() <= w[1].0.abs() + w[1].1.abs()) + ); + assert_eq!( + cells.iter().collect::>().len(), + cells.len() + ); + } + #[test] + fn only_camera_facing_exterior_faces() { + assert_eq!(face_mask(2, 2, 10.0, [true; 4]), 1 | 4 | 16); + assert_eq!(face_mask(-2, -2, -5.0, [true; 4]), 2 | 8 | 32); + assert_eq!(face_mask(2, 2, 0.0, [false; 4]), 3); + } + #[test] + fn connected_cells_have_no_exterior_walls() { + assert_eq!(face_mask(2, 2, 10.0, [false; 4]), 1); + } + #[test] + fn nearby_cells_keep_inward_faces_for_camera_inside_clouds() { + assert_eq!(face_mask(0, 0, 0.0, [false; 4]), 3 | (63 << 6)); + } +} diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 8a8a598f7..b15d34211 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -43,8 +43,8 @@ struct Out { let l = vec2(f32(light.y), f32(light.x)); let lm = textureSampleLevel(lightmap, lightmap_sampler, clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0); - // overlay 2: celestial bodies, 4: clouds; both use their vertex colour unlit. - var c = select(color * lm, color, overlay == 2u || overlay == 4u || overlay == 6u); + // Celestial bodies, clouds, beacon beams and breaking cracks are unlit. + var c = select(color * lm, color, overlay == 2u || overlay == 4u || overlay == 6u || overlay == 11u); // Overlay 6 (beacon beams): the light bytes carry the sprite's v range. out.wrap = vec2(f32(light.x | (light.y << 8u)), f32(light.z | (light.w << 8u))) / 65535.0; // Hurt overlay (OverlayTexture red tint). diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7f02bf53b..1ff8942d7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4606,14 +4606,7 @@ impl Game<'_> { f64::from(m.pos[2]), ) - camera) .as_vec3(); - let e = 0.002; - let corner = |x: f32, y: f32, z: f32| { - o + glam::Vec3::new( - x * (1.0 + 2.0 * e) - e, - y * (1.0 + 2.0 * e) - e, - z * (1.0 + 2.0 * e) - e, - ) - }; + let corner = |x: f32, y: f32, z: f32| o + glam::Vec3::new(x, y, z); let faces = [ [ corner(0., 1., 0.), @@ -4653,15 +4646,16 @@ impl Game<'_> { ], ]; for f in faces { - for (v, uv) in - f.iter() - .zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]) + for (v, uv) in f + .iter() + .zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]) + .rev() { out.push(Vertex { pos: v.to_array(), uv, - layer: 0, - color: 0xB4FF_FFFF, + layer: 11, + color: 0xFFFF_FFFF, light: (15 * 16) | ((15 * 16) << 8), }); } @@ -5079,69 +5073,74 @@ impl Game<'_> { let z_in = (cloud_z - cell_z as f64 * 12.0) as f32; let bottom = (cloud_height - camera.y) as f32; let filled = |cx: i64, cz: i64| cells[(cz.rem_euclid(h) * w + cx.rem_euclid(w)) as usize]; - let radius = (self.streaming.radius * 16 / 12 + 1) as i64; + let radius = (self.streaming.radius * 16 + 11) / 12; let c = sky.cloud_color; let color = |shade: f32| { let ch = |v: f32| ((v * shade).clamp(0.0, 1.0) * 255.0) as u32; ch(c[3].clamp(0.0, 1.0)) << 24 | ch(c[2]) << 16 | ch(c[1]) << 8 | ch(c[0]) }; let light = 240 | 240 << 8; - for dz in -radius..=radius { - for dx in -radius..=radius { - if dx * dx + dz * dz > radius * radius { - continue; + for (dx, dz) in horizon_client::clouds::cells(radius) { + let (dx, dz) = (i64::from(dx), i64::from(dz)); + let (cx, cz) = (cell_x + dx, cell_z + dz); + if !filled(cx, cz) { + continue; + } + let x0 = dx as f32 * 12.0 - x_in; + let z0 = dz as f32 * 12.0 - z_in; + let (x1, z1, y0, y1) = (x0 + 12.0, z0 + 12.0, bottom, bottom + 4.0); + let mut quad = |p: [[f32; 3]; 4], shade: f32| { + for v in p { + // Overlay 4: clouds (unlit, faded by the cloud fog end). + out.push(Vertex { + pos: v, + uv, + layer: 4, + color: color(shade), + light, + }); } - let (cx, cz) = (cell_x + dx, cell_z + dz); - if !filled(cx, cz) { - continue; - } - let x0 = dx as f32 * 12.0 - x_in; - let z0 = dz as f32 * 12.0 - z_in; - let (x1, z1, y0, y1) = (x0 + 12.0, z0 + 12.0, bottom, bottom + 4.0); - let mut quad = |p: [[f32; 3]; 4], shade: f32| { - for v in p { - // Overlay 4: clouds (unlit, faded by the cloud fog end). - out.push(Vertex { - pos: v, - uv, - layer: 4, - color: color(shade), - light, - }); - } - }; - quad( - [[x0, y1, z0], [x0, y1, z1], [x1, y1, z1], [x1, y1, z0]], - 1.0, - ); - quad( + }; + let faces = [ + ( [[x1, y0, z0], [x1, y0, z1], [x0, y0, z1], [x0, y0, z0]], 0.7, - ); - if !filled(cx, cz - 1) { - quad( - [[x0, y0, z0], [x0, y1, z0], [x1, y1, z0], [x1, y0, z0]], - 0.8, - ); - } - if !filled(cx, cz + 1) { - quad( - [[x1, y0, z1], [x1, y1, z1], [x0, y1, z1], [x0, y0, z1]], - 0.8, - ); - } - if !filled(cx - 1, cz) { - quad( - [[x0, y0, z1], [x0, y1, z1], [x0, y1, z0], [x0, y0, z0]], - 0.9, - ); - } - if !filled(cx + 1, cz) { - quad( - [[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]], - 0.9, - ); - } + ), + ( + [[x0, y1, z0], [x0, y1, z1], [x1, y1, z1], [x1, y1, z0]], + 1.0, + ), + ( + [[x0, y0, z0], [x0, y1, z0], [x1, y1, z0], [x1, y0, z0]], + 0.8, + ), + ( + [[x1, y0, z1], [x1, y1, z1], [x0, y1, z1], [x0, y0, z1]], + 0.8, + ), + ( + [[x0, y0, z1], [x0, y1, z1], [x0, y1, z0], [x0, y0, z0]], + 0.9, + ), + ( + [[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]], + 0.9, + ), + ]; + let mask = horizon_client::clouds::face_mask( + dx as i32, + dz as i32, + bottom, + [ + !filled(cx, cz - 1), + !filled(cx, cz + 1), + !filled(cx - 1, cz), + !filled(cx + 1, cz), + ], + ); + for (direction, inside) in horizon_client::clouds::faces(mask) { + let (p, shade) = faces[usize::from(direction)]; + quad(if inside { [p[3], p[2], p[1], p[0]] } else { p }, shade); } } } @@ -6490,13 +6489,7 @@ impl Game<'_> { 0.0 }; let inverse_height = 1.0 - self.heights.interpolated(a)[0]; - let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians()); - let forward = glam::Vec3::new( - -yaw.sin() * pitch.cos(), - -pitch.sin(), - yaw.cos() * pitch.cos(), - ); - let view = glam::Mat4::look_to_rh(glam::Vec3::ZERO, forward, glam::Vec3::Y); + let view = horizon_client::camera::view_matrix(self.yaw, self.pitch); let to_world = view.inverse(); let eye = self.eye_position().unwrap_or_default(); let light = self.world.light( @@ -8433,7 +8426,7 @@ pub fn run() -> Result<()> { ( w, h, - px.as_chunks::<4>().0.iter().map(|p| p[3] > 0).collect(), + px.as_chunks::<4>().0.iter().map(|p| p[3] >= 10).collect(), ) }) .unwrap_or((1, 1, vec![false])), diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 6aa0ae406..1953f3734 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -13,6 +13,42 @@ use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Instant}; use wgpu::util::DeviceExt; use winit::window::Window; +// RenderPipelines.CRUMBLING: dst * src + src * dst, alpha replaced. +const CRUMBLING_BLEND: wgpu::BlendState = wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Dst, + dst_factor: wgpu::BlendFactor::Src, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent::REPLACE, +}; + +// Separate special materials without changing entity order or their overlays. +fn batch_entities( + entities: &[Vertex], + additive: &[Vertex], + hand: &[Vertex], +) -> (Vec, [u32; 3]) { + let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len()); + let mut counts = [0u32; 3]; + for (i, layer) in [0, 11, 4].into_iter().enumerate() { + for quad in entities.as_chunks::<4>().0 { + let material = match quad[0].layer { + 11 => 11, + 4 => 4, + _ => 0, + }; + if material == layer { + combined.extend_from_slice(quad); + counts[i] += 1; + } + } + } + combined.extend_from_slice(additive); + combined.extend_from_slice(hand); + (combined, counts) +} + mod arena; mod occlusion; mod timing; @@ -153,6 +189,8 @@ pub struct Renderer { dark_disc: wgpu::RenderPipeline, lines: wgpu::RenderPipeline, entity_pipeline: wgpu::RenderPipeline, + crumbling_pipeline: wgpu::RenderPipeline, + cloud_pipeline: wgpu::RenderPipeline, additive_pipeline: wgpu::RenderPipeline, celestial_pipeline: wgpu::RenderPipeline, celestial_buffer: wgpu::Buffer, @@ -808,40 +846,62 @@ impl Renderer { step_mode: wgpu::VertexStepMode::Vertex, attributes: &vertex_attributes, })]; - let entity_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("Entities"), - layout: Some(&entity_layout), - vertex: wgpu::VertexState { - module: &entity_shader, - entry_point: Some("vs_entity"), - compilation_options: Default::default(), - buffers: &entity_vertex, + let entity_pipeline = |label, cull_mode, depth_write, bias, blend| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&entity_layout), + vertex: wgpu::VertexState { + module: &entity_shader, + entry_point: Some("vs_entity"), + compilation_options: Default::default(), + buffers: &entity_vertex, + }, + primitive: wgpu::PrimitiveState { + cull_mode, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(depth_write), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: Default::default(), + bias, + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &entity_shader, + entry_point: Some("fs_entity"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: config.format.remove_srgb_suffix(), + blend: Some(blend), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }; + let crumbling_pipeline = entity_pipeline( + "Breaking cracks", + Some(wgpu::Face::Back), + false, + wgpu::DepthBiasState { + constant: -10, + slope_scale: -1.0, + clamp: 0.0, }, - primitive: wgpu::PrimitiveState { - cull_mode: None, - ..Default::default() - }, - depth_stencil: Some(wgpu::DepthStencilState { - format: wgpu::TextureFormat::Depth32Float, - depth_write_enabled: Some(true), - depth_compare: Some(wgpu::CompareFunction::LessEqual), - stencil: Default::default(), - bias: Default::default(), - }), - multisample: Default::default(), - fragment: Some(wgpu::FragmentState { - module: &entity_shader, - entry_point: Some("fs_entity"), - compilation_options: Default::default(), - targets: &[Some(wgpu::ColorTargetState { - format: config.format.remove_srgb_suffix(), - blend: Some(alpha_blend), - write_mask: wgpu::ColorWrites::ALL, - })], - }), - multiview_mask: None, - cache: None, - }); + CRUMBLING_BLEND, + ); + let cloud_pipeline = entity_pipeline( + "Clouds", + Some(wgpu::Face::Back), + true, + Default::default(), + alpha_blend, + ); + let entity_pipeline = + entity_pipeline("Entities", None, true, Default::default(), alpha_blend); // BlendFunction.LIGHTNING: src alpha, one; no depth writes. let additive_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("Additive entities"), @@ -1204,6 +1264,8 @@ impl Renderer { dark_disc, lines, entity_pipeline, + crumbling_pipeline, + cloud_pipeline, additive_pipeline, celestial_pipeline, celestial_buffer, @@ -1538,17 +1600,10 @@ impl Renderer { } fn projection(&self, fov_degrees: f32, yaw: f32, pitch: f32, bob: Mat4, distance: f32) -> Mat4 { let aspect = self.config.width as f32 / self.config.height.max(1) as f32; - let (yaw, pitch) = (yaw.to_radians(), pitch.to_radians()); - // Minecraft yaw: 0 = +Z (south), 90 = -X (west); pitch positive looks down. - let forward = Vec3::new( - -yaw.sin() * pitch.cos(), - -pitch.sin(), - yaw.cos() * pitch.cos(), - ); let far = (distance * 4.0).max(1024.0); Mat4::perspective_rh(fov_degrees.to_radians(), aspect, 0.05, far) * bob - * Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y) + * crate::camera::view_matrix(yaw, pitch) } fn update_lightmap( &self, @@ -1694,13 +1749,7 @@ impl Renderer { ); let view_proj = self.view_projection(frame); let aspect = self.config.width as f32 / self.config.height.max(1) as f32; - let (yaw, pitch) = (frame.yaw.to_radians(), frame.pitch.to_radians()); - let forward = Vec3::new( - -yaw.sin() * pitch.cos(), - -pitch.sin(), - yaw.cos() * pitch.cos(), - ); - let view = Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y); + let view = crate::camera::view_matrix(frame.yaw, frame.pitch); let sun_angle = frame.sky.sun_angle.to_radians(); // Celestial bodies rotate around the X axis; angle 0 = noon. let sun = Vec3::new(0.0, sun_angle.cos(), -sun_angle.sin()); @@ -1919,17 +1968,10 @@ impl Renderer { self.queue .write_buffer(&self.outline, 0, bytemuck::cast_slice(&lines)); } - let mut combined; - let all_entities: &[Vertex] = if frame.hand.is_empty() && frame.additive.is_empty() { - frame.entities - } else { - combined = - Vec::with_capacity(frame.entities.len() + frame.additive.len() + frame.hand.len()); - combined.extend_from_slice(frame.entities); - combined.extend_from_slice(frame.additive); - combined.extend_from_slice(frame.hand); - &combined - }; + let (combined, [entity_quads, crumbling_quads, cloud_quads]) = + batch_entities(frame.entities, frame.additive, frame.hand); + let world_quads = entity_quads + crumbling_quads + cloud_quads; + let all_entities = &combined; let hand_quads = (frame.hand.len() / 4) as u32; let additive_quads = (frame.additive.len() / 4) as u32; let entity_vertices = all_entities.len() as u64; @@ -1954,9 +1996,8 @@ impl Renderer { bytemuck::cast_slice(&frame.celestial[..celestial_vertices]), ); } - let entity_quads = (entity_vertices / 4) as u32 - hand_quads - additive_quads; - if entity_quads + additive_quads + hand_quads > self.index_quads { - self.index_quads = (entity_quads + additive_quads + hand_quads).next_power_of_two(); + if world_quads + additive_quads + hand_quads > self.index_quads { + self.index_quads = (world_quads + additive_quads + hand_quads).next_power_of_two(); self.indices = Self::quad_indices(&self.device, self.index_quads); } if let Some(b) = &frame.border { @@ -2069,11 +2110,18 @@ impl Renderer { pass.draw_indexed(0..entity_quads * 6, 0, 0..1); pass.set_bind_group(0, &self.group, &[]); } + if crumbling_quads > 0 { + pass.set_pipeline(&self.crumbling_pipeline); + pass.set_bind_group(0, &self.entity_group, &[]); + pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); + pass.draw_indexed(0..crumbling_quads * 6, (entity_quads * 4) as i32, 0..1); + pass.set_bind_group(0, &self.group, &[]); + } if additive_quads > 0 { pass.set_pipeline(&self.additive_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); - pass.draw_indexed(0..additive_quads * 6, (entity_quads * 4) as i32, 0..1); + pass.draw_indexed(0..additive_quads * 6, (world_quads * 4) as i32, 0..1); pass.set_bind_group(0, &self.group, &[]); } if outline_edges > 0 { @@ -2097,6 +2145,16 @@ impl Renderer { } pass.set_bind_group(0, &self.group, &[]); } + if cloud_quads > 0 { + pass.set_pipeline(&self.cloud_pipeline); + pass.set_bind_group(0, &self.entity_group, &[]); + pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); + pass.draw_indexed( + 0..cloud_quads * 6, + ((entity_quads + crumbling_quads) * 4) as i32, + 0..1, + ); + } } if scaled.is_some() { self.world_post.finish(&mut encoder, &view_target); @@ -2130,7 +2188,7 @@ impl Renderer { pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); pass.draw_indexed( 0..hand_quads * 6, - ((entity_quads + additive_quads) * 4) as i32, + ((world_quads + additive_quads) * 4) as i32, 0..1, ); } @@ -2355,3 +2413,42 @@ fn frustum(m: Mat4) -> [Vec4; 6] { ]; planes.map(|p| p / p.truncate().length()) } + +#[cfg(test)] +mod tests { + #[test] + fn special_material_batches_preserve_quad_order_and_offsets() { + let quad = |layer, id| { + [super::Vertex { + pos: [0.0; 3], + uv: [0.0; 2], + layer, + color: 0xffff_ffff, + light: id, + }; 4] + }; + let entities: Vec<_> = [(0, 0), (4, 1), (11, 2), (7, 3), (4, 4)] + .into_iter() + .flat_map(|(layer, id)| quad(layer, id)) + .collect(); + let (vertices, counts) = super::batch_entities(&entities, &quad(3, 5), &quad(0, 6)); + assert_eq!(counts, [2, 1, 2]); + assert_eq!( + vertices + .as_chunks::<4>() + .0 + .iter() + .map(|q| q[0].light) + .collect::>(), + [0, 3, 2, 1, 4, 5, 6] + ); + } + #[test] + fn cracks_multiply_instead_of_covering_the_block() { + let blend = super::CRUMBLING_BLEND; + assert_eq!(blend.color.src_factor, wgpu::BlendFactor::Dst); + assert_eq!(blend.color.dst_factor, wgpu::BlendFactor::Src); + assert_eq!(blend.alpha.src_factor, wgpu::BlendFactor::One); + assert_eq!(blend.alpha.dst_factor, wgpu::BlendFactor::Zero); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index f7900e743..7dba33f7e 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -25,6 +25,7 @@ pub mod cauldron; pub mod chat; pub mod chunk; pub mod clock; +pub mod clouds; pub mod collisions; pub mod command; pub mod command_storage; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCloudRenderOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCloudRenderOracle.java new file mode 100644 index 000000000..c9666e931 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCloudRenderOracle.java @@ -0,0 +1,52 @@ +package dev.horizonlab.parity; + +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import net.minecraft.client.renderer.CloudRenderer; + +/** Invoke the shipped mesh builder without constructing GPU resources. */ +public final class VanillaCloudRenderOracle { + public static void main(String[] args) throws Exception { + Class unsafeClass = Class.forName("sun.misc.Unsafe"); + var field = unsafeClass.getDeclaredField("theUnsafe"); + field.setAccessible(true); + Object renderer = unsafeClass.getMethod("allocateInstance", Class.class) + .invoke(field.get(null), CloudRenderer.class); + Class relative = Class.forName("net.minecraft.client.renderer.CloudRenderer$RelativeCameraPos"); + Object[] positions = relative.getEnumConstants(); // ABOVE, INSIDE, BELOW + var cell = CloudRenderer.class.getDeclaredMethod("buildExtrudedCell", relative, ByteBuffer.class, int.class, int.class, long.class); + var mesh = CloudRenderer.class.getDeclaredMethod("buildMesh", relative, ByteBuffer.class, int.class, int.class, boolean.class, int.class); + cell.setAccessible(true); + mesh.setAccessible(true); + var texture = CloudRenderer.class.getDeclaredField("texture"); + texture.setAccessible(true); + texture.set(renderer, new CloudRenderer.TextureData(new long[]{0xfffffff0L}, 1, 1)); + StringBuilder output = new StringBuilder(); + int index = 0; + for (String line : Files.readAllLines(Path.of(args[0]))) { + String[] parts = line.split(" "); + int kind = Integer.parseInt(parts[0]), x = Integer.parseInt(parts[1]), z = Integer.parseInt(parts[2]); + int bottom = Integer.parseInt(parts[3]), neighbors = Integer.parseInt(parts[4]); + Object pos = positions[bottom > 0 ? 2 : bottom + 4 < 0 ? 0 : 1]; + ByteBuffer buffer = ByteBuffer.allocate(100000); + if (kind == 0) { + long flags = ((neighbors & 1) != 0 ? 8 : 0) | ((neighbors & 2) != 0 ? 2 : 0) + | ((neighbors & 4) != 0 ? 1 : 0) | ((neighbors & 8) != 0 ? 4 : 0); + cell.invoke(renderer, pos, buffer, x, z, 0xfffffff0L | flags); + } else { + mesh.invoke(renderer, pos, buffer, 0, 0, true, x); + } + output.append(index++); + buffer.flip(); + while (buffer.hasRemaining()) { + int cx = buffer.get(), cz = buffer.get(), flags = Byte.toUnsignedInt(buffer.get()); + cx = (cx << 1) | ((flags & 128) >> 7); + cz = (cz << 1) | ((flags & 64) >> 6); + output.append(" ").append(cx).append(",").append(cz).append(",").append(flags & 7).append(",").append((flags & 16) == 0 ? 0 : 1); + } + output.append("\n"); + } + Files.writeString(Path.of(args[1]), output); + } +} diff --git a/tools/test_cloud_render_parity.py b/tools/test_cloud_render_parity.py new file mode 100644 index 000000000..4df4d1668 --- /dev/null +++ b/tools/test_cloud_render_parity.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Compare fancy cloud exterior/interior faces and nearest-first mesh traversal with 26.3.""" +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def make_input(build): + cases = [] + for x in (-130, -2, -1, 0, 1, 2, 130): + for z in (-130, -2, -1, 0, 1, 2, 130): + for bottom in (-5, -4, 0, 1): + for empty in range(16): + cases.append(f"0 {x} {z} {bottom} {empty}\n") + for radius in range(11): + for bottom in (-5, -4, 0, 1): + cases.append(f"1 {radius} 0 {bottom} 0\n") + inputs = build / "inputs.txt" + inputs.write_text("".join(cases)) + return inputs, len(cases) + + +def main(): + harness.differential("cloud-render-parity", "VanillaCloudRenderOracle", "cloud_fixture", make_input, + "Fancy cloud face culling, interior winding flags and mesh traversal; not full framebuffer parity.", + sources=[lab.ROOT / "crates/horizon-client/src/clouds.rs"]) + + +if __name__ == "__main__": + main()