use wgpu::ShaderSource;
use crate::quad::{BoxVertex, TextVertex};
const BOX_SHADER: &str = r#"
struct VsOut {
@builtin(position) position: vec4<f32>,
@location(0) local: vec2<f32>,
@location(1) half: vec2<f32>,
@location(2) radius: f32,
@location(3) border_width: f32,
@location(4) fill: vec4<f32>,
@location(5) border: vec4<f32>,
@location(6) shadow_offset: vec2<f32>,
@location(7) shadow_blur: f32,
@location(8) shadow_spread: f32,
@location(9) shadow_color: vec4<f32>,
};
@vertex
fn vs(
@location(0) position: vec2<f32>,
@location(1) local: vec2<f32>,
@location(2) half: vec2<f32>,
@location(3) radius: f32,
@location(4) border_width: f32,
@location(5) fill: vec4<f32>,
@location(6) border: vec4<f32>,
@location(7) shadow_offset: vec2<f32>,
@location(8) shadow_blur: f32,
@location(9) shadow_spread: f32,
@location(10) shadow_color: vec4<f32>,
) -> VsOut {
var output: VsOut;
output.position = vec4<f32>(position, 0.0, 1.0);
output.local = local;
output.half = half;
output.radius = radius;
output.border_width = border_width;
output.fill = fill;
output.border = border;
output.shadow_offset = shadow_offset;
output.shadow_blur = shadow_blur;
output.shadow_spread = shadow_spread;
output.shadow_color = shadow_color;
return output;
}
// Distance in pixels from `p` to the edge of a box centred on the origin. A
// radius of zero makes this the distance to a plain rectangle, which is why a
// flat box needs no special case anywhere else.
fn sd_box(p: vec2<f32>, half: vec2<f32>, radius: f32) -> f32 {
let r = min(radius, min(half.x, half.y));
let q = abs(p) - half + vec2<f32>(r, r);
return length(max(q, vec2<f32>(0.0, 0.0))) + min(max(q.x, q.y), 0.0) - r;
}
// One layer of translucent colour over what is already there, in straight
// alpha, because the target blends with src-alpha.
fn over(base_rgb: vec3<f32>, base_a: f32, top_rgb: vec3<f32>, top_a: f32) -> vec4<f32> {
let a = top_a + base_a * (1.0 - top_a);
if a <= 0.0 {
return vec4<f32>(0.0, 0.0, 0.0, 0.0);
}
let rgb = (top_rgb * top_a + base_rgb * base_a * (1.0 - top_a)) / a;
return vec4<f32>(rgb, a);
}
@fragment
fn fs(input: VsOut) -> @location(0) vec4<f32> {
let sd = sd_box(input.local, input.half, input.radius);
// `sd` is in pixels, so one unit of it is one pixel of softness.
let fill_mask = 1.0 - smoothstep(-0.5, 0.5, sd);
var color = over(
vec3<f32>(0.0, 0.0, 0.0),
0.0,
input.fill.rgb,
fill_mask * input.fill.a,
);
if input.shadow_color.a > 0.0 {
let spread = input.shadow_spread;
let ssd = sd_box(
input.local - input.shadow_offset,
input.half + vec2<f32>(spread, spread),
input.radius + spread,
);
let blur = max(input.shadow_blur, 0.001);
let mask = 1.0 - smoothstep(-blur, blur, ssd);
color = over(color.rgb, color.a, input.shadow_color.rgb, mask * input.shadow_color.a);
}
if input.border_width > 0.0 && input.border.a > 0.0 {
// The border is the ring between the edge and one border-width inside
// it: distance from the edge greater than zero, and no more than the
// border's width. Masking only on the inner bound would flood the whole
// interior with the border colour.
let outside = smoothstep(-0.5, 0.5, sd + input.border_width);
let inside = 1.0 - smoothstep(-0.5, 0.5, sd);
let mask = outside * inside;
color = over(color.rgb, color.a, input.border.rgb, mask * input.border.a);
}
return color;
}
"#;
const TEXT_SHADER: &str = r#"
struct Uniforms {
viewport: vec2<f32>,
};
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var atlas: texture_2d_array<f32>;
@group(0) @binding(2) var atlas_sampler: sampler;
struct VsOut {
@builtin(position) position: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
@location(2) @interpolate(flat) layer: f32,
};
@vertex
fn vs(
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) color: vec4<f32>,
@location(3) layer: f32,
) -> VsOut {
var output: VsOut;
let ndc = vec2<f32>(
position.x / uniforms.viewport.x * 2.0 - 1.0,
1.0 - position.y / uniforms.viewport.y * 2.0,
);
output.position = vec4<f32>(ndc, 0.0, 1.0);
output.uv = uv;
output.color = color;
output.layer = layer;
return output;
}
@fragment
fn fs(input: VsOut) -> @location(0) vec4<f32> {
let coverage = textureSample(atlas, atlas_sampler, input.uv, i32(input.layer)).r;
return vec4<f32>(input.color.rgb, input.color.a * coverage);
}
"#;
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Viewport {
pub width: f32,
pub height: f32,
}
pub struct SolidPipeline {
pub pipeline: wgpu::RenderPipeline,
}
pub struct TextPipeline {
pub pipeline: wgpu::RenderPipeline,
pub layout: wgpu::PipelineLayout,
pub bind_group_layout: wgpu::BindGroupLayout,
pub uniform: wgpu::Buffer,
pub sampler: wgpu::Sampler,
pub bind_group: wgpu::BindGroup,
atlas: Option<(wgpu::Texture, wgpu::TextureView, usize)>,
}
impl SolidPipeline {
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> anyhow::Result<Self> {
let targets = blended_target(format);
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("rcus-box-shader"),
source: ShaderSource::Wgsl(BOX_SHADER.into()),
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("rcus-solid-layout"),
bind_group_layouts: &[],
push_constant_ranges: &[],
});
Ok(Self {
pipeline: device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("rcus-box-pipeline"),
layout: Some(&layout),
vertex: vertex_state(&shader, &box_attributes()),
fragment: Some(fragment_state(&shader, &targets)),
primitive: primitive_state(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
cache: None,
}),
})
}
}
impl TextPipeline {
pub fn new(
device: &wgpu::Device,
queue: &wgpu::Queue,
format: wgpu::TextureFormat,
) -> anyhow::Result<Self> {
let targets = blended_target(format);
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("rcus-text-shader"),
source: ShaderSource::Wgsl(TEXT_SHADER.into()),
});
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("rcus-text-bind-group-layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: wgpu::BufferSize::new(
std::mem::size_of::<Viewport>() as u64
),
},
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::D2Array,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("rcus-text-layout"),
bind_group_layouts: &[&bind_group_layout],
push_constant_ranges: &[],
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("rcus-text-pipeline"),
layout: Some(&layout),
vertex: vertex_state(&shader, &text_attributes()),
fragment: Some(fragment_state(&shader, &targets)),
primitive: primitive_state(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
cache: None,
});
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("rcus-viewport-uniform"),
size: std::mem::size_of::<Viewport>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
queue.write_buffer(
&uniform,
0,
bytemuck::bytes_of(&Viewport {
width: 1.0,
height: 1.0,
}),
);
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("rcus-atlas-sampler"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::FilterMode::Nearest,
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
..Default::default()
});
let atlas = device.create_texture(&wgpu::TextureDescriptor {
label: Some("rcus-atlas-placeholder"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("rcus-text-bind-group"),
layout: &bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&atlas.create_view(
&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
},
)),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
});
Ok(Self {
pipeline,
layout,
bind_group_layout,
uniform,
sampler,
bind_group,
atlas: None,
})
}
pub fn sync_atlas(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
set: &crate::text::AtlasSet,
) {
let layers = set.layers();
let current = self.atlas.as_ref().map(|(_, _, count)| *count);
if current == Some(layers) {
if let Some((texture, _, _)) = self.atlas.as_ref() {
crate::text::upload_atlas_layers(queue, texture, set);
}
return;
}
let texture = crate::text::create_atlas_texture(device, layers);
crate::text::upload_atlas_layers(queue, &texture, set);
let view = crate::text::atlas_view(&texture);
self.set_atlas(device, &view);
self.atlas = Some((texture, view, layers));
}
fn set_atlas(&mut self, device: &wgpu::Device, view: &wgpu::TextureView) {
self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("rcus-text-bind-group"),
layout: &self.bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: self.uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&self.sampler),
},
],
});
}
pub fn set_viewport(&self, queue: &wgpu::Queue, width: f32, height: f32) {
queue.write_buffer(
&self.uniform,
0,
bytemuck::bytes_of(&Viewport { width, height }),
);
}
}
fn vertex_state<'a>(
module: &'a wgpu::ShaderModule,
buffers: &'a [wgpu::VertexBufferLayout<'a>],
) -> wgpu::VertexState<'a> {
wgpu::VertexState {
module,
entry_point: "vs",
compilation_options: Default::default(),
buffers,
}
}
fn fragment_state<'a>(
module: &'a wgpu::ShaderModule,
targets: &'a [Option<wgpu::ColorTargetState>],
) -> wgpu::FragmentState<'a> {
wgpu::FragmentState {
module,
entry_point: "fs",
compilation_options: Default::default(),
targets,
}
}
fn blended_target(format: wgpu::TextureFormat) -> [Option<wgpu::ColorTargetState>; 1] {
[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
operation: wgpu::BlendOperation::Add,
},
}),
write_mask: wgpu::ColorWrites::ALL,
})]
}
fn primitive_state() -> wgpu::PrimitiveState {
wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: None,
unclipped_depth: false,
polygon_mode: wgpu::PolygonMode::Fill,
conservative: false,
}
}
const BOX_ATTRIBUTES: [wgpu::VertexAttribute; 11] = [
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 0,
shader_location: 0,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 8,
shader_location: 1,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 16,
shader_location: 2,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32,
offset: 24,
shader_location: 3,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32,
offset: 28,
shader_location: 4,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 32,
shader_location: 5,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 48,
shader_location: 6,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 64,
shader_location: 7,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32,
offset: 72,
shader_location: 8,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32,
offset: 76,
shader_location: 9,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 80,
shader_location: 10,
},
];
fn box_attributes() -> Vec<wgpu::VertexBufferLayout<'static>> {
vec![wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<BoxVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &BOX_ATTRIBUTES,
}]
}
fn text_attributes() -> Vec<wgpu::VertexBufferLayout<'static>> {
vec![wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<TextVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 0,
shader_location: 0,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 8,
shader_location: 1,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 16,
shader_location: 2,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32,
offset: 32,
shader_location: 3,
},
],
}]
}