From 7f1e19742824fc0f3f63fff2a3916dbc8c8d898c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:10:07 +0200 Subject: [PATCH] Section arena in pages; graphics docs and benchmark comparison At render distance 32 the single section arena grew past the 4 GiB buffer limit and the renderer panicked. Sections now live in pages of at most 256 MiB (or the device's buffer limit); draws keep their order and bind each page once per run of consecutive draws in it, so translucent sections stay back to front. docs/graphics.md describes the settings, the benchmark and what changed; graphics_bench.py --compare prints a before/after table and keeps each game's log. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/fast_hash.rs | 7 +- crates/horizon-client/src/game.rs | 37 ++++-- crates/horizon-client/src/game/creaking.rs | 5 +- crates/horizon-client/src/game/creatures.rs | 6 +- crates/horizon-client/src/gfx.rs | 119 ++++++++++++-------- crates/horizon-client/src/gfx/arena.rs | 97 ++++++++++++---- crates/horizon-client/src/gfx/post.rs | 10 +- crates/horizon-client/src/gfx/timing.rs | 5 +- crates/horizon-client/src/graphics.rs | 9 +- crates/horizon-client/src/graphics_style.rs | 24 +++- crates/horizon-client/src/graphics_ui.rs | 45 ++++++-- crates/horizon-client/src/lib.rs | 6 +- crates/horizon-client/src/perf_overlay.rs | 15 ++- crates/horizon-client/src/save.rs | 21 ++-- crates/horizon-client/src/streaming.rs | 2 +- docs/README.md | 1 + docs/graphics.md | 54 +++++++++ docs/native-client.md | 4 + tools/graphics_bench.py | 29 +++++ 19 files changed, 366 insertions(+), 130 deletions(-) create mode 100644 docs/graphics.md diff --git a/crates/horizon-client/src/fast_hash.rs b/crates/horizon-client/src/fast_hash.rs index e13de7211..6fbf02b6d 100644 --- a/crates/horizon-client/src/fast_hash.rs +++ b/crates/horizon-client/src/fast_hash.rs @@ -18,11 +18,10 @@ impl FxHasher { impl Hasher for FxHasher { #[inline] fn write(&mut self, bytes: &[u8]) { - let mut chunks = bytes.chunks_exact(8); - for c in &mut chunks { - self.add(u64::from_le_bytes(c.try_into().expect("eight bytes"))); + let (words, rest) = bytes.as_chunks::<8>(); + for word in words { + self.add(u64::from_le_bytes(*word)); } - let rest = chunks.remainder(); if !rest.is_empty() { let mut word = [0u8; 8]; word[..rest.len()].copy_from_slice(rest); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 497fa8418..e405ce572 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -224,7 +224,9 @@ impl Options { no_pause: false, control: None, offscreen: false, - spikes: std::env::var("HORIZON_SPIKES").ok().and_then(|v| v.parse().ok()), + spikes: std::env::var("HORIZON_SPIKES") + .ok() + .and_then(|v| v.parse().ok()), server: None, player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()), dedicated: None, @@ -1239,8 +1241,10 @@ impl Game<'_> { // ServerLevel.tick: only entities in entity-ticking chunks tick. let ticking = self.entity_ticking_area(); items.retain_mut(|item| { - !ticking(item.position.x.floor() as i32, item.position.z.floor() as i32) - || item.tick(&self.world, &self.res.facts, self.collision) + !ticking( + item.position.x.floor() as i32, + item.position.z.floor() as i32, + ) || item.tick(&self.world, &self.res.facts, self.collision) }); let Some(p) = self.player.as_ref() else { self.dropped = items; @@ -2860,7 +2864,9 @@ impl Game<'_> { if running { // ClientLevel.tickBlockEntities (not while paused or frozen): // chest lids, books, shulker boxes, bells, conduits, heads. - horizon_client::spans::time("tick_block_entity_anims", || self.tick_block_entity_anims()); + horizon_client::spans::time("tick_block_entity_anims", || { + self.tick_block_entity_anims() + }); horizon_client::spans::time("tick_particles", || self.tick_particles()); } if self.right && self.use_delay == 0 && self.screen == Screen::Playing { @@ -4410,12 +4416,14 @@ impl Game<'_> { ) }; let visible = r.block_entities().filter(|(p, state)| { - off_screen(*state) || view.is_none_or(|v| { - let o = (glam::DVec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2])) - - camera) - .as_vec3(); - v.intersects(o - glam::Vec3::ONE, o + glam::Vec3::splat(2.0)) - }) + off_screen(*state) + || view.is_none_or(|v| { + let o = + (glam::DVec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2])) + - camera) + .as_vec3(); + v.intersects(o - glam::Vec3::ONE, o + glam::Vec3::splat(2.0)) + }) }); self.res .block_entity_render @@ -7679,14 +7687,19 @@ impl Game<'_> { let far = |k: &(i32, i32, i32)| (k.0 - centre.0).pow(2) + (k.2 - centre.1).pow(2); pending.sort_unstable_by_key(|(k, _)| std::cmp::Reverse(far(k))); let (limit, budget) = if budgeted { - (g.chunk_updates as usize, u64::from(g.upload_budget_kib) * 1024) + ( + g.chunk_updates as usize, + u64::from(g.upload_budget_kib) * 1024, + ) } else { (0, 0) }; let (mut count, mut bytes) = (0, 0u64); while let Some((_, mesh)) = pending.last() { let size = ((mesh.solid.len() + mesh.translucent.len()) * 32) as u64; - if (limit > 0 && count >= limit) || (budget > 0 && bytes > 0 && bytes + size > budget) { + if (limit > 0 && count >= limit) + || (budget > 0 && bytes > 0 && bytes + size > budget) + { break; } let (key, mesh) = pending.pop().expect("checked above"); diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index 8e19b11b0..c87c98f7a 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -17,10 +17,7 @@ use horizon_core::{ random::{LegacyRandom, RandomSource}, }; use horizon_world::registry::BlockStateId; -use std::{ - collections::HashMap, - sync::Arc, -}; +use std::{collections::HashMap, sync::Arc}; type Pos = (i32, i32, i32); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 44cd07d17..07cdfe6ac 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2295,8 +2295,10 @@ impl Game<'_> { if let Some(view) = &self.view_frustum && horizon_client::mobs::guardian::beam(mob, alpha as f32).is_none() { - let lo = d.as_vec3() - glam::Vec3::new(w as f32 / 2.0 + 0.5, 0.5, w as f32 / 2.0 + 0.5); - let hi = d.as_vec3() + glam::Vec3::new(w as f32 / 2.0 + 0.5, h as f32 + 0.5, w as f32 / 2.0 + 0.5); + let lo = + d.as_vec3() - glam::Vec3::new(w as f32 / 2.0 + 0.5, 0.5, w as f32 / 2.0 + 0.5); + let hi = d.as_vec3() + + glam::Vec3::new(w as f32 / 2.0 + 0.5, h as f32 + 0.5, w as f32 / 2.0 + 0.5); if !view.intersects(lo, hi) { continue; } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 9c8dfac09..da0bf3b4e 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -38,7 +38,8 @@ struct Globals { } pub type SectionKey = (i32, i32, i32); struct SectionGpu { - /// First vertex in the section arena: solid quads, then translucent ones. + /// Arena page and first vertex in it: solid quads, then translucent ones. + page: u32, start: u64, solid: u32, translucent: u32, @@ -193,6 +194,8 @@ pub struct Renderer { /// `DrawIndexedIndirectArgs` words: index count, instance count, first /// index, base vertex, first instance. draws: Vec<[u32; 5]>, + /// The arena page of each of `draws`. + draw_pages: Vec, /// Block-entity blocks per meshed section (world position, state id). block_entities: HashMap>, /// VisGraph face connectivity per meshed section (cave culling). @@ -1178,6 +1181,7 @@ impl Renderer { visible: Vec::new(), origins: Vec::new(), draws: Vec::new(), + draw_pages: Vec::new(), block_entities: HashMap::new(), occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16), post, @@ -1331,14 +1335,14 @@ impl Renderer { self.indices = Self::quad_indices(&self.device, self.index_quads); } let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64; - let start = self.arena.alloc(&self.device, &self.queue, vertices); + let (page, start) = self.arena.alloc(&self.device, &self.queue, vertices); let stride = std::mem::size_of::() as u64; for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] { if !part.is_empty() { let bytes: &[u8] = bytemuck::cast_slice(part); self.uploaded_bytes += bytes.len() as u64; self.queue.write_buffer( - &self.arena.buffer, + self.arena.buffer(page), (start + offset as u64) * stride, bytes, ); @@ -1347,6 +1351,7 @@ impl Renderer { self.sections.insert( key, SectionGpu { + page, start, solid, translucent, @@ -1355,22 +1360,31 @@ impl Renderer { } /// Draws `count` section draws from `first` with the arena and section /// origins bound: one indirect multi-draw, or a loop without it. + /// Consecutive draws in one arena page share a vertex buffer binding, + /// keeping the list's order (translucent sections go back to front). fn draw_sections(&self, pass: &mut wgpu::RenderPass<'_>, first: u32, count: u32) { - if count == 0 { - return; - } - if self.multi_draw { - pass.multi_draw_indexed_indirect(&self.indirect, u64::from(first) * 20, count); - } else { - for d in &self.draws[first as usize..(first + count) as usize] { - pass.draw_indexed(0..d[0], d[3] as i32, d[4]..d[4] + 1); + let (mut i, end) = (first as usize, (first + count) as usize); + while i < end { + let page = self.draw_pages[i]; + let run = self.draw_pages[i..end] + .iter() + .take_while(|&&p| p == page) + .count(); + pass.set_vertex_buffer(0, self.arena.buffer(page).slice(..)); + if self.multi_draw { + pass.multi_draw_indexed_indirect(&self.indirect, i as u64 * 20, run as u32); + } else { + for d in &self.draws[i..i + run] { + pass.draw_indexed(0..d[0], d[3] as i32, d[4]..d[4] + 1); + } } + i += run; } } fn release_section(&mut self, key: SectionKey) { if let Some(s) = self.sections.remove(&key) { self.arena - .release(s.start, u64::from(s.solid + s.translucent) * 4); + .release(s.page, s.start, u64::from(s.solid + s.translucent) * 4); } } /// Block-entity blocks of every meshed section (see `SectionMesh::block_entities`). @@ -1401,11 +1415,13 @@ impl Renderer { return; } self.mipmaps = levels; - let sprite_view = self.sprite_texture.create_view(&wgpu::TextureViewDescriptor { - dimension: Some(wgpu::TextureViewDimension::D2Array), - mip_level_count: Some(levels + 1), - ..Default::default() - }); + let sprite_view = self + .sprite_texture + .create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::D2Array), + mip_level_count: Some(levels + 1), + ..Default::default() + }); self.group = self.device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("Horizon terrain resources"), layout: &self.terrain_layout, @@ -1710,30 +1726,30 @@ impl Renderer { visible.clear(); visible.extend( self.sections - .keys() - .filter(|&&k| !culling || reachable.contains(k)) - .filter_map(|&(sx, sy, sz)| { - let origin = DVec3::new( - f64::from(sx * 16), - f64::from(crate::chunk::MIN_Y + sy * 16), - f64::from(sz * 16), - ) - camera; - let center = origin + DVec3::splat(8.0); - let horizontal = (center.x * center.x + center.z * center.z).sqrt(); - if horizontal > f64::from(frame.distance) + 24.0 { - return None; - } - let min = origin.as_vec3(); - let max = min + Vec3::splat(16.0); - if !view.intersects(min, max) { - return None; - } - Some(( - (sx, sy, sz), - center.length_squared(), - origin.as_vec3().to_array(), - )) - }), + .keys() + .filter(|&&k| !culling || reachable.contains(k)) + .filter_map(|&(sx, sy, sz)| { + let origin = DVec3::new( + f64::from(sx * 16), + f64::from(crate::chunk::MIN_Y + sy * 16), + f64::from(sz * 16), + ) - camera; + let center = origin + DVec3::splat(8.0); + let horizontal = (center.x * center.x + center.z * center.z).sqrt(); + if horizontal > f64::from(frame.distance) + 24.0 { + return None; + } + let min = origin.as_vec3(); + let max = min + Vec3::splat(16.0); + if !view.intersects(min, max) { + return None; + } + Some(( + (sx, sy, sz), + center.length_squared(), + origin.as_vec3().to_array(), + )) + }), ); visible.sort_unstable_by(|a, b| a.1.total_cmp(&b.1)); self.drawn_sections = visible.len(); @@ -1759,20 +1775,27 @@ impl Renderer { // Solid sections front to back, then translucent ones back to front, // as one list of indirect draws over the section arena. self.draws.clear(); + self.draw_pages.clear(); let draw = |s: &SectionGpu, i: usize, translucent: bool| { let (quads, first) = if translucent { (s.translucent, s.start + u64::from(s.solid) * 4) } else { (s.solid, s.start) }; - (quads > 0).then_some([quads * 6, 1, 0, first as u32, i as u32]) + (quads > 0).then_some(([quads * 6, 1, 0, first as u32, i as u32], s.page)) }; for (i, (key, _, _)) in visible.iter().enumerate() { - self.draws.extend(draw(&self.sections[key], i, false)); + if let Some((d, page)) = draw(&self.sections[key], i, false) { + self.draws.push(d); + self.draw_pages.push(page); + } } let solid_draws = self.draws.len() as u32; for (i, (key, _, _)) in visible.iter().enumerate().rev() { - self.draws.extend(draw(&self.sections[key], i, true)); + if let Some((d, page)) = draw(&self.sections[key], i, true) { + self.draws.push(d); + self.draw_pages.push(page); + } } let translucent_draws = self.draws.len() as u32 - solid_draws; if self.multi_draw && !self.draws.is_empty() { @@ -1880,9 +1903,9 @@ impl Renderer { .write_buffer(&self.border_uniform, 0, bytemuck::bytes_of(&uniform)); } let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor { - format: Some(self.config.format.remove_srgb_suffix()), - ..Default::default() - }); + format: Some(self.config.format.remove_srgb_suffix()), + ..Default::default() + }); let mut encoder = self .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { @@ -1959,7 +1982,6 @@ impl Renderer { } pass.set_pipeline(&self.solid); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); - pass.set_vertex_buffer(0, self.arena.buffer.slice(..)); pass.set_vertex_buffer(1, self.instances.slice(..)); self.draw_sections(&mut pass, 0, solid_draws); if entity_quads > 0 { @@ -1983,7 +2005,6 @@ impl Renderer { } pass.set_pipeline(&self.translucent); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); - pass.set_vertex_buffer(0, self.arena.buffer.slice(..)); pass.set_vertex_buffer(1, self.instances.slice(..)); self.draw_sections(&mut pass, solid_draws, translucent_draws); // LevelRenderer: the world border after translucent terrain and weather. diff --git a/crates/horizon-client/src/gfx/arena.rs b/crates/horizon-client/src/gfx/arena.rs index d64d21551..1697d6b97 100644 --- a/crates/horizon-client/src/gfx/arena.rs +++ b/crates/horizon-client/src/gfx/arena.rs @@ -38,22 +38,36 @@ impl FreeList { } } -pub struct Arena { - pub buffer: wgpu::Buffer, +/// One vertex buffer of the arena; only the newest page grows. +struct Page { + buffer: wgpu::Buffer, /// Capacity in vertices. capacity: u64, - stride: u64, free: FreeList, } +/// Terrain vertices in pages of at most `page_limit` vertices (devices cap +/// buffer sizes): a section's vertices sit in one page. +pub struct Arena { + pages: Vec, + stride: u64, + page_limit: u64, +} + impl Arena { pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self { - let capacity = capacity.next_multiple_of(GRAIN); + // 256 MiB pages, or less where the device's buffers are smaller. + let bytes = device.limits().max_buffer_size.min(256 << 20); + let page_limit = (bytes / stride) / GRAIN * GRAIN; + let capacity = capacity.next_multiple_of(GRAIN).min(page_limit); Self { - buffer: Self::create(device, stride, capacity), - capacity, + pages: vec![Page { + buffer: Self::create(device, stride, capacity), + capacity, + free: FreeList::new(capacity), + }], stride, - free: FreeList::new(capacity), + page_limit, } } fn create(device: &wgpu::Device, stride: u64, capacity: u64) -> wgpu::Buffer { @@ -70,35 +84,68 @@ impl Arena { fn span(vertices: u64) -> u64 { vertices.max(1).next_multiple_of(GRAIN) } - /// A range of `vertices`, growing the buffer (copying its contents on the - /// GPU) when no free range is large enough. Returns the first vertex. - pub fn alloc(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, vertices: u64) -> u64 { - let len = Self::span(vertices); - if let Some(start) = self.free.take(len) { - return start; + pub fn buffer(&self, page: u32) -> &wgpu::Buffer { + &self.pages[page as usize].buffer + } + /// A range of `vertices`: (page, first vertex). Grows the newest page + /// (copying its contents on the GPU) or starts a new one when nothing + /// free is large enough. + pub fn alloc( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + vertices: u64, + ) -> (u32, u64) { + let len = Self::span(vertices).min(self.page_limit); + for (i, page) in self.pages.iter_mut().enumerate() { + if let Some(start) = page.free.take(len) { + return (i as u32, start); + } } - self.grow(device, queue, (self.capacity * 2).max(self.capacity + len)); - self.free.take(len).expect("grown arena has room") + let last = self.pages.len() - 1; + let current = self.pages[last].capacity; + if current < self.page_limit { + let grown = (current * 2).max(current + len).min(self.page_limit); + if grown - current >= len || grown == self.page_limit { + self.grow(device, queue, last, grown); + if let Some(start) = self.pages[last].free.take(len) { + return (last as u32, start); + } + } + } + let capacity = (1 << 20u64).max(len).min(self.page_limit); + let mut free = FreeList::new(capacity); + let start = free.take(len).expect("a new page fits one section"); + self.pages.push(Page { + buffer: Self::create(device, self.stride, capacity), + capacity, + free, + }); + ((self.pages.len() - 1) as u32, start) } - pub fn release(&mut self, start: u64, vertices: u64) { - self.free.give(start, Self::span(vertices)); + pub fn release(&mut self, page: u32, start: u64, vertices: u64) { + let len = Self::span(vertices).min(self.page_limit); + self.pages[page as usize].free.give(start, len); } - fn grow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, capacity: u64) { - let capacity = capacity.next_multiple_of(GRAIN); + fn grow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, page: usize, capacity: u64) { + let capacity = capacity.next_multiple_of(GRAIN).min(self.page_limit); let buffer = Self::create(device, self.stride, capacity); + let old = &mut self.pages[page]; let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Grow section arena"), }); - encoder.copy_buffer_to_buffer(&self.buffer, 0, &buffer, 0, self.capacity * self.stride); + encoder.copy_buffer_to_buffer(&old.buffer, 0, &buffer, 0, old.capacity * self.stride); // Writes queued for the old buffer run before this copy. queue.submit([encoder.finish()]); - let old = self.capacity; - self.buffer = buffer; - self.capacity = capacity; - self.free.give(old, capacity - old); + let previous = old.capacity; + old.buffer = buffer; + old.capacity = capacity; + old.free.give(previous, capacity - previous); } pub fn clear(&mut self) { - self.free = FreeList::new(self.capacity); + for page in &mut self.pages { + page.free = FreeList::new(page.capacity); + } } } diff --git a/crates/horizon-client/src/gfx/post.rs b/crates/horizon-client/src/gfx/post.rs index 061c61a0b..9e09eff56 100644 --- a/crates/horizon-client/src/gfx/post.rs +++ b/crates/horizon-client/src/gfx/post.rs @@ -161,7 +161,9 @@ impl Post { group, }); } - self.target.as_ref().map(|t| (t.color.clone(), t.depth.clone())) + self.target + .as_ref() + .map(|t| (t.color.clone(), t.depth.clone())) } /// Draw the scaled world onto `screen`. pub fn finish(&self, encoder: &mut wgpu::CommandEncoder, screen: &wgpu::TextureView) { @@ -180,7 +182,11 @@ impl Post { color_attachments: &attachments, ..Default::default() }); - pass.set_pipeline(if self.antialias { &self.fxaa } else { &self.copy }); + pass.set_pipeline(if self.antialias { + &self.fxaa + } else { + &self.copy + }); pass.set_bind_group(0, &target.group, &[]); pass.draw(0..3, 0..1); } diff --git a/crates/horizon-client/src/gfx/timing.rs b/crates/horizon-client/src/gfx/timing.rs index 90e69d08c..b3daeeaa4 100644 --- a/crates/horizon-client/src/gfx/timing.rs +++ b/crates/horizon-client/src/gfx/timing.rs @@ -98,7 +98,10 @@ impl GpuTimer { .buffer .slice(..) .map_async(wgpu::MapMode::Read, move |result| { - state.store(if result.is_ok() { MAPPED } else { FREE }, Ordering::Release); + state.store( + if result.is_ok() { MAPPED } else { FREE }, + Ordering::Release, + ); }); self.next = (slot + 1) % SLOTS; } diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index e2a03356b..34908838d 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -195,9 +195,7 @@ impl Graphics { } } "workers" => g.workers = number(g.workers).min(64), - "resolutionScale" => { - g.resolution_scale = number(g.resolution_scale).clamp(50, 200) - } + "resolutionScale" => g.resolution_scale = number(g.resolution_scale).clamp(50, 200), "fxaa" => g.fxaa = flag(g.fxaa), "overlay" => { g.overlay = match value { @@ -308,6 +306,9 @@ 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::default()); + assert_eq!( + Graphics::parse("workers:abc\nsky:maybe\n"), + Graphics::default() + ); } } diff --git a/crates/horizon-client/src/graphics_style.rs b/crates/horizon-client/src/graphics_style.rs index ccb3f2d47..45bd3db06 100644 --- a/crates/horizon-client/src/graphics_style.rs +++ b/crates/horizon-client/src/graphics_style.rs @@ -78,12 +78,26 @@ impl Style { let total = self.control_width + self.gap + self.text_width(screen_width); ((screen_width - total) / 2.0).floor() } - pub fn background(&self, batch: &mut HudBatch, atlas: &HudAtlas, top: f32, bottom: f32, in_world: bool) { + pub fn background( + &self, + batch: &mut HudBatch, + atlas: &HudAtlas, + top: f32, + bottom: f32, + in_world: bool, + ) { let (w, h) = (batch.width, batch.height); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, in_world); ui::list_background(batch, atlas, top, bottom, in_world); } - pub fn frame(&self, batch: &mut HudBatch, atlas: &HudAtlas, top: f32, bottom: f32, in_world: bool) { + pub fn frame( + &self, + batch: &mut HudBatch, + atlas: &HudAtlas, + top: f32, + bottom: f32, + in_world: bool, + ) { ui::separators(batch, atlas, top, bottom, in_world); } pub fn title(&self, batch: &mut HudBatch, atlas: &HudAtlas, text: &Text) { @@ -146,7 +160,11 @@ impl Style { fn wrap(atlas: &HudAtlas, text: &str, width: f32, indent: f32) -> Vec { let mut lines = vec![String::new()]; for word in text.split_whitespace() { - let room = if lines.len() == 1 { width - indent } else { width }; + let room = if lines.len() == 1 { + width - indent + } else { + width + }; let line = lines.last().expect("one line"); let candidate = if line.is_empty() { word.to_owned() diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index c0c0c35f8..3bc5e1df7 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -2,7 +2,7 @@ //! they show, in what groups, with what description and cost, and their //! input. How they look comes from `graphics_style`. use crate::{ - graphics::{Overlay, Pacing, Preset, PresentMode}, + graphics::{Overlay, Pacing, PresentMode, Preset}, graphics_style::{Cost, STYLE}, hud::{HudAtlas, HudBatch}, options_ui::Opt, @@ -73,7 +73,11 @@ fn rows(level: Level) -> Vec { High, "How far terrain is drawn, in chunks. The biggest lever on frame time.", ); - let fov = v(Opt::Fov, Low, "Field of view. Wider shows more terrain at once."); + let fov = v( + Opt::Fov, + Low, + "Field of view. Wider shows more terrain at once.", + ); let fps = v( Opt::MaxFps, None, @@ -144,13 +148,17 @@ fn rows(level: Level) -> Vec { "Distance fog. Off shows the edge of the loaded world.", ), h(H::Weather, Low, "Draws rain and snow."), - v(Opt::WeatherRadius, Low, "How far rain and snow fall around you."), v( - Opt::Particles, - Medium, - "How many particles effects spawn.", + Opt::WeatherRadius, + Low, + "How far rain and snow fall around you.", + ), + v(Opt::Particles, Medium, "How many particles effects spawn."), + v( + Opt::EntityShadows, + Low, + "Round shadows under mobs and items.", ), - v(Opt::EntityShadows, Low, "Round shadows under mobs and items."), v( Opt::CutoutLeaves, Medium, @@ -317,7 +325,11 @@ impl H { } } H::Overlay => { - g.overlay = step(&[Overlay::Off, Overlay::Fps, Overlay::Graph], g.overlay, back) + g.overlay = step( + &[Overlay::Off, Overlay::Fps, Overlay::Graph], + g.overlay, + back, + ) } _ => {} } @@ -339,7 +351,10 @@ impl Item { // The vanilla button shows the scale alone, under its own caption. Item::Vanilla(Opt::GuiScale) => Text::translate( "options.generic_value", - &[Text::translate("options.guiScale", &[]), Opt::GuiScale.label(s)], + &[ + Text::translate("options.guiScale", &[]), + Opt::GuiScale.label(s), + ], ), Item::Vanilla(o) => o.label(s), Item::Horizon(h) => h.label(s), @@ -364,7 +379,9 @@ impl Item { let presetless = matches!( self, Item::Horizon(H::Preset | H::Overlay | H::Pacing | H::PresentMode | H::Workers) - | Item::Vanilla(Opt::GuiScale | Opt::Fullscreen | Opt::Vsync | Opt::MaxFps | Opt::Fov) + | Item::Vanilla( + Opt::GuiScale | Opt::Fullscreen | Opt::Vsync | Opt::MaxFps | Opt::Fov + ) ); if !presetless { s.horizon.preset = Preset::Custom; @@ -529,7 +546,13 @@ impl GraphicsUi { Action::OpenSimple => "Simple...", _ => "Done", }; - STYLE.button(batch, atlas, (wd.x, wd.y, wd.w), &Text::literal(label), hover); + STYLE.button( + batch, + atlas, + (wd.x, wd.y, wd.w), + &Text::literal(label), + hover, + ); } } } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 7e085c9fb..d4d9e2fe9 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -47,10 +47,10 @@ pub mod fog; pub mod font; pub mod gamerules; pub mod gfx; +pub mod gossip; pub mod graphics; pub mod graphics_style; pub mod graphics_ui; -pub mod gossip; pub mod health; pub mod hotbar; pub mod hud; @@ -85,10 +85,10 @@ pub mod options_file; pub mod options_fixes; pub mod options_ui; pub mod pack_screen; -pub mod perf_overlay; pub mod packs; pub mod particles; pub mod patrol; +pub mod perf_overlay; pub mod pose; pub mod projectiles; pub mod raid; @@ -110,8 +110,8 @@ pub mod skins; pub mod snbt; pub mod sound_engine; pub mod sound_events; -pub mod sprint; pub mod spans; +pub mod sprint; pub mod sprites; pub mod stations; pub mod stopwatches; diff --git a/crates/horizon-client/src/perf_overlay.rs b/crates/horizon-client/src/perf_overlay.rs index 361dac9b6..c92ff6f54 100644 --- a/crates/horizon-client/src/perf_overlay.rs +++ b/crates/horizon-client/src/perf_overlay.rs @@ -53,7 +53,11 @@ impl FrameGraph { rgba(0, 0, 0, 144), ); for (i, line) in lines.iter().enumerate() { - let color = if i == 0 { rgba(255, 255, 255, 255) } else { rgba(200, 200, 200, 255) }; + let color = if i == 0 { + rgba(255, 255, 255, 255) + } else { + rgba(200, 200, 200, 255) + }; batch.text_styled( atlas, &Text::literal(line.clone()), @@ -93,7 +97,14 @@ impl FrameGraph { } for target in [16.7, 33.3] { let ly = gy + gh - target * scale; - batch.fill(atlas, x + 3.0, ly, width - 6.0, 1.0, rgba(255, 255, 255, 90)); + batch.fill( + atlas, + x + 3.0, + ly, + width - 6.0, + 1.0, + rgba(255, 255, 255, 90), + ); } } } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index f21ecda25..0b03efa24 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -36,13 +36,13 @@ use horizon_world::{ }; use std::{ collections::{BTreeMap, HashMap}, - sync::{ - Condvar, mpsc, - atomic::{AtomicU64, Ordering}, - }, fs, path::{Path, PathBuf}, - sync::{Arc, Mutex, OnceLock}, + sync::{ + Arc, Condvar, Mutex, OnceLock, + atomic::{AtomicU64, Ordering}, + mpsc, + }, }; pub const VERSION_NAME: &str = "26.3"; @@ -1361,7 +1361,11 @@ impl SaveDir { batch.push((key, record, seq)); } } - *self.outstanding.count.lock().map_err(|_| "writer poisoned")? += 1; + *self + .outstanding + .count + .lock() + .map_err(|_| "writer poisoned")? += 1; let mut writer = self.writer.lock().map_err(|_| "writer poisoned")?; let writer = writer.get_or_insert_with(|| self.start_writer()); if writer.send.send((entities, batch)).is_err() { @@ -1395,7 +1399,10 @@ impl SaveDir { // Readers find the files (and a fresh region cache) from here on. if let Ok(mut pending) = pending.lock() { for (k, _, seq) in &batch { - if pending.get(&(entities, k.0, k.1)).is_some_and(|p| p.0 == *seq) { + if pending + .get(&(entities, k.0, k.1)) + .is_some_and(|p| p.0 == *seq) + { pending.remove(&(entities, k.0, k.1)); } } diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 26ca37a15..dbbcc6d00 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -2,6 +2,7 @@ //! around the player, closest first. The game thread owns the world and only //! hands immutable `Arc` snapshots to workers; results carry a sequence number //! so stale work is dropped. +use crate::fast_hash::{FxHashMap, FxHashSet}; use crate::{ chunk::{Chunk, SECTIONS}, light::{LightTables, light_chunk}, @@ -9,7 +10,6 @@ use crate::{ world::World, }; use horizon_core::biome::BiomeZoom; -use crate::fast_hash::{FxHashMap, FxHashSet}; use std::{ collections::{BinaryHeap, HashSet}, sync::{ diff --git a/docs/README.md b/docs/README.md index 43c936664..909bd8901 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,6 +6,7 @@ To play, use [the launcher](../launcher/README.md). These pages are for develope - [Build from source](../README.md#build-from-source): your own copy of the game, resource preparation, `cargo run`. - [Native client](native-client.md): options, controls, the dedicated server, `horizon-ctl` scripting, packaging, architecture. +- [Graphics](graphics.md): the Simple and Advanced graphics settings, the graphics benchmark and what it measured. - [Launcher](../launcher/README.md): installs, updates and starts builds; its CLI and MCP server; releasing it. ## Parity diff --git a/docs/graphics.md b/docs/graphics.md new file mode 100644 index 000000000..d9a3e2757 --- /dev/null +++ b/docs/graphics.md @@ -0,0 +1,54 @@ +# Graphics: settings and performance + +## Settings + +**Options → Video Settings** starts with two buttons for Horizon's own screens: + +- **Horizon Graphics…** (Simple): a preset (Performance, Balanced, Quality, Ultra or Custom), render distance, FOV, max framerate, VSync and GUI scale. +- **Advanced Graphics…**: every setting, grouped under Rendering, Quality, Display, Performance and Overlay. + +Every row has a one-line description and its cost in frame time (none, low, medium, high), and applies at once, except worker threads, which apply at the next start. A preset sets the quality settings together; changing one of them turns it into Custom. Display preferences (FOV, framerate, VSync, GUI scale, fullscreen, present mode, pacing) leave the preset as it is. + +![Simple](media/settings-simple.png) +![Advanced](media/settings-advanced.png) + +| Group | Setting | Stored in | +| --- | --- | --- | +| Rendering | render distance, simulation distance, entity distance | `options.txt` (vanilla keys) | +| | cave culling, chunk updates per frame | `horizon-graphics.txt` | +| Quality | smooth lighting, mipmap levels, biome blend, clouds, cloud distance, weather radius, particles, entity shadows, cutout leaves | `options.txt` | +| | sky, fog, weather, animated textures | `horizon-graphics.txt` | +| Display | FOV, max framerate, VSync, fullscreen, GUI scale | `options.txt` | +| | resolution scale, anti-aliasing (FXAA), present mode, frame pacing | `horizon-graphics.txt` | +| Performance | worker threads, upload budget per frame | `horizon-graphics.txt` | +| Overlay | performance overlay: FPS, frame/CPU/GPU times, frame-time graph | `horizon-graphics.txt` | + +`options.txt` keeps exactly vanilla's keys and values, so the options harness still compares it with vanilla; Horizon's settings live in `horizon-graphics.txt` beside it. Their defaults render as vanilla does: cave culling on, no upload budgets, sky, fog and weather on, 100% resolution, no FXAA, the present mode following VSync. Frame pacing defaults to Efficient: the limiter sleeps through the last half millisecond where vanilla spins, which changes timing, not pixels. + +The screens' layout is in `crates/horizon-client/src/graphics_ui.rs`; every colour, size and widget call is in `graphics_style.rs`, the one place a menu theme replaces. + +Not implemented: distant-terrain LOD, anisotropic filtering (wgpu needs linear magnification for it, which blurs close blocks), MSAA (FXAA instead) and exclusive fullscreen (fullscreen is borderless). + +## Benchmark + +`tools/graphics_bench.py` opens a fresh creative world (seed 1234) on a virtual screen and flies the camera along four fixed 192-block paths, over a village, a forest, the ocean and a mountain, at render distances 8, 16 and 32, one game per distance. Each flight takes 12 seconds and reports average FPS, 1% lows, frame-time percentiles, CPU time per frame (frame time minus waits for the GPU, the display and the limiter), the split of that CPU time (world update, ticks, frame preparation, renderer) for all frames and for the slowest 1%, and GPU time per frame from timestamp queries. + +```sh +cargo build --release -p horizon-client --bins +python3 tools/graphics_bench.py --label mine # lavapipe on vscreen: CPU-side numbers +python3 tools/graphics_bench.py --label mine-gpu --offscreen # the desktop's RTX 4080 +python3 tools/graphics_bench.py --compare baseline-4080 mine-gpu # markdown table +``` + +vscreen is a headless compositor whose frames are software-rendered (lavapipe), so its frame times measure the CPU, rasterisation included. `--offscreen` (`horizon-client --offscreen`) renders into a texture on the most powerful GPU instead of the window, which measures the RTX 4080 under the same compositor. `--distances`, `--scenes` and `--build` pick a subset or another build. Results go to `benchmarks/graphics/