diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index f8271845f..810a71538 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -144,6 +144,8 @@ impl Game<'_> { r.gamma = s.gamma; r.set_present_mode(s.vsync, s.horizon.present_mode); r.animated_textures = s.horizon.animated_textures; + r.set_mipmap_levels(s.mipmap_levels.max(0) as u32); + r.set_world_post(s.horizon.resolution_scale as f32 / 100.0, s.horizon.fxaa); } if let Some(w) = &self.window { let want = s.fullscreen; diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index d1d346456..9c8dfac09 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -15,6 +15,7 @@ use winit::window::Window; mod arena; mod occlusion; +mod post; mod timing; #[repr(C)] @@ -166,6 +167,12 @@ pub struct Renderer { lightmap: wgpu::Texture, sprite_texture: wgpu::Texture, mip_levels: u32, + /// The mipmap levels sampled (the Mipmap Levels option), at most `mip_levels - 1`. + mipmaps: u32, + terrain_layout: wgpu::BindGroupLayout, + sprite_sampler: wgpu::Sampler, + lightmap_view: wgpu::TextureView, + lightmap_sampler: wgpu::Sampler, animations: Vec<(SpriteAnimation, usize)>, indices: wgpu::Buffer, index_quads: u32, @@ -190,6 +197,8 @@ pub struct Renderer { block_entities: HashMap>, /// VisGraph face connectivity per meshed section (cave culling). occlusion: occlusion::Occlusion, + /// Resolution scale and FXAA (Horizon settings). + post: post::Post, pub hud: HudRenderer, pub info: wgpu::AdapterInfo, pub suspended: bool, @@ -1111,6 +1120,7 @@ impl Renderer { let multi_draw = device .features() .contains(wgpu::Features::INDIRECT_FIRST_INSTANCE); + let post = post::Post::new(&device, config.format.remove_srgb_suffix()); Ok(Self { instance, surface, @@ -1148,6 +1158,11 @@ impl Renderer { lightmap, sprite_texture, mip_levels, + mipmaps: mip_levels - 1, + terrain_layout: bindings, + sprite_sampler, + lightmap_view, + lightmap_sampler, animations: animations.iter().map(|a| (a.clone(), usize::MAX)).collect(), indices, index_quads, @@ -1165,6 +1180,7 @@ impl Renderer { draws: Vec::new(), block_entities: HashMap::new(), occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16), + post, hud, info, suspended: size.width == 0 || size.height == 0, @@ -1372,6 +1388,51 @@ impl Renderer { self.occlusion.remove(key); self.release_section(key); } + /// Horizon's resolution scale (world pixels per window pixel) and FXAA. + pub fn set_world_post(&mut self, scale: f32, antialias: bool) { + self.post.scale = scale.clamp(0.25, 2.0); + self.post.antialias = antialias; + } + /// The Mipmap Levels option: block textures sample at most `levels` + /// reduced copies (0: none). + pub fn set_mipmap_levels(&mut self, levels: u32) { + let levels = levels.min(self.mip_levels - 1); + if levels == self.mipmaps { + 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() + }); + self.group = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Horizon terrain resources"), + layout: &self.terrain_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: self.globals.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&sprite_view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&self.sprite_sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(&self.lightmap_view), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Sampler(&self.lightmap_sampler), + }, + ], + }); + } pub fn view_projection(&self, frame: &Frame) -> Mat4 { self.projection( frame.fov_degrees, @@ -1830,9 +1891,17 @@ impl Renderer { if let Some(timer) = &mut self.gpu_timer { timer.begin(&mut encoder); } + // The world's targets: the screen, or the scaled target of `post`. + let scaled = self + .post + .prepare(&self.device, [self.config.width, self.config.height]); + let (world_view, world_depth) = match &scaled { + Some((color, depth)) => (color, depth), + None => (&view_target, &self.depth), + }; { let attachments = [Some(wgpu::RenderPassColorAttachment { - view: &view_target, + view: world_view, resolve_target: None, depth_slice: None, ops: wgpu::Operations { @@ -1855,7 +1924,7 @@ impl Renderer { label: Some("Horizon world"), color_attachments: &attachments, depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &self.depth, + view: world_depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard, @@ -1930,6 +1999,9 @@ impl Renderer { pass.set_bind_group(0, &self.group, &[]); } } + if scaled.is_some() { + self.post.finish(&mut encoder, &view_target); + } if hand_quads > 0 { let attachments = [Some(wgpu::RenderPassColorAttachment { view: &view_target, diff --git a/crates/horizon-client/src/gfx/post.rs b/crates/horizon-client/src/gfx/post.rs new file mode 100644 index 000000000..061c61a0b --- /dev/null +++ b/crates/horizon-client/src/gfx/post.rs @@ -0,0 +1,187 @@ +//! Resolution scale and FXAA (Horizon settings): the world renders into its +//! own target at the scaled size, then one full-screen pass copies or +//! anti-aliases it onto the screen, under the hand and HUD. With neither +//! setting on, the world renders straight to the screen as before. + +struct WorldTarget { + size: [u32; 2], + color: wgpu::TextureView, + depth: wgpu::TextureView, + group: wgpu::BindGroup, +} + +pub struct Post { + layout: wgpu::BindGroupLayout, + sampler: wgpu::Sampler, + copy: wgpu::RenderPipeline, + fxaa: wgpu::RenderPipeline, + format: wgpu::TextureFormat, + /// World resolution relative to the window (0.5..=2.0). + pub scale: f32, + pub antialias: bool, + target: Option, +} + +impl Post { + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Horizon post"), + source: wgpu::ShaderSource::Wgsl(include_str!("../post.wgsl").into()), + }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Horizon post bindings"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Horizon post"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pipeline = |entry: &str| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Horizon post"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_post"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some(entry), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }; + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Horizon post"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + Self { + copy: pipeline("fs_copy"), + fxaa: pipeline("fs_fxaa"), + layout, + sampler, + format, + scale: 1.0, + antialias: false, + target: None, + } + } + /// The world's colour and depth targets this frame, or `None` to draw + /// it straight to the screen. + pub fn prepare( + &mut self, + device: &wgpu::Device, + window: [u32; 2], + ) -> Option<(wgpu::TextureView, wgpu::TextureView)> { + if self.scale == 1.0 && !self.antialias { + self.target = None; + return None; + } + let size = window.map(|v| ((v as f32 * self.scale).round() as u32).clamp(1, 8192)); + if self.target.as_ref().is_none_or(|t| t.size != size) { + let extent = wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }; + let texture = |label, format, usage| { + device + .create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: extent, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + .create_view(&Default::default()) + }; + let color = texture( + "Scaled world", + self.format, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + ); + let depth = texture( + "Scaled world depth", + wgpu::TextureFormat::Depth32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT, + ); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Horizon post"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&color), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&self.sampler), + }, + ], + }); + self.target = Some(WorldTarget { + size, + color, + depth, + group, + }); + } + 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) { + let Some(target) = &self.target else { return }; + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: screen, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Horizon post"), + color_attachments: &attachments, + ..Default::default() + }); + 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/graphics.rs b/crates/horizon-client/src/graphics.rs index 6eff301de..e2a03356b 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -130,6 +130,10 @@ pub struct Graphics { /// Chunk worker threads; 0 uses every core but one. Applies at the next start. pub workers: u32, pub overlay: Overlay, + /// World resolution as a percentage of the window's (50..=200). + pub resolution_scale: u32, + /// FXAA over the world. + pub fxaa: bool, } impl Default for Graphics { fn default() -> Self { @@ -146,6 +150,8 @@ impl Default for Graphics { pacing: Pacing::Efficient, workers: 0, overlay: Overlay::Off, + resolution_scale: 100, + fxaa: false, } } } @@ -189,6 +195,10 @@ impl Graphics { } } "workers" => g.workers = number(g.workers).min(64), + "resolutionScale" => { + g.resolution_scale = number(g.resolution_scale).clamp(50, 200) + } + "fxaa" => g.fxaa = flag(g.fxaa), "overlay" => { g.overlay = match value { "fps" => Overlay::Fps, @@ -203,7 +213,7 @@ impl Graphics { } pub fn serialize(&self) -> String { format!( - "preset:{}\ncaveCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\n", + "preset:{}\ncaveCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\n", self.preset.name(), bool_text(self.cave_culling), self.chunk_updates, @@ -223,6 +233,8 @@ impl Graphics { Overlay::Fps => "fps", Overlay::Graph => "graph", }, + self.resolution_scale, + bool_text(self.fxaa), ) } pub fn save(&self, dir: &Path) { @@ -291,6 +303,8 @@ mod tests { pacing: Pacing::Precise, workers: 6, overlay: Overlay::Graph, + resolution_scale: 75, + fxaa: true, }; assert_eq!(Graphics::parse(&g.serialize()), g); assert_eq!(Graphics::parse(""), Graphics::default()); diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index 6c87d7f10..c0c0c35f8 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -32,6 +32,8 @@ pub enum H { Pacing, Workers, Overlay, + ResolutionScale, + Antialiasing, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -119,6 +121,11 @@ fn rows(level: Level) -> Vec { Low, "Soft shadows in corners. Costs chunk building time only.", ), + v( + Opt::Mipmaps, + Low, + "Smaller copies of block textures for distant terrain: less shimmer.", + ), v( Opt::BiomeBlend, Low, @@ -158,6 +165,16 @@ fn rows(level: Level) -> Vec { fov, fps, vsync, + h( + H::ResolutionScale, + High, + "World pixels per screen pixel. Below 100% is faster on the GPU.", + ), + h( + H::Antialiasing, + Low, + "FXAA smooths jagged edges of the world; slightly softer image.", + ), h( H::PresentMode, None, @@ -213,6 +230,7 @@ impl H { Some(i as f32 / (UPLOAD_STEPS.len() - 1) as f32) } H::Workers => Some(g.workers as f32 / max_workers() as f32), + H::ResolutionScale => Some((g.resolution_scale as f32 - 50.0) / 150.0), _ => None, } } @@ -246,6 +264,8 @@ impl H { 0 => labelled("Worker Threads", format!("Auto ({})", g.worker_threads())), n => labelled("Worker Threads", n), }, + H::ResolutionScale => labelled("Resolution Scale", format!("{}%", g.resolution_scale)), + H::Antialiasing => labelled("Anti-aliasing", if g.fxaa { "FXAA" } else { "Off" }), H::Overlay => labelled( "Performance Overlay", match g.overlay { @@ -265,6 +285,7 @@ impl H { UPLOAD_STEPS[(v * (UPLOAD_STEPS.len() - 1) as f32).round() as usize] } H::Workers => g.workers = (v * max_workers() as f32).round() as u32, + H::ResolutionScale => g.resolution_scale = (50.0 + (v * 30.0).round() * 5.0) as u32, _ => {} } } @@ -288,6 +309,7 @@ impl H { H::Weather => g.weather = !g.weather, H::AnimatedTextures => g.animated_textures = !g.animated_textures, H::PresentMode => g.present_mode = step(&PresentMode::ALL, g.present_mode, back), + H::Antialiasing => g.fxaa = !g.fxaa, H::Pacing => { g.pacing = match g.pacing { Pacing::Efficient => Pacing::Precise, diff --git a/crates/horizon-client/src/post.wgsl b/crates/horizon-client/src/post.wgsl new file mode 100644 index 000000000..7332213c5 --- /dev/null +++ b/crates/horizon-client/src/post.wgsl @@ -0,0 +1,55 @@ +// Horizon's world post pass: the world, rendered at the resolution scale, +// copied (bilinear) or anti-aliased with FXAA onto the screen before the +// hand and HUD. Only used when a non-vanilla setting asks for it. +@group(0) @binding(0) var world: texture_2d; +@group(0) @binding(1) var world_sampler: sampler; + +struct PostOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +}; + +@vertex fn vs_post(@builtin(vertex_index) i: u32) -> PostOut { + let p = vec2(f32((i << 1u) & 2u), f32(i & 2u)); + var out: PostOut; + out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0); + out.uv = vec2(p.x, 1.0 - p.y); + return out; +} + +@fragment fn fs_copy(in: PostOut) -> @location(0) vec4 { + return vec4(textureSampleLevel(world, world_sampler, in.uv, 0.0).rgb, 1.0); +} + +fn luma(c: vec3) -> f32 { + return dot(c, vec3(0.299, 0.587, 0.114)); +} + +// FXAA 3.11 (console quality): blend along the local edge direction. +@fragment fn fs_fxaa(in: PostOut) -> @location(0) vec4 { + let texel = 1.0 / vec2(textureDimensions(world)); + let rgb_m = textureSampleLevel(world, world_sampler, in.uv, 0.0).rgb; + let nw = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(-0.5, -0.5) * texel, 0.0).rgb); + let ne = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(0.5, -0.5) * texel, 0.0).rgb); + let sw = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(-0.5, 0.5) * texel, 0.0).rgb); + let se = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(0.5, 0.5) * texel, 0.0).rgb); + let m = luma(rgb_m); + let lo = min(m, min(min(nw, ne), min(sw, se))); + let hi = max(m, max(max(nw, ne), max(sw, se))); + if hi - lo < max(0.0312, hi * 0.125) { + return vec4(rgb_m, 1.0); + } + var dir = vec2(-((nw + ne) - (sw + se)), (nw + sw) - (ne + se)); + let reduce = max((nw + ne + sw + se) * 0.25 * 0.125, 1.0 / 128.0); + let scale = 1.0 / (min(abs(dir.x), abs(dir.y)) + reduce); + dir = clamp(dir * scale, vec2(-8.0), vec2(8.0)) * texel; + let a = 0.5 * (textureSampleLevel(world, world_sampler, in.uv + dir * (1.0 / 3.0 - 0.5), 0.0).rgb + + textureSampleLevel(world, world_sampler, in.uv + dir * (2.0 / 3.0 - 0.5), 0.0).rgb); + let b = a * 0.5 + 0.25 * (textureSampleLevel(world, world_sampler, in.uv - dir * 0.5, 0.0).rgb + + textureSampleLevel(world, world_sampler, in.uv + dir * 0.5, 0.0).rgb); + let lb = luma(b); + if lb < lo || lb > hi { + return vec4(a, 1.0); + } + return vec4(b, 1.0); +}