Screen overlays: one texture sample, as on main
The vignette, drawn over every frame, went from one texture sample to up to four texel loads and per-pixel address arithmetic: +0.85 ms of GPU a frame on an HD 620 (integer modulo, removed in the commit before), still +0.4 ms after it. - A blurred sprite gets a one-texel border in the atlas, copied from its opposite edges: the hardware's bilinear sample of the atlas with the entity group's linear sampler is then GL_LINEAR with repeat, edges included. Clamp-to-edge keeps the sample point half a texel inside the sprite, which is what the hardware's clamp does for both filters. - Each sampling has its own pipeline, the shader specialised by override constants: a repeat sprite runs main's arithmetic and one sample, nearest or linear; only clamp adds a clamp. The sampling moves from the vertices to the quad, so the vertex layout is main's again. - A black vignette changes no pixel (it darkens by texture x colour), and is no longer drawn: in daylight its brightness fades to 0 within half a minute, so most frames outdoors skip it, which main never could. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -357,8 +357,9 @@ pub struct Renderer {
|
||||
border_group: wgpu::BindGroup,
|
||||
border_uniform: wgpu::Buffer,
|
||||
border_vertices: wgpu::Buffer,
|
||||
/// Screen effects: alpha-blended and vignette (`dst * (1 - src)`) pipelines.
|
||||
screen_pipelines: [wgpu::RenderPipeline; 2],
|
||||
/// Screen effects: alpha-blended, then vignette (`dst * (1 - src)`)
|
||||
/// pipelines, each for every sampling (index `blend * 4 + sampling`).
|
||||
screen_pipelines: [wgpu::RenderPipeline; 8],
|
||||
screen_buffer: wgpu::Buffer,
|
||||
screen_capacity: u64,
|
||||
entity_group: wgpu::BindGroup,
|
||||
@@ -1983,7 +1984,7 @@ impl Renderer {
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("screen.wgsl").into()),
|
||||
});
|
||||
let screen_attributes =
|
||||
wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4,4=>Uint32];
|
||||
wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4];
|
||||
let screen_vertex = [Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<crate::screen_effects::ScreenVertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
@@ -2001,37 +2002,52 @@ impl Renderer {
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
};
|
||||
let screen_pipelines =
|
||||
[("fs_screen", alpha_blend), ("fs_vignette", vignette_blend)].map(|(entry, blend)| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Screen effects"),
|
||||
layout: Some(&entity_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &screen_shader,
|
||||
entry_point: Some("vs_screen"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &screen_vertex,
|
||||
},
|
||||
primitive: wgpu::PrimitiveState {
|
||||
cull_mode: None,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &screen_shader,
|
||||
entry_point: Some(entry),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: config.format.remove_srgb_suffix(),
|
||||
blend: Some(blend),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
});
|
||||
// One per blend and `.png.mcmeta` sampling (screen_effects::SAMPLE_*):
|
||||
// the shader is specialised, so a pixel pays for none of the others.
|
||||
let screen_pipelines: [wgpu::RenderPipeline; 8] = std::array::from_fn(|i| {
|
||||
let (entry, blend) = if i & 4 == 0 {
|
||||
("fs_screen", alpha_blend)
|
||||
} else {
|
||||
("fs_vignette", vignette_blend)
|
||||
};
|
||||
let on = |bit: u32| f64::from(u8::from(i as u32 & bit != 0));
|
||||
let constants = [
|
||||
("BLUR", on(crate::screen_effects::SAMPLE_BLUR)),
|
||||
("CLAMP", on(crate::screen_effects::SAMPLE_CLAMP)),
|
||||
];
|
||||
let compilation_options = wgpu::PipelineCompilationOptions {
|
||||
constants: &constants,
|
||||
..Default::default()
|
||||
};
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Screen effects"),
|
||||
layout: Some(&entity_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &screen_shader,
|
||||
entry_point: Some("vs_screen"),
|
||||
compilation_options: compilation_options.clone(),
|
||||
buffers: &screen_vertex,
|
||||
},
|
||||
primitive: wgpu::PrimitiveState {
|
||||
cull_mode: None,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &screen_shader,
|
||||
entry_point: Some(entry),
|
||||
compilation_options,
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: config.format.remove_srgb_suffix(),
|
||||
blend: Some(blend),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
});
|
||||
let screen_capacity = 64;
|
||||
let screen_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Screen effect vertices"),
|
||||
@@ -3911,11 +3927,11 @@ impl Renderer {
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(0, self.screen_buffer.slice(..));
|
||||
for (i, quad) in frame.screen.iter().enumerate() {
|
||||
let pipeline = match quad.blend {
|
||||
crate::screen_effects::Blend::Alpha => &self.screen_pipelines[0],
|
||||
crate::screen_effects::Blend::Vignette => &self.screen_pipelines[1],
|
||||
let blend = match quad.blend {
|
||||
crate::screen_effects::Blend::Alpha => 0,
|
||||
crate::screen_effects::Blend::Vignette => 4,
|
||||
};
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_pipeline(&self.screen_pipelines[blend + (quad.sampling & 3) as usize]);
|
||||
pass.draw_indexed(0..6, (i * 4) as i32, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,20 @@ fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
}
|
||||
/// A packed atlas image: sprite name, size and RGBA pixels.
|
||||
type PackedImage = (String, u32, u32, Vec<u8>);
|
||||
/// `image` inside a one-texel border copied from its opposite edges, the
|
||||
/// texels repeat addressing reads past each edge.
|
||||
fn wrap_border((name, w, h, data): &PackedImage) -> PackedImage {
|
||||
let (bw, bh) = (w + 2, h + 2);
|
||||
let mut out = Vec::with_capacity((bw * bh * 4) as usize);
|
||||
for y in 0..bh {
|
||||
let row = (y + h - 1) % h;
|
||||
for x in 0..bw {
|
||||
let at = ((row * w + (x + w - 1) % w) * 4) as usize;
|
||||
out.extend_from_slice(&data[at..at + 4]);
|
||||
}
|
||||
}
|
||||
(name.clone(), bw, bh, out)
|
||||
}
|
||||
/// Sprites the atlas definitions (`atlases/*.json`) add beyond the texture
|
||||
/// files already packed: generated ones (`paletted_permutations` such as the
|
||||
/// armour trim sprites, `unstitch` regions) and files listed under another id.
|
||||
@@ -326,6 +340,16 @@ impl HudAtlas {
|
||||
if full {
|
||||
Self::slots(&mut images, crate::trims::slot_size(root));
|
||||
}
|
||||
// Blurred sprites are sampled linearly in the atlas (screen.wgsl): a
|
||||
// border wrapped from their own edges keeps the filter off their
|
||||
// neighbours, as repeat addressing of their own texture would.
|
||||
let mut bordered = std::collections::HashSet::new();
|
||||
for image in &mut images {
|
||||
if flags.get(&image.0).is_some_and(|f: &TextureFlags| f.blur) {
|
||||
*image = wrap_border(image);
|
||||
bordered.insert(image.0.clone());
|
||||
}
|
||||
}
|
||||
images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1)));
|
||||
let width = 4096u32;
|
||||
let mut placements = Vec::with_capacity(images.len());
|
||||
@@ -350,6 +374,8 @@ impl HudAtlas {
|
||||
let dst = (((py + row) * width + px) * 4) as usize;
|
||||
pixels[dst..dst + (w * 4) as usize].copy_from_slice(src);
|
||||
}
|
||||
let b = u32::from(bordered.contains(name));
|
||||
let (px, py, w, h) = (px + b, py + b, w - 2 * b, h - 2 * b);
|
||||
sprites.insert(
|
||||
name.clone(),
|
||||
Rect {
|
||||
@@ -357,8 +383,8 @@ impl HudAtlas {
|
||||
v0: py as f32 / height as f32,
|
||||
u1: (px + w) as f32 / width as f32,
|
||||
v1: (py + h) as f32 / height as f32,
|
||||
w: *w,
|
||||
h: *h,
|
||||
w,
|
||||
h,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1246,6 +1272,30 @@ impl HudRenderer {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_wrapped_border_repeats_the_opposite_edges() {
|
||||
// 2x2 texels a b / c d, one byte each in red.
|
||||
let image = (
|
||||
"x".to_owned(),
|
||||
2,
|
||||
2,
|
||||
[1u8, 2, 3, 4]
|
||||
.iter()
|
||||
.flat_map(|&v| [v, 0, 0, 255])
|
||||
.collect(),
|
||||
);
|
||||
let (_, w, h, data) = wrap_border(&image);
|
||||
assert_eq!((w, h), (4, 4));
|
||||
let red: Vec<u8> = data.chunks(4).map(|t| t[0]).collect();
|
||||
#[rustfmt::skip]
|
||||
assert_eq!(red, [
|
||||
4, 3, 4, 3,
|
||||
2, 1, 2, 1,
|
||||
4, 3, 4, 3,
|
||||
2, 1, 2, 1,
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fonts_only_atlas_measures_text_like_the_full_one() {
|
||||
// A synthetic default font: two 8x8 glyphs, 3 and 5 pixels wide.
|
||||
|
||||
@@ -3,51 +3,49 @@
|
||||
// with the sampler vanilla gives it (ReloadableTexture.setSampler: linear
|
||||
// when `blur`, clamp-to-edge when `clamp`, else nearest and repeat).
|
||||
@group(0) @binding(1) var atlas: texture_2d<f32>;
|
||||
// The block sprites' sampler (nearest), and the entity group's lightmap
|
||||
// sampler (linear) for `blur`. A blurred sprite has a one-texel border in the
|
||||
// atlas, wrapped as repeat reads it (hud.rs), so the hardware's bilinear
|
||||
// sample is GL_LINEAR with repeat; clamp-to-edge keeps the sample point half
|
||||
// a texel inside. Each sampling has its own pipeline (gfx.rs), so a pixel
|
||||
// costs what it did with nearest and repeat only: one sample.
|
||||
@group(0) @binding(2) var nearest_sampler: sampler;
|
||||
@group(0) @binding(4) var linear_sampler: sampler;
|
||||
override BLUR: bool = false;
|
||||
override CLAMP: bool = false;
|
||||
struct Out {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
@location(1) @interpolate(flat) rect: vec4<f32>,
|
||||
@location(2) color: vec4<f32>,
|
||||
@location(3) @interpolate(flat) sampling: u32,
|
||||
// With clamp-to-edge, the sprite's first and last texel centres.
|
||||
@location(3) @interpolate(flat) edges: vec4<f32>,
|
||||
}
|
||||
@vertex fn vs_screen(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) rect: vec4<f32>, @location(3) color: vec4<f32>,
|
||||
@location(4) sampling: u32) -> Out {
|
||||
@location(2) rect: vec4<f32>, @location(3) color: vec4<f32>) -> Out {
|
||||
var out: Out;
|
||||
out.clip = vec4(pos, 0.0, 1.0);
|
||||
out.uv = uv;
|
||||
out.rect = rect;
|
||||
out.color = color;
|
||||
out.sampling = sampling;
|
||||
let half = 0.5 / vec2<f32>(textureDimensions(atlas));
|
||||
out.edges = vec4(rect.xy + half, rect.zw - half);
|
||||
return out;
|
||||
}
|
||||
const SAMPLE_BLUR: u32 = 1u;
|
||||
const SAMPLE_CLAMP: u32 = 2u;
|
||||
// A texel of the sprite, addressed by repeat or clamp-to-edge. With repeat, `p` is at most one
|
||||
// texel outside the sprite (`sample` reduces the coordinate first), so wrapping is a select: no
|
||||
// integer division, which Intel GPUs emulate (it cost 0.85 ms a frame on the vignette on an HD 620).
|
||||
fn texel(origin: vec2<i32>, size: vec2<i32>, p: vec2<i32>, clamp_edge: bool) -> vec4<f32> {
|
||||
var q = select(select(p, p - size, p >= size), p + size, p < vec2(0));
|
||||
if clamp_edge { q = clamp(p, vec2(0), size - 1); }
|
||||
return textureLoad(atlas, origin + q, 0);
|
||||
}
|
||||
fn sample(in: Out) -> vec4<f32> {
|
||||
let dims = vec2<f32>(textureDimensions(atlas));
|
||||
let origin = vec2<i32>(round(in.rect.xy * dims));
|
||||
let size = max(vec2<i32>(round((in.rect.zw - in.rect.xy) * dims)), vec2(1));
|
||||
let clamp_edge = (in.sampling & SAMPLE_CLAMP) != 0u;
|
||||
// Repeat: one period of the sprite, so every texel read is at most one outside it.
|
||||
let p = select(fract(in.uv), in.uv, clamp_edge) * vec2<f32>(size);
|
||||
if (in.sampling & SAMPLE_BLUR) == 0u {
|
||||
return texel(origin, size, vec2<i32>(floor(p)), clamp_edge) * in.color;
|
||||
var f = in.uv;
|
||||
if !CLAMP {
|
||||
// Repeat: one period of the sprite.
|
||||
f = fract(f);
|
||||
}
|
||||
// GL_LINEAR: the four texels around the sample point, weighted.
|
||||
let c = p - 0.5;
|
||||
let i = vec2<i32>(floor(c));
|
||||
let t = c - floor(c);
|
||||
let a = mix(texel(origin, size, i, clamp_edge), texel(origin, size, i + vec2(1, 0), clamp_edge), t.x);
|
||||
let b = mix(texel(origin, size, i + vec2(0, 1), clamp_edge), texel(origin, size, i + vec2(1, 1), clamp_edge), t.x);
|
||||
return mix(a, b, t.y) * in.color;
|
||||
var uv = in.rect.xy + f * (in.rect.zw - in.rect.xy);
|
||||
if CLAMP {
|
||||
uv = clamp(uv, in.edges.xy, in.edges.zw);
|
||||
}
|
||||
if BLUR {
|
||||
return textureSampleLevel(atlas, linear_sampler, uv, 0.0) * in.color;
|
||||
}
|
||||
return textureSampleLevel(atlas, nearest_sampler, uv, 0.0) * in.color;
|
||||
}
|
||||
@fragment fn fs_screen(in: Out) -> @location(0) vec4<f32> {
|
||||
let c = sample(in);
|
||||
|
||||
@@ -27,8 +27,6 @@ pub struct ScreenVertex {
|
||||
/// Atlas rectangle (u0, v0, u1, v1) of the sprite.
|
||||
pub rect: [f32; 4],
|
||||
pub color: [f32; 4],
|
||||
/// How the sprite is sampled: [`SAMPLE_BLUR`] and [`SAMPLE_CLAMP`].
|
||||
pub sampling: u32,
|
||||
}
|
||||
/// Linear filtering (`TextureMetadataSection.blur`), else nearest.
|
||||
pub const SAMPLE_BLUR: u32 = 1;
|
||||
@@ -43,6 +41,8 @@ pub fn sampling(flags: TextureFlags) -> u32 {
|
||||
pub struct ScreenQuad {
|
||||
pub vertices: [ScreenVertex; 4],
|
||||
pub blend: Blend,
|
||||
/// How the sprite is sampled: [`SAMPLE_BLUR`] and [`SAMPLE_CLAMP`].
|
||||
pub sampling: u32,
|
||||
}
|
||||
|
||||
/// What the camera sees this frame.
|
||||
@@ -124,9 +124,9 @@ impl ScreenEffects {
|
||||
uv: uv[i],
|
||||
rect,
|
||||
color,
|
||||
sampling,
|
||||
}),
|
||||
blend: Blend::Alpha,
|
||||
sampling,
|
||||
};
|
||||
let full = [[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]];
|
||||
// ScreenEffectRenderer.submitBlockSprite: u1/v1 at (-1, -1), colour 0xFF191919.
|
||||
@@ -187,10 +187,10 @@ impl ScreenEffects {
|
||||
uv: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]][i],
|
||||
rect,
|
||||
color,
|
||||
sampling,
|
||||
}
|
||||
}),
|
||||
blend,
|
||||
sampling,
|
||||
};
|
||||
let rgba = |c: u32| {
|
||||
let [a, r, g, b] = c.to_be_bytes();
|
||||
@@ -213,6 +213,12 @@ impl ScreenEffects {
|
||||
} else {
|
||||
Blend::Alpha
|
||||
};
|
||||
// The vignette darkens by texture × colour: black (in
|
||||
// daylight its brightness fades to 0 within half a
|
||||
// minute) leaves every pixel as it was.
|
||||
if blend == Blend::Vignette && color & 0x00ff_ffff == 0 {
|
||||
continue;
|
||||
}
|
||||
if let Some(rect) = sprite(texture) {
|
||||
out.push(gui(rect, rgba(*color), blend, texture_sampling(texture)));
|
||||
}
|
||||
@@ -283,7 +289,18 @@ mod tests {
|
||||
let quads = e.build(&input);
|
||||
assert_eq!(quads.len(), 1);
|
||||
assert_eq!(quads[0].blend, Blend::Vignette);
|
||||
assert_eq!(quads[0].vertices[0].sampling, 0);
|
||||
assert_eq!(quads[0].sampling, 0);
|
||||
// A black vignette (faded out in daylight) changes no pixel: no quad.
|
||||
// Below 1/255 the colour's channels are 0; a border warning tints it.
|
||||
for (brightness, warning, drawn) in [(0.003, 0.0, 0), (0.004, 0.0, 1), (0.0, 0.5, 1)] {
|
||||
let overlays = [crate::hud_overlays::vignette(320, 240, brightness, warning)];
|
||||
let input = ScreenInputs {
|
||||
block_overlay: None,
|
||||
gui_overlays: &overlays,
|
||||
..input
|
||||
};
|
||||
assert_eq!(e.build(&input).len(), drawn, "{brightness} {warning}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn standalone_textures_sample_by_their_metadata() {
|
||||
@@ -323,7 +340,7 @@ mod tests {
|
||||
on_fire: false,
|
||||
gui_overlays: &[crate::hud_overlays::vignette(320, 240, 1.0, 0.0)],
|
||||
});
|
||||
let sampling: Vec<_> = quads.iter().map(|q| q.vertices[0].sampling).collect();
|
||||
let sampling: Vec<_> = quads.iter().map(|q| q.sampling).collect();
|
||||
assert_eq!(sampling, [0, SAMPLE_CLAMP, SAMPLE_BLUR]);
|
||||
}
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user