use std::collections::HashMap;
pub const VS: &str = crate::wgsl!(
r#"
struct FullscreenVertex {
@builtin(position) clip : vec4<f32>,
@location(0) uv : vec2<f32>,
};
@vertex
fn vs_main(@builtin(vertex_index) vid : u32) -> FullscreenVertex {
let x = f32((vid << 1u) & 2u);
let y = f32(vid & 2u);
var out : FullscreenVertex;
out.uv = vec2<f32>(x, y);
out.clip = vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
return out;
}
"#
);
pub const VS_ENTRY: &str = "vs_main";
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Load {
Clear,
Keep,
}
fn next_fbo_id() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(1);
NEXT.fetch_add(1, Ordering::Relaxed)
}
pub struct Fbo {
pub texture: wgpu::Texture,
pub view: wgpu::TextureView,
pub width: u32,
pub height: u32,
pub id: u64,
}
impl Fbo {
pub fn new(
device: &wgpu::Device,
label: &str,
width: u32,
height: u32,
format: wgpu::TextureFormat,
) -> Self {
let (width, height) = (width.max(1), height.max(1));
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
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: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
Self {
id: next_fbo_id(),
texture,
view,
width,
height,
}
}
pub fn texel(&self) -> [f32; 2] {
[1.0 / self.width as f32, 1.0 / self.height as f32]
}
pub fn size(&self) -> (u32, u32) {
(self.width, self.height)
}
pub fn format(&self) -> wgpu::TextureFormat {
self.texture.format()
}
pub fn target(&self) -> Target<'_> {
Target {
view: &self.view,
format: self.texture.format(),
width: self.width,
height: self.height,
}
}
}
pub struct DoubleFbo {
pub read: Fbo,
pub write: Fbo,
}
impl DoubleFbo {
pub fn new(
device: &wgpu::Device,
label: &str,
width: u32,
height: u32,
format: wgpu::TextureFormat,
) -> Self {
Self {
read: Fbo::new(device, label, width, height, format),
write: Fbo::new(device, label, width, height, format),
}
}
pub fn swap(&mut self) {
std::mem::swap(&mut self.read, &mut self.write);
}
pub fn width(&self) -> u32 {
self.read.width
}
pub fn height(&self) -> u32 {
self.read.height
}
pub fn size(&self) -> (u32, u32) {
self.read.size()
}
pub fn texel(&self) -> [f32; 2] {
self.read.texel()
}
}
#[derive(Clone, Copy)]
pub struct Target<'a> {
pub view: &'a wgpu::TextureView,
pub format: wgpu::TextureFormat,
pub width: u32,
pub height: u32,
}
impl<'a> Target<'a> {
pub fn from_texture(texture: &wgpu::Texture, view: &'a wgpu::TextureView) -> Self {
Self {
view,
format: texture.format(),
width: texture.width(),
height: texture.height(),
}
}
pub fn size(&self) -> (u32, u32) {
(self.width, self.height)
}
pub fn texel(&self) -> [f32; 2] {
[
1.0 / self.width.max(1) as f32,
1.0 / self.height.max(1) as f32,
]
}
}
impl<'a> From<&'a super::RenderTarget> for Target<'a> {
fn from(rt: &'a super::RenderTarget) -> Self {
Self {
view: &rt.color_view,
format: rt.format,
width: rt.width,
height: rt.height,
}
}
}
pub fn begin<'a>(
encoder: &'a mut wgpu::CommandEncoder,
view: &'a wgpu::TextureView,
load: Load,
) -> wgpu::RenderPass<'a> {
begin_with(encoder, view, load, wgpu::Color::TRANSPARENT, "fullscreen")
}
pub fn begin_with<'a>(
encoder: &'a mut wgpu::CommandEncoder,
view: &'a wgpu::TextureView,
load: Load,
clear: wgpu::Color,
label: &str,
) -> wgpu::RenderPass<'a> {
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some(label),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: match load {
Load::Clear => wgpu::LoadOp::Clear(clear),
Load::Keep => wgpu::LoadOp::Load,
},
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
})
}
pub fn draw(
encoder: &mut wgpu::CommandEncoder,
view: &wgpu::TextureView,
load: Load,
pipeline: &wgpu::RenderPipeline,
bind_group: &wgpu::BindGroup,
) {
draw_timed(encoder, view, load, pipeline, bind_group, None);
}
pub fn draw_timed(
encoder: &mut wgpu::CommandEncoder,
view: &wgpu::TextureView,
load: Load,
pipeline: &wgpu::RenderPipeline,
bind_group: &wgpu::BindGroup,
timestamps: Option<wgpu::RenderPassTimestampWrites<'_>>,
) {
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("fullscreen"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: match load {
Load::Clear => wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
Load::Keep => wgpu::LoadOp::Load,
},
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: timestamps,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(pipeline);
pass.set_bind_group(0, bind_group, &[]);
pass.draw(0..3, 0..1);
}
pub fn linear_sampler(device: &wgpu::Device) -> wgpu::Sampler {
sampler(device, wgpu::FilterMode::Linear, "fullscreen linear")
}
pub fn nearest_sampler(device: &wgpu::Device) -> wgpu::Sampler {
sampler(device, wgpu::FilterMode::Nearest, "fullscreen nearest")
}
fn sampler(device: &wgpu::Device, filter: wgpu::FilterMode, label: &str) -> wgpu::Sampler {
device.create_sampler(&wgpu::SamplerDescriptor {
label: Some(label),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: filter,
min_filter: filter,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
})
}
pub struct FormatPipelines<T> {
by_format: HashMap<wgpu::TextureFormat, T>,
}
impl<T> Default for FormatPipelines<T> {
fn default() -> Self {
Self {
by_format: HashMap::new(),
}
}
}
impl<T> FormatPipelines<T> {
pub fn new() -> Self {
Self::default()
}
pub fn get_or_build(&mut self, format: wgpu::TextureFormat, make: impl FnOnce() -> T) -> &T {
self.by_format.entry(format).or_insert_with(make)
}
pub fn get(&self, format: wgpu::TextureFormat) -> Option<&T> {
self.by_format.get(&format)
}
pub fn len(&self) -> usize {
self.by_format.len()
}
pub fn is_empty(&self) -> bool {
self.by_format.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_vertex_stage_is_valid_wgsl() {
let source = format!(
"{VS}\n@fragment fn fs(v : FullscreenVertex) -> @location(0) vec4<f32> {{ \
return vec4<f32>(v.uv, 0.0, 1.0); }}"
);
let module = wgpu::naga::front::wgsl::parse_str(&source).expect("the vertex stage parses");
wgpu::naga::valid::Validator::new(
wgpu::naga::valid::ValidationFlags::all(),
wgpu::naga::valid::Capabilities::all(),
)
.validate(&module)
.expect("the vertex stage validates");
assert!(VS.contains(&format!("fn {VS_ENTRY}")));
}
#[test]
fn the_triangle_covers_the_viewport_with_uv_at_the_top_left() {
let vertex = |vid: u32| {
let x = ((vid << 1) & 2) as f32;
let y = (vid & 2) as f32;
([x, y], [x * 2.0 - 1.0, 1.0 - y * 2.0])
};
let vs: Vec<_> = (0..3).map(vertex).collect();
assert_eq!(vs[0], ([0.0, 0.0], [-1.0, 1.0]), "uv 0,0 is the top left");
assert_eq!(
vs[1],
([2.0, 0.0], [3.0, 1.0]),
"second corner is off-screen right"
);
assert_eq!(
vs[2],
([0.0, 2.0], [-1.0, -3.0]),
"third is off-screen below"
);
for corner in [[-1.0f32, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]] {
let (a, b, c) = (vs[0].1, vs[1].1, vs[2].1);
let det = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1]);
let l0 =
((b[1] - c[1]) * (corner[0] - c[0]) + (c[0] - b[0]) * (corner[1] - c[1])) / det;
let l1 =
((c[1] - a[1]) * (corner[0] - c[0]) + (a[0] - c[0]) * (corner[1] - c[1])) / det;
let l2 = 1.0 - l0 - l1;
assert!(
l0 >= -1e-6 && l1 >= -1e-6 && l2 >= -1e-6,
"{corner:?} is outside the triangle"
);
}
}
#[test]
fn the_pipeline_cache_builds_once_per_format() {
let mut built = 0;
let mut cache: FormatPipelines<u32> = FormatPipelines::new();
for _ in 0..3 {
cache.get_or_build(wgpu::TextureFormat::Rgba8Unorm, || {
built += 1;
1
});
}
cache.get_or_build(wgpu::TextureFormat::Bgra8Unorm, || {
built += 1;
2
});
assert_eq!(built, 2, "a format was rebuilt");
assert_eq!(cache.len(), 2);
}
}