Merge pull request #420 from ludovic111/contrib/cull-leaves-387

Optional leaf and entity culling (Online5277's #387, rebased)
This commit is contained in:
Ludovic Marie
2026-10-16 02:13:02 +02:00
committed by GitHub
26 changed files with 689 additions and 20 deletions
+2
View File
@@ -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)).
+31
View File
@@ -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.
```
@@ -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;
@@ -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();
+266
View File
@@ -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<usize>,
}
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<crate::mesher::Vertex>,
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<i32> {
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!()
));
}
}
+32 -5
View File
@@ -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<horizon_client::gfx::Frustum>,
entity_culler: Option<horizon_client::entity_culling::Culler>,
/// A scripted flight from the control socket (`fly`).
flight: Option<control::Flight>,
/// The running agent action from the control socket (game/agent.rs).
@@ -5300,6 +5302,7 @@ impl Game<'_> {
alpha: f64,
mut out: Vec<Vertex>,
) -> Vec<Vertex> {
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(),
@@ -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);
}
}
}
@@ -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;
+2
View File
@@ -701,6 +701,7 @@ impl Game<'_> {
pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
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);
}
}
}
@@ -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)
@@ -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<Vertex>, 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(&section)
&& !self.streaming.is_meshing(section)
&& !self.pending_uploads.iter().any(|(key, _)| *key == section)
});
}
}
}
+6
View File
@@ -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);
}
}
}
@@ -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);
}
}
}
+4
View File
@@ -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);
}
}
}
@@ -1213,6 +1213,7 @@ impl Game<'_> {
pub(super) fn cart_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
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.
@@ -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);
}
}
}
+3
View File
@@ -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() {
+14 -2
View File
@@ -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()
);
}
+102
View File
@@ -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<Row> {
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");
}
}
+1
View File
@@ -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;
+22 -13
View File
@@ -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 {
@@ -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(&center);
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(&region, (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))
);
}
@@ -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,
+8
View File
@@ -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<LightTables>,
/// 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(&section)
}
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,
},
),
);
@@ -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,
+2
View File
@@ -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')