From 76576daa6987857e910da03fbbffb1fe7e0c2d14 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Thu, 17 Nov 2022 15:38:07 -0700 Subject: [PATCH] This makes webgpu actually render It doesn't have some of the functions from the egl shader yet, but the text is visible! --- wezterm-gui/src/quad.rs | 20 ++++ wezterm-gui/src/renderstate.rs | 51 ++++++++- wezterm-gui/src/shader.wgsl | 73 +++++++++++-- wezterm-gui/src/termwindow/mod.rs | 16 +-- wezterm-gui/src/termwindow/render.rs | 125 ++++++++++++++++++---- wezterm-gui/src/termwindow/webgpu.rs | 153 ++++++++++++++++++--------- 6 files changed, 354 insertions(+), 84 deletions(-) diff --git a/wezterm-gui/src/quad.rs b/wezterm-gui/src/quad.rs index 9ae18e586..3de1d18b0 100644 --- a/wezterm-gui/src/quad.rs +++ b/wezterm-gui/src/quad.rs @@ -44,6 +44,26 @@ pub struct Vertex { Vertex, position, tex, fg_color, alt_color, hsv, has_color, mix_value ); +impl Vertex { + const ATTRIBS: [wgpu::VertexAttribute; 7] = wgpu::vertex_attr_array![ + 0 => Float32x2, + 1 => Float32x2, + 2 => Float32x4, + 3 => Float32x4, + 4 => Float32x3, + 5 => Float32, + 6 => Float32, + ]; + + pub fn desc() -> wgpu::VertexBufferLayout<'static> { + wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as wgpu::BufferAddress, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &Self::ATTRIBS, + } + } +} + pub trait QuadTrait { /// Assign the texture coordinates fn set_texture(&mut self, coords: TextureRect) { diff --git a/wezterm-gui/src/renderstate.rs b/wezterm-gui/src/renderstate.rs index 59a3feef0..c88f22053 100644 --- a/wezterm-gui/src/renderstate.rs +++ b/wezterm-gui/src/renderstate.rs @@ -130,6 +130,12 @@ impl IndexBuffer { _ => unreachable!(), } } + pub fn webgpu(&self) -> &WebGpuIndexBuffer { + match self { + Self::WebGpu(g) => g, + _ => unreachable!(), + } + } } pub enum VertexBuffer { @@ -144,6 +150,18 @@ impl VertexBuffer { _ => unreachable!(), } } + pub fn webgpu(&self) -> &WebGpuVertexBuffer { + match self { + Self::WebGpu(g) => g, + _ => unreachable!(), + } + } + pub fn webgpu_mut(&mut self) -> &mut WebGpuVertexBuffer { + match self { + Self::WebGpu(g) => g, + _ => unreachable!(), + } + } } enum MappedVertexBuffer { @@ -177,10 +195,19 @@ pub struct WebGpuMappedVertexBuffer { pub struct WebGpuVertexBuffer { buf: wgpu::Buffer, + num_vertices: usize, + state: Rc, +} + +impl std::ops::Deref for WebGpuVertexBuffer { + type Target = wgpu::Buffer; + fn deref(&self) -> &Self::Target { + &self.buf + } } impl WebGpuVertexBuffer { - pub fn new(num_vertices: usize, state: &WebGpuState) -> Self { + pub fn new(num_vertices: usize, state: &Rc) -> Self { Self { buf: state.device.create_buffer(&wgpu::BufferDescriptor { label: Some("Vertex Buffer"), @@ -188,6 +215,8 @@ impl WebGpuVertexBuffer { usage: wgpu::BufferUsages::VERTEX, mapped_at_creation: true, }), + num_vertices, + state: Rc::clone(state), } } @@ -202,11 +231,28 @@ impl WebGpuVertexBuffer { } } } + + pub fn recreate(&mut self) -> wgpu::Buffer { + let mut new_buf = self.state.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Vertex Buffer"), + size: (self.num_vertices * std::mem::size_of::()) as wgpu::BufferAddress, + usage: wgpu::BufferUsages::VERTEX, + mapped_at_creation: true, + }); + std::mem::swap(&mut new_buf, &mut self.buf); + new_buf + } } pub struct WebGpuIndexBuffer { buf: wgpu::Buffer, - num_indices: usize, +} + +impl std::ops::Deref for WebGpuIndexBuffer { + type Target = wgpu::Buffer; + fn deref(&self) -> &Self::Target { + &self.buf + } } impl WebGpuIndexBuffer { @@ -219,7 +265,6 @@ impl WebGpuIndexBuffer { usage: wgpu::BufferUsages::INDEX, contents: bytemuck::cast_slice(indices), }), - num_indices: indices.len(), } } } diff --git a/wezterm-gui/src/shader.wgsl b/wezterm-gui/src/shader.wgsl index cae11553d..7868ad68d 100644 --- a/wezterm-gui/src/shader.wgsl +++ b/wezterm-gui/src/shader.wgsl @@ -1,22 +1,50 @@ // Vertex shader struct VertexInput { - @location(0) position: vec3, - @location(1) color: vec3, + @location(0) position: vec2, + @location(1) tex: vec2, + @location(2) fg_color: vec4, + @location(3) alt_color: vec4, + @location(4) hsv: vec3, + @location(5) has_color: f32, + @location(6) mix_value: f32, }; struct VertexOutput { @builtin(position) clip_position: vec4, - @location(0) color: vec3, + @location(0) tex: vec2, + @location(1) fg_color: vec4, + @location(2) alt_color: vec4, + @location(3) hsv: vec3, + @location(4) has_color: f32, + @location(5) mix_value: f32, }; +struct ShaderUniform { + foreground_text_hsb: vec3, + milliseconds: u32, + projection: mat4x4, +}; +@group(0) @binding(0) var uniforms: ShaderUniform; + +@group(1) @binding(0) var atlas_linear_tex: texture_2d; +@group(1) @binding(1) var atlas_linear_sampler: sampler; + +@group(2) @binding(0) var atlas_nearest_tex: texture_2d; +@group(2) @binding(1) var atlas_nearest_sampler: sampler; + @vertex fn vs_main( model: VertexInput, ) -> VertexOutput { var out: VertexOutput; - out.color = model.color; - out.clip_position = vec4(model.position, 1.0); + out.tex = model.tex; + out.fg_color = model.fg_color; + out.alt_color = model.alt_color; + out.hsv = model.hsv; + out.has_color = model.has_color; + out.mix_value = model.mix_value; + out.clip_position = uniforms.projection * vec4(model.position, 0.0, 1.0); return out; } @@ -24,6 +52,39 @@ fn vs_main( @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4 { - return vec4(in.color, 1.0); + var fg_color: vec4 = mix(in.fg_color, in.alt_color, in.mix_value); + var color: vec4 = fg_color; + var linear_tex: vec4 = textureSample(atlas_linear_tex, atlas_linear_sampler, in.tex); + var nearest_tex: vec4 = textureSample(atlas_nearest_tex, atlas_nearest_sampler, in.tex); + + if in.has_color == 3.0 { + // Solid color block + } else if in.has_color == 2.0 { + // Window background attachment + // Apply window_background_image_opacity to the background image + color = linear_tex; + color.a *= fg_color.a; + } else if in.has_color == 1.0 { + // the texture is full color info (eg: color emoji glyph) + color = nearest_tex; + } else if in.has_color == 4.0 { + // Grayscale poly quad for non-aa text render layers + color = fg_color; + color.a *= nearest_tex.a; + } else if in.has_color == 0.0 { + // the texture is the alpha channel/color mask + // and we need to tint with the fg_color + color = fg_color; + color.a = nearest_tex.a; + // color = apply_hsv(color, foreground_text_hsb); + } + + // color = apply_hsv(color, in.hsv); + + // We MUST output SRGB and tell glium that we do that (outputs_srgb), + // otherwise something in glium over-gamma-corrects depending on the gl setup. + // color = to_srgb(color); + + return color; } diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs index 0f200c149..0596aa255 100644 --- a/wezterm-gui/src/termwindow/mod.rs +++ b/wezterm-gui/src/termwindow/mod.rs @@ -531,7 +531,7 @@ impl TermWindow { self.emit_window_event("window-focus-changed", None); } - fn created(&mut self, window: &Window, ctx: RenderContext) -> anyhow::Result<()> { + fn created(&mut self, ctx: RenderContext) -> anyhow::Result<()> { self.render_state = None; let render_info = ctx.renderer_info(); @@ -826,11 +826,11 @@ impl TermWindow { if let Some(gl) = gl { myself.gl.replace(Rc::clone(&gl)); - myself.created(&window, RenderContext::Glium(Rc::clone(&gl)))?; + myself.created(RenderContext::Glium(Rc::clone(&gl)))?; } if let Some(webgpu) = webgpu { myself.webgpu.replace(Rc::clone(&webgpu)); - myself.created(&window, RenderContext::WebGpu(Rc::clone(&webgpu)))?; + myself.created(RenderContext::WebGpu(Rc::clone(&webgpu)))?; } myself.load_os_parameters(); window.show(); @@ -910,7 +910,7 @@ impl TermWindow { window.invalidate(); Ok(true) } - WindowEvent::NeedRepaint if self.webgpu.is_some() => self.do_paint_webgpu(window), + WindowEvent::NeedRepaint if self.webgpu.is_some() => self.do_paint_webgpu(), WindowEvent::NeedRepaint => Ok(self.do_paint(window)), WindowEvent::Notification(item) => { if let Ok(notif) = item.downcast::() { @@ -964,15 +964,15 @@ impl TermWindow { window.finish_frame(frame).is_ok() } - fn do_paint_webgpu(&mut self, window: &Window) -> anyhow::Result { + fn do_paint_webgpu(&mut self) -> anyhow::Result { self.webgpu.as_mut().unwrap().resize(self.dimensions); - match self.do_paint_webgpu_impl(window) { + match self.do_paint_webgpu_impl() { Ok(ok) => Ok(ok), Err(err) => { match err.downcast_ref::() { Some(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => { self.webgpu.as_mut().unwrap().resize(self.dimensions); - return self.do_paint_webgpu_impl(window); + return self.do_paint_webgpu_impl(); } _ => {} } @@ -981,7 +981,7 @@ impl TermWindow { } } - fn do_paint_webgpu_impl(&mut self, window: &Window) -> anyhow::Result { + fn do_paint_webgpu_impl(&mut self) -> anyhow::Result { self.paint_impl(&mut RenderFrame::WebGpu); Ok(true) } diff --git a/wezterm-gui/src/termwindow/render.rs b/wezterm-gui/src/termwindow/render.rs index a4208d6e7..7001be679 100644 --- a/wezterm-gui/src/termwindow/render.rs +++ b/wezterm-gui/src/termwindow/render.rs @@ -9,6 +9,7 @@ use crate::quad::{ use crate::selection::SelectionRange; use crate::shapecache::*; use crate::tabbar::{TabBarItem, TabEntry}; +use crate::termwindow::webgpu::ShaderUniform; use crate::termwindow::{ BorrowedShapeCacheKey, RenderFrame, RenderState, ScrollHit, ShapedInfo, TermWindowNotif, UIItem, UIItemType, @@ -1903,7 +1904,10 @@ impl super::TermWindow { } fn call_draw_webgpu(&mut self) -> anyhow::Result<()> { + use crate::termwindow::webgpu::WebGpuTexture; + let webgpu = self.webgpu.as_mut().unwrap(); + let render_state = self.render_state.as_ref().unwrap(); let output = webgpu.surface.get_current_texture()?; let view = output @@ -1914,29 +1918,112 @@ impl super::TermWindow { .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Render Encoder"), }); + let tex = render_state.glyph_cache.borrow().atlas.texture(); + let tex = tex.downcast_ref::().unwrap(); + let texture_view = tex.create_view(&wgpu::TextureViewDescriptor::default()); - { - let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("Render Pass"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &view, - resolve_target: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Clear(wgpu::Color { - r: 0.1, - g: 0.2, - b: 0.3, - a: 1.0, - }), - store: true, + let texture_linear_bind_group = + webgpu.device.create_bind_group(&wgpu::BindGroupDescriptor { + layout: &webgpu.texture_bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&texture_view), }, - })], - depth_stencil_attachment: None, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&webgpu.texture_linear_sampler), + }, + ], + label: Some("linear bind group"), }); - render_pass.set_pipeline(&webgpu.render_pipeline); - render_pass.set_vertex_buffer(0, webgpu.vertex_buffer.slice(..)); - render_pass.draw(0..webgpu.num_vertices, 0..1); + let texture_nearest_bind_group = + webgpu.device.create_bind_group(&wgpu::BindGroupDescriptor { + layout: &webgpu.texture_bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&texture_view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&webgpu.texture_nearest_sampler), + }, + ], + label: Some("nearest bind group"), + }); + + let mut cleared = false; + let foreground_text_hsb = self.config.foreground_text_hsb; + let foreground_text_hsb = [ + foreground_text_hsb.hue, + foreground_text_hsb.saturation, + foreground_text_hsb.brightness, + ]; + + let milliseconds = self.created.elapsed().as_millis() as u32; + let projection = euclid::Transform3D::::ortho( + -(self.dimensions.pixel_width as f32) / 2.0, + self.dimensions.pixel_width as f32 / 2.0, + self.dimensions.pixel_height as f32 / 2.0, + -(self.dimensions.pixel_height as f32) / 2.0, + -1.0, + 1.0, + ) + .to_arrays_transposed(); + + for layer in render_state.layers.borrow().iter() { + for idx in 0..3 { + let vb = &layer.vb.borrow()[idx]; + let (vertex_count, index_count) = vb.vertex_index_count(); + let vertex_buffer; + let uniforms; + if vertex_count > 0 { + let mut vertices = vb.current_vb_mut(); + let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Render Pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + ops: wgpu::Operations { + load: if cleared { + wgpu::LoadOp::Load + } else { + wgpu::LoadOp::Clear(wgpu::Color { + r: 0., + g: 0., + b: 0., + a: 0., + }) + }, + store: true, + }, + })], + depth_stencil_attachment: None, + }); + cleared = true; + + uniforms = webgpu.create_uniform(ShaderUniform { + foreground_text_hsb, + milliseconds, + projection, + }); + + render_pass.set_pipeline(&webgpu.render_pipeline); + render_pass.set_bind_group(0, &uniforms, &[]); + render_pass.set_bind_group(1, &texture_linear_bind_group, &[]); + render_pass.set_bind_group(2, &texture_nearest_bind_group, &[]); + vertex_buffer = vertices.webgpu_mut().recreate(); + vertex_buffer.unmap(); + render_pass.set_vertex_buffer(0, vertex_buffer.slice(..)); + render_pass + .set_index_buffer(vb.indices.webgpu().slice(..), wgpu::IndexFormat::Uint32); + render_pass.draw_indexed(0..index_count as _, 0, 0..1); + } + + vb.next_index(); + } } // submit will accept anything that implements IntoIter diff --git a/wezterm-gui/src/termwindow/webgpu.rs b/wezterm-gui/src/termwindow/webgpu.rs index 4b91348ed..b9b9c0e03 100644 --- a/wezterm-gui/src/termwindow/webgpu.rs +++ b/wezterm-gui/src/termwindow/webgpu.rs @@ -1,3 +1,4 @@ +use crate::quad::Vertex; use anyhow::anyhow; use std::cell::RefCell; use std::num::NonZeroU32; @@ -10,40 +11,15 @@ use window::raw_window_handle::{ use window::{BitmapImage, Dimensions, Rect, Window}; #[repr(C)] -#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] -struct Vertex { - position: [f32; 3], - color: [f32; 3], +#[derive(Copy, Clone, Default, Debug, bytemuck::Pod, bytemuck::Zeroable)] +pub struct ShaderUniform { + pub foreground_text_hsb: [f32; 3], + pub milliseconds: u32, + pub projection: [[f32; 4]; 4], + // sampler2D atlas_nearest_sampler; + // sampler2D atlas_linear_sampler; } -impl Vertex { - const ATTRIBS: [wgpu::VertexAttribute; 2] = - wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3]; - - fn desc<'a>() -> wgpu::VertexBufferLayout<'a> { - wgpu::VertexBufferLayout { - array_stride: std::mem::size_of::() as wgpu::BufferAddress, - step_mode: wgpu::VertexStepMode::Vertex, - attributes: &Self::ATTRIBS, - } - } -} - -const VERTICES: &[Vertex] = &[ - Vertex { - position: [0.0, 0.5, 0.0], - color: [1.0, 0.0, 0.0], - }, - Vertex { - position: [-0.5, -0.5, 0.0], - color: [0.0, 1.0, 0.0], - }, - Vertex { - position: [0.5, -0.5, 0.0], - color: [0.0, 0.0, 1.0], - }, -]; - pub struct WebGpuState { pub surface: wgpu::Surface, pub device: wgpu::Device, @@ -51,8 +27,10 @@ pub struct WebGpuState { pub config: RefCell, pub dimensions: RefCell, pub render_pipeline: wgpu::RenderPipeline, - pub vertex_buffer: wgpu::Buffer, - pub num_vertices: u32, + shader_uniform_bind_group_layout: wgpu::BindGroupLayout, + pub texture_bind_group_layout: wgpu::BindGroupLayout, + pub texture_nearest_sampler: wgpu::Sampler, + pub texture_linear_sampler: wgpu::Sampler, pub handle: RawHandlePair, } @@ -89,6 +67,13 @@ pub struct WebGpuTexture { queue: Arc, } +impl std::ops::Deref for WebGpuTexture { + type Target = wgpu::Texture; + fn deref(&self) -> &Self::Target { + &self.texture + } +} + impl Texture2d for WebGpuTexture { fn write(&self, rect: Rect, im: &dyn BitmapImage) { let (im_width, im_height) = im.image_dimensions(); @@ -204,10 +189,71 @@ impl WebGpuState { let shader = device.create_shader_module(wgpu::include_wgsl!("../shader.wgsl")); + let shader_uniform_bind_group_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }], + label: Some("ShaderUniform bind group layout"), + }); + + let texture_nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + address_mode_w: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Nearest, + min_filter: wgpu::FilterMode::Nearest, + mipmap_filter: wgpu::FilterMode::Nearest, + ..Default::default() + }); + let texture_linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + address_mode_w: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + + let texture_bind_group_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + view_dimension: wgpu::TextureViewDimension::D2, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + label: Some("texture bind group layout"), + }); + let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Render Pipeline Layout"), - bind_group_layouts: &[], + bind_group_layouts: &[ + &shader_uniform_bind_group_layout, + &texture_bind_group_layout, + &texture_bind_group_layout, + ], push_constant_ranges: &[], }); @@ -224,7 +270,7 @@ impl WebGpuState { entry_point: "fs_main", targets: &[Some(wgpu::ColorTargetState { format: config.format, - blend: Some(wgpu::BlendState::REPLACE), + blend: Some(wgpu::BlendState::ALPHA_BLENDING), write_mask: wgpu::ColorWrites::ALL, })], }), @@ -233,12 +279,9 @@ impl WebGpuState { topology: wgpu::PrimitiveTopology::TriangleList, strip_index_format: None, front_face: wgpu::FrontFace::Ccw, - cull_mode: Some(wgpu::Face::Back), - // Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE + cull_mode: None, polygon_mode: wgpu::PolygonMode::Fill, - // Requires Features::DEPTH_CLIP_CONTROL unclipped_depth: false, - // Requires Features::CONSERVATIVE_RASTERIZATION conservative: false, }, depth_stencil: None, @@ -250,12 +293,6 @@ impl WebGpuState { multiview: None, }); - let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("Vertex Buffer"), - contents: bytemuck::cast_slice(VERTICES), - usage: wgpu::BufferUsages::VERTEX, - }); - Ok(Self { surface, device, @@ -263,9 +300,29 @@ impl WebGpuState { config: RefCell::new(config), dimensions: RefCell::new(dimensions), render_pipeline, - vertex_buffer, - num_vertices: VERTICES.len() as u32, handle, + shader_uniform_bind_group_layout, + texture_bind_group_layout, + texture_nearest_sampler, + texture_linear_sampler, + }) + } + + pub fn create_uniform(&self, uniform: ShaderUniform) -> wgpu::BindGroup { + let buffer = self + .device + .create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("ShaderUniform Buffer"), + contents: bytemuck::cast_slice(&[uniform]), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + }); + self.device.create_bind_group(&wgpu::BindGroupDescriptor { + layout: &self.shader_uniform_bind_group_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: buffer.as_entire_binding(), + }], + label: Some("ShaderUniform Bind Group"), }) }