diff --git a/README.md b/README.md index 02efe2016..f4f3094ae 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,8 @@ It runs rustfmt, clippy with warnings denied, the tests of the crates you touche [MIT](LICENSE), for the project's original work only. Dependencies keep their own licences. Minecraft is a trademark of Mojang Synergies AB; Minecraft code and assets belong to Mojang and Microsoft and are covered by the [Minecraft EULA](https://www.minecraft.net/en-us/eula). Decompiled game source and prepared resources stay on your machine and are never published. +Third-party credits and licenses: [Third-party notices](THIRD_PARTY_NOTICES.md). + ## Author Made by [Ludovic Marie](https://lu4ovic.com) ([@ludovic111](https://github.com/ludovic111)). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 000000000..585224f8f --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,31 @@ +# Third-party notices + +## CullLeaves + +The optional leaf and mangrove-root face-culling behavior is adapted from +[CullLeaves](https://github.com/TeamMidnightDust/CullLeaves) by MidnightDust. +Its MIT license is reproduced below. + +```text +MIT License + +Copyright (c) 2020 MidnightDust + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/crates/horizon-client/examples/chunk_bench.rs b/crates/horizon-client/examples/chunk_bench.rs index 0d4a71ce6..6ad2cbd99 100644 --- a/crates/horizon-client/examples/chunk_bench.rs +++ b/crates/horizon-client/examples/chunk_bench.rs @@ -139,6 +139,7 @@ fn main() -> Result<()> { blend_radius: 2, smooth_lighting: true, cutout_leaves: true, + cull_leaves: false, }; let mut best = f64::MAX; let mut quads = 0usize; diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/section_mesh_fixture.rs index 7d4f5547d..a42448794 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/section_mesh_fixture.rs @@ -134,6 +134,7 @@ fn scene( blend_radius, smooth_lighting, cutout_leaves, + cull_leaves: false, }; let section_y = int(&row["section_y"])?; let started = Instant::now(); diff --git a/crates/horizon-client/src/entity_culling.rs b/crates/horizon-client/src/entity_culling.rs new file mode 100644 index 000000000..611eff1af --- /dev/null +++ b/crates/horizon-client/src/entity_culling.rs @@ -0,0 +1,266 @@ +//! Conservative, budgeted occlusion against full opaque block cross-sections. +//! +//! A covered projection rectangle proves that an entire bounding box is hidden. +//! Testing a few rays would miss openings between those rays. +use std::cell::Cell; + +const EPSILON: f64 = 1.0e-5; + +pub struct Culler { + pub camera: [f64; 3], + remaining: Cell, +} + +impl Culler { + pub fn new(camera: [f64; 3], budget: usize) -> Self { + Self { + camera, + remaining: Cell::new(budget), + } + } + + /// Remove only this entity's completed camera-relative mesh when hidden. + pub fn cull_vertices( + &self, + vertices: &mut Vec, + start: usize, + opaque: impl FnMut([i32; 3]) -> bool, + ) -> bool { + if start >= vertices.len() || self.remaining.get() == 0 { + return false; + } + let mut min = [f64::INFINITY; 3]; + let mut max = [f64::NEG_INFINITY; 3]; + for vertex in &vertices[start..] { + for a in 0..3 { + let value = f64::from(vertex.pos[a]) + self.camera[a]; + if !value.is_finite() { + return false; + } + min[a] = min[a].min(value); + max[a] = max[a].max(value); + } + } + // Cover floating-point and rasterization edges as well as the vertices. + if self.occluded(min.map(|v| v - 0.05), max.map(|v| v + 0.05), opaque) { + vertices.truncate(start); + return true; + } + false + } + + /// Returns true only when a complete opaque block plane covers the bounds. + /// Unknown blocks, invalid bounds and an exhausted lookup budget stay visible. + pub fn occluded( + &self, + min: [f64; 3], + max: [f64; 3], + mut opaque: impl FnMut([i32; 3]) -> bool, + ) -> bool { + if (0..3).any(|a| { + !self.camera[a].is_finite() + || !min[a].is_finite() + || !max[a].is_finite() + || min[a] > max[a] + }) { + return false; + } + let mut best = (0, 0.0, 0.0); + for a in 0..3 { + let (gap, sign) = if self.camera[a] < min[a] { + (min[a] - self.camera[a], 1.0) + } else { + (self.camera[a] - max[a], -1.0) + }; + if gap > best.1 { + best = (a, gap, sign); + } + } + let (axis, gap, sign) = best; + if !gap.is_finite() || gap <= EPSILON { + return false; + } + let across = [(axis + 1) % 3, (axis + 2) % 3]; + let Some(mut cell) = floor_cell(self.camera[axis]) else { + return false; + }; + let step = sign as i32; + if (f64::from(cell) + 0.5 - self.camera[axis]) * sign <= EPSILON { + let Some(next) = cell.checked_add(step) else { + return false; + }; + cell = next; + } + loop { + let depth = (f64::from(cell) + 0.5 - self.camera[axis]) * sign; + if depth >= gap - EPSILON || self.remaining.get() == 0 { + return false; + } + let mut lo = [f64::INFINITY; 2]; + let mut hi = [f64::NEG_INFINITY; 2]; + for corner in 0..8 { + let point: [f64; 3] = std::array::from_fn(|a| { + if corner & (1 << a) == 0 { + min[a] + } else { + max[a] + } + }); + let t = depth / ((point[axis] - self.camera[axis]) * sign); + for (i, &a) in across.iter().enumerate() { + let p = self.camera[a] + t * (point[a] - self.camera[a]); + if !p.is_finite() { + return false; + } + lo[i] = lo[i].min(p); + hi[i] = hi[i].max(p); + } + } + let bounds = [ + floor_cell(lo[0] - EPSILON), + floor_cell(hi[0] + EPSILON), + floor_cell(lo[1] - EPSILON), + floor_cell(hi[1] + EPSILON), + ]; + let [Some(x0), Some(x1), Some(y0), Some(y1)] = bounds else { + return false; + }; + let mut pos = [0; 3]; + pos[axis] = cell; + pos[across[0]] = x0 + ((i64::from(x1) - i64::from(x0)) / 2) as i32; + pos[across[1]] = y0 + ((i64::from(y1) - i64::from(y0)) / 2) as i32; + self.remaining.set(self.remaining.get() - 1); + if opaque(pos) { + let area = (i64::from(x1) - i64::from(x0) + 1) + .checked_mul(i64::from(y1) - i64::from(y0) + 1) + .and_then(|n| usize::try_from(n).ok()); + let Some(area) = area.filter(|&n| n <= self.remaining.get()) else { + return false; + }; + // Reserve the worst-case lookups before walking the rectangle. + self.remaining.set(self.remaining.get() - area); + let covered = (x0..=x1).all(|x| { + (y0..=y1).all(|y| { + pos[across[0]] = x; + pos[across[1]] = y; + opaque(pos) + }) + }); + if covered { + return true; + } + } + let Some(next) = cell.checked_add(step) else { + return false; + }; + cell = next; + } + } +} + +fn floor_cell(value: f64) -> Option { + let n = value.floor(); + (n.is_finite() && n >= f64::from(i32::MIN) && n <= f64::from(i32::MAX)).then_some(n as i32) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn completed_mesh_culling_preserves_prior_geometry_and_protruding_parts() { + let vertex = |pos| crate::mesher::Vertex { + pos, + uv: [0.0; 2], + layer: 0, + color: u32::MAX, + light: 0, + normal: [0; 4], + }; + let prior = vertex([0.0; 3]); + let body = [vertex([8.0, -1.0, -1.0]), vertex([10.0, 1.0, 1.0])]; + let wall = |p: [i32; 3]| p[0] == 4 && (-1..=0).contains(&p[1]); + let mut hidden = vec![prior]; + hidden.extend(body); + assert!(Culler::new([0.0; 3], 1_000).cull_vertices(&mut hidden, 1, wall)); + assert_eq!(hidden.len(), 1); + assert_eq!(hidden[0].pos, prior.pos); + + // A held item or animated part beyond the wall keeps the whole model. + let mut exposed = vec![prior]; + exposed.extend(body); + exposed.push(vertex([8.0, 5.0, 0.0])); + let before = exposed.clone(); + assert!(!Culler::new([0.0; 3], 1_000).cull_vertices(&mut exposed, 1, wall)); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&exposed), + bytemuck::cast_slice::<_, u8>(&before) + ); + assert!(!Culler::new([0.0; 3], 0).cull_vertices(&mut exposed, 1, |_| panic!())); + } + + #[test] + fn opaque_walls_hide_bounds_in_all_directions() { + for axis in 0..3 { + for sign in [-1.0, 1.0] { + let mut min = [-2.0; 3]; + let mut max = [2.0; 3]; + min[axis] = if sign > 0.0 { 8.0 } else { -10.0 }; + max[axis] = if sign > 0.0 { 10.0 } else { -8.0 }; + let wall = if sign > 0.0 { 4 } else { -5 }; + assert!(Culler::new([0.0; 3], 1_000).occluded(min, max, |p| p[axis] == wall)); + } + } + } + + #[test] + fn windows_slits_and_partial_walls_stay_visible() { + let min = [8.0, -4.0, -4.0]; + let max = [10.0, 4.0, 4.0]; + for opening in 0..3 { + assert!(!Culler::new([0.0; 3], 1_000).occluded(min, max, |p| { + p[0] == 4 + && match opening { + 0 => !(p[1] == 1 && p[2] == 1), + 1 => p[1] != 1, + _ => p[1] < 0, + } + })); + } + assert!(!Culler::new([0.0; 3], 1_000).occluded(min, max, |_| false)); + } + + #[test] + fn budgets_are_shared_and_exhaustion_fails_open() { + let culler = Culler::new([0.0; 3], 3); + let calls = Cell::new(0); + for _ in 0..2 { + assert!(!culler.occluded([8.0; 3], [10.0; 3], |_| { + calls.set(calls.get() + 1); + false + })); + } + assert_eq!(calls.get(), 3); + assert!(!Culler::new([0.0; 3], 0).occluded([8.0; 3], [10.0; 3], |_| panic!())); + assert!(!Culler::new([0.0; 3], 1).occluded([8.0; 3], [10.0; 3], |_| true)); + } + + #[test] + fn camera_inside_invalid_and_target_crossing_wall_stay_visible() { + let culler = Culler::new([0.0; 3], 1_000); + assert!(!culler.occluded([-1.0; 3], [1.0; 3], |_| panic!())); + assert!(!culler.occluded([f64::NAN; 3], [1.0; 3], |_| panic!())); + assert!(!culler.occluded([2.0; 3], [1.0; 3], |_| panic!())); + assert!(!culler.occluded([4.0, -1.0, -1.0], [8.0, 1.0, 1.0], |p| p[0] == 4)); + assert!(!Culler::new([f64::INFINITY; 3], 1_000).occluded( + [8.0; 3], + [10.0; 3], + |_| panic!() + )); + assert!(!Culler::new([f64::MAX; 3], 1_000).occluded( + [-f64::MAX; 3], + [-1.0; 3], + |_| panic!() + )); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index ed1e6b69a..b4787eb0b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -34,6 +34,7 @@ mod dispenser; mod dragon; mod enchant_effects; mod end; +mod entity_culling; mod events; mod explosion; mod extras; @@ -967,6 +968,7 @@ struct Game<'a> { pending_uploads: Vec<((i32, i32, i32), horizon_client::mesher::SectionMesh)>, /// This frame's view frustum, for culling entities and block entities. view_frustum: Option, + entity_culler: Option, /// A scripted flight from the control socket (`fly`). flight: Option, /// The running agent action from the control socket (game/agent.rs). @@ -5300,6 +5302,7 @@ impl Game<'_> { alpha: f64, mut out: Vec, ) -> Vec { + self.prepare_entity_culling(camera); let fire_yaw = if self.camera_type == perspective::CameraType::ThirdPersonFront { self.yaw + 180.0 } else { @@ -5487,9 +5490,21 @@ impl Game<'_> { v.intersects(o - glam::Vec3::ONE, o + glam::Vec3::splat(2.0)) }) }); - self.res - .block_entity_render - .render(&scene, visible, &mut out); + if self.entity_culler.is_some() { + for block in visible { + let start = out.len(); + self.res + .block_entity_render + .render(&scene, std::iter::once(block), &mut out); + if !off_screen(block.1) { + self.cull_entity_vertices(&mut out, start); + } + } + } else { + self.res + .block_entity_render + .render(&scene, visible, &mut out); + } } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. if let Some(r) = self @@ -6417,6 +6432,7 @@ impl Game<'_> { streaming.biome_blend = self.settings.biome_blend; streaming.smooth_lighting = self.settings.smooth_lighting; streaming.cutout_leaves = self.settings.cutout_leaves; + streaming.cull_leaves = self.settings.horizon.cull_leaves; streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed)); streaming.sky_light = dim != Dim::Nether; streaming.nether_shading = dim == Dim::Nether; @@ -7677,11 +7693,21 @@ impl Game<'_> { // Options.biomeBlendRadius, ambientOcclusion and cutoutLeaves: // LevelExtractor.allChanged when they change. let (s, st) = (&self.settings, &self.streaming); - let remesh = (s.biome_blend, s.smooth_lighting, s.cutout_leaves) - != (st.biome_blend, st.smooth_lighting, st.cutout_leaves); + let remesh = ( + s.biome_blend, + s.smooth_lighting, + s.cutout_leaves, + s.horizon.cull_leaves, + ) != ( + st.biome_blend, + st.smooth_lighting, + st.cutout_leaves, + st.cull_leaves, + ); self.streaming.biome_blend = self.settings.biome_blend; self.streaming.smooth_lighting = self.settings.smooth_lighting; self.streaming.cutout_leaves = self.settings.cutout_leaves; + self.streaming.cull_leaves = self.settings.horizon.cull_leaves; if remesh { self.all_sections_changed(); } @@ -10058,6 +10084,7 @@ pub fn run() -> Result<()> { events: Default::default(), agent: agent::Agent::default(), view_frustum: None, + entity_culler: None, pending_uploads: Vec::new(), frame_graph: Default::default(), extras: Default::default(), diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index fd988b19c..c8be758ab 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -409,6 +409,7 @@ impl Game<'_> { return; }; for a in &self.armor_stands { + let entity_start = out.len(); if a.invisible { continue; } @@ -524,6 +525,7 @@ impl Game<'_> { out, ); } + self.cull_entity_vertices(out, entity_start); } } } diff --git a/crates/horizon-client/src/game/backdrop.rs b/crates/horizon-client/src/game/backdrop.rs index 3fe6959bc..15ca99ba9 100644 --- a/crates/horizon-client/src/game/backdrop.rs +++ b/crates/horizon-client/src/game/backdrop.rs @@ -174,6 +174,7 @@ impl Game<'_> { streaming.biome_blend = self.settings.biome_blend; streaming.smooth_lighting = self.settings.smooth_lighting; streaming.cutout_leaves = self.settings.cutout_leaves; + streaming.cull_leaves = self.settings.horizon.cull_leaves; streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed)); streaming.paused = true; self.streaming = streaming; diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 9a06c6777..40211161d 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -701,6 +701,7 @@ impl Game<'_> { pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let a = alpha as f32; for b in &self.boats { + let entity_start = out.len(); let models = if b.chest { &self.boat_models.chest_models } else { @@ -768,6 +769,7 @@ impl Game<'_> { 0, out, ); + self.cull_entity_vertices(out, entity_start); } } } diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 48a28ebca..98d85e811 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2701,6 +2701,7 @@ impl Game<'_> { let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let scale = f64::from(self.settings.entity_distance); for mob in &self.mobs { + let entity_start = out.len(); let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera; // Entity.shouldRenderAtSqrDistance: 64 times the bounding box's // mean edge, scaled by the entity distance option. @@ -2748,6 +2749,11 @@ impl Game<'_> { out, ); self.mob_block_geometry(mob, camera, alpha, packed, out); + // Glowing outlines and a guardian's beam remain visible independently + // of whether the body is hidden behind terrain. + if !mob.glowing && horizon_client::mobs::guardian::beam(mob, alpha as f32).is_none() { + self.cull_entity_vertices(out, entity_start); + } // GuardianRenderer: the laser to the locked target. if let Some((time, scale)) = horizon_client::mobs::guardian::beam(mob, alpha as f32) && let Some(target) = self.beam_target(mob.ai.target, alpha) diff --git a/crates/horizon-client/src/game/entity_culling.rs b/crates/horizon-client/src/game/entity_culling.rs new file mode 100644 index 000000000..71ab13378 --- /dev/null +++ b/crates/horizon-client/src/game/entity_culling.rs @@ -0,0 +1,51 @@ +//! Entity occlusion affects mesh submission, never entity ticking or interaction. +use super::{Game, Vertex}; +use horizon_client::chunk::MIN_Y; +use horizon_client::{ + blocks::{RenderShape, StateFacts}, + entity_culling::Culler, +}; + +fn opaque(facts: &StateFacts) -> bool { + facts.render_shape == RenderShape::Model + && facts.can_occlude + && facts.solid_render + && facts.full_collision +} + +impl Game<'_> { + pub(super) fn prepare_entity_culling(&mut self, camera: glam::DVec3) { + let at = camera.to_array().map(|v| v.floor() as i32); + self.entity_culler = (self.settings.horizon.entity_culling + // Packs can replace an opaque block's model or texture. + && self.settings.resource_packs.iter().all(|id| id == "vanilla") + && self.player.is_some() + && !self.spectator() + && !opaque(self.res.facts.get(self.world.block(at[0], at[1], at[2])))) + .then(|| Culler::new(camera.to_array(), 8_192)); + } + + /// Use complete generated geometry so equipment, animation and custom + /// models cannot stick out of an assumed collision-sized culling box. + pub(super) fn cull_entity_vertices(&self, vertices: &mut Vec, start: usize) { + if let Some(culler) = &self.entity_culler { + culler.cull_vertices(vertices, start, |pos| { + let state = self.world.block(pos[0], pos[1], pos[2]); + if !opaque(self.res.facts.get(state)) { + return false; + } + let Some(y) = pos[1].checked_sub(MIN_Y) else { + return false; + }; + let section = (pos[0] >> 4, y.div_euclid(16), pos[2] >> 4); + // Newly edited or not-yet-uploaded terrain is not an occluder. + self.renderer + .as_ref() + .is_some_and(|r| r.has_section(section)) + && !self.world.dirty_sections.contains(§ion) + && !self.streaming.is_meshing(section) + && !self.pending_uploads.iter().any(|(key, _)| *key == section) + }); + } + } +} diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index c09f5ad17..26e195d4e 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -305,6 +305,7 @@ impl Game<'_> { let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new(); let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new(); for f in &self.item_frames { + let entity_start = out.len(); let map = f.item.as_ref().and_then(super::maps::map_id); let s = f.step(); // Pose: to the block centre, then X/Y rotation by facing. @@ -371,6 +372,7 @@ impl Game<'_> { ); } } + self.cull_entity_vertices(out, entity_start); if let Some(id) = map { // ItemFrameRenderer: the map fills the face, in 90-degree steps. let depth = if f.invisible { 0.5 } else { 0.4375 }; @@ -400,6 +402,7 @@ impl Game<'_> { } // `extractRenderState`: FIXED, seeded by the frame entity. for (stack, id, m, light) in items { + let entity_start = out.len(); let owner = super::item_draw::owner_at([0.0; 3], 0.0, "minecraft:item_frame"); let state = self.resolve_item( &stack, @@ -413,9 +416,12 @@ impl Game<'_> { horizon_client::block_entity_render::vertex_light(light), out, ); + self.cull_entity_vertices(out, entity_start); } for (id, m, light) in maps { + let entity_start = out.len(); self.map_vertices(id, m, light, out); + self.cull_entity_vertices(out, entity_start); } } } diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index 664455be7..87599042e 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -330,6 +330,7 @@ impl Game<'_> { _ => None, }); for (item, at, partial) in live.chain(taken) { + let entity_start = out.len(); let q = item.position; let pos = glam::DVec3::from_array(at) - camera; if pos.length_squared() > 64.0 * 64.0 { @@ -369,6 +370,7 @@ impl Game<'_> { ) { self.submit_item_world(&state, copy, vertex_light(packed), out); } + self.cull_entity_vertices(out, entity_start); } } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index de7ef6832..9bdbac2e0 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -878,6 +878,7 @@ impl Game<'_> { let atlas = &self.res.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); for m in host.models.values() { + let entity_start = out.len(); let light = self.world.light( m.position.x.floor() as i32, (m.position.y + 1.62).floor() as i32, @@ -895,6 +896,9 @@ impl Game<'_> { out, ); self.held_item_geometry(m, camera, alpha, packed, true, out); + if !m.glowing { + self.cull_entity_vertices(out, entity_start); + } } } diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 06d5466da..fe9008cd7 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1213,6 +1213,7 @@ impl Game<'_> { pub(super) fn cart_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let a = alpha as f32; for c in &self.carts { + let entity_start = out.len(); let Some(model) = self.cart_models.models.get(&c.kind) else { continue; }; @@ -1309,6 +1310,7 @@ impl Game<'_> { let m = base * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); let poses = Poses::new(model); horizon_client::mobs::render::draw(model, m, &poses, uv, 0xFFFF_FFFF, packed, 0, out); + self.cull_entity_vertices(out, entity_start); } } /// The chest inside a chest minecart, drawn by the chest block-entity renderer. diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs index 09d6d4a36..06bb7f6d0 100644 --- a/crates/horizon-client/src/game/paintings.rs +++ b/crates/horizon-client/src/game/paintings.rs @@ -254,6 +254,7 @@ impl Game<'_> { return; }; for p in &self.paintings { + let entity_start = out.len(); let Some(v) = self.painting_variants.get(&p.variant) else { continue; }; @@ -366,6 +367,7 @@ impl Game<'_> { strip, 0.6, ); + self.cull_entity_vertices(out, entity_start); } } } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index d4658dbd0..6b0d046ee 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1590,6 +1590,9 @@ impl Renderer { pub fn section_count(&self) -> usize { self.sections.len() } + pub fn has_section(&self, key: SectionKey) -> bool { + self.sections.contains_key(&key) + } pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) { self.occlusion.set(key, mesh.visibility); if mesh.block_entities.is_empty() { diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index 3a74750a8..f10c6b3b3 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -117,6 +117,10 @@ pub struct Graphics { pub preset: Preset, /// Skip sections hidden behind closed ones (vanilla's occlusion graph). pub cave_culling: bool, + /// Hide shared leaf and mangrove-root faces, reducing foliage density. + pub cull_leaves: bool, + /// Skip drawing entities hidden behind opaque terrain. + pub entity_culling: bool, /// Meshed sections uploaded per frame; 0 uploads all that are ready. pub chunk_updates: u32, /// Section mesh bytes uploaded per frame, in KiB; 0 is unlimited. @@ -149,6 +153,8 @@ impl Default for Graphics { Self { preset: Preset::Custom, cave_culling: true, + cull_leaves: false, + entity_culling: false, chunk_updates: 0, upload_budget_kib: 0, sky: true, @@ -192,6 +198,8 @@ impl Graphics { match key.trim() { "preset" => g.preset = Preset::parse(value), "caveCulling" => g.cave_culling = flag(g.cave_culling), + "cullLeaves" => g.cull_leaves = flag(g.cull_leaves), + "entityCulling" => g.entity_culling = flag(g.entity_culling), "chunkUpdates" => g.chunk_updates = number(g.chunk_updates).min(512), "uploadBudgetKiB" => g.upload_budget_kib = number(g.upload_budget_kib).min(65536), "sky" => g.sky = flag(g.sky), @@ -226,9 +234,11 @@ impl Graphics { } pub fn serialize(&self) -> String { format!( - "preset:{}\ncaveCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\n", + "preset:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\n", self.preset.name(), bool_text(self.cave_culling), + bool_text(self.cull_leaves), + bool_text(self.entity_culling), self.chunk_updates, self.upload_budget_kib, bool_text(self.sky), @@ -321,6 +331,8 @@ mod tests { let g = Graphics { preset: Preset::Balanced, cave_culling: false, + cull_leaves: true, + entity_culling: true, chunk_updates: 12, upload_budget_kib: 4096, sky: false, @@ -340,7 +352,7 @@ mod tests { assert_eq!(Graphics::parse(&g.serialize()), g); assert_eq!(Graphics::parse(""), Graphics::default()); assert_eq!( - Graphics::parse("workers:abc\nsky:maybe\n"), + Graphics::parse("workers:abc\nsky:maybe\ncullLeaves:maybe\nentityCulling:maybe\n"), Graphics::default() ); } diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index 526f04f71..c03041152 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -22,6 +22,8 @@ pub enum Level { pub enum H { Preset, CaveCulling, + CullLeaves, + EntityCulling, ChunkUpdates, UploadBudget, Sky, @@ -117,6 +119,16 @@ pub fn rows(level: Level) -> Vec { None, "Skips terrain hidden behind closed sections. Off costs a lot.", ), + h( + H::CullLeaves, + None, + "Hides shared leaf and mangrove root faces; foliage can look less dense.", + ), + h( + H::EntityCulling, + None, + "Hides models behind opaque blocks. Entities update. Off with custom packs.", + ), h( H::ChunkUpdates, Low, @@ -282,6 +294,8 @@ impl H { match self { H::Preset => labelled("Preset", g.preset.label()), H::CaveCulling => labelled("Cave Culling", on_off(g.cave_culling)), + H::CullLeaves => labelled("Cull Leaves", on_off(g.cull_leaves)), + H::EntityCulling => labelled("Entity Culling", on_off(g.entity_culling)), H::ChunkUpdates => match g.chunk_updates { 0 => labelled("Chunk Updates", "Unlimited"), n => labelled("Chunk Updates", format!("{n} per frame")), @@ -352,6 +366,8 @@ impl H { let g = &mut s.horizon; match self { H::CaveCulling => g.cave_culling = !g.cave_culling, + H::CullLeaves => g.cull_leaves = !g.cull_leaves, + H::EntityCulling => g.entity_culling = !g.entity_culling, H::Sky => g.sky = !g.sky, H::Fog => g.fog = !g.fog, H::Weather => g.weather = !g.weather, @@ -397,6 +413,8 @@ impl Item { let g = &s.horizon; Some(match self { Item::Horizon(H::CaveCulling) => g.cave_culling, + Item::Horizon(H::CullLeaves) => g.cull_leaves, + Item::Horizon(H::EntityCulling) => g.entity_culling, Item::Horizon(H::Sky) => g.sky, Item::Horizon(H::Fog) => g.fog, Item::Horizon(H::Weather) => g.weather, @@ -896,4 +914,88 @@ mod tests { H::UploadBudget.set_slider(&mut s, 0.0); assert_eq!(s.horizon.upload_budget_kib, 0); } + + #[test] + fn cull_leaves_is_opt_in_and_toggles_from_advanced_graphics() { + let mut s = Settings::default(); + let item = Item::Horizon(H::CullLeaves); + assert_eq!(item.switch(&s), Some(false)); + assert_eq!(item.label(&s).plain(), "Cull Leaves: Off"); + for enabled in [false, true] { + s.horizon.cull_leaves = enabled; + for preset in Preset::ALL { + crate::graphics::apply_preset(preset, &mut s); + assert_eq!(s.horizon.cull_leaves, enabled); + } + } + + let mut ui = GraphicsUi::default(); + let size = (480.0, 4000.0); + let (widgets, _, _) = ui.layout(Level::Advanced, size.0, size.1); + let switch = widgets + .iter() + .find(|w| matches!(w.target, Target::Item(i) if i == item)) + .unwrap(); + let point = (switch.x + 1.0, switch.y + 1.0); + for enabled in [false, true] { + s.horizon.preset = Preset::Balanced; + assert_eq!( + ui.click( + Level::Advanced, + &mut s, + point, + size, + [854, 480], + false, + false + ), + vec![Action::ButtonClick, Action::Changed] + ); + assert_eq!(item.switch(&s), Some(enabled)); + assert_eq!(s.horizon.preset, Preset::Custom); + } + assert_eq!(item.label(&s).plain(), "Cull Leaves: On"); + } + + #[test] + fn entity_culling_is_opt_in_and_toggles_from_advanced_graphics() { + let mut s = Settings::default(); + let item = Item::Horizon(H::EntityCulling); + assert_eq!(item.switch(&s), Some(false)); + assert_eq!(item.label(&s).plain(), "Entity Culling: Off"); + for enabled in [false, true] { + s.horizon.entity_culling = enabled; + for preset in Preset::ALL { + crate::graphics::apply_preset(preset, &mut s); + assert_eq!(s.horizon.entity_culling, enabled); + } + } + + let mut ui = GraphicsUi::default(); + let size = (480.0, 4000.0); + let (widgets, _, _) = ui.layout(Level::Advanced, size.0, size.1); + let switch = widgets + .iter() + .find(|w| matches!(w.target, Target::Item(i) if i == item)) + .unwrap(); + let point = (switch.x + 1.0, switch.y + 1.0); + for enabled in [false, true] { + s.horizon.preset = Preset::Balanced; + assert_eq!( + ui.click( + Level::Advanced, + &mut s, + point, + size, + [854, 480], + false, + false + ), + vec![Action::ButtonClick, Action::Changed] + ); + assert_eq!(item.switch(&s), Some(enabled)); + assert_eq!(s.horizon.preset, Preset::Custom); + } + assert_eq!(item.label(&s).plain(), "Entity Culling: On"); + } } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 266bde023..49506b2b3 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -51,6 +51,7 @@ pub mod effects; pub mod enchant; pub mod end_crystal; pub mod entities; +pub mod entity_culling; pub mod entity_nbt; pub mod environment; pub mod extras; diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index 1f0b0b128..cb436a947 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -167,6 +167,8 @@ fn visibility(pad: &Padded, info: &[Info]) -> u64 { result } #[cfg(test)] +mod leaf_culling_tests; +#[cfg(test)] mod visibility_tests; #[derive(Clone, Copy, PartialEq, Eq)] enum Tint { @@ -208,6 +210,7 @@ struct Info { overlay: bool, /// `LeavesBlock`: with opaque leaves the faces between two leaf blocks are skipped. leaves: bool, + mangrove_roots: bool, blocks_flow: bool, ice: bool, sturdy: u8, @@ -368,6 +371,7 @@ impl MeshTables { legacy_solid: s.legacy_solid, overlay: s.has_class("HalfTransparentBlock") || s.has_class("LeavesBlock"), leaves: s.has_class("LeavesBlock"), + mangrove_roots: s.has_class("MangroveRootsBlock"), blocks_flow: assets.blocks_fluid_flow.contains(&*s.name), ice: s.has_class("IceBlock"), sturdy: s.sturdy_full, @@ -596,6 +600,8 @@ pub struct Mesher<'a> { pub smooth_lighting: bool, /// The `cutoutLeaves` option (fancy graphics); off makes leaves opaque. pub cutout_leaves: bool, + /// Cull shared leaf and mangrove-root faces, including transparent leaves. + pub cull_leaves: bool, } impl Mesher<'_> { /// `region[dz][dx]` are the chunks around the meshed column (centre 1,1). @@ -673,19 +679,22 @@ impl Mesher<'_> { for d in Direction::ALL { let [dx, dy, dz] = d.normal(); let neighbor = pad.blocks[pi(x + dx, y + dy, z + dz)]; - visible[d as usize] = self - .visibility - .should_render_face( - BlockStateId(id.into()), - BlockStateId(neighbor.into()), - d, - true, - ) - .unwrap_or(true); - // LeavesBlock.skipRendering with opaque leaves. - if !self.cutout_leaves && state.leaves && info[neighbor as usize].leaves { - visible[d as usize] = false; - } + let other = &info[neighbor as usize]; + // Adapted from CullLeaves (MIT); see THIRD_PARTY_NOTICES.md. + let shared_foliage = (state.leaves + && other.leaves + && (!self.cutout_leaves || self.cull_leaves)) + || (self.cull_leaves && state.mangrove_roots && other.mangrove_roots); + visible[d as usize] = !shared_foliage + && self + .visibility + .should_render_face( + BlockStateId(id.into()), + BlockStateId(neighbor.into()), + d, + true, + ) + .unwrap_or(true); } for (_, model) in &models { for face in &model.faces { diff --git a/crates/horizon-client/src/mesher/leaf_culling_tests.rs b/crates/horizon-client/src/mesher/leaf_culling_tests.rs new file mode 100644 index 000000000..42ed2b8b6 --- /dev/null +++ b/crates/horizon-client/src/mesher/leaf_culling_tests.rs @@ -0,0 +1,124 @@ +use super::*; +use horizon_assets::model::Direction as ModelDirection; + +#[test] +fn leaf_culling_removes_only_internal_leaf_and_root_faces() { + let root = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + if !root.join("horizon-resources.json").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let facts = BlockFacts::load(&root, assets.registry).unwrap(); + let visibility = crate::models::load_visibility(&root, assets.registry).unwrap(); + let tables = MeshTables::new(&assets, &facts, visibility.clone()).unwrap(); + let biomes = Biomes::load(&root).unwrap(); + let state = |name| assets.registry.default_state(name).unwrap().0 as u16; + let oak = state("minecraft:oak_leaves"); + let birch = state("minecraft:birch_leaves"); + let roots = state("minecraft:mangrove_roots"); + let stone = state("minecraft:stone"); + let mesh = |blocks: &[([i32; 3], u16)], cull_leaves, cutout_leaves| { + let mut center = Chunk::empty(0, 0); + let mut east = Chunk::empty(1, 0); + for &([x, y, z], state) in blocks { + let chunk = if x < 16 { &mut center } else { &mut east }; + chunk.set(x, y, z, state); + } + let mut region = [[None; 3]; 3]; + region[1][1] = Some(¢er); + region[1][2] = Some(&east); + Mesher { + nether_shading: false, + assets: &assets, + tables: &tables, + biomes: &biomes, + visibility: visibility.clone(), + zoom: BiomeZoom::new(0), + blend_radius: 0, + smooth_lighting: false, + cutout_leaves, + cull_leaves, + } + .mesh(®ion, (0 - MIN_Y) / 16) + .solid + }; + + // Native leaves can contain unculled interior geometry as well as their + // outer faces. Select the touching cull group from the actual baked model, + // preserving every other quad and its full vertex attributes. + let without_face = |at: [i32; 3], id, direction| { + let vertices = mesh(&[(at, id)], false, true); + let models = assets + .model_catalog + .collect(BlockStateId(id.into()), BlockPos::new(at[0], at[1], at[2])) + .unwrap(); + let faces: Vec<_> = models.iter().flat_map(|(_, model)| &model.faces).collect(); + assert_eq!(vertices.len(), faces.len() * 4); + let retained: Vec<_> = vertices + .as_chunks::<4>() + .0 + .iter() + .zip(faces) + .filter(|(_, face)| face.quad.cull != Some(direction)) + .flat_map(|(quad, _)| quad.iter().copied()) + .collect(); + assert!(retained.len() < vertices.len(), "fixture has a cull group"); + retained + }; + + // Same-species leaves, mixed leaves and roots hide only their touching + // model groups. Disabling the option restores the isolated models. + for (a, b) in [(oak, oak), (oak, birch), (roots, roots)] { + let blocks = [([7, 7, 7], a), ([8, 7, 7], b)]; + let off = mesh(&blocks, false, true); + let on = mesh(&blocks, true, true); + assert_eq!( + off.len(), + mesh(&[blocks[0]], false, true).len() + mesh(&[blocks[1]], false, true).len() + ); + let mut retained = without_face(blocks[0].0, a, ModelDirection::East); + retained.extend(without_face(blocks[1].0, b, ModelDirection::West)); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&on), + bytemuck::cast_slice::<_, u8>(&retained) + ); + } + + // Roots do not join leaves into a single culling group. Ordinary opaque + // neighbors also keep their existing occlusion behavior. + for (a, b) in [(oak, roots), (roots, oak), (oak, stone)] { + let blocks = [([7, 7, 7], a), ([8, 7, 7], b)]; + let off = mesh(&blocks, false, true); + let on = mesh(&blocks, true, true); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&on), + bytemuck::cast_slice::<_, u8>(&off) + ); + } + + // Opaque leaves already hide internal leaf faces independently of this + // option, and a leaf beside air retains its complete baked model. + let pair = [([7, 7, 7], oak), ([8, 7, 7], birch)]; + assert_eq!( + mesh(&pair, false, false).len(), + mesh(&pair, true, false).len() + ); + let isolated = [([7, 7, 7], oak)]; + assert_eq!( + bytemuck::cast_slice::<_, u8>(&mesh(&isolated, false, true)), + bytemuck::cast_slice::<_, u8>(&mesh(&isolated, true, true)) + ); + + // The padding read must also remove the center chunk's internal face + // against a different leaf species in the neighboring chunk. + let boundary = [([15, 7, 7], oak), ([16, 7, 7], birch)]; + assert_eq!( + mesh(&boundary, false, true).len(), + mesh(&[boundary[0]], false, true).len() + ); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&mesh(&boundary, true, true)), + bytemuck::cast_slice::<_, u8>(&without_face(boundary[0].0, oak, ModelDirection::East)) + ); +} diff --git a/crates/horizon-client/src/mesher/visibility_tests.rs b/crates/horizon-client/src/mesher/visibility_tests.rs index c96793087..2f95c45cf 100644 --- a/crates/horizon-client/src/mesher/visibility_tests.rs +++ b/crates/horizon-client/src/mesher/visibility_tests.rs @@ -87,6 +87,7 @@ fn info(solid: bool) -> Info { legacy_solid: false, overlay: false, leaves: false, + mangrove_roots: false, blocks_flow: false, ice: false, sturdy: 0, diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 94dca0560..5ea173d73 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -81,6 +81,7 @@ struct MeshSettings { blend_radius: i32, smooth_lighting: bool, cutout_leaves: bool, + cull_leaves: bool, } enum Job { Generate(i32, i32), @@ -183,6 +184,7 @@ pub struct Streaming { /// The `ao` and `cutoutLeaves` options. pub smooth_lighting: bool, pub cutout_leaves: bool, + pub cull_leaves: bool, /// Incremental relighting of block edits on lit chunks (see `light::relight`). light_tables: Arc, /// Applied edits by sequence, replayed onto light jobs snapshotted before them. @@ -401,6 +403,7 @@ impl Streaming { blend_radius: settings.blend_radius, smooth_lighting: settings.smooth_lighting, cutout_leaves: settings.cutout_leaves, + cull_leaves: settings.cull_leaves, assets: &context.assets, tables: &context.tables, biomes: &context.biomes, @@ -454,6 +457,7 @@ impl Streaming { biome_blend: 2, smooth_lighting: true, cutout_leaves: true, + cull_leaves: false, light_tables, light_log: Vec::new(), light_edit_sequence: 0, @@ -615,6 +619,9 @@ impl Streaming { pub fn is_lit(&self, x: i32, z: i32) -> bool { self.lit.contains(&(x, z)) } + pub fn is_meshing(&self, section: (i32, i32, i32)) -> bool { + self.meshing.contains_key(§ion) + } pub fn pending(&self) -> usize { self.shared.queue.lock().unwrap().len() } @@ -1005,6 +1012,7 @@ impl Streaming { blend_radius: self.biome_blend, smooth_lighting: self.smooth_lighting, cutout_leaves: self.cutout_leaves, + cull_leaves: self.cull_leaves, }, ), ); diff --git a/crates/horizon-client/tests/streaming_meshes.rs b/crates/horizon-client/tests/streaming_meshes.rs index 23e3f7f6b..74edd5049 100644 --- a/crates/horizon-client/tests/streaming_meshes.rs +++ b/crates/horizon-client/tests/streaming_meshes.rs @@ -210,6 +210,7 @@ fn relit_columns_keep_every_mesh_current() { blend_radius: 2, smooth_lighting: true, cutout_leaves: true, + cull_leaves: false, assets: &context.assets, tables: &context.tables, biomes: &context.biomes, diff --git a/tools/package_native_client.py b/tools/package_native_client.py index 92498436a..70f8c64ac 100644 --- a/tools/package_native_client.py +++ b/tools/package_native_client.py @@ -102,6 +102,8 @@ def main(): archive = args.out / f'{name}.tar.gz' with tarfile.open(archive, 'w:gz', compresslevel=1) as tar: tar.add(args.binary, 'horizon/horizon-client') + tar.add(ROOT / 'LICENSE', 'horizon/LICENSE') + tar.add(ROOT / 'THIRD_PARTY_NOTICES.md', 'horizon/THIRD_PARTY_NOTICES.md') ctl = args.binary.with_name('horizon-ctl') # built with --bins: scripts and agents play through it if ctl.is_file(): tar.add(ctl, 'horizon/horizon-ctl')