diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 146e5c8f0..7f0221119 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -598,6 +598,7 @@ pub struct Resources { biomes: Arc, environment: Environment, atlas: HudAtlas, + panorama: horizon_client::gfx::panorama::Faces, layer_names: HashMap, mob_types: HashMap>, mob_data: horizon_client::mobs::MobData, @@ -6040,91 +6041,6 @@ impl Game<'_> { self.capture(false); Ok(()) } - /// The title panorama as six camera-centred faces (panorama_0..5: - /// front, right, back, left, up, down). - fn panorama_geometry(&self) -> Vec { - let mut out = Vec::new(); - let d = 100.0; - let faces: [(&str, [glam::Vec3; 4]); 6] = [ - ( - "0", - [ - glam::Vec3::new(-d, d, -d), - glam::Vec3::new(d, d, -d), - glam::Vec3::new(d, -d, -d), - glam::Vec3::new(-d, -d, -d), - ], - ), - ( - "1", - [ - glam::Vec3::new(d, d, -d), - glam::Vec3::new(d, d, d), - glam::Vec3::new(d, -d, d), - glam::Vec3::new(d, -d, -d), - ], - ), - ( - "2", - [ - glam::Vec3::new(d, d, d), - glam::Vec3::new(-d, d, d), - glam::Vec3::new(-d, -d, d), - glam::Vec3::new(d, -d, d), - ], - ), - ( - "3", - [ - glam::Vec3::new(-d, d, d), - glam::Vec3::new(-d, d, -d), - glam::Vec3::new(-d, -d, -d), - glam::Vec3::new(-d, -d, d), - ], - ), - ( - "4", - [ - glam::Vec3::new(-d, d, d), - glam::Vec3::new(d, d, d), - glam::Vec3::new(d, d, -d), - glam::Vec3::new(-d, d, -d), - ], - ), - ( - "5", - [ - glam::Vec3::new(-d, -d, -d), - glam::Vec3::new(d, -d, -d), - glam::Vec3::new(d, -d, d), - glam::Vec3::new(-d, -d, d), - ], - ), - ]; - for (index, corners) in faces { - let Some(r) = self - .res - .atlas - .sprites - .get(&format!("gui/title/background/panorama_{index}")) - .copied() - else { - continue; - }; - let uv = [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]]; - for (p, uv) in corners.iter().zip(uv) { - out.push(Vertex { - normal: [0; 4], - pos: p.to_array(), - uv, - layer: 2, - color: 0xFFFF_FFFF, - light: 0, - }); - } - } - out - } /// Equipment attribute modifiers (LivingEntity.collectEquipmentChanges). fn apply_equipment(&mut self) { let Some(player) = self.player.as_mut() else { @@ -7006,6 +6922,7 @@ impl Game<'_> { self.res.atlas.height, ), (&self.res.forcefield.2, self.res.forcefield.0), + &self.res.panorama, )) } fn apply_settings(&mut self) { @@ -7822,7 +7739,7 @@ impl Game<'_> { } } let celestial = if title && !live { - self.panorama_geometry() + Vec::new() } else if self.dim == Dim::Overworld && self.potions.effects.get("darkness").is_none() && self.potions.effects.get("blindness").is_none() @@ -8949,6 +8866,7 @@ pub fn run() -> Result<()> { let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); log::info!("load tables: {:.2}s", started.elapsed().as_secs_f32()); let atlas = HudAtlas::build(&root)?; + let panorama = horizon_client::gfx::panorama::Faces::load(&root); horizon_client::ui::load_metadata(&root); horizon_client::lang::set(horizon_client::lang::Language::load( &[&root], @@ -9016,6 +8934,7 @@ pub fn run() -> Result<()> { biomes, environment, atlas, + panorama, item_renderer: Arc::new(horizon_client::item_render::ItemRenderer::load(&root)?), layer_names, providers: Providers::load(&root), diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index f1e476f8d..0d3f8a74a 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -112,6 +112,7 @@ impl Game<'_> { fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { let assets = std::sync::Arc::new(self.res.assets.reload(root)?); let mut atlas = HudAtlas::build(root)?; + let panorama = horizon_client::gfx::panorama::Faces::load(root); atlas.font.uniform = self.settings.force_unicode; atlas.font.japanese = self.settings.japanese_glyphs; let item_renderer = horizon_client::item_render::ItemRenderer::load(root)?; @@ -137,6 +138,7 @@ impl Game<'_> { self.res.assets = assets; self.res.context = context.clone(); self.res.atlas = atlas; + self.res.panorama = panorama; self.res.item_renderer = std::sync::Arc::new(item_renderer); self.res.clouds = super::load_clouds(root); self.res.forcefield = super::load_forcefield(root); diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 5438b15fe..08251da1d 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -83,6 +83,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] mod arena; mod occlusion; +pub mod panorama; mod timing; mod world_post; @@ -137,7 +138,7 @@ pub struct Frame<'a> { /// Skip sections the camera cannot see through open faces (vanilla's /// occlusion graph; off in spectator-like views inside blocks). pub cave_culling: bool, - /// Title screen: only the panorama (in `celestial`) and the HUD. + /// Title screen: only the dedicated panorama cube map and the HUD. pub title: bool, /// Dimensions without a skybox (the Nether) clear to the fog colour. pub skybox: bool, @@ -246,6 +247,7 @@ pub struct Renderer { additive_pipeline: wgpu::RenderPipeline, celestial_pipeline: wgpu::RenderPipeline, celestial_buffer: wgpu::Buffer, + panorama: panorama::Panorama, /// `RenderPipelines.WORLD_BORDER` and its buffers. border_pipeline: wgpu::RenderPipeline, border_group: wgpu::BindGroup, @@ -401,6 +403,7 @@ impl Renderer { animations: &[SpriteAnimation], hud_atlas: (&[u8], u32, u32), forcefield: (&[u8], u32), + panorama_faces: &panorama::Faces, ) -> Result { let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); @@ -1361,6 +1364,12 @@ impl Renderer { .features() .contains(wgpu::Features::INDIRECT_FIRST_INSTANCE); let world_post = world_post::Post::new(&device, config.format.remove_srgb_suffix()); + let panorama = panorama::Panorama::new( + &device, + &queue, + config.format.remove_srgb_suffix(), + panorama_faces, + ); Ok(Self { instance, surface, @@ -1389,6 +1398,7 @@ impl Renderer { additive_pipeline, celestial_pipeline, celestial_buffer, + panorama, border_pipeline, border_group, border_uniform, @@ -1875,6 +1885,15 @@ impl Renderer { frame.block_flicker, ); let view_proj = self.view_projection(frame); + if frame.title { + self.panorama.prepare( + &self.queue, + self.config.width, + self.config.height, + frame.yaw, + frame.pitch, + ); + } let aspect = self.config.width as f32 / self.config.height.max(1) as f32; let view = crate::camera::view_matrix(frame.yaw, frame.pitch); let sun_angle = frame.sky.sun_angle.to_radians(); @@ -2221,12 +2240,15 @@ impl Renderer { Some(f) => f.sky_end > 2.0, None => !frame.underwater, }; - if sky_visible && (frame.skybox || frame.end_sky) { + if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) { if !frame.title && frame.skybox { pass.set_pipeline(&self.sky); pass.draw(0..3, 0..1); } - if celestial_vertices > 0 { + if frame.title { + self.panorama.draw(&mut pass); + pass.set_bind_group(0, &self.group, &[]); + } else if celestial_vertices > 0 { pass.set_pipeline(&self.celestial_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); diff --git a/crates/horizon-client/src/gfx/panorama.rs b/crates/horizon-client/src/gfx/panorama.rs new file mode 100644 index 000000000..d53cd4501 --- /dev/null +++ b/crates/horizon-client/src/gfx/panorama.rs @@ -0,0 +1,346 @@ +//! Vanilla 26.3's CubeMapTexture and CubeMap, separate from the pixel-filtered GUI atlas. +use crate::{Result, hud::decode}; +use glam::Mat4; +use std::path::Path; +use wgpu::util::DeviceExt; + +/// Native cube order: +X, -X, +Y, -Y, +Z, -Z (CubeMapTexture.SUFFIXES). +const FACE_ORDER: [u8; 6] = [1, 3, 5, 4, 0, 2]; + +#[derive(Debug)] +pub struct Faces { + pub size: u32, + pub pixels: Vec, +} + +impl Faces { + pub fn load(root: &Path) -> Self { + Self::try_load(root).unwrap_or_else(|error| { + log::warn!("Horizon: title panorama unavailable ({error})"); + Self { + size: 1, + pixels: [96, 110, 111, 255].repeat(6), + } + }) + } + + fn try_load(root: &Path) -> Result { + let background = root.join("assets/minecraft/textures/gui/title/background"); + let mut size = 0; + let mut pixels = Vec::new(); + for face in FACE_ORDER { + let path = background.join(format!("panorama_{face}.png")); + let (w, h, data) = decode(&path)?; + if w != h || (size != 0 && w != size) { + return Err(format!( + "{}: panorama faces must be equally sized squares", + path.display() + ) + .into()); + } + size = w; + // CubeMapTexture copies each original image with flipY=true. Keep every texel. + for row in data.chunks_exact((w * 4) as usize).rev() { + pixels.extend_from_slice(row); + } + } + Ok(Self { size, pixels }) + } +} + +fn projection(width: u32, height: u32, yaw: f32, pitch: f32) -> Mat4 { + // CubeMap.render: 85-degree FOV, near/far 0.05/10, rotationX(PI), rotateX, rotateY. + Mat4::perspective_rh( + 85.0f32.to_radians(), + width as f32 / height.max(1) as f32, + 0.05, + 10.0, + ) * Mat4::from_rotation_x(std::f32::consts::PI) + * Mat4::from_rotation_x(pitch.to_radians()) + * Mat4::from_rotation_y(yaw.to_radians()) +} + +pub(super) struct Panorama { + pipeline: wgpu::RenderPipeline, + group: wgpu::BindGroup, + uniform: wgpu::Buffer, +} + +impl Panorama { + pub(super) fn new( + device: &wgpu::Device, + queue: &wgpu::Queue, + format: wgpu::TextureFormat, + faces: &Faces, + ) -> Self { + let texture = device.create_texture_with_data( + queue, + &wgpu::TextureDescriptor { + label: Some("Title panorama cube"), + size: wgpu::Extent3d { + width: faces.size, + height: faces.size, + depth_or_array_layers: 6, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + &faces.pixels, + ); + let view = texture.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::Cube), + ..Default::default() + }); + // CubeMapTexture's blur=true metadata: linear minification and magnification, no mips. + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Title panorama linear filtering"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Title panorama projection"), + size: 64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Title panorama bindings"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::Cube, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Title panorama resources"), + layout: &layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: uniform.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + ], + }); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Title panorama shader"), + source: wgpu::ShaderSource::Wgsl(include_str!("panorama.wgsl").into()), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Title panorama layout"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Title panorama"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_panorama"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: wgpu::PrimitiveState { + cull_mode: None, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::Always), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_panorama"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + Self { + pipeline, + group, + uniform, + } + } + + pub(super) fn prepare( + &self, + queue: &wgpu::Queue, + width: u32, + height: u32, + yaw: f32, + pitch: f32, + ) { + queue.write_buffer( + &self.uniform, + 0, + bytemuck::cast_slice(&projection(width, height, yaw, pitch).to_cols_array()), + ); + } + + pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>) { + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &self.group, &[]); + pass.draw(0..36, 0..1); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + fs, + sync::atomic::{AtomicU32, Ordering}, + }; + + struct Fixture(std::path::PathBuf); + impl Fixture { + fn new(size: u32) -> Self { + static NEXT: AtomicU32 = AtomicU32::new(0); + let root = std::env::temp_dir().join(format!( + "horizon-panorama-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed), + )); + let fixture = Self(root); + fs::create_dir_all(fixture.background()).unwrap(); + for face in 0..6 { + fixture.write(face, size, size); + } + fixture + } + fn background(&self) -> std::path::PathBuf { + self.0 + .join("assets/minecraft/textures/gui/title/background") + } + fn write(&self, face: u8, w: u32, h: u32) { + let file = + fs::File::create(self.background().join(format!("panorama_{face}.png"))).unwrap(); + let mut encoder = png::Encoder::new(file, w, h); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let pixels: Vec = (0..h) + .flat_map(|y| { + (0..w).flat_map(move |x| [face, (x % 251) as u8, (y % 253) as u8, 255]) + }) + .collect(); + encoder + .write_header() + .unwrap() + .write_image_data(&pixels) + .unwrap(); + } + } + impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + #[test] + fn original_resolution_texels_and_vanilla_cube_orientation_are_preserved() { + let f = Fixture::new(1024); + let faces = Faces::try_load(&f.0).unwrap(); + assert_eq!(faces.size, 1024); + assert_eq!(faces.pixels.len(), 6 * 1024 * 1024 * 4); + // CubeMapTexture's actual layer suffixes, with each source row flipped vertically. + for (layer, source_face) in [1, 3, 5, 4, 0, 2].into_iter().enumerate() { + for y in 0..1024 { + for x in 0..1024 { + let at = ((layer * 1024 + y) * 1024 + x) * 4; + assert_eq!( + faces.pixels[at..at + 4], + [source_face, (x % 251) as u8, ((1023 - y) % 253) as u8, 255] + ); + } + } + } + } + + #[test] + fn placeholders_load_and_incomplete_or_mismatched_cubes_fall_back() { + let f = Fixture::new(1); + assert_eq!(Faces::try_load(&f.0).unwrap().size, 1); + f.write(5, 2, 1); + assert!( + Faces::try_load(&f.0) + .unwrap_err() + .to_string() + .contains("equally sized squares") + ); + let fallback = Faces::load(&f.0); + assert_eq!(fallback.pixels.len(), 24); + f.write(5, 2, 2); + assert!(Faces::try_load(&f.0).is_err()); + fs::remove_file(f.background().join("panorama_5.png")).unwrap(); + assert!(Faces::try_load(&f.0).is_err()); + assert_eq!(Faces::load(&f.0).size, 1); + } + + #[test] + fn cube_shader_validates() { + let module = naga::front::wgsl::parse_str(include_str!("panorama.wgsl")).unwrap(); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + .unwrap(); + } + + #[test] + fn vanilla_camera_centres_the_positive_z_face_and_pitches_ten_degrees() { + let straight = projection(1920, 1080, 0.0, 0.0) * glam::Vec4::new(0.0, 0.0, 1.0, 1.0); + assert!((straight.x / straight.w).abs() < 1e-6); + assert!((straight.y / straight.w).abs() < 1e-6); + assert!(straight.w > 0.0); + let pitched = projection(1920, 1080, 0.0, 10.0) * glam::Vec4::new(0.0, 0.0, 1.0, 1.0); + let expected_y = 10.0f32.to_radians().tan() / 42.5f32.to_radians().tan(); + assert!((pitched.y / pitched.w - expected_y).abs() < 1e-6); + } +} diff --git a/crates/horizon-client/src/gfx/panorama.wgsl b/crates/horizon-client/src/gfx/panorama.wgsl new file mode 100644 index 000000000..26c53949a --- /dev/null +++ b/crates/horizon-client/src/gfx/panorama.wgsl @@ -0,0 +1,30 @@ +// CubeMap's position-only cube and panorama.vsh/fsh: sample its untransformed direction. +struct Projection { view_proj: mat4x4 } +@group(0) @binding(0) var projection: Projection; +@group(0) @binding(1) var panorama: texture_cube; +@group(0) @binding(2) var panorama_sampler: sampler; +struct Out { + @builtin(position) clip: vec4, + @location(0) direction: vec3, +} +@vertex fn vs_panorama(@builtin(vertex_index) index: u32) -> Out { + let corners = array, 8>( + vec3(-1.0, -1.0, -1.0), vec3(1.0, -1.0, -1.0), + vec3(1.0, 1.0, -1.0), vec3(-1.0, 1.0, -1.0), + vec3(-1.0, -1.0, 1.0), vec3(1.0, -1.0, 1.0), + vec3(1.0, 1.0, 1.0), vec3(-1.0, 1.0, 1.0), + ); + let indices = array( + 4, 7, 6, 4, 6, 5, 5, 6, 2, 5, 2, 1, + 1, 2, 3, 1, 3, 0, 0, 3, 7, 0, 7, 4, + 7, 3, 2, 7, 2, 6, 0, 4, 5, 0, 5, 1, + ); + let position = corners[indices[index]]; + var out: Out; + out.clip = projection.view_proj * vec4(position, 1.0); + out.direction = position; + return out; +} +@fragment fn fs_panorama(in: Out) -> @location(0) vec4 { + return textureSample(panorama, panorama_sampler, in.direction); +} diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 0f105ff28..7f047b988 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -151,9 +151,7 @@ impl HudAtlas { walk(&textures.join("map"), &mut files); files.retain(|p| { let s = p.to_string_lossy(); - (!s.contains("title/background") || s.contains("panorama_")) - && !s.contains("realms") - && !s.contains("presets") + !s.contains("title/background") && !s.contains("realms") && !s.contains("presets") }); let decode_one = |path: &PathBuf| -> Option<(String, u32, u32, Vec)> { let name = path @@ -170,18 +168,6 @@ impl HudAtlas { } else { pixels }; - // Title panorama faces are downsampled to 256 for the shared atlas. - if name.contains("panorama_") && w >= 512 && w == h { - let step = (w / 256) as usize; - let mut small = Vec::with_capacity(256 * 256 * 4); - for y in 0..256usize { - for x in 0..256usize { - let i = ((y * step) * w as usize + x * step) * 4; - small.extend_from_slice(&pixels[i..i + 4]); - } - } - return Some((name, 256, 256, small)); - } (w <= 1024 && (h <= 512 || name.starts_with("font/"))).then_some((name, w, h, pixels)) }; let threads = std::thread::available_parallelism().map_or(2, |n| n.get());