From 8479be746552db7d927a0dc8f31b4c5f751a2dfe Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Tue, 15 Nov 2022 18:19:48 -0700 Subject: [PATCH] Basic useless wgpu based rendering foundation --- Cargo.lock | 315 +++++++++++++++++++++++++++ Cargo.toml | 3 +- config/src/frontend.rs | 1 + mux/src/localpane.rs | 1 + wezterm-gui/Cargo.toml | 2 + wezterm-gui/src/shader.wgsl | 29 +++ wezterm-gui/src/termwindow/mod.rs | 97 ++++++++- wezterm-gui/src/termwindow/resize.rs | 5 + wezterm-gui/src/termwindow/webgpu.rs | 218 ++++++++++++++++++ window/src/lib.rs | 2 + window/src/os/macos/window.rs | 42 +++- window/src/os/wayland/window.rs | 23 +- window/src/os/windows/window.rs | 19 +- window/src/os/x11/window.rs | 32 ++- window/src/os/x_and_wayland.rs | 14 +- 15 files changed, 786 insertions(+), 17 deletions(-) create mode 100644 wezterm-gui/src/shader.wgsl create mode 100644 wezterm-gui/src/termwindow/webgpu.rs diff --git a/Cargo.lock b/Cargo.lock index c8fb8fbe1..ae3d618d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -82,6 +82,15 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" +[[package]] +name = "ash" +version = "0.37.0+1.3.209" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "006ca68e0f2b03f22d6fa9f2860f85aed430d257fec20f8879b2145e7c7ae1a6" +dependencies = [ + "libloading 0.7.4", +] + [[package]] name = "assert_fs" version = "1.0.9" @@ -308,6 +317,21 @@ checksum = "3937429ef059161c005a608ae02451b64e5e98d26d2038f43674f506b571bad6" name = "bintree" version = "0.1.0" +[[package]] +name = "bit-set" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" + [[package]] name = "bit_field" version = "0.10.1" @@ -392,6 +416,20 @@ name = "bytemuck" version = "1.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aaa3a8d9a1ca92e282c96a32d6511b695d7d994d1d102ba85d279f9b2756947f" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fe233b960f12f8007e3db2d136e3cb1c291bfd7396e384ee76025fc1a3932b4" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "byteorder" @@ -450,6 +488,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + [[package]] name = "cgl" version = "0.3.2" @@ -1010,6 +1054,17 @@ dependencies = [ "syn", ] +[[package]] +name = "d3d12" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "827914e1f53b1e0e025ecd3d967a7836b7bcb54520f90e21ef8df7b4d88a2759" +dependencies = [ + "bitflags", + "libloading 0.7.4", + "winapi", +] + [[package]] name = "darling" version = "0.14.2" @@ -1648,6 +1703,15 @@ dependencies = [ "thread_local", ] +[[package]] +name = "fxhash" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" +dependencies = [ + "byteorder", +] + [[package]] name = "generate-bidi" version = "0.1.0" @@ -1777,6 +1841,18 @@ dependencies = [ "walkdir", ] +[[package]] +name = "glow" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8bd5877156a19b8ac83a29b2306fe20537429d318f3ff0a1a2119f8d9c61919" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "governor" version = "0.4.2" @@ -1794,6 +1870,45 @@ dependencies = [ "smallvec", ] +[[package]] +name = "gpu-alloc" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fc59e5f710e310e76e6707f86c561dd646f69a8876da9131703b2f717de818d" +dependencies = [ + "bitflags", + "gpu-alloc-types", +] + +[[package]] +name = "gpu-alloc-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54804d0d6bc9d7f26db4eaec1ad10def69b599315f487d32c334a80d1efe67a5" +dependencies = [ + "bitflags", +] + +[[package]] +name = "gpu-descriptor" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b0c02e1ba0bdb14e965058ca34e09c020f8e507a760df1121728e0aef68d57a" +dependencies = [ + "bitflags", + "gpu-descriptor-types", + "hashbrown 0.12.3", +] + +[[package]] +name = "gpu-descriptor-types" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "363e3677e55ad168fef68cf9de3a4a310b53124c5e784c53a1d70e92d23f2126" +dependencies = [ + "bitflags", +] + [[package]] name = "guillotiere" version = "0.6.2" @@ -1908,6 +2023,12 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hexf-parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" + [[package]] name = "hostname" version = "0.3.1" @@ -2222,6 +2343,17 @@ dependencies = [ "term_size", ] +[[package]] +name = "khronos-egl" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c2352bd1d0bceb871cb9d40f24360c8133c11d7486b68b5381c1dd1a32015e3" +dependencies = [ + "libc", + "libloading 0.7.4", + "pkg-config", +] + [[package]] name = "khronos_api" version = "3.1.0" @@ -2592,6 +2724,20 @@ dependencies = [ "autocfg", ] +[[package]] +name = "metal" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de11355d1f6781482d027a3b4d4de7825dcedb197bf573e0596d00008402d060" +dependencies = [ + "bitflags", + "block", + "core-graphics-types", + "foreign-types", + "log", + "objc", +] + [[package]] name = "metrics" version = "0.17.1" @@ -2761,6 +2907,26 @@ dependencies = [ "wezterm-term", ] +[[package]] +name = "naga" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "262d2840e72dbe250e8cf2f522d080988dfca624c4112c096238a4845f591707" +dependencies = [ + "bit-set", + "bitflags", + "codespan-reporting", + "hexf-parse", + "indexmap", + "log", + "num-traits", + "rustc-hash", + "spirv", + "termcolor", + "thiserror", + "unicode-xid", +] + [[package]] name = "names" version = "0.12.0" @@ -3029,6 +3195,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" dependencies = [ "malloc_buf", + "objc_exception", ] [[package]] @@ -3042,6 +3209,15 @@ dependencies = [ "objc_id", ] +[[package]] +name = "objc_exception" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad970fb455818ad6cba4c122ad012fae53ae8b4795f86378bce65e4f6bab2ca4" +dependencies = [ + "cc", +] + [[package]] name = "objc_id" version = "0.1.1" @@ -3607,6 +3783,12 @@ dependencies = [ "wezterm-dynamic", ] +[[package]] +name = "profiling" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74605f360ce573babfe43964cbe520294dcb081afbf8c108fc6e23036b4da2df" + [[package]] name = "promise" version = "0.2.0" @@ -3753,6 +3935,12 @@ dependencies = [ "rand_core 0.5.1", ] +[[package]] +name = "range-alloc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e935c45e09cc6dcf00d2f0b2d630a58f4095320223d47fc68918722f0538b6" + [[package]] name = "rangeset" version = "0.1.0" @@ -3875,6 +4063,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "renderdoc-sys" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1382d1f0a252c4bf97dc20d979a2fdd05b024acd7c2ed0f7595d7817666a157" + [[package]] name = "reqwest" version = "0.11.12" @@ -4362,6 +4556,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "slotmap" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1e08e261d0e8f5c43123b7adf3e4ca1690d655377ac93a03b2c9d3e98de1342" +dependencies = [ + "version_check", +] + [[package]] name = "smallvec" version = "1.10.0" @@ -4480,6 +4683,16 @@ dependencies = [ "lock_api", ] +[[package]] +name = "spirv" +version = "0.2.0+1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "246bfa38fe3db3f1dfc8ca5a2cdeb7348c78be2112740cc0ec8ef18b6d94f830" +dependencies = [ + "bitflags", + "num-traits", +] + [[package]] name = "sqlite-cache" version = "0.1.3" @@ -5129,6 +5342,12 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" +[[package]] +name = "unicode-xid" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c" + [[package]] name = "unsafe-libyaml" version = "0.2.4" @@ -5602,6 +5821,7 @@ dependencies = [ "anyhow", "benchmarking", "bitflags", + "bytemuck", "cc", "chrono", "clap 4.0.23", @@ -5671,6 +5891,7 @@ dependencies = [ "wezterm-ssh", "wezterm-term", "wezterm-toast-notification", + "wgpu", "winapi", "window", "window-funcs", @@ -5824,6 +6045,100 @@ dependencies = [ "zvariant", ] +[[package]] +name = "wgpu" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2272b17bffc8a0c7d53897435da7c1db587c87d3a14e8dae9cdb8d1d210fc0f" +dependencies = [ + "arrayvec", + "js-sys", + "log", + "naga", + "parking_lot 0.12.1", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73d14cad393054caf992ee02b7da6a372245d39a484f7461c1f44f6f6359bd28" +dependencies = [ + "arrayvec", + "bit-vec", + "bitflags", + "cfg_aliases", + "codespan-reporting", + "fxhash", + "log", + "naga", + "parking_lot 0.12.1", + "profiling", + "raw-window-handle", + "smallvec", + "thiserror", + "web-sys", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-hal" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cc320a61acb26be4f549c9b1b53405c10a223fbfea363ec39474c32c348d12f" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags", + "block", + "core-graphics-types", + "d3d12", + "foreign-types", + "fxhash", + "glow", + "gpu-alloc", + "gpu-descriptor", + "js-sys", + "khronos-egl", + "libloading 0.7.4", + "log", + "metal", + "naga", + "objc", + "parking_lot 0.12.1", + "profiling", + "range-alloc", + "raw-window-handle", + "renderdoc-sys", + "smallvec", + "thiserror", + "wasm-bindgen", + "web-sys", + "wgpu-types", + "winapi", +] + +[[package]] +name = "wgpu-types" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb6b28ef22cac17b9109b25b3bf8c9a103eeb293d7c5f78653979b09140375f6" +dependencies = [ + "bitflags", +] + [[package]] name = "whoami" version = "1.2.3" diff --git a/Cargo.toml b/Cargo.toml index cddf37216..848fb8bce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,8 @@ opt-level = 3 [profile.dev] # https://jakedeichert.com/blog/reducing-rust-incremental-compilation-times-on-macos-by-70-percent/ -split-debuginfo = "unpacked" +# Disabled because it breaks builds on Windows +#split-debuginfo = "unpacked" [patch.crates-io] xcb = {version="1.1.1", git="https://github.com/rust-x-bindings/rust-xcb", rev="a85a4cf8937898b1da972367df4648143ede38ea"} diff --git a/config/src/frontend.rs b/config/src/frontend.rs index f701c63f3..71994839e 100644 --- a/config/src/frontend.rs +++ b/config/src/frontend.rs @@ -3,6 +3,7 @@ use wezterm_dynamic::{FromDynamic, ToDynamic}; #[derive(Debug, Clone, Copy, PartialEq, Eq, FromDynamic, ToDynamic)] pub enum FrontEndSelection { OpenGL, + WebGpu, Software, } diff --git a/mux/src/localpane.rs b/mux/src/localpane.rs index 93a8db0f1..9fdda817a 100644 --- a/mux/src/localpane.rs +++ b/mux/src/localpane.rs @@ -74,6 +74,7 @@ impl Pane for LocalPane { } fn get_metadata(&self) -> Value { + #[allow(unused_mut)] let mut map: BTreeMap = BTreeMap::new(); #[cfg(unix)] diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.toml index 0b9f6314f..ae7a6e278 100644 --- a/wezterm-gui/Cargo.toml +++ b/wezterm-gui/Cargo.toml @@ -35,6 +35,7 @@ cc = "1.0" [dependencies] anyhow = "1.0" bitflags = "1.3" +bytemuck = { version="1.4", features=["derive"]} chrono = {version="0.4", features=["unstable-locales"]} clap = {version="4.0", features=["derive"]} codec = { path = "../codec" } @@ -98,6 +99,7 @@ wezterm-mux-server-impl = { path = "../wezterm-mux-server-impl" } wezterm-ssh = { path = "../wezterm-ssh" } wezterm-term = { path = "../term", features=["use_serde"] } wezterm-toast-notification = { path = "../wezterm-toast-notification" } +wgpu = "0.14" window = { path = "../window" } window-funcs = { path = "../lua-api-crates/window-funcs" } diff --git a/wezterm-gui/src/shader.wgsl b/wezterm-gui/src/shader.wgsl new file mode 100644 index 000000000..cae11553d --- /dev/null +++ b/wezterm-gui/src/shader.wgsl @@ -0,0 +1,29 @@ +// Vertex shader + +struct VertexInput { + @location(0) position: vec3, + @location(1) color: vec3, +}; + +struct VertexOutput { + @builtin(position) clip_position: vec4, + @location(0) color: vec3, +}; + +@vertex +fn vs_main( + model: VertexInput, +) -> VertexOutput { + var out: VertexOutput; + out.color = model.color; + out.clip_position = vec4(model.position, 1.0); + return out; +} + +// Fragment shader + +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + return vec4(in.color, 1.0); +} + diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs index 5d27a1164..a3d0f1220 100644 --- a/wezterm-gui/src/termwindow/mod.rs +++ b/wezterm-gui/src/termwindow/mod.rs @@ -24,6 +24,7 @@ use crate::termwindow::render::{ CachedLineState, LineQuadCacheKey, LineQuadCacheValue, LineToEleShapeCacheKey, LineToElementShapeItem, }; +use crate::termwindow::webgpu::WebGpuState; use ::wezterm_term::input::{ClickPosition, MouseButton as TMB}; use ::window::*; use anyhow::{anyhow, ensure, Context}; @@ -32,8 +33,8 @@ use config::keyassignment::{ QuickSelectArguments, RotationDirection, SpawnCommand, SplitSize, }; use config::{ - configuration, AudibleBell, ConfigHandle, Dimension, DimensionContext, TermConfig, - WindowCloseConfirmation, + configuration, AudibleBell, ConfigHandle, Dimension, DimensionContext, FrontEndSelection, + TermConfig, WindowCloseConfirmation, }; use lfucache::*; use mlua::{FromLua, UserData, UserDataFields}; @@ -77,6 +78,7 @@ mod render; pub mod resize; mod selection; pub mod spawn; +pub mod webgpu; use prevcursor::PrevCursorPos; use spawn::SpawnWhere; @@ -439,6 +441,7 @@ pub struct TermWindow { pub fps: f32, gl: Option>, + webgpu: Option, config_subscription: Option, } @@ -557,10 +560,6 @@ impl TermWindow { } } - self.load_os_parameters(); - - window.show(); - if self.render_state.is_none() { panic!("No OpenGL"); } @@ -667,6 +666,7 @@ impl TermWindow { config_subscription: None, os_parameters: None, gl: None, + webgpu: None, window: None, window_background, config: config.clone(), @@ -812,11 +812,18 @@ impl TermWindow { } }); - let gl = window.enable_opengl().await?; + let gl = match config.front_end { + FrontEndSelection::WebGpu => None, + _ => Some(window.enable_opengl().await?), + }; + { let mut myself = tw.borrow_mut(); + let webgpu = match config.front_end { + FrontEndSelection::WebGpu => Some(WebGpuState::new(&window, dimensions).await?), + _ => None, + }; myself.config_subscription.replace(config_subscription); - myself.gl.replace(Rc::clone(&gl)); if config.use_resize_increments { window.set_resize_increments( myself.render_metrics.cell_size.width as u16, @@ -824,7 +831,16 @@ impl TermWindow { ); } - myself.created(&window, Rc::clone(&gl))?; + if let Some(gl) = gl { + myself.gl.replace(Rc::clone(&gl)); + myself.created(&window, Rc::clone(&gl))?; + } + myself.webgpu = webgpu; + myself.load_os_parameters(); + window.show(); + if myself.webgpu.is_some() { + log::info!("using webgpu"); + } myself.subscribe_to_pane_updates(); myself.emit_window_event("window-config-reloaded", None); myself.emit_status_event(); @@ -841,6 +857,7 @@ impl TermWindow { event: WindowEvent, window: &Window, ) -> anyhow::Result { + log::debug!("{event:?}"); match event { WindowEvent::Destroyed => Ok(false), WindowEvent::CloseRequested => { @@ -900,6 +917,7 @@ impl TermWindow { window.invalidate(); Ok(true) } + WindowEvent::NeedRepaint if self.webgpu.is_some() => self.do_paint_webgpu(window), WindowEvent::NeedRepaint => Ok(self.do_paint(window)), WindowEvent::Notification(item) => { if let Ok(notif) = item.downcast::() { @@ -954,6 +972,67 @@ impl TermWindow { window.finish_frame(frame).is_ok() } + fn do_paint_webgpu(&mut self, window: &Window) -> anyhow::Result { + self.webgpu.as_mut().unwrap().resize(self.dimensions); + match self.do_paint_webgpu_impl(window) { + 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); + } + _ => {} + } + Err(err) + } + } + } + + fn do_paint_webgpu_impl(&mut self, window: &Window) -> anyhow::Result { + let webgpu = self.webgpu.as_mut().unwrap(); + + let output = webgpu.surface.get_current_texture()?; + let view = output + .texture + .create_view(&wgpu::TextureViewDescriptor::default()); + let mut encoder = webgpu + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("Render Encoder"), + }); + + { + 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, + }, + })], + depth_stencil_attachment: None, + }); + + 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); + } + + // submit will accept anything that implements IntoIter + webgpu.queue.submit(std::iter::once(encoder.finish())); + output.present(); + + Ok(true) + } + fn dispatch_notif(&mut self, notif: TermWindowNotif, window: &Window) -> anyhow::Result<()> { fn chan_err(e: smol::channel::TrySendError) -> anyhow::Error { anyhow::anyhow!("{}", e) diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rs index a2b5ac5fb..ce17da2b7 100644 --- a/wezterm-gui/src/termwindow/resize.rs +++ b/wezterm-gui/src/termwindow/resize.rs @@ -45,6 +45,11 @@ impl super::TermWindow { if last_state != self.window_state { self.load_os_parameters(); } + + if let Some(webgpu) = self.webgpu.as_mut() { + webgpu.resize(dimensions); + } + // For simple, user-interactive resizes where the dpi doesn't change, // skip our scaling recalculation if live_resizing && self.dimensions.dpi == dimensions.dpi { diff --git a/wezterm-gui/src/termwindow/webgpu.rs b/wezterm-gui/src/termwindow/webgpu.rs new file mode 100644 index 000000000..69814d139 --- /dev/null +++ b/wezterm-gui/src/termwindow/webgpu.rs @@ -0,0 +1,218 @@ +use anyhow::anyhow; +use wgpu::util::DeviceExt; +use window::raw_window_handle::{ + HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle, +}; +use window::{Dimensions, Window}; + +#[repr(C)] +#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] +struct Vertex { + position: [f32; 3], + color: [f32; 3], +} + +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, + pub queue: wgpu::Queue, + pub config: wgpu::SurfaceConfiguration, + pub dimensions: Dimensions, + pub render_pipeline: wgpu::RenderPipeline, + pub vertex_buffer: wgpu::Buffer, + pub num_vertices: u32, + pub handle: RawHandlePair, +} + +pub struct RawHandlePair { + window: RawWindowHandle, + display: RawDisplayHandle, +} + +impl RawHandlePair { + fn new(window: &Window) -> Self { + Self { + window: window.raw_window_handle(), + display: window.raw_display_handle(), + } + } +} + +unsafe impl HasRawWindowHandle for RawHandlePair { + fn raw_window_handle(&self) -> RawWindowHandle { + self.window + } +} + +unsafe impl HasRawDisplayHandle for RawHandlePair { + fn raw_display_handle(&self) -> RawDisplayHandle { + self.display + } +} + +impl WebGpuState { + pub async fn new(window: &Window, dimensions: Dimensions) -> anyhow::Result { + let handle = RawHandlePair::new(window); + Self::new_impl(handle, dimensions).await + } + + pub async fn new_impl(handle: RawHandlePair, dimensions: Dimensions) -> anyhow::Result { + let instance = wgpu::Instance::new(wgpu::Backends::all()); + let surface = unsafe { instance.create_surface(&handle) }; + let adapter = instance + .request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::default(), + compatible_surface: Some(&surface), + force_fallback_adapter: false, + }) + .await + .ok_or_else(|| anyhow!("no matching adapter found"))?; + + let (device, queue) = adapter + .request_device( + &wgpu::DeviceDescriptor { + features: wgpu::Features::empty(), + // WebGL doesn't support all of wgpu's features, so if + // we're building for the web we'll have to disable some. + limits: if cfg!(target_arch = "wasm32") { + wgpu::Limits::downlevel_webgl2_defaults() + } else { + wgpu::Limits::default() + }, + label: None, + }, + None, // Trace path + ) + .await?; + + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: surface.get_supported_formats(&adapter)[0], + width: dimensions.pixel_width as u32, + height: dimensions.pixel_height as u32, + present_mode: wgpu::PresentMode::Fifo, + alpha_mode: wgpu::CompositeAlphaMode::Auto, + }; + surface.configure(&device, &config); + + let shader = device.create_shader_module(wgpu::include_wgsl!("../shader.wgsl")); + + let render_pipeline_layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Render Pipeline Layout"), + bind_group_layouts: &[], + push_constant_ranges: &[], + }); + + let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Render Pipeline"), + layout: Some(&render_pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: "vs_main", + buffers: &[Vertex::desc()], + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: "fs_main", + targets: &[Some(wgpu::ColorTargetState { + format: config.format, + blend: Some(wgpu::BlendState::REPLACE), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + + primitive: wgpu::PrimitiveState { + 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 + polygon_mode: wgpu::PolygonMode::Fill, + // Requires Features::DEPTH_CLIP_CONTROL + unclipped_depth: false, + // Requires Features::CONSERVATIVE_RASTERIZATION + conservative: false, + }, + depth_stencil: None, + multisample: wgpu::MultisampleState { + count: 1, + mask: !0, + alpha_to_coverage_enabled: false, + }, + 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, + queue, + config, + dimensions, + render_pipeline, + vertex_buffer, + num_vertices: VERTICES.len() as u32, + handle, + }) + } + + #[allow(unused_mut)] + pub fn resize(&mut self, mut dims: Dimensions) { + // During a live resize on Windows, the Dimensions that we're processing may be + // lagging behind the true client size. We have to take the very latest value + // from the window or else the underlying driver will raise an error about + // the mismatch, so we need to sneakily read through the handle + match self.handle.window { + #[cfg(windows)] + RawWindowHandle::Win32(h) => { + let mut rect = unsafe { std::mem::zeroed() }; + unsafe { winapi::um::winuser::GetClientRect(h.hwnd as _, &mut rect) }; + dims.pixel_width = (rect.right - rect.left) as usize; + dims.pixel_height = (rect.bottom - rect.top) as usize; + } + _ => {} + } + + if dims == self.dimensions { + return; + } + self.dimensions = dims; + self.config.width = dims.pixel_width as u32; + self.config.height = dims.pixel_height as u32; + self.surface.configure(&self.device, &self.config); + } +} diff --git a/window/src/lib.rs b/window/src/lib.rs index 1a647117b..4c8983126 100644 --- a/window/src/lib.rs +++ b/window/src/lib.rs @@ -14,6 +14,8 @@ pub mod os; pub mod screen; mod spawn; +pub use raw_window_handle; + #[cfg(target_os = "macos")] pub(crate) const DEFAULT_DPI: f64 = 72.0; #[cfg(not(target_os = "macos"))] diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs index ca72288d6..6eec7e781 100644 --- a/window/src/os/macos/window.rs +++ b/window/src/os/macos/window.rs @@ -36,7 +36,10 @@ use objc::rc::{StrongPtr, WeakPtr}; use objc::runtime::{Class, Object, Protocol, Sel}; use objc::*; use promise::Future; -use raw_window_handle::{AppKitWindowHandle, HasRawWindowHandle, RawWindowHandle}; +use raw_window_handle::{ + AppKitDisplayHandle, AppKitWindowHandle, HasRawDisplayHandle, HasRawWindowHandle, + RawDisplayHandle, RawWindowHandle, +}; use std::any::Any; use std::cell::RefCell; use std::ffi::c_void; @@ -571,6 +574,12 @@ impl Window { } } +unsafe impl HasRawDisplayHandle for Window { + fn raw_display_handle(&self) -> RawDisplayHandle { + RawDisplayHandle::AppKit(AppKitDisplayHandle::empty()) + } +} + unsafe impl HasRawWindowHandle for Window { fn raw_window_handle(&self) -> RawWindowHandle { let mut handle = AppKitWindowHandle::empty(); @@ -2501,9 +2510,23 @@ impl WindowView { } } + extern "C" fn update_layer(view: &mut Object, sel: Sel) { + log::info!("update_layer called"); + } + + extern "C" fn wants_update_layer(view: &mut Object, sel: Sel) -> BOOL { + log::info!("wants_update_layer called"); + YES + } + + extern "C" fn display_layer(view: &mut Object, sel: Sel, _layer_id: id) { + log::info!("display_layer"); + } + extern "C" fn draw_rect(view: &mut Object, sel: Sel, _dirty_rect: NSRect) { if let Some(this) = Self::get_this(view) { let mut inner = this.inner.borrow_mut(); + log::info!("draw_rect called"); if inner.screen_changed { // If the screen resolution changed (which can also @@ -2625,6 +2648,8 @@ impl WindowView { Protocol::get("NSTextInputClient").expect("failed to get NSTextInputClient protocol"), ); + cls.add_protocol(Protocol::get("CALayerDelegate").expect("CALayerDelegate not defined")); + unsafe { cls.add_method( sel!(dealloc), @@ -2646,6 +2671,21 @@ impl WindowView { Self::draw_rect as extern "C" fn(&mut Object, Sel, NSRect), ); + cls.add_method( + sel!(updateLayer), + Self::update_layer as extern "C" fn(&mut Object, Sel), + ); + + cls.add_method( + sel!(wantsUpdateLayer), + Self::wants_update_layer as extern "C" fn(&mut Object, Sel) -> BOOL, + ); + + cls.add_method( + sel!(displayLayer:), + Self::display_layer as extern "C" fn(&mut Object, Sel, id), + ); + cls.add_method( sel!(isFlipped), Self::is_flipped as extern "C" fn(&Object, Sel) -> BOOL, diff --git a/window/src/os/wayland/window.rs b/window/src/os/wayland/window.rs index 6a239ff3b..f78d74c58 100644 --- a/window/src/os/wayland/window.rs +++ b/window/src/os/wayland/window.rs @@ -16,7 +16,10 @@ use async_trait::async_trait; use config::ConfigHandle; use filedescriptor::FileDescriptor; use promise::{Future, Promise}; -use raw_window_handle::{HasRawWindowHandle, RawWindowHandle, WaylandWindowHandle}; +use raw_window_handle::{ + HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle, + WaylandDisplayHandle, WaylandWindowHandle, +}; use smithay_client_toolkit as toolkit; use std::any::Any; use std::cell::RefCell; @@ -389,6 +392,15 @@ impl WaylandWindow { } } +unsafe impl HasRawDisplayHandle for WaylandWindowInner { + fn raw_display_handle(&self) -> RawDisplayHandle { + let mut handle = WaylandDisplayHandle::empty(); + let conn = WaylandConnection::get().unwrap().wayland(); + handle.display = conn.display.borrow().c_ptr() as _; + RawDisplayHandle::Wayland(handle) + } +} + unsafe impl HasRawWindowHandle for WaylandWindowInner { fn raw_window_handle(&self) -> RawWindowHandle { let mut handle = WaylandWindowHandle::empty(); @@ -807,6 +819,15 @@ impl WaylandWindowInner { } } +unsafe impl HasRawDisplayHandle for WaylandWindow { + fn raw_display_handle(&self) -> RawDisplayHandle { + let mut handle = WaylandDisplayHandle::empty(); + let conn = WaylandConnection::get().unwrap().wayland(); + handle.display = conn.display.borrow().c_ptr() as _; + RawDisplayHandle::Wayland(handle) + } +} + unsafe impl HasRawWindowHandle for WaylandWindow { fn raw_window_handle(&self) -> RawWindowHandle { let conn = Connection::get().expect("raw_window_handle only callable on main thread"); diff --git a/window/src/os/windows/window.rs b/window/src/os/windows/window.rs index 191cf653d..4103a1991 100644 --- a/window/src/os/windows/window.rs +++ b/window/src/os/windows/window.rs @@ -12,7 +12,10 @@ use async_trait::async_trait; use config::{ConfigHandle, ImePreeditRendering}; use lazy_static::lazy_static; use promise::Future; -use raw_window_handle::{HasRawWindowHandle, RawWindowHandle, Win32WindowHandle}; +use raw_window_handle::{ + HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle, Win32WindowHandle, + WindowsDisplayHandle, +}; use shared_library::shared_library; use std::any::Any; use std::cell::RefCell; @@ -177,11 +180,17 @@ fn callback_behavior() -> glium::debug::DebugCallbackBehavior { } } +unsafe impl HasRawDisplayHandle for WindowInner { + fn raw_display_handle(&self) -> RawDisplayHandle { + RawDisplayHandle::Windows(WindowsDisplayHandle::empty()) + } +} + unsafe impl HasRawWindowHandle for WindowInner { fn raw_window_handle(&self) -> RawWindowHandle { let mut handle = Win32WindowHandle::empty(); handle.hwnd = self.hwnd.0 as *mut _; - handle.hinstance = unsafe { GetModuleHandleW(null()) }; + handle.hinstance = unsafe { GetModuleHandleW(null()) } as _; RawWindowHandle::Win32(handle) } } @@ -652,6 +661,12 @@ impl WindowInner { } } +unsafe impl HasRawDisplayHandle for Window { + fn raw_display_handle(&self) -> RawDisplayHandle { + RawDisplayHandle::Windows(WindowsDisplayHandle::empty()) + } +} + unsafe impl HasRawWindowHandle for Window { fn raw_window_handle(&self) -> RawWindowHandle { let conn = Connection::get().expect("raw_window_handle only callable on main thread"); diff --git a/window/src/os/x11/window.rs b/window/src/os/x11/window.rs index 7c2f4b991..89fb5b69a 100644 --- a/window/src/os/x11/window.rs +++ b/window/src/os/x11/window.rs @@ -11,7 +11,10 @@ use anyhow::{anyhow, Context as _}; use async_trait::async_trait; use config::ConfigHandle; use promise::{Future, Promise}; -use raw_window_handle::{HasRawWindowHandle, RawWindowHandle, XcbWindowHandle}; +use raw_window_handle::{ + HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle, XcbDisplayHandle, + XcbWindowHandle, +}; use std::any::Any; use std::convert::TryInto; use std::rc::{Rc, Weak}; @@ -99,11 +102,23 @@ impl Drop for XWindowInner { } } +unsafe impl HasRawDisplayHandle for XWindowInner { + fn raw_display_handle(&self) -> RawDisplayHandle { + let mut handle = XcbDisplayHandle::empty(); + if let Some(conn) = self.conn.upgrade() { + handle.connection = conn.conn.get_raw_conn() as _; + handle.screen = conn.screen_num; + } + + RawDisplayHandle::Xcb(handle) + } +} + unsafe impl HasRawWindowHandle for XWindowInner { fn raw_window_handle(&self) -> RawWindowHandle { let mut handle = XcbWindowHandle::empty(); handle.window = self.window_id.resource_id(); - handle.visual_id = self.conn.upgrade().unwrap().visual; + handle.visual_id = self.conn.upgrade().unwrap().visual.visual_id(); RawWindowHandle::Xcb(handle) } } @@ -1470,6 +1485,19 @@ impl XWindowInner { } } +unsafe impl HasRawDisplayHandle for XWindow { + fn raw_display_handle(&self) -> RawDisplayHandle { + let conn = Connection::get() + .expect("raw_window_handle only callable on main thread") + .x11(); + let mut handle = XcbDisplayHandle::empty(); + handle.connection = conn.get_raw_conn() as _; + handle.screen = conn.screen_num; + + RawDisplayHandle::Xcb(handle) + } +} + unsafe impl HasRawWindowHandle for XWindow { fn raw_window_handle(&self) -> RawWindowHandle { let conn = Connection::get().expect("raw_window_handle only callable on main thread"); diff --git a/window/src/os/x_and_wayland.rs b/window/src/os/x_and_wayland.rs index d422d7345..4176cf4b5 100644 --- a/window/src/os/x_and_wayland.rs +++ b/window/src/os/x_and_wayland.rs @@ -15,7 +15,9 @@ use crate::{ use async_trait::async_trait; use config::ConfigHandle; use promise::*; -use raw_window_handle::{HasRawWindowHandle, RawWindowHandle}; +use raw_window_handle::{ + HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle, +}; use std::any::Any; use std::rc::Rc; use wezterm_font::FontConfiguration; @@ -192,6 +194,16 @@ impl Window { } } +unsafe impl HasRawDisplayHandle for Window { + fn raw_display_handle(&self) -> RawDisplayHandle { + match self { + Self::X11(x) => x.raw_display_handle(), + #[cfg(feature = "wayland")] + Self::Wayland(w) => w.raw_display_handle(), + } + } +} + unsafe impl HasRawWindowHandle for Window { fn raw_window_handle(&self) -> RawWindowHandle { match self {