#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum DownsampleFilter {
Box,
Tent,
#[default]
Mitchell,
Lanczos2,
}
impl DownsampleFilter {
fn radius(self) -> f32 {
match self {
Self::Box => 0.5,
Self::Tent => 1.0,
Self::Mitchell | Self::Lanczos2 => 2.0,
}
}
fn weight(self, x: f32) -> f32 {
let x = x.abs();
match self {
Self::Box => {
if x < 0.5 {
1.0
} else {
0.0
}
}
Self::Tent => (1.0 - x).max(0.0),
Self::Mitchell => {
const B: f32 = 1.0 / 3.0;
const C: f32 = 1.0 / 3.0;
let (x2, x3) = (x * x, x * x * x);
if x < 1.0 {
((12.0 - 9.0 * B - 6.0 * C) * x3
+ (-18.0 + 12.0 * B + 6.0 * C) * x2
+ (6.0 - 2.0 * B))
/ 6.0
} else if x < 2.0 {
((-B - 6.0 * C) * x3
+ (6.0 * B + 30.0 * C) * x2
+ (-12.0 * B - 48.0 * C) * x
+ (8.0 * B + 24.0 * C))
/ 6.0
} else {
0.0
}
}
Self::Lanczos2 => {
if x < 1.0e-6 {
1.0
} else if x < 2.0 {
let pi_x = std::f32::consts::PI * x;
(pi_x.sin() / pi_x) * ((pi_x * 0.5).sin() / (pi_x * 0.5))
} else {
0.0
}
}
}
}
fn taps(self, factor: u32) -> (Vec<f32>, i32) {
let f = factor as f32;
if self == Self::Box {
return (vec![1.0 / f; factor as usize], 0);
}
let half = (self.radius() * f).ceil() as i32;
let n = 2 * half;
let off = -half + factor as i32 / 2;
let mut w: Vec<f32> = (0..n)
.map(|k| self.weight(((k + off) as f32 + 0.5 - f * 0.5) / f))
.collect();
let sum: f32 = w.iter().sum();
if sum.abs() < 1.0e-8 {
return (vec![1.0 / f; factor as usize], 0);
}
for v in &mut w {
*v /= sum;
}
(w, off)
}
}
pub struct Downsampler {
factor: u32,
filter: DownsampleFilter,
width: u32,
height: u32,
texture: wgpu::Texture,
mid: Option<wgpu::Texture>,
stages: Vec<Stage>,
}
struct Stage {
target: wgpu::TextureView,
bind: wgpu::BindGroup,
pipeline: wgpu::RenderPipeline,
}
fn holds_encoded_srgb(format: wgpu::TextureFormat) -> bool {
super::shader_applies_transfer(format)
}
impl Downsampler {
pub fn new(device: &wgpu::Device, src: &wgpu::Texture, factor: u32) -> Option<Self> {
Self::with_filter(device, src, factor, DownsampleFilter::default())
}
pub fn with_filter(
device: &wgpu::Device,
src: &wgpu::Texture,
factor: u32,
filter: DownsampleFilter,
) -> Option<Self> {
let format = src.format();
let (sw, sh) = (src.width(), src.height());
if factor < 2 || !Self::renderable(format) || sw % factor != 0 || sh % factor != 0 {
return None;
}
let (width, height) = (sw / factor, sh / factor);
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers downsample layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
}],
});
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers downsample pipeline layout"),
bind_group_layouts: &[Some(&layout)],
immediate_size: 0,
});
let mut extra_formats = Vec::new();
for v in [format.add_srgb_suffix(), format.remove_srgb_suffix()] {
if v != format && !extra_formats.contains(&v) {
extra_formats.push(v);
}
}
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers downsample target"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_SRC,
view_formats: &extra_formats,
});
let (taps, off) = filter.taps(factor);
let decode = holds_encoded_srgb(format);
let build = |label: &str,
source: String,
src_view: &wgpu::TextureView,
target: wgpu::TextureView,
out: wgpu::TextureFormat|
-> Stage {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some(label),
source: wgpu::ShaderSource::Wgsl(
format!("{}\n{source}", crate::renderer::fullscreen::VS).into(),
),
});
Stage {
target,
bind: device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers downsample bind"),
layout: &layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(src_view),
}],
}),
pipeline: device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers downsample pipeline"),
layout: Some(&pl),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(crate::renderer::fullscreen::VS_ENTRY),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs"),
targets: &[Some(out.into())],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
}),
}
};
let src_view = src.create_view(&wgpu::TextureViewDescriptor::default());
let (mid, stages) = if filter == DownsampleFilter::Box {
let stage = build(
"threers downsample (box)",
box_shader(factor, decode),
&src_view,
texture.create_view(&wgpu::TextureViewDescriptor::default()),
format,
);
(None, vec![stage])
} else {
let mid = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers downsample scratch"),
size: wgpu::Extent3d {
width,
height: sh,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let mid_view = mid.create_view(&wgpu::TextureViewDescriptor::default());
let h = build(
"threers downsample (horizontal)",
separable_shader(&taps, off, factor, Axis::X, decode, false),
&src_view,
mid.create_view(&wgpu::TextureViewDescriptor::default()),
wgpu::TextureFormat::Rgba16Float,
);
let v = build(
"threers downsample (vertical)",
separable_shader(&taps, off, factor, Axis::Y, false, decode),
&mid_view,
texture.create_view(&wgpu::TextureViewDescriptor::default()),
format,
);
(Some(mid), vec![h, v])
};
Some(Self {
factor,
filter,
width,
height,
texture,
mid,
stages,
})
}
fn renderable(format: wgpu::TextureFormat) -> bool {
matches!(
format,
wgpu::TextureFormat::Rgba8Unorm
| wgpu::TextureFormat::Rgba8UnormSrgb
| wgpu::TextureFormat::Bgra8Unorm
| wgpu::TextureFormat::Rgba16Float
)
}
pub fn resolve(&self, encoder: &mut wgpu::CommandEncoder) {
for stage in &self.stages {
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers downsample pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &stage.target,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(&stage.pipeline);
pass.set_bind_group(0, &stage.bind, &[]);
pass.draw(0..3, 0..1);
}
}
pub fn texture(&self) -> &wgpu::Texture {
&self.texture
}
pub fn size(&self) -> (u32, u32) {
(self.width, self.height)
}
pub fn factor(&self) -> u32 {
self.factor
}
pub fn filter(&self) -> DownsampleFilter {
self.filter
}
pub fn scratch_bytes(&self) -> u64 {
match &self.mid {
Some(t) => t.width() as u64 * t.height() as u64 * 8,
None => 0,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Axis {
X,
Y,
}
fn preamble() -> String {
format!(
"\n@group(0) @binding(0) var src : texture_2d<f32>;\n{}",
super::colorspace::WGSL
)
}
fn tap_fn(decode: bool) -> String {
let d = if decode {
"srgb_to_linear(c.rgb)"
} else {
"c.rgb"
};
format!(
"
fn tap(at : vec2<i32>, dims : vec2<i32>) -> vec4<f32> {{
let c = textureLoad(src, clamp(at, vec2<i32>(0), dims - vec2<i32>(1)), 0);
return vec4<f32>({d}, c.a);
}}
"
)
}
fn finish(encode: bool) -> &'static str {
if encode {
" let rgb = clamp(acc.rgb, vec3<f32>(0.0), vec3<f32>(1.0));
return vec4<f32>(linear_to_srgb(rgb), clamp(acc.a, 0.0, 1.0));"
} else {
" return vec4<f32>(max(acc.rgb, vec3<f32>(0.0)), clamp(acc.a, 0.0, 1.0));"
}
}
fn box_shader(factor: u32, srgb: bool) -> String {
format!(
"{}{}
@fragment
fn fs(@builtin(position) pos : vec4<f32>) -> @location(0) vec4<f32> {{
let dims = vec2<i32>(textureDimensions(src));
// `pos` is the fragment centre, so truncating gives the output pixel.
let base = vec2<i32>(pos.xy) * {factor};
var acc = vec4<f32>(0.0);
for (var y = 0; y < {factor}; y = y + 1) {{
for (var x = 0; x < {factor}; x = x + 1) {{
acc = acc + tap(base + vec2<i32>(x, y), dims);
}}
}}
acc = acc / {n:?};
{}
}}
",
preamble(),
tap_fn(srgb),
finish(srgb),
n = (factor * factor) as f32,
)
}
fn separable_shader(
taps: &[f32],
off: i32,
factor: u32,
axis: Axis,
decode: bool,
encode: bool,
) -> String {
let mut body = String::new();
for (k, w) in taps.iter().enumerate() {
let d = k as i32 + off;
let at = match axis {
Axis::X => format!("vec2<i32>(base + ({d}), o.y)"),
Axis::Y => format!("vec2<i32>(o.x, base + ({d}))"),
};
body.push_str(&format!(" acc = acc + tap({at}, dims) * {w:?};\n"));
}
let base = match axis {
Axis::X => format!("o.x * {factor}"),
Axis::Y => format!("o.y * {factor}"),
};
format!(
"{}{}
@fragment
fn fs(@builtin(position) pos : vec4<f32>) -> @location(0) vec4<f32> {{
let dims = vec2<i32>(textureDimensions(src));
let o = vec2<i32>(pos.xy);
let base = {base};
var acc = vec4<f32>(0.0);
{body}{}
}}
",
preamble(),
tap_fn(decode),
finish(encode),
)
}
pub fn average_blocks_srgb(src: &[u8], w: u32, h: u32, factor: u32) -> Vec<u8> {
let (dw, dh) = (w / factor, h / factor);
let mut out = vec![0u8; (dw * dh * 4) as usize];
let n = (factor * factor) as f32;
let to_linear = |b: u8| {
let s = b as f32 / 255.0;
if s <= 0.04045 {
s / 12.92
} else {
((s + 0.055) / 1.055).powf(2.4)
}
};
let to_srgb = |l: f32| {
let s = if l <= 0.0031308 {
l * 12.92
} else {
1.055 * l.powf(1.0 / 2.4) - 0.055
};
(s.clamp(0.0, 1.0) * 255.0).round() as u8
};
for y in 0..dh {
for x in 0..dw {
let mut acc = [0.0f32; 4];
for sy in 0..factor {
for sx in 0..factor {
let i = (((y * factor + sy) * w + (x * factor + sx)) * 4) as usize;
acc[0] += to_linear(src[i]);
acc[1] += to_linear(src[i + 1]);
acc[2] += to_linear(src[i + 2]);
acc[3] += src[i + 3] as f32 / 255.0;
}
}
let o = ((y * dw + x) * 4) as usize;
out[o] = to_srgb(acc[0] / n);
out[o + 1] = to_srgb(acc[1] / n);
out[o + 2] = to_srgb(acc[2] / n);
out[o + 3] = ((acc[3] / n).clamp(0.0, 1.0) * 255.0).round() as u8;
}
}
out
}