Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

thinkterm-render: extract the renderer's portable half into a crate

RoversXeef0d6d909bb
diff --git a/Cargo.lock b/Cargo.lock
index e3a7454e..38a914f1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -991,6 +991,7 @@ dependencies = [
"toml 0.8.23",
"umask",
"wezterm-bidi 0.2.3",
+ "wezterm-color-types 0.3.0",
"wezterm-config-derive",
"wezterm-dynamic 0.2.1",
"wezterm-input-types 0.1.0",
@@ -6470,6 +6471,27 @@ dependencies = [
"wezterm-term",
]
+[[package]]
+name = "thinkterm-render"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytemuck",
+ "downcast-rs",
+ "euclid",
+ "glium",
+ "guillotiere",
+ "line_drawing",
+ "log",
+ "metrics",
+ "naga",
+ "resize",
+ "thiserror 1.0.69",
+ "wezterm-color-types 0.3.0",
+ "wezterm-input-types 0.1.0",
+ "wgpu",
+]
+
[[package]]
name = "thinkterm-session"
version = "0.1.0"
@@ -8102,6 +8124,7 @@ dependencies = [
"textwrap",
"thinkterm-core",
"thinkterm-proto",
+ "thinkterm-render",
"thinkterm-syntax",
"thinkterm-update",
"thiserror 1.0.69",
@@ -8593,7 +8616,6 @@ dependencies = [
"core-foundation 0.10.0",
"core-graphics 0.24.0",
"dirs-next",
- "downcast-rs",
"euclid",
"filedescriptor 0.8.3",
"foreign-types 0.5.0",
@@ -8601,12 +8623,10 @@ dependencies = [
"futures-util",
"gl_generator",
"glium",
- "guillotiere",
"k9",
"lazy_static",
"libc",
"libloading",
- "line_drawing",
"log",
"metrics",
"mio 0.8.11",
@@ -8616,11 +8636,11 @@ dependencies = [
"plist",
"promise",
"raw-window-handle",
- "resize",
"serde",
"shared_library",
"shlex 1.3.0",
"smithay-client-toolkit",
+ "thinkterm-render",
"thiserror 1.0.69",
"tiny-skia",
"url",
diff --git a/Cargo.toml b/Cargo.toml
index 07971ef7..fe0de646 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -8,6 +8,7 @@ members = [
"thinkterm-syntax",
"thinkterm-core",
"thinkterm-proto",
+ "thinkterm-render",
"thinkterm-session",
"thinkterm-tui",
"thinkterm-update",
@@ -78,6 +79,7 @@ colorgrad = "0.6"
config = { path = "config" }
thinkterm-core = { path = "thinkterm-core" }
thinkterm-proto = { path = "thinkterm-proto" }
+thinkterm-render = { path = "thinkterm-render" }
thinkterm-session = { path = "thinkterm-session" }
thinkterm-update = { path = "thinkterm-update" }
core-foundation = "=0.10.0"
diff --git a/color-types/src/lib.rs b/color-types/src/lib.rs
index 5bac168f..855f26bb 100644
--- a/color-types/src/lib.rs
+++ b/color-types/src/lib.rs
@@ -17,8 +17,35 @@ use wezterm_dynamic::{FromDynamic, FromDynamicOptions, ToDynamic, Value};
extern crate alloc;
+/// A hue/saturation/brightness multiplier applied to a colour on the GPU.
+/// 1.0 on every axis is the identity. Lives here, not in `config`, so the
+/// renderer core can name it without depending on the configuration crate.
+#[derive(Debug, Copy, Clone, PartialEq, FromDynamic, ToDynamic)]
+pub struct HsbTransform {
+ #[dynamic(default = "default_one_point_oh")]
+ pub hue: f32,
+ #[dynamic(default = "default_one_point_oh")]
+ pub saturation: f32,
+ #[dynamic(default = "default_one_point_oh")]
+ pub brightness: f32,
+}
+
+fn default_one_point_oh() -> f32 {
+ 1.0
+}
+
+impl Default for HsbTransform {
+ fn default() -> Self {
+ Self {
+ hue: 1.,
+ saturation: 1.,
+ brightness: 1.,
+ }
+ }
+}
+
use alloc::format;
-use alloc::string::String;
+use alloc::string::{String, ToString};
use alloc::vec::Vec;
#[cfg(feature = "std")]
diff --git a/config/Cargo.toml b/config/Cargo.toml
index 2afaa4de..47fff60e 100644
--- a/config/Cargo.toml
+++ b/config/Cargo.toml
@@ -15,6 +15,7 @@ tempfile.workspace = true
distro-defaults = []
[dependencies]
+wezterm-color-types.workspace = true
anyhow.workspace = true
bitflags.workspace = true
colorgrad.workspace = true
diff --git a/config/src/color.rs b/config/src/color.rs
index 4e8dea48..c58dec29 100644
--- a/config/src/color.rs
+++ b/config/src/color.rs
@@ -8,25 +8,7 @@ pub use termwiz::color::{AnsiColor, ColorAttribute, RgbColor, SrgbaTuple};
use wezterm_dynamic::{FromDynamic, ToDynamic};
use wezterm_term::color::ColorPalette;
-#[derive(Debug, Copy, Clone, FromDynamic, ToDynamic)]
-pub struct HsbTransform {
- #[dynamic(default = "default_one_point_oh")]
- pub hue: f32,
- #[dynamic(default = "default_one_point_oh")]
- pub saturation: f32,
- #[dynamic(default = "default_one_point_oh")]
- pub brightness: f32,
-}
-
-impl Default for HsbTransform {
- fn default() -> Self {
- Self {
- hue: 1.,
- saturation: 1.,
- brightness: 1.,
- }
- }
-}
+pub use wezterm_color_types::HsbTransform;
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, FromDynamic, ToDynamic)]
#[dynamic(try_from = "String", into = "String")]
diff --git a/thinkterm-render/Cargo.toml b/thinkterm-render/Cargo.toml
new file mode 100644
index 00000000..38f88726
--- /dev/null
+++ b/thinkterm-render/Cargo.toml
@@ -0,0 +1,39 @@
+[package]
+name = "thinkterm-render"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+# The GPU-backend-neutral half of the terminal renderer: the WGSL shader,
+# the vertex layout and quad machinery, CPU bitmaps, the glyph atlas and
+# (behind the `wgpu` feature) the pipeline setup. Shared by the desktop
+# window and the browser client so the two cannot drift. This crate must
+# always build for wasm32-unknown-unknown: no processes, files, sockets,
+# threads or std::time, and never a dependency on config, window, mux or
+# wezterm-font. The `glium` feature exists only so the desktop's OpenGL
+# fallback can keep one Vertex definition; wasm never enables it.
+
+[features]
+default = []
+glium = ["dep:glium"]
+wgpu = ["dep:wgpu"]
+
+[dependencies]
+anyhow.workspace = true
+bytemuck.workspace = true
+downcast-rs.workspace = true
+euclid.workspace = true
+glium = { workspace = true, optional = true }
+guillotiere.workspace = true
+line_drawing.workspace = true
+log.workspace = true
+metrics.workspace = true
+resize.workspace = true
+thiserror.workspace = true
+wezterm-color-types.workspace = true
+wezterm-input-types.workspace = true
+wgpu = { workspace = true, optional = true }
+
+[dev-dependencies]
+# The WGSL validation test runs whatever features are on.
+naga = { version = "25", features = ["wgsl-in"] }
diff --git a/window/src/bitmaps/atlas.rs b/thinkterm-render/src/atlas.rs
similarity index 92%
rename from window/src/bitmaps/atlas.rs
rename to thinkterm-render/src/atlas.rs
index 41541364..afb9f401 100644
--- a/window/src/bitmaps/atlas.rs
+++ b/thinkterm-render/src/atlas.rs
@@ -1,5 +1,7 @@
-use crate::bitmaps::{BitmapImage, Texture2d, TextureRect};
-use crate::{Point, Rect, Size};
+//! The glyph/sprite atlas: guillotiere packing over a `Texture2d`.
+
+use crate::bitmaps::{BitmapImage, Image, Texture2d, TextureRect};
+use crate::geom::{Point, Rect, Size};
use anyhow::{ensure, Result as Fallible};
use guillotiere::{SimpleAtlasAllocator, Size as AtlasSize};
use std::convert::TryInto;
@@ -103,7 +105,7 @@ impl Atlas {
let side = texture.width();
let iside = side as isize;
- let image = crate::Image::new(side, side);
+ let image = Image::new(side, side);
let rect = Rect::new(Point::new(0, 0), Size::new(iside, iside));
texture.write(rect, &image);
@@ -148,7 +150,7 @@ impl Atlas {
let (width, height) = im.image_dimensions();
if let Some(scale_down) = scale_down {
- let mut copied = crate::Image::new(width, height);
+ let mut copied = Image::new(width, height);
copied.draw_image(Point::new(0, 0), None, im);
// A source smaller than the divisor must not become 0x0: the
@@ -175,6 +177,7 @@ impl Atlas {
let reserve_width = reserve_width + padding.unwrap_or(0) as i32 + PADDING * 2;
let reserve_height = reserve_height + padding.unwrap_or(0) as i32 + PADDING * 2;
+ #[cfg(not(target_family = "wasm"))]
let start = std::time::Instant::now();
let res = if let Some(allocation) = self
.allocator
@@ -206,6 +209,7 @@ impl Atlas {
current_size: self.side,
})
};
+ #[cfg(not(target_family = "wasm"))]
metrics::histogram!("window.atlas.allocate.latency").record(start.elapsed());
res
@@ -223,7 +227,7 @@ impl Atlas {
/// Zero out the texture, and forget all allocated regions
pub fn clear(&mut self) {
let iside = self.side as isize;
- let image = crate::Image::new(self.side, self.side);
+ let image = Image::new(self.side, self.side);
let rect = Rect::new(Point::new(0, 0), Size::new(iside, iside));
self.texture.write(rect, &image);
self.allocator.clear();
@@ -265,7 +269,7 @@ impl Sprite {
#[cfg(test)]
mod usage_tests {
use super::{Atlas, AtlasTag, AtlasUsage, PADDING};
- use crate::bitmaps::{ImageTexture, Texture2d};
+ use crate::bitmaps::{Image, ImageTexture, Texture2d};
use std::rc::Rc;
fn atlas(side: usize) -> Atlas {
@@ -280,8 +284,8 @@ mod usage_tests {
#[test]
fn accounts_padded_area_per_tag_and_tracks_the_largest_rect() {
let mut atlas = atlas(64);
- let glyph = crate::Image::new(10, 10);
- let frame = crate::Image::new(20, 5);
+ let glyph = Image::new(10, 10);
+ let frame = Image::new(20, 5);
atlas
.allocate_tagged(&glyph, None, None, AtlasTag::Glyph)
.unwrap();
@@ -310,10 +314,10 @@ mod usage_tests {
fn max_rect_follows_the_longest_side_not_the_area() {
let mut atlas = atlas(256);
atlas
- .allocate_tagged(&crate::Image::new(200, 1), None, None, AtlasTag::Image)
+ .allocate_tagged(&Image::new(200, 1), None, None, AtlasTag::Image)
.unwrap();
atlas
- .allocate_tagged(&crate::Image::new(50, 50), None, None, AtlasTag::Glyph)
+ .allocate_tagged(&Image::new(50, 50), None, None, AtlasTag::Glyph)
.unwrap();
// 52x52 has the larger area, but 202x3 is what forces the atlas side.
assert_eq!(atlas.usage().max_rect, padded(200, 1));
@@ -322,7 +326,7 @@ mod usage_tests {
#[test]
fn scaled_allocations_account_the_scaled_rect() {
let mut atlas = atlas(64);
- let big = crate::Image::new(40, 40);
+ let big = Image::new(40, 40);
atlas
.allocate_tagged(&big, None, Some(2), AtlasTag::Image)
.unwrap();
@@ -337,8 +341,8 @@ mod usage_tests {
#[test]
fn failures_count_and_clear_resets_everything() {
let mut atlas = atlas(32);
- atlas.allocate(&crate::Image::new(8, 8)).unwrap();
- assert!(atlas.allocate(&crate::Image::new(100, 100)).is_err());
+ atlas.allocate(&Image::new(8, 8)).unwrap();
+ assert!(atlas.allocate(&Image::new(100, 100)).is_err());
assert_eq!(atlas.usage().failures, 1);
assert_eq!(atlas.usage().allocations, 1);
diff --git a/window/src/bitmaps/mod.rs b/thinkterm-render/src/bitmaps.rs
similarity index 91%
rename from window/src/bitmaps/mod.rs
rename to thinkterm-render/src/bitmaps.rs
index 305707ed..0f7c86d0 100644
--- a/window/src/bitmaps/mod.rs
+++ b/thinkterm-render/src/bitmaps.rs
@@ -1,17 +1,17 @@
-use crate::color::{LinearRgba, SrgbaPixel};
-use crate::{Point, Rect, Size};
+//! CPU-side bitmaps and the texture trait the atlas uploads through.
+
+use wezterm_color_types::{LinearRgba, SrgbaPixel};
+use crate::geom::{Point, Rect, Size};
use downcast_rs::{impl_downcast, Downcast};
-use glium::texture::SrgbTexture2d;
use std::cell::RefCell;
-pub mod atlas;
pub struct TextureUnit;
pub type TextureCoord = euclid::Point2D<f32, TextureUnit>;
pub type TextureRect = euclid::Rect<f32, TextureUnit>;
pub type TextureSize = euclid::Size2D<f32, TextureUnit>;
-/// Represents a big endian bgra32 bitmap that may not be present
+/// Represents an rgba32 bitmap that may not be present
/// in local RAM, but may be addressable in eg: video RAM
pub trait Texture2d: Downcast {
/// Copy the bits from the source bitmap to the texture at the location
@@ -43,43 +43,7 @@ pub trait Texture2d: Downcast {
}
impl_downcast!(Texture2d);
-impl Texture2d for SrgbTexture2d {
- fn write(&self, rect: Rect, im: &dyn BitmapImage) {
- let (im_width, im_height) = im.image_dimensions();
-
- let source = glium::texture::RawImage2d {
- data: std::borrow::Cow::Borrowed(im.pixels()),
- width: im_width as u32,
- height: im_height as u32,
- format: glium::texture::ClientFormat::U8U8U8U8,
- };
-
- SrgbTexture2d::write(
- self,
- glium::Rect {
- left: rect.min_x() as u32,
- bottom: rect.min_y() as u32,
- width: rect.size.width as u32,
- height: rect.size.height as u32,
- },
- source,
- )
- }
-
- fn read(&self, _rect: Rect, _im: &mut dyn BitmapImage) {
- unimplemented!();
- }
-
- fn width(&self) -> usize {
- SrgbTexture2d::width(self) as usize
- }
-
- fn height(&self) -> usize {
- SrgbTexture2d::height(self) as usize
- }
-}
-
-/// A bitmap in big endian rbga32 color format with abstract
+/// A bitmap in rgba32 color format (R, G, B, A byte order) with abstract
/// storage filled in by the trait implementation.
pub trait BitmapImage {
/// Obtain a read only pointer to the pixel data
diff --git a/thinkterm-render/src/geom.rs b/thinkterm-render/src/geom.rs
new file mode 100644
index 00000000..ee2d82a4
--- /dev/null
+++ b/thinkterm-render/src/geom.rs
@@ -0,0 +1,18 @@
+//! Geometry shared by every renderer. Pixel-space points and rects come
+//! from `wezterm-input-types`; this module adds what the quads need on top.
+
+pub use wezterm_input_types::{PixelUnit, Point, PointF};
+
+pub type ULength = euclid::Length<usize, PixelUnit>;
+pub type Rect = euclid::Rect<isize, PixelUnit>;
+pub type RectF = euclid::Rect<f32, PixelUnit>;
+pub type Size = euclid::Size2D<isize, PixelUnit>;
+pub type SizeF = euclid::Size2D<f32, PixelUnit>;
+
+/// The size of the surface being drawn, in physical pixels, and its DPI.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Dimensions {
+ pub pixel_width: usize,
+ pub pixel_height: usize,
+ pub dpi: usize,
+}
diff --git a/thinkterm-render/src/lib.rs b/thinkterm-render/src/lib.rs
new file mode 100644
index 00000000..b07b41da
--- /dev/null
+++ b/thinkterm-render/src/lib.rs
@@ -0,0 +1,33 @@
+//! The GPU-backend-neutral terminal renderer core. See Cargo.toml for the
+//! charter. The desktop (`wezterm-gui`, through `window`) and the browser
+//! client both build their frames out of these pieces.
+
+pub mod atlas;
+pub mod bitmaps;
+pub mod geom;
+#[cfg(feature = "wgpu")]
+pub mod pipeline;
+pub mod quad;
+pub mod vertex;
+
+pub use geom::Dimensions;
+pub use wezterm_color_types::HsbTransform;
+
+/// The one shader every ThinkTerm renderer draws with. Kept as source so
+/// each backend compiles it for its own device.
+pub const SHADER_SOURCE: &str = include_str!("shader.wgsl");
+
+#[cfg(test)]
+mod shader_tests {
+ #[test]
+ fn main_wgsl_shader_parses_and_validates() {
+ let module = naga::front::wgsl::parse_str(super::SHADER_SOURCE)
+ .expect("main WGSL shader should parse");
+ naga::valid::Validator::new(
+ naga::valid::ValidationFlags::all(),
+ naga::valid::Capabilities::all(),
+ )
+ .validate(&module)
+ .expect("main WGSL shader should validate");
+ }
+}
diff --git a/thinkterm-render/src/pipeline.rs b/thinkterm-render/src/pipeline.rs
new file mode 100644
index 00000000..3e180105
--- /dev/null
+++ b/thinkterm-render/src/pipeline.rs
@@ -0,0 +1,339 @@
+//! The wgpu side of the renderer: the one shader compiled into a pipeline,
+//! the bind-group layouts and samplers it expects, the uniform block, the
+//! centred projection, and an atlas texture the `Atlas` can upload into.
+//! Backend-neutral in the sense that matters here: a desktop window surface
+//! and a browser canvas both configure it with their own target format.
+
+use crate::bitmaps::{BitmapImage, Texture2d};
+use crate::geom::Rect;
+use crate::vertex::Vertex;
+use std::sync::Arc;
+
+/// Matches `ShaderUniform` in shader.wgsl field for field.
+#[repr(C)]
+#[derive(Copy, Clone, Default, Debug, bytemuck::Pod, bytemuck::Zeroable)]
+pub struct ShaderUniform {
+ pub foreground_text_hsb: [f32; 3],
+ pub milliseconds: u32,
+ pub viewport_and_corner: [f32; 4],
+ pub window_border: [f32; 4],
+ pub projection: [[f32; 4]; 4],
+}
+
+/// The projection every ThinkTerm frame draws with: orthographic, centred
+/// on the surface, so quad positions are offsets from the middle. The
+/// transposed array is what the WGSL expects for a symmetric ortho.
+pub fn centred_projection(width: f32, height: f32) -> [[f32; 4]; 4] {
+ euclid::Transform3D::<f32, f32, f32>::ortho(
+ -width / 2.0,
+ width / 2.0,
+ height / 2.0,
+ -height / 2.0,
+ -1.0,
+ 1.0,
+ )
+ .to_arrays_transposed()
+}
+
+/// The sRGB name of a target format: WebGPU canvases can only be configured
+/// with the linear name, and are then viewed as sRGB so the hardware encodes
+/// on write, exactly as the desktop's already-sRGB surface does.
+pub fn srgb_format(format: wgpu::TextureFormat) -> wgpu::TextureFormat {
+ format.add_srgb_suffix()
+}
+
+/// A view of `texture` as `format`; the view a frame is rendered into.
+pub fn view_as(texture: &wgpu::Texture, format: wgpu::TextureFormat) -> wgpu::TextureView {
+ texture.create_view(&wgpu::TextureViewDescriptor {
+ format: Some(format),
+ ..Default::default()
+ })
+}
+
+/// The compiled shader and everything a draw binds to it.
+pub struct Pipeline {
+ pub render_pipeline: wgpu::RenderPipeline,
+ pub uniform_layout: wgpu::BindGroupLayout,
+ pub texture_layout: wgpu::BindGroupLayout,
+ pub nearest_sampler: wgpu::Sampler,
+ pub linear_sampler: wgpu::Sampler,
+ /// The colour target format the pipeline was built for.
+ pub target_format: wgpu::TextureFormat,
+}
+
+pub struct AtlasBindGroups {
+ pub linear: wgpu::BindGroup,
+ pub nearest: wgpu::BindGroup,
+}
+
+impl Pipeline {
+ pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("shader.wgsl"),
+ source: wgpu::ShaderSource::Wgsl(crate::SHADER_SOURCE.into()),
+ });
+
+ let uniform_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ entries: &[wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
+ 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 sampler = |filter: wgpu::FilterMode| {
+ 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: filter,
+ min_filter: filter,
+ mipmap_filter: filter,
+ ..Default::default()
+ })
+ };
+ let nearest_sampler = sampler(wgpu::FilterMode::Nearest);
+ let linear_sampler = sampler(wgpu::FilterMode::Linear);
+
+ let texture_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 layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("Render Pipeline Layout"),
+ bind_group_layouts: &[&uniform_layout, &texture_layout, &texture_layout],
+ push_constant_ranges: &[],
+ });
+
+ let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Render Pipeline"),
+ layout: Some(&layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some("vs_main"),
+ buffers: &[Vertex::desc()],
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: target_format,
+ blend: Some(wgpu::BlendState::ALPHA_BLENDING),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ strip_index_format: None,
+ front_face: wgpu::FrontFace::Ccw,
+ cull_mode: None,
+ polygon_mode: wgpu::PolygonMode::Fill,
+ unclipped_depth: false,
+ conservative: false,
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState {
+ count: 1,
+ mask: !0,
+ alpha_to_coverage_enabled: false,
+ },
+ multiview: None,
+ cache: None,
+ });
+
+ Self {
+ render_pipeline,
+ uniform_layout,
+ texture_layout,
+ nearest_sampler,
+ linear_sampler,
+ target_format,
+ }
+ }
+
+ pub fn uniform_bind_group(&self, device: &wgpu::Device, buffer: &wgpu::Buffer) -> wgpu::BindGroup {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ layout: &self.uniform_layout,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: buffer.as_entire_binding(),
+ }],
+ label: Some("ShaderUniform bind group"),
+ })
+ }
+
+ /// Both sampler flavours of the atlas: the shader picks linear when a
+ /// quad is minified and nearest otherwise.
+ pub fn atlas_bind_groups(&self, device: &wgpu::Device, view: &wgpu::TextureView) -> AtlasBindGroups {
+ let make = |sampler: &wgpu::Sampler, label: &str| {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ layout: &self.texture_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::TextureView(view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::Sampler(sampler),
+ },
+ ],
+ label: Some(label),
+ })
+ };
+ AtlasBindGroups {
+ linear: make(&self.linear_sampler, "atlas linear"),
+ nearest: make(&self.nearest_sampler, "atlas nearest"),
+ }
+ }
+}
+
+/// The index pattern for quads laid out as `Vertex` corners TL, TR, BL, BR:
+/// two triangles per quad, six indices.
+pub fn quad_indices(num_quads: usize) -> Vec<u32> {
+ use crate::vertex::{VERTICES_PER_CELL, V_BOT_LEFT, V_BOT_RIGHT, V_TOP_LEFT, V_TOP_RIGHT};
+ let mut indices = Vec::with_capacity(num_quads * 6);
+ for q in 0..num_quads {
+ let idx = (q * VERTICES_PER_CELL) as u32;
+ indices.push(idx + V_TOP_LEFT as u32);
+ indices.push(idx + V_TOP_RIGHT as u32);
+ indices.push(idx + V_BOT_LEFT as u32);
+ indices.push(idx + V_TOP_RIGHT as u32);
+ indices.push(idx + V_BOT_LEFT as u32);
+ indices.push(idx + V_BOT_RIGHT as u32);
+ }
+ indices
+}
+
+/// An RGBA sRGB texture on the device that the `Atlas` writes sprites into.
+pub struct GpuTexture {
+ texture: wgpu::Texture,
+ queue: Arc<wgpu::Queue>,
+ width: u32,
+ height: u32,
+ /// Distinct for every texture ever made, so a cache keyed by it cannot
+ /// mistake a new texture at an old address for the old one.
+ id: usize,
+}
+
+static NEXT_TEXTURE_ID: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1);
+
+impl GpuTexture {
+ pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;
+
+ pub fn new(
+ device: &wgpu::Device,
+ queue: Arc<wgpu::Queue>,
+ width: u32,
+ height: u32,
+ ) -> anyhow::Result<Self> {
+ let limit = device.limits().max_texture_dimension_2d;
+ if width > limit || height > limit {
+ // wgpu panics rather than failing on an oversized texture.
+ anyhow::bail!(
+ "texture dimensions {width}x{height} exceed the max dimension {limit} \
+ supported by this GPU"
+ );
+ }
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: Self::FORMAT,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ label: Some("Texture Atlas"),
+ view_formats: &[],
+ });
+ Ok(Self {
+ texture,
+ queue,
+ width,
+ height,
+ id: NEXT_TEXTURE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
+ })
+ }
+
+ pub fn id(&self) -> usize {
+ self.id
+ }
+
+ pub fn view(&self) -> wgpu::TextureView {
+ self.texture.create_view(&Default::default())
+ }
+
+ pub fn texture(&self) -> &wgpu::Texture {
+ &self.texture
+ }
+}
+
+impl Texture2d for GpuTexture {
+ fn write(&self, rect: Rect, im: &dyn BitmapImage) {
+ let (im_width, im_height) = im.image_dimensions();
+ self.queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: rect.min_x() as u32,
+ y: rect.min_y() as u32,
+ z: 0,
+ },
+ aspect: wgpu::TextureAspect::All,
+ },
+ im.pixel_data_slice(),
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(im_width as u32 * 4),
+ rows_per_image: Some(im_height as u32),
+ },
+ wgpu::Extent3d {
+ width: im_width as u32,
+ height: im_height as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+
+ fn read(&self, _rect: Rect, _im: &mut dyn BitmapImage) {
+ unimplemented!("reading back the atlas is not supported");
+ }
+
+ fn width(&self) -> usize {
+ self.width as usize
+ }
+
+ fn height(&self) -> usize {
+ self.height as usize
+ }
+}
diff --git a/thinkterm-render/src/quad.rs b/thinkterm-render/src/quad.rs
new file mode 100644
index 00000000..48503719
--- /dev/null
+++ b/thinkterm-render/src/quad.rs
@@ -0,0 +1,1348 @@
+//! Quads: four vertices per cell, the allocators that hand them out and the
+//! heap-recorded surfaces that can be replayed, clipped and shifted later.
+
+use crate::geom::Dimensions;
+use crate::vertex::*;
+use crate::bitmaps::TextureRect;
+use wezterm_color_types::{HsbTransform, LinearRgba};
+
+pub trait QuadTrait {
+ /// Assign the texture coordinates
+ fn set_texture(&mut self, coords: TextureRect) {
+ let x1 = coords.min_x();
+ let x2 = coords.max_x();
+ let y1 = coords.min_y();
+ let y2 = coords.max_y();
+ self.set_texture_discrete(x1, x2, y1, y2);
+ }
+ fn set_texture_discrete(&mut self, x1: f32, x2: f32, y1: f32, y2: f32);
+ fn set_has_color_impl(&mut self, has_color: f32);
+
+ /// Set the color glyph "flag"
+ fn set_has_color(&mut self, has_color: bool) {
+ self.set_has_color_impl(if has_color { IS_COLOR_EMOJI } else { IS_GLYPH });
+ }
+
+ /// Mark as a grayscale polyquad; color and alpha will be
+ /// multipled with those in the texture
+ fn set_grayscale(&mut self) {
+ self.set_has_color_impl(IS_GRAY_SCALE);
+ }
+
+ /// Mark this quad as a background image.
+ /// Mutually exclusive with set_has_color.
+ fn set_is_background_image(&mut self) {
+ self.set_has_color_impl(IS_BG_IMAGE);
+ }
+
+ fn set_is_background(&mut self) {
+ self.set_has_color_impl(IS_SOLID_COLOR);
+ }
+
+ fn set_fg_color(&mut self, color: LinearRgba);
+
+ /// Set an independently colored corner on each vertex. The GPU
+ /// interpolates these colors across the quad, allowing a subtle
+ /// two-dimensional native UI gradient without uploading a texture.
+ fn set_corner_gradient(
+ &mut self,
+ top_left: LinearRgba,
+ top_right: LinearRgba,
+ bottom_left: LinearRgba,
+ bottom_right: LinearRgba,
+ );
+
+ /// Set a smoothly interpolated foreground color from the top edge to the
+ /// bottom edge. Solid-background quads use this for native UI gradients.
+ fn set_vertical_gradient(&mut self, top: LinearRgba, bottom: LinearRgba);
+
+ /// Must be called after set_fg_color
+ fn set_alt_color_and_mix_value(&mut self, color: LinearRgba, mix_value: f32);
+
+ fn set_hsv(&mut self, hsv: Option<HsbTransform>);
+ fn set_position(&mut self, left: f32, top: f32, right: f32, bottom: f32);
+}
+
+pub enum QuadImpl<'a> {
+ Vert(Quad<'a>),
+ Boxed(&'a mut BoxedQuad),
+ TransformedBoxed(&'a mut BoxedQuad, QuadPositionTransform),
+ Tee(Quad<'a>, &'a mut BoxedQuad),
+}
+
+/// Maps quad positions from a naturally rendered source rect into an exact
+/// destination rect while the quad is being authored. Live thumbnails use
+/// this instead of walking every glyph a second time after paint.
+#[derive(Clone, Copy, Debug)]
+pub struct QuadPositionTransform {
+ scale_x: f32,
+ scale_y: f32,
+ offset_x: f32,
+ offset_y: f32,
+}
+
+impl QuadPositionTransform {
+ pub fn new(source: QuadClipRect, target: QuadClipRect) -> Option<Self> {
+ let source_width = source.width();
+ let source_height = source.bottom() - source.top();
+ let target_width = target.width();
+ let target_height = target.bottom() - target.top();
+ if !(source_width > 0.0 && source_height > 0.0 && target_width > 0.0 && target_height > 0.0)
+ {
+ return None;
+ }
+ let scale_x = target_width / source_width;
+ let scale_y = target_height / source_height;
+ let offset_x = target.left() - source.left() * scale_x;
+ let offset_y = target.top() - source.top() * scale_y;
+ (scale_x.is_finite() && scale_y.is_finite() && offset_x.is_finite() && offset_y.is_finite())
+ .then_some(Self {
+ scale_x,
+ scale_y,
+ offset_x,
+ offset_y,
+ })
+ }
+
+ fn map_position(self, left: f32, top: f32, right: f32, bottom: f32) -> (f32, f32, f32, f32) {
+ (
+ left * self.scale_x + self.offset_x,
+ top * self.scale_y + self.offset_y,
+ right * self.scale_x + self.offset_x,
+ bottom * self.scale_y + self.offset_y,
+ )
+ }
+}
+
+impl<'a> QuadTrait for QuadImpl<'a> {
+ fn set_texture_discrete(&mut self, x1: f32, x2: f32, y1: f32, y2: f32) {
+ match self {
+ Self::Vert(q) => q.set_texture_discrete(x1, x2, y1, y2),
+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_texture_discrete(x1, x2, y1, y2),
+ Self::Tee(gpu, heap) => {
+ gpu.set_texture_discrete(x1, x2, y1, y2);
+ heap.set_texture_discrete(x1, x2, y1, y2);
+ }
+ }
+ }
+
+ fn set_has_color_impl(&mut self, has_color: f32) {
+ match self {
+ Self::Vert(q) => q.set_has_color_impl(has_color),
+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_has_color_impl(has_color),
+ Self::Tee(gpu, heap) => {
+ gpu.set_has_color_impl(has_color);
+ heap.set_has_color_impl(has_color);
+ }
+ }
+ }
+
+ fn set_fg_color(&mut self, color: LinearRgba) {
+ match self {
+ Self::Vert(q) => q.set_fg_color(color),
+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_fg_color(color),
+ Self::Tee(gpu, heap) => {
+ gpu.set_fg_color(color);
+ heap.set_fg_color(color);
+ }
+ }
+ }
+
+ fn set_corner_gradient(
+ &mut self,
+ top_left: LinearRgba,
+ top_right: LinearRgba,
+ bottom_left: LinearRgba,
+ bottom_right: LinearRgba,
+ ) {
+ match self {
+ Self::Vert(q) => q.set_corner_gradient(top_left, top_right, bottom_left, bottom_right),
+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => {
+ q.set_corner_gradient(top_left, top_right, bottom_left, bottom_right)
+ }
+ Self::Tee(gpu, heap) => {
+ gpu.set_corner_gradient(top_left, top_right, bottom_left, bottom_right);
+ heap.set_corner_gradient(top_left, top_right, bottom_left, bottom_right);
+ }
+ }
+ }
+
+ fn set_vertical_gradient(&mut self, top: LinearRgba, bottom: LinearRgba) {
+ match self {
+ Self::Vert(q) => q.set_vertical_gradient(top, bottom),
+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_vertical_gradient(top, bottom),
+ Self::Tee(gpu, heap) => {
+ gpu.set_vertical_gradient(top, bottom);
+ heap.set_vertical_gradient(top, bottom);
+ }
+ }
+ }
+
+ fn set_alt_color_and_mix_value(&mut self, color: LinearRgba, mix_value: f32) {
+ match self {
+ Self::Vert(q) => q.set_alt_color_and_mix_value(color, mix_value),
+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => {
+ q.set_alt_color_and_mix_value(color, mix_value)
+ }
+ Self::Tee(gpu, heap) => {
+ gpu.set_alt_color_and_mix_value(color, mix_value);
+ heap.set_alt_color_and_mix_value(color, mix_value);
+ }
+ }
+ }
+
+ fn set_hsv(&mut self, hsv: Option<HsbTransform>) {
+ match self {
+ Self::Vert(q) => q.set_hsv(hsv),
+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_hsv(hsv),
+ Self::Tee(gpu, heap) => {
+ gpu.set_hsv(hsv);
+ heap.set_hsv(hsv);
+ }
+ }
+ }
+
+ fn set_position(&mut self, left: f32, top: f32, right: f32, bottom: f32) {
+ match self {
+ Self::Vert(q) => q.set_position(left, top, right, bottom),
+ Self::Boxed(q) => q.set_position(left, top, right, bottom),
+ Self::TransformedBoxed(q, transform) => {
+ let (left, top, right, bottom) = transform.map_position(left, top, right, bottom);
+ q.set_position(left, top, right, bottom);
+ }
+ Self::Tee(gpu, heap) => {
+ gpu.set_position(left, top, right, bottom);
+ heap.set_position(left, top, right, bottom);
+ }
+ }
+ }
+}
+
+/// A helper for updating the 4 vertices that compose a glyph cell
+pub struct Quad<'a> {
+ pub vert: &'a mut [Vertex],
+}
+
+impl<'a> QuadTrait for Quad<'a> {
+ fn set_texture_discrete(&mut self, x1: f32, x2: f32, y1: f32, y2: f32) {
+ self.vert[V_TOP_LEFT].tex = [x1, y1];
+ self.vert[V_TOP_RIGHT].tex = [x2, y1];
+ self.vert[V_BOT_LEFT].tex = [x1, y2];
+ self.vert[V_BOT_RIGHT].tex = [x2, y2];
+ }
+
+ fn set_has_color_impl(&mut self, has_color: f32) {
+ for v in self.vert.iter_mut() {
+ v.has_color = has_color;
+ }
+ }
+
+ fn set_fg_color(&mut self, color: LinearRgba) {
+ for v in self.vert.iter_mut() {
+ v.fg_color = color.into();
+ }
+ self.set_alt_color_and_mix_value(color, 0.);
+ }
+
+ fn set_corner_gradient(
+ &mut self,
+ top_left: LinearRgba,
+ top_right: LinearRgba,
+ bottom_left: LinearRgba,
+ bottom_right: LinearRgba,
+ ) {
+ self.vert[V_TOP_LEFT].fg_color = top_left.into();
+ self.vert[V_TOP_RIGHT].fg_color = top_right.into();
+ self.vert[V_BOT_LEFT].fg_color = bottom_left.into();
+ self.vert[V_BOT_RIGHT].fg_color = bottom_right.into();
+ }
+
+ fn set_vertical_gradient(&mut self, top: LinearRgba, bottom: LinearRgba) {
+ self.set_corner_gradient(top, top, bottom, bottom);
+ }
+
+ /// Must be called after set_fg_color
+ fn set_alt_color_and_mix_value(&mut self, color: LinearRgba, mix_value: f32) {
+ for v in self.vert.iter_mut() {
+ v.alt_color = color.into();
+ v.mix_value = mix_value;
+ }
+ }
+
+ fn set_hsv(&mut self, hsv: Option<HsbTransform>) {
+ let (h, s, v) = hsv
+ .map(|t| (t.hue, t.saturation, t.brightness))
+ .unwrap_or((1., 1., 1.));
+ for vert in self.vert.iter_mut() {
+ vert.hsv = [h, s, v];
+ }
+ }
+
+ fn set_position(&mut self, left: f32, top: f32, right: f32, bottom: f32) {
+ self.vert[V_TOP_LEFT].position = [left, top];
+ self.vert[V_TOP_RIGHT].position = [right, top];
+ self.vert[V_BOT_LEFT].position = [left, bottom];
+ self.vert[V_BOT_RIGHT].position = [right, bottom];
+ }
+}
+
+pub trait QuadAllocator {
+ fn allocate(&mut self) -> anyhow::Result<QuadImpl<'_>>;
+ fn extend_with(&mut self, vertices: &[Vertex]);
+}
+
+pub trait TripleLayerQuadAllocatorTrait {
+ fn allocate(&mut self, layer_num: usize) -> anyhow::Result<QuadImpl<'_>>;
+ fn extend_with(&mut self, layer_num: usize, vertices: &[Vertex]);
+}
+
+impl<T: TripleLayerQuadAllocatorTrait + ?Sized> TripleLayerQuadAllocatorTrait for &mut T {
+ fn allocate(&mut self, layer_num: usize) -> anyhow::Result<QuadImpl<'_>> {
+ (**self).allocate(layer_num)
+ }
+
+ fn extend_with(&mut self, layer_num: usize, vertices: &[Vertex]) {
+ (**self).extend_with(layer_num, vertices)
+ }
+}
+
+/// We prefer to allocate a quad at a time for HeapQuadAllocator
+/// because we tend to end up with fairly large arrays of Vertex
+/// and the total amount of contiguous memory is in the MB range,
+/// which is a bit gnarly to reallocate, and can waste several MB
+/// in unused capacity
+#[derive(Clone, Default)]
+pub struct BoxedQuad {
+ position: (f32, f32, f32, f32),
+ fg_color: [f32; 4],
+ fg_color_corners: Option<Box<[[f32; 4]; 4]>>,
+ alt_color: [f32; 4],
+ tex: (f32, f32, f32, f32),
+ hsv: [f32; 3],
+ has_color: f32,
+ mix_value: f32,
+}
+
+impl QuadTrait for BoxedQuad {
+ fn set_texture_discrete(&mut self, x1: f32, x2: f32, y1: f32, y2: f32) {
+ self.tex = (x1, x2, y1, y2);
+ }
+
+ fn set_has_color_impl(&mut self, has_color: f32) {
+ self.has_color = has_color;
+ }
+
+ fn set_fg_color(&mut self, color: LinearRgba) {
+ self.fg_color = color.into();
+ self.fg_color_corners = None;
+ }
+ fn set_corner_gradient(
+ &mut self,
+ top_left: LinearRgba,
+ top_right: LinearRgba,
+ bottom_left: LinearRgba,
+ bottom_right: LinearRgba,
+ ) {
+ let colors = [
+ top_left.into(),
+ top_right.into(),
+ bottom_left.into(),
+ bottom_right.into(),
+ ];
+ self.fg_color = colors[V_TOP_LEFT];
+ self.fg_color_corners = colors
+ .iter()
+ .skip(1)
+ .any(|color| *color != colors[V_TOP_LEFT])
+ .then(|| Box::new(colors));
+ }
+ fn set_vertical_gradient(&mut self, top: LinearRgba, bottom: LinearRgba) {
+ self.set_corner_gradient(top, top, bottom, bottom);
+ }
+ fn set_alt_color_and_mix_value(&mut self, color: LinearRgba, mix_value: f32) {
+ self.alt_color = color.into();
+ self.mix_value = mix_value;
+ }
+ fn set_hsv(&mut self, hsv: Option<HsbTransform>) {
+ let (h, s, v) = hsv
+ .map(|t| (t.hue, t.saturation, t.brightness))
+ .unwrap_or((1., 1., 1.));
+ self.hsv = [h, s, v];
+ }
+
+ fn set_position(&mut self, left: f32, top: f32, right: f32, bottom: f32) {
+ self.position = (left, top, right, bottom);
+ }
+}
+
+impl BoxedQuad {
+ fn from_vertices(verts: &[Vertex; VERTICES_PER_CELL]) -> Self {
+ let [x1, y1] = verts[V_TOP_LEFT].tex;
+ let [x2, y2] = verts[V_BOT_RIGHT].tex;
+
+ let [left, top] = verts[V_TOP_LEFT].position;
+ let [right, bottom] = verts[V_BOT_RIGHT].position;
+ let fg_color_corners = [
+ verts[V_TOP_LEFT].fg_color,
+ verts[V_TOP_RIGHT].fg_color,
+ verts[V_BOT_LEFT].fg_color,
+ verts[V_BOT_RIGHT].fg_color,
+ ];
+ let fg_color = fg_color_corners[V_TOP_LEFT];
+ Self {
+ tex: (x1, x2, y1, y2),
+ position: (left, top, right, bottom),
+ has_color: verts[V_TOP_LEFT].has_color,
+ alt_color: verts[V_TOP_LEFT].alt_color,
+ fg_color,
+ fg_color_corners: fg_color_corners
+ .iter()
+ .skip(1)
+ .any(|color| *color != fg_color)
+ .then(|| Box::new(fg_color_corners)),
+ hsv: verts[V_TOP_LEFT].hsv,
+ mix_value: verts[V_TOP_LEFT].mix_value,
+ }
+ }
+
+ fn to_vertices(&self) -> [Vertex; VERTICES_PER_CELL] {
+ let mut vert: [Vertex; VERTICES_PER_CELL] = Default::default();
+ let mut quad = Quad { vert: &mut vert };
+
+ let (x1, x2, y1, y2) = self.tex;
+ quad.set_texture_discrete(x1, x2, y1, y2);
+
+ let (left, top, right, bottom) = self.position;
+ quad.set_position(left, top, right, bottom);
+
+ quad.set_has_color_impl(self.has_color);
+ let [hue, saturation, brightness] = self.hsv;
+ quad.set_hsv(Some(HsbTransform {
+ hue,
+ saturation,
+ brightness,
+ }));
+ if let Some(colors) = self.fg_color_corners.as_deref() {
+ quad.set_corner_gradient(
+ colors[V_TOP_LEFT].into(),
+ colors[V_TOP_RIGHT].into(),
+ colors[V_BOT_LEFT].into(),
+ colors[V_BOT_RIGHT].into(),
+ );
+ } else {
+ quad.set_fg_color(self.fg_color.into());
+ }
+ quad.set_alt_color_and_mix_value(self.alt_color.into(), self.mix_value);
+
+ vert
+ }
+
+ /// Scale every colour's alpha, for compositing a recorded surface at
+ /// partial opacity.
+ ///
+ /// Every shader branch multiplies by this, so a whole recorded surface --
+ /// fills, gradients, UI text, terminal glyphs, colour emoji -- fades as
+ /// one picture. `IS_GLYPH` and `IS_COLOR_EMOJI` used to take their alpha
+ /// from the glyph texture alone and drop the vertex colour's, which left
+ /// terminal text standing solid over everything else as it faded.
+ fn with_opacity(mut self, opacity: f32) -> Self {
+ self.fg_color[3] *= opacity;
+ self.alt_color[3] *= opacity;
+ if let Some(corners) = self.fg_color_corners.as_deref_mut() {
+ for corner in corners.iter_mut() {
+ corner[3] *= opacity;
+ }
+ }
+ self
+ }
+
+ /// Translate this quad and crop it to `clip`, preserving texture
+ /// coordinates and per-corner colors for the visible portion.
+ fn translated_clipped(&self, offset_x: f32, offset_y: f32, clip: QuadClipRect) -> Option<Self> {
+ let (left, top, right, bottom) = self.position;
+ let translated_left = left + offset_x;
+ let translated_top = top + offset_y;
+ let translated_right = right + offset_x;
+ let translated_bottom = bottom + offset_y;
+ self.positioned_clipped(
+ translated_left,
+ translated_top,
+ translated_right,
+ translated_bottom,
+ clip,
+ )
+ }
+
+ /// Scale and offset this quad into a destination rect, then crop it.
+ ///
+ /// Unlike the desktop allocator's heap position transform, which
+ /// maps positions as a surface is being authored, this remaps a surface
+ /// that was already recorded. That is what lets one captured frame be
+ /// replayed at a different size on every frame of a transition instead of
+ /// the whole window being painted again each time -- at the cost of the
+ /// glyph textures being sampled below their rasterised size, so the text
+ /// softens as it shrinks.
+ fn transformed_clipped(
+ &self,
+ transform: QuadPositionTransform,
+ clip: QuadClipRect,
+ ) -> Option<Self> {
+ let (left, top, right, bottom) = self.position;
+ let (left, top, right, bottom) = transform.map_position(left, top, right, bottom);
+ self.positioned_clipped(left, top, right, bottom, clip)
+ }
+
+ /// Crop this quad after its four position edges have already been mapped.
+ /// Keeping the mapping outside avoids cloning an intermediate quad for the
+ /// scaled-preview path, which touches thousands of tiny glyph quads.
+ fn positioned_clipped(
+ &self,
+ left: f32,
+ top: f32,
+ right: f32,
+ bottom: f32,
+ clip: QuadClipRect,
+ ) -> Option<Self> {
+ if !(right > left
+ && bottom > top
+ && clip.right() > clip.left()
+ && clip.bottom() > clip.top())
+ {
+ return None;
+ }
+
+ let visible_left = left.max(clip.left());
+ let visible_top = top.max(clip.top());
+ let visible_right = right.min(clip.right());
+ let visible_bottom = bottom.min(clip.bottom());
+ if visible_right <= visible_left || visible_bottom <= visible_top {
+ return None;
+ }
+
+ let x0 = (visible_left - left) / (right - left);
+ let x1 = (visible_right - left) / (right - left);
+ let y0 = (visible_top - top) / (bottom - top);
+ let y1 = (visible_bottom - top) / (bottom - top);
+ let (u0, u1, v0, v1) = self.tex;
+ let source_colors = self
+ .fg_color_corners
+ .as_deref()
+ .copied()
+ .unwrap_or([self.fg_color; VERTICES_PER_CELL]);
+ let clipped_colors = [
+ bilerp_color(source_colors, x0, y0),
+ bilerp_color(source_colors, x1, y0),
+ bilerp_color(source_colors, x0, y1),
+ bilerp_color(source_colors, x1, y1),
+ ];
+ let fg_color = clipped_colors[V_TOP_LEFT];
+
+ let mut clipped = Self {
+ position: (visible_left, visible_top, visible_right, visible_bottom),
+ fg_color,
+ fg_color_corners: clipped_colors
+ .iter()
+ .skip(1)
+ .any(|color| *color != fg_color)
+ .then(|| Box::new(clipped_colors)),
+ alt_color: self.alt_color,
+ tex: (
+ lerp(u0, u1, x0),
+ lerp(u0, u1, x1),
+ lerp(v0, v1, y0),
+ lerp(v0, v1, y1),
+ ),
+ hsv: self.hsv,
+ has_color: self.has_color,
+ mix_value: self.mix_value,
+ };
+ // Solid-colour quads conventionally use zero-width texture intervals.
+ // Preserve those intervals exactly rather than introducing tiny
+ // floating-point differences while cropping.
+ if u0 == u1 {
+ clipped.tex.0 = u0;
+ clipped.tex.1 = u1;
+ }
+ if v0 == v1 {
+ clipped.tex.2 = v0;
+ clipped.tex.3 = v1;
+ }
+ Some(clipped)
+ }
+}
+
+fn lerp(start: f32, end: f32, amount: f32) -> f32 {
+ start + (end - start) * amount
+}
+
+fn lerp_color(start: [f32; 4], end: [f32; 4], amount: f32) -> [f32; 4] {
+ std::array::from_fn(|index| lerp(start[index], end[index], amount))
+}
+
+fn bilerp_color(corners: [[f32; 4]; 4], x: f32, y: f32) -> [f32; 4] {
+ let top = lerp_color(corners[V_TOP_LEFT], corners[V_TOP_RIGHT], x);
+ let bottom = lerp_color(corners[V_BOT_LEFT], corners[V_BOT_RIGHT], x);
+ lerp_color(top, bottom, y)
+}
+
+#[derive(Default, Clone)]
+pub struct HeapQuadAllocator {
+ // Quads are stored inline: a cached surface with hundreds of thousands of
+ // quads would otherwise be that many separate 96-byte allocations, which
+ // both fragments the heap and makes every replay a pointer chase. Callers
+ // only ever hold the `QuadImpl` borrow from `allocate` until the next
+ // allocation, so element addresses do not need to survive vector growth.
+ layer0: Vec<BoxedQuad>,
+ layer1: Vec<BoxedQuad>,
+ layer2: Vec<BoxedQuad>,
+ position_transform: Option<QuadPositionTransform>,
+}
+
+impl std::fmt::Debug for HeapQuadAllocator {
+ fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ fmt.debug_struct("HeapQuadAllocator").finish()
+ }
+}
+
+/// A clip rectangle in the window-centre-relative space that quad positions
+/// live in.
+///
+/// Every painter goes through `filled_rectangle` and friends, which subtract
+/// half the window size from each edge, so a quad's `position` is *not* in the
+/// same coordinates as the layout rects (`workspace_sidebar_rect`, the list
+/// viewport, …) that describe where it was asked to go. Clipping against an
+/// un-rebased rect does not fail loudly: every quad simply falls outside and
+/// is dropped. That is how the space-swipe transition once drew an entirely
+/// empty sidebar while every offset in the logs looked correct.
+///
+/// The fields are private and [`Self::from_top_left_pixels`] is the only way
+/// in, so layout coordinates cannot reach the clipper by accident. Bands
+/// carved out of an existing rect go through [`Self::with_vertical`] /
+/// [`Self::with_horizontal`], which inherit the already-converted edges.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct QuadClipRect {
+ left: f32,
+ top: f32,
+ right: f32,
+ bottom: f32,
+}
+
+impl QuadClipRect {
+ /// Rebase a top-left pixel rect -- sidebar geometry, a list viewport, a
+ /// UI item's bounds -- into the quads' own space.
+ ///
+ /// Takes the window's own [`Dimensions`] rather than a pair of numbers on
+ /// purpose: the conversion is only correct against the surface the quads
+ /// were laid out for, and a caller with two loose `usize`s can silently
+ /// pass the wrong ones (or zeroes) and get a rect that quietly matches
+ /// nothing.
+ pub fn from_top_left_pixels(
+ left: f32,
+ top: f32,
+ right: f32,
+ bottom: f32,
+ dimensions: &Dimensions,
+ ) -> Self {
+ let dx = dimensions.pixel_width as f32 / 2.0;
+ let dy = dimensions.pixel_height as f32 / 2.0;
+ Self {
+ left: left - dx,
+ top: top - dy,
+ right: right - dx,
+ bottom: bottom - dy,
+ }
+ }
+
+ pub fn left(&self) -> f32 {
+ self.left
+ }
+
+ pub fn top(&self) -> f32 {
+ self.top
+ }
+
+ pub fn right(&self) -> f32 {
+ self.right
+ }
+
+ pub fn bottom(&self) -> f32 {
+ self.bottom
+ }
+
+ pub fn width(&self) -> f32 {
+ self.right - self.left
+ }
+
+ /// A horizontal band of this rect. Both edges are already centre-relative.
+ pub fn with_vertical(&self, top: f32, bottom: f32) -> Self {
+ Self {
+ top,
+ bottom,
+ ..*self
+ }
+ }
+
+ /// A vertical band of this rect. Both edges are already centre-relative.
+ pub fn with_horizontal(&self, left: f32, right: f32) -> Self {
+ Self {
+ left,
+ right,
+ ..*self
+ }
+ }
+}
+
+/// How many quads a [`HeapQuadAllocator`] held at some point during a paint.
+///
+/// Splitting a recorded frame by screen position cannot distinguish a scrolling
+/// row from the chrome drawn over it: the two overlap on purpose, so any
+/// horizontal line drawn through them cuts something in half. Recording where
+/// the painter *was* instead splits by what was being drawn, which is the
+/// question a compositor actually needs answered.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct HeapQuadMark {
+ layer0: usize,
+ layer1: usize,
+ layer2: usize,
+}
+
+impl HeapQuadAllocator {
+ /// Empty the allocator but keep its capacity for whatever is recorded
+ /// next. For a caller that records many surfaces in a row -- the overview
+ /// draws one per visible card, every frame -- this makes re-recording
+ /// allocation-free.
+ pub fn recycle(&mut self) {
+ self.layer0.clear();
+ self.layer1.clear();
+ self.layer2.clear();
+ self.position_transform = None;
+ }
+
+ /// Estimated resident heap bytes for the recorded quads. Counts vector
+ /// capacity, not length: a buffer that grew during recording keeps that
+ /// allocation until it is dropped, and capacity is what a byte-accounted
+ /// cache needs to know about.
+ pub fn resident_bytes(&self) -> usize {
+ (self.layer0.capacity() + self.layer1.capacity() + self.layer2.capacity())
+ .saturating_mul(std::mem::size_of::<BoxedQuad>())
+ }
+
+ /// Where the next quad will land, for later use with [`Self::apply_before`],
+ /// [`Self::apply_between`] and [`Self::apply_after`].
+ pub fn mark(&self) -> HeapQuadMark {
+ HeapQuadMark {
+ layer0: self.layer0.len(),
+ layer1: self.layer1.len(),
+ layer2: self.layer2.len(),
+ }
+ }
+
+ fn layers(&self) -> [(usize, &Vec<BoxedQuad>); 3] {
+ [(0, &self.layer0), (1, &self.layer1), (2, &self.layer2)]
+ }
+
+ fn layer_bounds(mark: &HeapQuadMark, layer_num: usize) -> usize {
+ match layer_num {
+ 0 => mark.layer0,
+ 1 => mark.layer1,
+ 2 => mark.layer2,
+ _ => unreachable!(),
+ }
+ }
+
+ pub fn apply_to(&self, other: &mut dyn TripleLayerQuadAllocatorTrait) -> anyhow::Result<()> {
+ #[cfg(not(target_family = "wasm"))]
+ let start = std::time::Instant::now();
+ for (layer_num, quads) in self.layers() {
+ for quad in quads {
+ other.extend_with(layer_num, &quad.to_vertices());
+ }
+ }
+ #[cfg(not(target_family = "wasm"))]
+ metrics::histogram!("quad_buffer_apply").record(start.elapsed());
+ Ok(())
+ }
+
+ /// Copy every recorded quad into `other`, cropped to `clip` and scaled to
+ /// `opacity`.
+ /// Flatten the recorded quads into a plain vertex stream: sub-layer 0,
+ /// then 1, then 2, in recorded order -- the order a replay would draw
+ /// them. Used to render a card's picture into its own texture, where
+ /// the render pass's projection does the placement and cropping, so the
+ /// vertices go out untransformed and unclipped.
+ pub fn extract_vertices(&self, out: &mut Vec<Vertex>) {
+ for (_layer_num, quads) in self.layers() {
+ for quad in quads {
+ out.extend_from_slice(&quad.to_vertices());
+ }
+ }
+ }
+
+ pub fn quad_count(&self) -> usize {
+ self.layers().iter().map(|(_, quads)| quads.len()).sum()
+ }
+
+ /// Position, texture coordinates and per-corner colors are transformed
+ /// together by the same primitive used by Space swipe composition.
+ ///
+ /// See [`BoxedQuad::with_opacity`] for which quads an opacity below 1
+ /// actually reaches.
+ pub fn apply_to_clipped(
+ &self,
+ other: &mut dyn TripleLayerQuadAllocatorTrait,
+ clip: QuadClipRect,
+ opacity: f32,
+ ) -> anyhow::Result<()> {
+ self.apply_to_clipped_at(other, 0.0, 0.0, clip, opacity)
+ }
+
+ /// `apply_to_clipped`, shifted by `offset` on the way out.
+ ///
+ /// Lets a caller record a surface in its own local space — its left edge
+ /// at 0 — and place it on replay. That matters when the surface's real
+ /// origin is off-screen: the painters take unsigned pixel coordinates, so
+ /// a negative origin cannot be expressed at record time, and clamping it
+ /// to 0 lays the contents out from the wrong place.
+ pub fn apply_to_clipped_at(
+ &self,
+ other: &mut dyn TripleLayerQuadAllocatorTrait,
+ offset_x: f32,
+ offset_y: f32,
+ clip: QuadClipRect,
+ opacity: f32,
+ ) -> anyhow::Result<()> {
+ #[cfg(not(target_family = "wasm"))]
+ let started = std::time::Instant::now();
+ for (layer_num, quads) in self.layers() {
+ for quad in quads {
+ let Some(clipped) = quad.translated_clipped(offset_x, offset_y, clip) else {
+ continue;
+ };
+ let clipped = if opacity < 1.0 {
+ clipped.with_opacity(opacity)
+ } else {
+ clipped
+ };
+ other.extend_with(layer_num, &clipped.to_vertices());
+ }
+ }
+ #[cfg(not(target_family = "wasm"))]
+ metrics::histogram!("quad_buffer_apply_clipped").record(started.elapsed());
+ Ok(())
+ }
+
+ /// Replay this whole surface scaled into `target`, cropped to `clip` and
+ /// composited at `opacity`.
+ ///
+ /// `source` is the rect the surface was recorded in; the two together give
+ /// the scale and offset. Used to fly a captured window into the card it
+ /// becomes.
+ pub fn apply_to_scaled(
+ &self,
+ other: &mut dyn TripleLayerQuadAllocatorTrait,
+ source: QuadClipRect,
+ target: QuadClipRect,
+ clip: QuadClipRect,
+ opacity: f32,
+ ) -> anyhow::Result<()> {
+ #[cfg(not(target_family = "wasm"))]
+ let started = std::time::Instant::now();
+ let Some(transform) = QuadPositionTransform::new(source, target) else {
+ return Ok(());
+ };
+ for (layer_num, quads) in self.layers() {
+ for quad in quads {
+ let Some(mapped) = quad.transformed_clipped(transform, clip) else {
+ continue;
+ };
+ let mapped = if opacity < 1.0 {
+ mapped.with_opacity(opacity)
+ } else {
+ mapped
+ };
+ other.extend_with(layer_num, &mapped.to_vertices());
+ }
+ }
+ #[cfg(not(target_family = "wasm"))]
+ metrics::histogram!("quad_buffer_apply_scaled").record(started.elapsed());
+ Ok(())
+ }
+
+ /// Replay everything recorded before `mark`, in place.
+ pub fn apply_before(
+ &self,
+ other: &mut dyn TripleLayerQuadAllocatorTrait,
+ mark: &HeapQuadMark,
+ ) -> anyhow::Result<()> {
+ for (layer_num, quads) in self.layers() {
+ let end = Self::layer_bounds(mark, layer_num).min(quads.len());
+ for quad in &quads[..end] {
+ other.extend_with(layer_num, &quad.to_vertices());
+ }
+ }
+ Ok(())
+ }
+
+ /// Replay everything recorded from `mark` onwards, in place.
+ pub fn apply_after(
+ &self,
+ other: &mut dyn TripleLayerQuadAllocatorTrait,
+ mark: &HeapQuadMark,
+ ) -> anyhow::Result<()> {
+ for (layer_num, quads) in self.layers() {
+ let begin = Self::layer_bounds(mark, layer_num).min(quads.len());
+ for quad in &quads[begin..] {
+ other.extend_with(layer_num, &quad.to_vertices());
+ }
+ }
+ Ok(())
+ }
+
+ /// Replay `start..end`, shifted horizontally and clipped.
+ ///
+ /// The clip is a containment bound -- it stops the shifted quads escaping
+ /// the surface they belong to -- and not a way to carve the frame into
+ /// moving and stationary parts. Use the marks for that.
+ pub fn apply_between(
+ &self,
+ other: &mut dyn TripleLayerQuadAllocatorTrait,
+ start: &HeapQuadMark,
+ end: &HeapQuadMark,
+ offset_x: f32,
+ clip: QuadClipRect,
+ ) -> anyhow::Result<()> {
+ #[cfg(not(target_family = "wasm"))]
+ let started = std::time::Instant::now();
+ for (layer_num, quads) in self.layers() {
+ let begin = Self::layer_bounds(start, layer_num).min(quads.len());
+ let finish = Self::layer_bounds(end, layer_num)
+ .min(quads.len())
+ .max(begin);
+ for quad in &quads[begin..finish] {
+ let Some(clipped) = quad.translated_clipped(offset_x, 0.0, clip) else {
+ continue;
+ };
+ other.extend_with(layer_num, &clipped.to_vertices());
+ }
+ }
+ #[cfg(not(target_family = "wasm"))]
+ metrics::histogram!("quad_buffer_translated_rect_clip_apply").record(started.elapsed());
+ Ok(())
+ }
+
+ /// Replay every recorded quad into ONE sub-layer of `other`, shifted
+ /// horizontally and cropped to `clip`.
+ ///
+ /// The sub-layer a quad was recorded in decides only *when* it is drawn:
+ /// each layer's three buffers are submitted 0, 1, 2 whatever order they
+ /// were filled in (see `render/draw.rs`). A surface that has to float
+ /// over the terminal therefore cannot keep its own sub-layers -- the
+ /// terminal's glyphs live in sub-buffer 2 and would draw straight through
+ /// a panel background recorded in sub-buffer 0. Collapsing the recording
+ /// into the last sub-buffer, in recorded order, keeps the surface's own
+ /// back-to-front order and puts all of it above anything drawn earlier:
+ /// the same arrangement the context menu gets by painting its panel into
+ /// sub-layer 2 by hand.
+ pub fn apply_to_single_layer(
+ &self,
+ other: &mut dyn TripleLayerQuadAllocatorTrait,
+ layer_num: usize,
+ offset_x: f32,
+ clip: QuadClipRect,
+ ) -> anyhow::Result<()> {
+ #[cfg(not(target_family = "wasm"))]
+ let started = std::time::Instant::now();
+ for (_recorded_layer, quads) in self.layers() {
+ for quad in quads {
+ let Some(clipped) = quad.translated_clipped(offset_x, 0.0, clip) else {
+ continue;
+ };
+ other.extend_with(layer_num, &clipped.to_vertices());
+ }
+ }
+ #[cfg(not(target_family = "wasm"))]
+ metrics::histogram!("quad_buffer_single_layer_apply").record(started.elapsed());
+ Ok(())
+ }
+
+ pub fn set_position_transform(&mut self, transform: Option<QuadPositionTransform>) {
+ self.position_transform = transform;
+ }
+}
+
+impl TripleLayerQuadAllocatorTrait for HeapQuadAllocator {
+ fn allocate(&mut self, layer_num: usize) -> anyhow::Result<QuadImpl<'_>> {
+ let position_transform = self.position_transform;
+ let quads = match layer_num {
+ 0 => &mut self.layer0,
+ 1 => &mut self.layer1,
+ 2 => &mut self.layer2,
+ _ => unreachable!(),
+ };
+
+ quads.push(BoxedQuad::default());
+
+ let quad = quads.last_mut().unwrap();
+ Ok(match position_transform {
+ Some(transform) => QuadImpl::TransformedBoxed(quad, transform),
+ None => QuadImpl::Boxed(quad),
+ })
+ }
+
+ fn extend_with(&mut self, layer_num: usize, vertices: &[Vertex]) {
+ if vertices.is_empty() {
+ return;
+ }
+
+ let position_transform = self.position_transform;
+ let dest_quads = match layer_num {
+ 0 => &mut self.layer0,
+ 1 => &mut self.layer1,
+ 2 => &mut self.layer2,
+ _ => unreachable!(),
+ };
+
+ // This is logically equivalent to
+ // https://doc.rust-lang.org/std/primitive.slice.html#method.as_chunks_unchecked
+ // which is currently nightly-only
+ assert_eq!(vertices.len() % VERTICES_PER_CELL, 0);
+ let src_quads: &[[Vertex; VERTICES_PER_CELL]] =
+ unsafe { std::slice::from_raw_parts(vertices.as_ptr().cast(), vertices.len() / 4) };
+
+ for quad in src_quads {
+ let mut quad = BoxedQuad::from_vertices(quad);
+ if let Some(transform) = position_transform {
+ let (left, top, right, bottom) = quad.position;
+ quad.position = transform.map_position(left, top, right, bottom);
+ }
+ dest_quads.push(quad);
+ }
+ }
+}
+
+#[cfg(test)]
+const TEST_ORIGIN: Dimensions = Dimensions {
+ pixel_width: 0,
+ pixel_height: 0,
+ dpi: 96,
+};
+
+#[cfg(test)]
+#[test]
+fn size() {
+ assert_eq!(std::mem::size_of::<Vertex>() * VERTICES_PER_CELL, 272);
+ assert_eq!(std::mem::size_of::<BoxedQuad>(), 96);
+}
+
+#[cfg(test)]
+#[test]
+fn boxed_quad_preserves_vertical_gradient_colors() {
+ let top = LinearRgba::with_components(0.1, 0.2, 0.3, 1.0);
+ let bottom = LinearRgba::with_components(0.4, 0.5, 0.6, 1.0);
+ let mut quad = BoxedQuad::default();
+ quad.set_vertical_gradient(top, bottom);
+ let vertices = quad.to_vertices();
+ let top: [f32; 4] = top.into();
+ let bottom: [f32; 4] = bottom.into();
+ assert_eq!(vertices[V_TOP_LEFT].fg_color, top);
+ assert_eq!(vertices[V_TOP_RIGHT].fg_color, top);
+ assert_eq!(vertices[V_BOT_LEFT].fg_color, bottom);
+ assert_eq!(vertices[V_BOT_RIGHT].fg_color, bottom);
+}
+
+#[cfg(test)]
+#[test]
+fn boxed_quad_preserves_corner_gradient_colors() {
+ let top_left = LinearRgba::with_components(0.1, 0.2, 0.3, 1.0);
+ let top_right = LinearRgba::with_components(0.2, 0.3, 0.4, 1.0);
+ let bottom_left = LinearRgba::with_components(0.3, 0.4, 0.5, 1.0);
+ let bottom_right = LinearRgba::with_components(0.4, 0.5, 0.6, 1.0);
+ let mut quad = BoxedQuad::default();
+ quad.set_corner_gradient(top_left, top_right, bottom_left, bottom_right);
+ let vertices = quad.to_vertices();
+ assert_eq!(vertices[V_TOP_LEFT].fg_color, <[f32; 4]>::from(top_left));
+ assert_eq!(vertices[V_TOP_RIGHT].fg_color, <[f32; 4]>::from(top_right));
+ assert_eq!(vertices[V_BOT_LEFT].fg_color, <[f32; 4]>::from(bottom_left));
+ assert_eq!(
+ vertices[V_BOT_RIGHT].fg_color,
+ <[f32; 4]>::from(bottom_right)
+ );
+}
+
+#[cfg(test)]
+#[test]
+fn boxed_quad_keeps_solid_colors_inline() {
+ let color = LinearRgba::with_components(0.1, 0.2, 0.3, 1.0);
+ let mut quad = BoxedQuad::default();
+ quad.set_fg_color(color);
+ assert!(quad.fg_color_corners.is_none());
+ quad.set_vertical_gradient(color, color);
+ assert!(quad.fg_color_corners.is_none());
+}
+
+#[cfg(test)]
+#[test]
+fn boxed_quad_translation_and_clip_crop_position_texture_and_gradient_together() {
+ let mut quad = BoxedQuad::default();
+ quad.set_position(0.0, 0.0, 100.0, 80.0);
+ quad.set_texture_discrete(0.1, 0.9, 0.2, 0.6);
+ quad.set_corner_gradient(
+ LinearRgba::with_components(0.0, 0.0, 0.0, 1.0),
+ LinearRgba::with_components(1.0, 0.0, 0.0, 1.0),
+ LinearRgba::with_components(0.0, 1.0, 0.0, 1.0),
+ LinearRgba::with_components(1.0, 1.0, 0.0, 1.0),
+ );
+
+ let clip = QuadClipRect::from_top_left_pixels(35.0, 25.0, 85.0, 65.0, &TEST_ORIGIN);
+ let clipped = quad.translated_clipped(10.0, 5.0, clip).unwrap();
+ assert_eq!(clipped.position, (35.0, 25.0, 85.0, 65.0));
+ for (actual, expected) in std::iter::zip(
+ [clipped.tex.0, clipped.tex.1, clipped.tex.2, clipped.tex.3]
+ .iter()
+ .copied(),
+ [0.3, 0.7, 0.3, 0.5].iter().copied(),
+ ) {
+ assert!((actual - expected).abs() < 0.000_001);
+ }
+ let colors = clipped.fg_color_corners.unwrap();
+ assert_eq!(colors[V_TOP_LEFT], [0.25, 0.25, 0.0, 1.0]);
+ assert_eq!(colors[V_TOP_RIGHT], [0.75, 0.25, 0.0, 1.0]);
+ assert_eq!(colors[V_BOT_LEFT], [0.25, 0.75, 0.0, 1.0]);
+ assert_eq!(colors[V_BOT_RIGHT], [0.75, 0.75, 0.0, 1.0]);
+}
+
+#[cfg(test)]
+#[test]
+fn heap_position_transform_maps_new_and_cached_quads_in_one_pass() {
+ let source = QuadClipRect::from_top_left_pixels(0.0, 0.0, 100.0, 100.0, &TEST_ORIGIN);
+ let target = QuadClipRect::from_top_left_pixels(10.0, 20.0, 210.0, 70.0, &TEST_ORIGIN);
+ let mut heap = HeapQuadAllocator::default();
+ {
+ let mut layers = &mut heap;
+ layers.set_position_transform(Some(QuadPositionTransform::new(source, target).unwrap()));
+
+ let mut authored = layers.allocate(0).unwrap();
+ authored.set_position(20.0, 10.0, 40.0, 50.0);
+ drop(authored);
+
+ let mut cached = BoxedQuad::default();
+ cached.set_position(20.0, 10.0, 40.0, 50.0);
+ layers.extend_with(1, &cached.to_vertices());
+ layers.set_position_transform(None);
+ }
+
+ assert_eq!(heap.layer0[0].position, (50.0, 25.0, 90.0, 45.0));
+ assert_eq!(heap.layer1[0].position, (50.0, 25.0, 90.0, 45.0));
+}
+
+#[cfg(test)]
+#[test]
+fn single_layer_replay_flattens_three_sub_layers_in_recorded_order() {
+ let mut heap = HeapQuadAllocator::default();
+ {
+ let mut layers = &mut heap;
+ for (layer_num, x) in [(0usize, 0.0f32), (1, 100.0), (2, 200.0)] {
+ let mut quad = layers.allocate(layer_num).unwrap();
+ quad.set_position(x, 0.0, x + 50.0, 50.0);
+ }
+ }
+
+ let mut target_heap = HeapQuadAllocator::default();
+ {
+ let mut target = &mut target_heap;
+ let clip = QuadClipRect::from_top_left_pixels(-500.0, -500.0, 500.0, 500.0, &TEST_ORIGIN);
+ heap.apply_to_single_layer(&mut target, 2, -10.0, clip)
+ .unwrap();
+ }
+
+ assert!(target_heap.layer0.is_empty());
+ assert!(target_heap.layer1.is_empty());
+ assert_eq!(target_heap.layer2.len(), 3);
+ // Recorded order 0 -> 1 -> 2 survives as draw order, shifted by -10.
+ assert_eq!(target_heap.layer2[0].position, (-10.0, 0.0, 40.0, 50.0));
+ assert_eq!(target_heap.layer2[1].position, (90.0, 0.0, 140.0, 50.0));
+ assert_eq!(target_heap.layer2[2].position, (190.0, 0.0, 240.0, 50.0));
+}
+
+#[cfg(test)]
+#[test]
+fn single_layer_replay_drops_quads_the_shift_pushes_out_of_the_clip() {
+ let mut heap = HeapQuadAllocator::default();
+ {
+ let mut layers = &mut heap;
+ let mut quad = layers.allocate(0).unwrap();
+ quad.set_position(0.0, 0.0, 50.0, 50.0);
+ }
+
+ let mut target_heap = HeapQuadAllocator::default();
+ {
+ let mut target = &mut target_heap;
+ let clip = QuadClipRect::from_top_left_pixels(0.0, 0.0, 500.0, 500.0, &TEST_ORIGIN);
+ // Shifted fully left of the clip: nothing lands.
+ heap.apply_to_single_layer(&mut target, 2, -100.0, clip)
+ .unwrap();
+ }
+ assert_eq!(target_heap.quad_count(), 0);
+}
+
+#[cfg(test)]
+#[test]
+fn boxed_quad_clip_rejects_outside_and_preserves_inside() {
+ let mut quad = BoxedQuad::default();
+ quad.set_position(10.0, 20.0, 30.0, 40.0);
+ quad.set_texture_discrete(0.2, 0.6, 0.3, 0.7);
+ let outside = QuadClipRect::from_top_left_pixels(30.0, 0.0, 50.0, 50.0, &TEST_ORIGIN);
+ assert!(quad.translated_clipped(0.0, 0.0, outside).is_none());
+ let full = QuadClipRect::from_top_left_pixels(0.0, 0.0, 50.0, 50.0, &TEST_ORIGIN);
+ let inside = quad.translated_clipped(0.0, 0.0, full).unwrap();
+ assert_eq!(inside.position, quad.position);
+ assert_eq!(inside.tex, quad.tex);
+}
+
+#[cfg(test)]
+mod translated_clip_tests {
+ use super::*;
+
+ /// Fixtures below that predate the rebase work state their coordinates
+ /// already centre-relative, so they convert against a zero-sized window.
+ const ORIGIN: Dimensions = Dimensions {
+ pixel_width: 0,
+ pixel_height: 0,
+ dpi: 96,
+ };
+
+ #[test]
+ fn translated_rect_clip_moves_positions_and_crops_texture_coordinates_together() {
+ let quad = BoxedQuad {
+ position: (10.0, 2.0, 30.0, 8.0),
+ tex: (0.2, 0.6, 0.1, 0.9),
+ ..Default::default()
+ };
+ let clip = QuadClipRect::from_top_left_pixels(25.0, 3.0, 35.0, 7.0, &ORIGIN);
+ let vertices = quad
+ .translated_clipped(10.0, 0.0, clip)
+ .expect("visible clip")
+ .to_vertices();
+
+ assert_eq!(vertices[V_TOP_LEFT].position, [25.0, 3.0]);
+ assert_eq!(vertices[V_BOT_RIGHT].position, [35.0, 7.0]);
+ assert!((vertices[V_TOP_LEFT].tex[0] - 0.3).abs() < 0.0001);
+ assert!((vertices[V_TOP_RIGHT].tex[0] - 0.5).abs() < 0.0001);
+ assert!((vertices[V_TOP_LEFT].tex[1] - (0.1 + 0.8 / 6.0)).abs() < 0.0001);
+ assert!((vertices[V_BOT_LEFT].tex[1] - (0.9 - 0.8 / 6.0)).abs() < 0.0001);
+ }
+
+ /// Regression: the swipe transition built its clip rect straight from the
+ /// sidebar's top-left layout geometry and handed it to the quad clipper,
+ /// whose quads are window-centre relative. Every one of the ~300 quads
+ /// failed the bounds test, so the sidebar drew nothing at all for the
+ /// whole 220ms -- with correct-looking offsets in every log. Nothing about
+ /// that is visible from inside the clipper, so pin the conversion here.
+ #[test]
+ fn a_clip_rect_is_useless_until_it_is_rebased_into_the_quads_own_space() {
+ let window = Dimensions {
+ pixel_width: 2560,
+ pixel_height: 1600,
+ dpi: 144,
+ };
+ // A window of zero size is the only way to express the old bug now.
+ let no_window = Dimensions {
+ pixel_width: 0,
+ pixel_height: 0,
+ dpi: 144,
+ };
+
+ // A sidebar row as a painter would emit it: laid out at top-left
+ // pixels x 0..465, y 300..320, then written centre-relative.
+ let row = QuadClipRect::from_top_left_pixels(0.0, 300.0, 465.0, 320.0, &window);
+ let quad = BoxedQuad {
+ position: (row.left(), row.top(), row.right(), row.bottom()),
+ ..Default::default()
+ };
+
+ // The list viewport in the layout's own coordinates. Used as-is, it
+ // silently discards a row that is plainly inside it.
+ // `QuadClipRect` has private fields, so this is only expressible in a
+ // test that reaches for the raw numbers on purpose.
+ let unrebased = QuadClipRect::from_top_left_pixels(0.0, 204.0, 465.0, 1316.0, &no_window);
+ assert!(
+ quad.translated_clipped(0.0, 0.0, unrebased).is_none(),
+ "an un-rebased clip rect drops everything -- this is the failure \
+ mode, not a healthy result"
+ );
+
+ // Rebased against the real window, the row survives.
+ let list = QuadClipRect::from_top_left_pixels(0.0, 204.0, 465.0, 1316.0, &window);
+ assert!(quad.translated_clipped(0.0, 0.0, list).is_some());
+ }
+
+ /// Regression: the transition used to decide what slides by cutting the
+ /// sidebar at a y coordinate. It cannot work. The bottom fade and the
+ /// settings row are painted *over* the list on purpose, so any horizontal
+ /// line drawn between "moving" and "stationary" runs straight through
+ /// whichever list row happens to reach that far -- the row's top half slid
+ /// away while its bottom half stayed put, already showing the destination.
+ /// Splitting by paint order instead asks the question that has an answer.
+ #[test]
+ fn chrome_painted_over_the_list_stays_put_when_the_list_slides_under_it() {
+ const WINDOW: Dimensions = Dimensions {
+ pixel_width: 1000,
+ pixel_height: 800,
+ dpi: 96,
+ };
+ fn quad_at(left: f32, top: f32, right: f32, bottom: f32) -> BoxedQuad {
+ let rect = QuadClipRect::from_top_left_pixels(left, top, right, bottom, &WINDOW);
+ BoxedQuad {
+ position: (rect.left(), rect.top(), rect.right(), rect.bottom()),
+ ..Default::default()
+ }
+ }
+ // Left edge of a top-left `x`, in the centre-relative space quads use.
+ let at = |x: f32| x - WINDOW.pixel_width as f32 / 2.0;
+
+ let mut frame = HeapQuadAllocator::default();
+ // Chrome above the list.
+ frame.layer2.push(quad_at(0.0, 0.0, 400.0, 100.0));
+
+ let list_start = frame.mark();
+ // A row reaching down into the band the footer chrome covers. Inset
+ // from the sidebar edges so a horizontal shift is visible rather than
+ // being cropped away by the containment clip.
+ frame.layer2.push(quad_at(100.0, 600.0, 300.0, 660.0));
+ let list_end = frame.mark();
+
+ // The fade and the settings row: painted last, and deliberately
+ // overlapping the row above.
+ frame.layer2.push(quad_at(0.0, 620.0, 400.0, 700.0));
+
+ let mut out = HeapQuadAllocator::default();
+ let mut sink = &mut out;
+ let clip = QuadClipRect::from_top_left_pixels(0.0, 0.0, 400.0, 800.0, &WINDOW);
+ frame.apply_before(&mut sink, &list_start).unwrap();
+ frame
+ .apply_between(&mut sink, &list_start, &list_end, -50.0, clip)
+ .unwrap();
+ frame.apply_after(&mut sink, &list_end).unwrap();
+ drop(sink);
+
+ let left_edges: Vec<f32> = out.layer2.iter().map(|q| q.position.0).collect();
+ assert_eq!(
+ left_edges,
+ vec![at(0.0), at(50.0), at(0.0)],
+ "only the marked list span may move, and the chrome recorded after \
+ it must still be replayed last so it keeps masking the row"
+ );
+ }
+
+ #[test]
+ fn translated_rect_clip_discards_quads_outside_the_sidebar_page() {
+ let quad = BoxedQuad {
+ position: (10.0, 2.0, 30.0, 8.0),
+ ..Default::default()
+ };
+ let full = QuadClipRect::from_top_left_pixels(0.0, 0.0, 40.0, 10.0, &ORIGIN);
+ let below = QuadClipRect::from_top_left_pixels(0.0, 20.0, 40.0, 30.0, &ORIGIN);
+ assert!(quad.translated_clipped(-100.0, 0.0, full).is_none());
+ assert!(quad.translated_clipped(0.0, 0.0, below).is_none());
+ }
+}
diff --git a/wezterm-gui/src/shader.wgsl b/thinkterm-render/src/shader.wgsl
similarity index 100%
rename from wezterm-gui/src/shader.wgsl
rename to thinkterm-render/src/shader.wgsl
diff --git a/thinkterm-render/src/vertex.rs b/thinkterm-render/src/vertex.rs
new file mode 100644
index 00000000..21e6cfb7
--- /dev/null
+++ b/thinkterm-render/src/vertex.rs
@@ -0,0 +1,62 @@
+//! The vertex layout shared by the WGSL shader and every backend.
+//! `VertexInput` in shader.wgsl matches `Vertex` field for field.
+
+/// Each cell is composed of two triangles built from 4 vertices.
+/// The buffer is organized row by row.
+pub const VERTICES_PER_CELL: usize = 4;
+pub const V_TOP_LEFT: usize = 0;
+pub const V_TOP_RIGHT: usize = 1;
+pub const V_BOT_LEFT: usize = 2;
+pub const V_BOT_RIGHT: usize = 3;
+
+/// a regular monochrome text glyph
+pub const IS_GLYPH: f32 = 0.0;
+/// a color emoji glyph
+pub const IS_COLOR_EMOJI: f32 = 1.0;
+/// a full color texture attached as the
+/// background image of the window
+pub const IS_BG_IMAGE: f32 = 2.0;
+/// like 2.0, except that instead of an
+/// image, we use the solid bg color
+pub const IS_SOLID_COLOR: f32 = 3.0;
+/// Grayscale poly quad for non-aa text render layers
+pub const IS_GRAY_SCALE: f32 = 4.0;
+
+#[repr(C)]
+#[derive(Copy, Clone, Default, Debug, bytemuck::Pod, bytemuck::Zeroable)]
+pub struct Vertex {
+ // Physical position of the corner of the character cell
+ pub position: [f32; 2],
+ // glyph texture
+ pub tex: [f32; 2],
+ pub fg_color: [f32; 4],
+ pub alt_color: [f32; 4],
+ pub hsv: [f32; 3],
+ pub has_color: f32,
+ pub mix_value: f32,
+}
+#[cfg(feature = "glium")]
+glium::implement_vertex!(
+ Vertex, position, tex, fg_color, alt_color, hsv, has_color, mix_value
+);
+
+#[cfg(feature = "wgpu")]
+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::<Self>() as wgpu::BufferAddress,
+ step_mode: wgpu::VertexStepMode::Vertex,
+ attributes: &Self::ATTRIBS,
+ }
+ }
+}
diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.toml
index dd6a4700..bd9fedb7 100644
--- a/wezterm-gui/Cargo.toml
+++ b/wezterm-gui/Cargo.toml
@@ -105,6 +105,7 @@ termwiz-funcs.workspace = true
termwiz.workspace = true
textwrap.workspace = true
thinkterm-proto.workspace = true
+thinkterm-render = { workspace = true, features = ["glium", "wgpu"] }
thinkterm-update.workspace = true
thiserror.workspace = true
tiny-skia.workspace = true
diff --git a/wezterm-gui/src/quad.rs b/wezterm-gui/src/quad.rs
index 5a202f09..b064912c 100644
--- a/wezterm-gui/src/quad.rs
+++ b/wezterm-gui/src/quad.rs
@@ -1,1064 +1,9 @@
-// Clippy hates the implement_vertex macro and won't let me scope
-// this warning to its use
-#![allow(clippy::unneeded_field_pattern)]
+//! The desktop's view of the shared quad machinery, plus the one allocator
+//! that knows about GPU render layers.
+pub use thinkterm_render::quad::*;
+pub use thinkterm_render::vertex::*;
use crate::renderstate::BorrowedLayers;
-use ::window::bitmaps::TextureRect;
-use ::window::color::LinearRgba;
-use ::window::Dimensions;
-use config::HsbTransform;
-
-/// Each cell is composed of two triangles built from 4 vertices.
-/// The buffer is organized row by row.
-pub const VERTICES_PER_CELL: usize = 4;
-pub const V_TOP_LEFT: usize = 0;
-pub const V_TOP_RIGHT: usize = 1;
-pub const V_BOT_LEFT: usize = 2;
-pub const V_BOT_RIGHT: usize = 3;
-
-/// a regular monochrome text glyph
-const IS_GLYPH: f32 = 0.0;
-/// a color emoji glyph
-const IS_COLOR_EMOJI: f32 = 1.0;
-/// a full color texture attached as the
-/// background image of the window
-const IS_BG_IMAGE: f32 = 2.0;
-/// like 2.0, except that instead of an
-/// image, we use the solid bg color
-const IS_SOLID_COLOR: f32 = 3.0;
-/// Grayscale poly quad for non-aa text render layers
-const IS_GRAY_SCALE: f32 = 4.0;
-
-#[repr(C)]
-#[derive(Copy, Clone, Default, Debug, bytemuck::Pod, bytemuck::Zeroable)]
-pub struct Vertex {
- // Physical position of the corner of the character cell
- pub position: [f32; 2],
- // glyph texture
- pub tex: [f32; 2],
- pub fg_color: [f32; 4],
- pub alt_color: [f32; 4],
- pub hsv: [f32; 3],
- pub has_color: f32,
- pub mix_value: f32,
-}
-::window::glium::implement_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::<Self>() 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) {
- let x1 = coords.min_x();
- let x2 = coords.max_x();
- let y1 = coords.min_y();
- let y2 = coords.max_y();
- self.set_texture_discrete(x1, x2, y1, y2);
- }
- fn set_texture_discrete(&mut self, x1: f32, x2: f32, y1: f32, y2: f32);
- fn set_has_color_impl(&mut self, has_color: f32);
-
- /// Set the color glyph "flag"
- fn set_has_color(&mut self, has_color: bool) {
- self.set_has_color_impl(if has_color { IS_COLOR_EMOJI } else { IS_GLYPH });
- }
-
- /// Mark as a grayscale polyquad; color and alpha will be
- /// multipled with those in the texture
- fn set_grayscale(&mut self) {
- self.set_has_color_impl(IS_GRAY_SCALE);
- }
-
- /// Mark this quad as a background image.
- /// Mutually exclusive with set_has_color.
- fn set_is_background_image(&mut self) {
- self.set_has_color_impl(IS_BG_IMAGE);
- }
-
- fn set_is_background(&mut self) {
- self.set_has_color_impl(IS_SOLID_COLOR);
- }
-
- fn set_fg_color(&mut self, color: LinearRgba);
-
- /// Set an independently colored corner on each vertex. The GPU
- /// interpolates these colors across the quad, allowing a subtle
- /// two-dimensional native UI gradient without uploading a texture.
- fn set_corner_gradient(
- &mut self,
- top_left: LinearRgba,
- top_right: LinearRgba,
- bottom_left: LinearRgba,
- bottom_right: LinearRgba,
- );
-
- /// Set a smoothly interpolated foreground color from the top edge to the
- /// bottom edge. Solid-background quads use this for native UI gradients.
- fn set_vertical_gradient(&mut self, top: LinearRgba, bottom: LinearRgba);
-
- /// Must be called after set_fg_color
- fn set_alt_color_and_mix_value(&mut self, color: LinearRgba, mix_value: f32);
-
- fn set_hsv(&mut self, hsv: Option<HsbTransform>);
- fn set_position(&mut self, left: f32, top: f32, right: f32, bottom: f32);
-}
-
-pub enum QuadImpl<'a> {
- Vert(Quad<'a>),
- Boxed(&'a mut BoxedQuad),
- TransformedBoxed(&'a mut BoxedQuad, QuadPositionTransform),
- Tee(Quad<'a>, &'a mut BoxedQuad),
-}
-
-/// Maps quad positions from a naturally rendered source rect into an exact
-/// destination rect while the quad is being authored. Live thumbnails use
-/// this instead of walking every glyph a second time after paint.
-#[derive(Clone, Copy, Debug)]
-pub struct QuadPositionTransform {
- scale_x: f32,
- scale_y: f32,
- offset_x: f32,
- offset_y: f32,
-}
-
-impl QuadPositionTransform {
- fn new(source: QuadClipRect, target: QuadClipRect) -> Option<Self> {
- let source_width = source.width();
- let source_height = source.bottom() - source.top();
- let target_width = target.width();
- let target_height = target.bottom() - target.top();
- if !(source_width > 0.0 && source_height > 0.0 && target_width > 0.0 && target_height > 0.0)
- {
- return None;
- }
- let scale_x = target_width / source_width;
- let scale_y = target_height / source_height;
- let offset_x = target.left() - source.left() * scale_x;
- let offset_y = target.top() - source.top() * scale_y;
- (scale_x.is_finite() && scale_y.is_finite() && offset_x.is_finite() && offset_y.is_finite())
- .then_some(Self {
- scale_x,
- scale_y,
- offset_x,
- offset_y,
- })
- }
-
- fn map_position(self, left: f32, top: f32, right: f32, bottom: f32) -> (f32, f32, f32, f32) {
- (
- left * self.scale_x + self.offset_x,
- top * self.scale_y + self.offset_y,
- right * self.scale_x + self.offset_x,
- bottom * self.scale_y + self.offset_y,
- )
- }
-}
-
-impl<'a> QuadTrait for QuadImpl<'a> {
- fn set_texture_discrete(&mut self, x1: f32, x2: f32, y1: f32, y2: f32) {
- match self {
- Self::Vert(q) => q.set_texture_discrete(x1, x2, y1, y2),
- Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_texture_discrete(x1, x2, y1, y2),
- Self::Tee(gpu, heap) => {
- gpu.set_texture_discrete(x1, x2, y1, y2);
- heap.set_texture_discrete(x1, x2, y1, y2);
- }
- }
- }
-
- fn set_has_color_impl(&mut self, has_color: f32) {
- match self {
- Self::Vert(q) => q.set_has_color_impl(has_color),
- Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_has_color_impl(has_color),
- Self::Tee(gpu, heap) => {
- gpu.set_has_color_impl(has_color);
- heap.set_has_color_impl(has_color);
- }
- }
- }
-
- fn set_fg_color(&mut self, color: LinearRgba) {
- match self {
- Self::Vert(q) => q.set_fg_color(color),
- Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_fg_color(color),
- Self::Tee(gpu, heap) => {
- gpu.set_fg_color(color);
- heap.set_fg_color(color);
- }
- }
- }
-
- fn set_corner_gradient(
- &mut self,
- top_left: LinearRgba,
- top_right: LinearRgba,
- bottom_left: LinearRgba,
- bottom_right: LinearRgba,
- ) {
- match self {
- Self::Vert(q) => q.set_corner_gradient(top_left, top_right, bottom_left, bottom_right),
- Self::Boxed(q) | Self::TransformedBoxed(q, _) => {
- q.set_corner_gradient(top_left, top_right, bottom_left, bottom_right)
- }
- Self::Tee(gpu, heap) => {
- gpu.set_corner_gradient(top_left, top_right, bottom_left, bottom_right);
- heap.set_corner_gradient(top_left, top_right, bottom_left, bottom_right);
- }
- }
- }
-
- fn set_vertical_gradient(&mut self, top: LinearRgba, bottom: LinearRgba) {
- match self {
- Self::Vert(q) => q.set_vertical_gradient(top, bottom),
- Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_vertical_gradient(top, bottom),
- Self::Tee(gpu, heap) => {
- gpu.set_vertical_gradient(top, bottom);
- heap.set_vertical_gradient(top, bottom);
- }
- }
- }
-
- fn set_alt_color_and_mix_value(&mut self, color: LinearRgba, mix_value: f32) {
- match self {
- Self::Vert(q) => q.set_alt_color_and_mix_value(color, mix_value),
- Self::Boxed(q) | Self::TransformedBoxed(q, _) => {
- q.set_alt_color_and_mix_value(color, mix_value)
- }
- Self::Tee(gpu, heap) => {
- gpu.set_alt_color_and_mix_value(color, mix_value);
- heap.set_alt_color_and_mix_value(color, mix_value);
- }
- }
- }
-
- fn set_hsv(&mut self, hsv: Option<HsbTransform>) {
- match self {
- Self::Vert(q) => q.set_hsv(hsv),
- Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_hsv(hsv),
- Self::Tee(gpu, heap) => {
- gpu.set_hsv(hsv);
- heap.set_hsv(hsv);
- }
- }
- }
-
- fn set_position(&mut self, left: f32, top: f32, right: f32, bottom: f32) {
- match self {
- Self::Vert(q) => q.set_position(left, top, right, bottom),
- Self::Boxed(q) => q.set_position(left, top, right, bottom),
- Self::TransformedBoxed(q, transform) => {
- let (left, top, right, bottom) = transform.map_position(left, top, right, bottom);
- q.set_position(left, top, right, bottom);
- }
- Self::Tee(gpu, heap) => {
- gpu.set_position(left, top, right, bottom);
- heap.set_position(left, top, right, bottom);
- }
- }
- }
-}
-
-/// A helper for updating the 4 vertices that compose a glyph cell
-pub struct Quad<'a> {
- pub(crate) vert: &'a mut [Vertex],
-}
-
-impl<'a> QuadTrait for Quad<'a> {
- fn set_texture_discrete(&mut self, x1: f32, x2: f32, y1: f32, y2: f32) {
- self.vert[V_TOP_LEFT].tex = [x1, y1];
- self.vert[V_TOP_RIGHT].tex = [x2, y1];
- self.vert[V_BOT_LEFT].tex = [x1, y2];
- self.vert[V_BOT_RIGHT].tex = [x2, y2];
- }
-
- fn set_has_color_impl(&mut self, has_color: f32) {
- for v in self.vert.iter_mut() {
- v.has_color = has_color;
- }
- }
-
- fn set_fg_color(&mut self, color: LinearRgba) {
- for v in self.vert.iter_mut() {
- v.fg_color = color.into();
- }
- self.set_alt_color_and_mix_value(color, 0.);
- }
-
- fn set_corner_gradient(
- &mut self,
- top_left: LinearRgba,
- top_right: LinearRgba,
- bottom_left: LinearRgba,
- bottom_right: LinearRgba,
- ) {
- self.vert[V_TOP_LEFT].fg_color = top_left.into();
- self.vert[V_TOP_RIGHT].fg_color = top_right.into();
- self.vert[V_BOT_LEFT].fg_color = bottom_left.into();
- self.vert[V_BOT_RIGHT].fg_color = bottom_right.into();
- }
-
- fn set_vertical_gradient(&mut self, top: LinearRgba, bottom: LinearRgba) {
- self.set_corner_gradient(top, top, bottom, bottom);
- }
-
- /// Must be called after set_fg_color
- fn set_alt_color_and_mix_value(&mut self, color: LinearRgba, mix_value: f32) {
- for v in self.vert.iter_mut() {
- v.alt_color = color.into();
- v.mix_value = mix_value;
- }
- }
-
- fn set_hsv(&mut self, hsv: Option<HsbTransform>) {
- let (h, s, v) = hsv
- .map(|t| (t.hue, t.saturation, t.brightness))
- .unwrap_or((1., 1., 1.));
- for vert in self.vert.iter_mut() {
- vert.hsv = [h, s, v];
- }
- }
-
- fn set_position(&mut self, left: f32, top: f32, right: f32, bottom: f32) {
- self.vert[V_TOP_LEFT].position = [left, top];
- self.vert[V_TOP_RIGHT].position = [right, top];
- self.vert[V_BOT_LEFT].position = [left, bottom];
- self.vert[V_BOT_RIGHT].position = [right, bottom];
- }
-}
-
-pub trait QuadAllocator {
- fn allocate(&mut self) -> anyhow::Result<QuadImpl<'_>>;
- fn extend_with(&mut self, vertices: &[Vertex]);
-}
-
-pub trait TripleLayerQuadAllocatorTrait {
- fn allocate(&mut self, layer_num: usize) -> anyhow::Result<QuadImpl<'_>>;
- fn extend_with(&mut self, layer_num: usize, vertices: &[Vertex]);
-}
-
-/// We prefer to allocate a quad at a time for HeapQuadAllocator
-/// because we tend to end up with fairly large arrays of Vertex
-/// and the total amount of contiguous memory is in the MB range,
-/// which is a bit gnarly to reallocate, and can waste several MB
-/// in unused capacity
-#[derive(Clone, Default)]
-pub struct BoxedQuad {
- position: (f32, f32, f32, f32),
- fg_color: [f32; 4],
- fg_color_corners: Option<Box<[[f32; 4]; 4]>>,
- alt_color: [f32; 4],
- tex: (f32, f32, f32, f32),
- hsv: [f32; 3],
- has_color: f32,
- mix_value: f32,
-}
-
-impl QuadTrait for BoxedQuad {
- fn set_texture_discrete(&mut self, x1: f32, x2: f32, y1: f32, y2: f32) {
- self.tex = (x1, x2, y1, y2);
- }
-
- fn set_has_color_impl(&mut self, has_color: f32) {
- self.has_color = has_color;
- }
-
- fn set_fg_color(&mut self, color: LinearRgba) {
- self.fg_color = color.into();
- self.fg_color_corners = None;
- }
- fn set_corner_gradient(
- &mut self,
- top_left: LinearRgba,
- top_right: LinearRgba,
- bottom_left: LinearRgba,
- bottom_right: LinearRgba,
- ) {
- let colors = [
- top_left.into(),
- top_right.into(),
- bottom_left.into(),
- bottom_right.into(),
- ];
- self.fg_color = colors[V_TOP_LEFT];
- self.fg_color_corners = colors
- .iter()
- .skip(1)
- .any(|color| *color != colors[V_TOP_LEFT])
- .then(|| Box::new(colors));
- }
- fn set_vertical_gradient(&mut self, top: LinearRgba, bottom: LinearRgba) {
- self.set_corner_gradient(top, top, bottom, bottom);
- }
- fn set_alt_color_and_mix_value(&mut self, color: LinearRgba, mix_value: f32) {
- self.alt_color = color.into();
- self.mix_value = mix_value;
- }
- fn set_hsv(&mut self, hsv: Option<HsbTransform>) {
- let (h, s, v) = hsv
- .map(|t| (t.hue, t.saturation, t.brightness))
- .unwrap_or((1., 1., 1.));
- self.hsv = [h, s, v];
- }
-
- fn set_position(&mut self, left: f32, top: f32, right: f32, bottom: f32) {
- self.position = (left, top, right, bottom);
- }
-}
-
-impl BoxedQuad {
- fn from_vertices(verts: &[Vertex; VERTICES_PER_CELL]) -> Self {
- let [x1, y1] = verts[V_TOP_LEFT].tex;
- let [x2, y2] = verts[V_BOT_RIGHT].tex;
-
- let [left, top] = verts[V_TOP_LEFT].position;
- let [right, bottom] = verts[V_BOT_RIGHT].position;
- let fg_color_corners = [
- verts[V_TOP_LEFT].fg_color,
- verts[V_TOP_RIGHT].fg_color,
- verts[V_BOT_LEFT].fg_color,
- verts[V_BOT_RIGHT].fg_color,
- ];
- let fg_color = fg_color_corners[V_TOP_LEFT];
- Self {
- tex: (x1, x2, y1, y2),
- position: (left, top, right, bottom),
- has_color: verts[V_TOP_LEFT].has_color,
- alt_color: verts[V_TOP_LEFT].alt_color,
- fg_color,
- fg_color_corners: fg_color_corners
- .iter()
- .skip(1)
- .any(|color| *color != fg_color)
- .then(|| Box::new(fg_color_corners)),
- hsv: verts[V_TOP_LEFT].hsv,
- mix_value: verts[V_TOP_LEFT].mix_value,
- }
- }
-
- fn to_vertices(&self) -> [Vertex; VERTICES_PER_CELL] {
- let mut vert: [Vertex; VERTICES_PER_CELL] = Default::default();
- let mut quad = Quad { vert: &mut vert };
-
- let (x1, x2, y1, y2) = self.tex;
- quad.set_texture_discrete(x1, x2, y1, y2);
-
- let (left, top, right, bottom) = self.position;
- quad.set_position(left, top, right, bottom);
-
- quad.set_has_color_impl(self.has_color);
- let [hue, saturation, brightness] = self.hsv;
- quad.set_hsv(Some(HsbTransform {
- hue,
- saturation,
- brightness,
- }));
- if let Some(colors) = self.fg_color_corners.as_deref() {
- quad.set_corner_gradient(
- colors[V_TOP_LEFT].into(),
- colors[V_TOP_RIGHT].into(),
- colors[V_BOT_LEFT].into(),
- colors[V_BOT_RIGHT].into(),
- );
- } else {
- quad.set_fg_color(self.fg_color.into());
- }
- quad.set_alt_color_and_mix_value(self.alt_color.into(), self.mix_value);
-
- vert
- }
-
- /// Scale every colour's alpha, for compositing a recorded surface at
- /// partial opacity.
- ///
- /// Every shader branch multiplies by this, so a whole recorded surface --
- /// fills, gradients, UI text, terminal glyphs, colour emoji -- fades as
- /// one picture. `IS_GLYPH` and `IS_COLOR_EMOJI` used to take their alpha
- /// from the glyph texture alone and drop the vertex colour's, which left
- /// terminal text standing solid over everything else as it faded.
- fn with_opacity(mut self, opacity: f32) -> Self {
- self.fg_color[3] *= opacity;
- self.alt_color[3] *= opacity;
- if let Some(corners) = self.fg_color_corners.as_deref_mut() {
- for corner in corners.iter_mut() {
- corner[3] *= opacity;
- }
- }
- self
- }
-
- /// Translate this quad and crop it to `clip`, preserving texture
- /// coordinates and per-corner colors for the visible portion.
- fn translated_clipped(&self, offset_x: f32, offset_y: f32, clip: QuadClipRect) -> Option<Self> {
- let (left, top, right, bottom) = self.position;
- let translated_left = left + offset_x;
- let translated_top = top + offset_y;
- let translated_right = right + offset_x;
- let translated_bottom = bottom + offset_y;
- self.positioned_clipped(
- translated_left,
- translated_top,
- translated_right,
- translated_bottom,
- clip,
- )
- }
-
- /// Scale and offset this quad into a destination rect, then crop it.
- ///
- /// Unlike [`TripleLayerQuadAllocator::set_heap_position_transform`], which
- /// maps positions as a surface is being authored, this remaps a surface
- /// that was already recorded. That is what lets one captured frame be
- /// replayed at a different size on every frame of a transition instead of
- /// the whole window being painted again each time -- at the cost of the
- /// glyph textures being sampled below their rasterised size, so the text
- /// softens as it shrinks.
- fn transformed_clipped(
- &self,
- transform: QuadPositionTransform,
- clip: QuadClipRect,
- ) -> Option<Self> {
- let (left, top, right, bottom) = self.position;
- let (left, top, right, bottom) = transform.map_position(left, top, right, bottom);
- self.positioned_clipped(left, top, right, bottom, clip)
- }
-
- /// Crop this quad after its four position edges have already been mapped.
- /// Keeping the mapping outside avoids cloning an intermediate quad for the
- /// scaled-preview path, which touches thousands of tiny glyph quads.
- fn positioned_clipped(
- &self,
- left: f32,
- top: f32,
- right: f32,
- bottom: f32,
- clip: QuadClipRect,
- ) -> Option<Self> {
- if !(right > left
- && bottom > top
- && clip.right() > clip.left()
- && clip.bottom() > clip.top())
- {
- return None;
- }
-
- let visible_left = left.max(clip.left());
- let visible_top = top.max(clip.top());
- let visible_right = right.min(clip.right());
- let visible_bottom = bottom.min(clip.bottom());
- if visible_right <= visible_left || visible_bottom <= visible_top {
- return None;
- }
-
- let x0 = (visible_left - left) / (right - left);
- let x1 = (visible_right - left) / (right - left);
- let y0 = (visible_top - top) / (bottom - top);
- let y1 = (visible_bottom - top) / (bottom - top);
- let (u0, u1, v0, v1) = self.tex;
- let source_colors = self
- .fg_color_corners
- .as_deref()
- .copied()
- .unwrap_or([self.fg_color; VERTICES_PER_CELL]);
- let clipped_colors = [
- bilerp_color(source_colors, x0, y0),
- bilerp_color(source_colors, x1, y0),
- bilerp_color(source_colors, x0, y1),
- bilerp_color(source_colors, x1, y1),
- ];
- let fg_color = clipped_colors[V_TOP_LEFT];
-
- let mut clipped = Self {
- position: (visible_left, visible_top, visible_right, visible_bottom),
- fg_color,
- fg_color_corners: clipped_colors
- .iter()
- .skip(1)
- .any(|color| *color != fg_color)
- .then(|| Box::new(clipped_colors)),
- alt_color: self.alt_color,
- tex: (
- lerp(u0, u1, x0),
- lerp(u0, u1, x1),
- lerp(v0, v1, y0),
- lerp(v0, v1, y1),
- ),
- hsv: self.hsv,
- has_color: self.has_color,
- mix_value: self.mix_value,
- };
- // Solid-colour quads conventionally use zero-width texture intervals.
- // Preserve those intervals exactly rather than introducing tiny
- // floating-point differences while cropping.
- if u0 == u1 {
- clipped.tex.0 = u0;
- clipped.tex.1 = u1;
- }
- if v0 == v1 {
- clipped.tex.2 = v0;
- clipped.tex.3 = v1;
- }
- Some(clipped)
- }
-}
-
-fn lerp(start: f32, end: f32, amount: f32) -> f32 {
- start + (end - start) * amount
-}
-
-fn lerp_color(start: [f32; 4], end: [f32; 4], amount: f32) -> [f32; 4] {
- std::array::from_fn(|index| lerp(start[index], end[index], amount))
-}
-
-fn bilerp_color(corners: [[f32; 4]; 4], x: f32, y: f32) -> [f32; 4] {
- let top = lerp_color(corners[V_TOP_LEFT], corners[V_TOP_RIGHT], x);
- let bottom = lerp_color(corners[V_BOT_LEFT], corners[V_BOT_RIGHT], x);
- lerp_color(top, bottom, y)
-}
-
-#[derive(Default, Clone)]
-pub struct HeapQuadAllocator {
- // Quads are stored inline: a cached surface with hundreds of thousands of
- // quads would otherwise be that many separate 96-byte allocations, which
- // both fragments the heap and makes every replay a pointer chase. Callers
- // only ever hold the `QuadImpl` borrow from `allocate` until the next
- // allocation, so element addresses do not need to survive vector growth.
- layer0: Vec<BoxedQuad>,
- layer1: Vec<BoxedQuad>,
- layer2: Vec<BoxedQuad>,
- position_transform: Option<QuadPositionTransform>,
-}
-
-impl std::fmt::Debug for HeapQuadAllocator {
- fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- fmt.debug_struct("HeapQuadAllocator").finish()
- }
-}
-
-/// A clip rectangle in the window-centre-relative space that quad positions
-/// live in.
-///
-/// Every painter goes through `filled_rectangle` and friends, which subtract
-/// half the window size from each edge, so a quad's `position` is *not* in the
-/// same coordinates as the layout rects (`workspace_sidebar_rect`, the list
-/// viewport, …) that describe where it was asked to go. Clipping against an
-/// un-rebased rect does not fail loudly: every quad simply falls outside and
-/// is dropped. That is how the space-swipe transition once drew an entirely
-/// empty sidebar while every offset in the logs looked correct.
-///
-/// The fields are private and [`Self::from_top_left_pixels`] is the only way
-/// in, so layout coordinates cannot reach the clipper by accident. Bands
-/// carved out of an existing rect go through [`Self::with_vertical`] /
-/// [`Self::with_horizontal`], which inherit the already-converted edges.
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub struct QuadClipRect {
- left: f32,
- top: f32,
- right: f32,
- bottom: f32,
-}
-
-impl QuadClipRect {
- /// Rebase a top-left pixel rect -- sidebar geometry, a list viewport, a
- /// UI item's bounds -- into the quads' own space.
- ///
- /// Takes the window's own [`Dimensions`] rather than a pair of numbers on
- /// purpose: the conversion is only correct against the surface the quads
- /// were laid out for, and a caller with two loose `usize`s can silently
- /// pass the wrong ones (or zeroes) and get a rect that quietly matches
- /// nothing.
- pub fn from_top_left_pixels(
- left: f32,
- top: f32,
- right: f32,
- bottom: f32,
- dimensions: &Dimensions,
- ) -> Self {
- let dx = dimensions.pixel_width as f32 / 2.0;
- let dy = dimensions.pixel_height as f32 / 2.0;
- Self {
- left: left - dx,
- top: top - dy,
- right: right - dx,
- bottom: bottom - dy,
- }
- }
-
- pub fn left(&self) -> f32 {
- self.left
- }
-
- pub fn top(&self) -> f32 {
- self.top
- }
-
- pub fn right(&self) -> f32 {
- self.right
- }
-
- pub fn bottom(&self) -> f32 {
- self.bottom
- }
-
- pub fn width(&self) -> f32 {
- self.right - self.left
- }
-
- /// A horizontal band of this rect. Both edges are already centre-relative.
- pub fn with_vertical(&self, top: f32, bottom: f32) -> Self {
- Self {
- top,
- bottom,
- ..*self
- }
- }
-
- /// A vertical band of this rect. Both edges are already centre-relative.
- pub fn with_horizontal(&self, left: f32, right: f32) -> Self {
- Self {
- left,
- right,
- ..*self
- }
- }
-}
-
-/// How many quads a [`HeapQuadAllocator`] held at some point during a paint.
-///
-/// Splitting a recorded frame by screen position cannot distinguish a scrolling
-/// row from the chrome drawn over it: the two overlap on purpose, so any
-/// horizontal line drawn through them cuts something in half. Recording where
-/// the painter *was* instead splits by what was being drawn, which is the
-/// question a compositor actually needs answered.
-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
-pub struct HeapQuadMark {
- layer0: usize,
- layer1: usize,
- layer2: usize,
-}
-
-impl HeapQuadAllocator {
- /// Empty the allocator but keep its capacity for whatever is recorded
- /// next. For a caller that records many surfaces in a row -- the overview
- /// draws one per visible card, every frame -- this makes re-recording
- /// allocation-free.
- pub fn recycle(&mut self) {
- self.layer0.clear();
- self.layer1.clear();
- self.layer2.clear();
- self.position_transform = None;
- }
-
- /// Estimated resident heap bytes for the recorded quads. Counts vector
- /// capacity, not length: a buffer that grew during recording keeps that
- /// allocation until it is dropped, and capacity is what a byte-accounted
- /// cache needs to know about.
- pub fn resident_bytes(&self) -> usize {
- (self.layer0.capacity() + self.layer1.capacity() + self.layer2.capacity())
- .saturating_mul(std::mem::size_of::<BoxedQuad>())
- }
-
- /// Where the next quad will land, for later use with [`Self::apply_before`],
- /// [`Self::apply_between`] and [`Self::apply_after`].
- pub fn mark(&self) -> HeapQuadMark {
- HeapQuadMark {
- layer0: self.layer0.len(),
- layer1: self.layer1.len(),
- layer2: self.layer2.len(),
- }
- }
-
- fn layers(&self) -> [(usize, &Vec<BoxedQuad>); 3] {
- [(0, &self.layer0), (1, &self.layer1), (2, &self.layer2)]
- }
-
- fn layer_bounds(mark: &HeapQuadMark, layer_num: usize) -> usize {
- match layer_num {
- 0 => mark.layer0,
- 1 => mark.layer1,
- 2 => mark.layer2,
- _ => unreachable!(),
- }
- }
-
- pub fn apply_to(&self, other: &mut TripleLayerQuadAllocator) -> anyhow::Result<()> {
- let start = std::time::Instant::now();
- for (layer_num, quads) in self.layers() {
- for quad in quads {
- other.extend_with(layer_num, &quad.to_vertices());
- }
- }
- metrics::histogram!("quad_buffer_apply").record(start.elapsed());
- Ok(())
- }
-
- /// Copy every recorded quad into `other`, cropped to `clip` and scaled to
- /// `opacity`.
- /// Flatten the recorded quads into a plain vertex stream: sub-layer 0,
- /// then 1, then 2, in recorded order -- the order a replay would draw
- /// them. Used to render a card's picture into its own texture, where
- /// the render pass's projection does the placement and cropping, so the
- /// vertices go out untransformed and unclipped.
- pub fn extract_vertices(&self, out: &mut Vec<Vertex>) {
- for (_layer_num, quads) in self.layers() {
- for quad in quads {
- out.extend_from_slice(&quad.to_vertices());
- }
- }
- }
-
- pub fn quad_count(&self) -> usize {
- self.layers().iter().map(|(_, quads)| quads.len()).sum()
- }
-
- /// Position, texture coordinates and per-corner colors are transformed
- /// together by the same primitive used by Space swipe composition.
- ///
- /// See [`BoxedQuad::with_opacity`] for which quads an opacity below 1
- /// actually reaches.
- pub fn apply_to_clipped(
- &self,
- other: &mut TripleLayerQuadAllocator,
- clip: QuadClipRect,
- opacity: f32,
- ) -> anyhow::Result<()> {
- self.apply_to_clipped_at(other, 0.0, 0.0, clip, opacity)
- }
-
- /// `apply_to_clipped`, shifted by `offset` on the way out.
- ///
- /// Lets a caller record a surface in its own local space — its left edge
- /// at 0 — and place it on replay. That matters when the surface's real
- /// origin is off-screen: the painters take unsigned pixel coordinates, so
- /// a negative origin cannot be expressed at record time, and clamping it
- /// to 0 lays the contents out from the wrong place.
- pub fn apply_to_clipped_at(
- &self,
- other: &mut TripleLayerQuadAllocator,
- offset_x: f32,
- offset_y: f32,
- clip: QuadClipRect,
- opacity: f32,
- ) -> anyhow::Result<()> {
- let started = std::time::Instant::now();
- for (layer_num, quads) in self.layers() {
- for quad in quads {
- let Some(clipped) = quad.translated_clipped(offset_x, offset_y, clip) else {
- continue;
- };
- let clipped = if opacity < 1.0 {
- clipped.with_opacity(opacity)
- } else {
- clipped
- };
- other.extend_with(layer_num, &clipped.to_vertices());
- }
- }
- metrics::histogram!("quad_buffer_apply_clipped").record(started.elapsed());
- Ok(())
- }
-
- /// Replay this whole surface scaled into `target`, cropped to `clip` and
- /// composited at `opacity`.
- ///
- /// `source` is the rect the surface was recorded in; the two together give
- /// the scale and offset. Used to fly a captured window into the card it
- /// becomes.
- pub fn apply_to_scaled(
- &self,
- other: &mut TripleLayerQuadAllocator,
- source: QuadClipRect,
- target: QuadClipRect,
- clip: QuadClipRect,
- opacity: f32,
- ) -> anyhow::Result<()> {
- let started = std::time::Instant::now();
- let Some(transform) = QuadPositionTransform::new(source, target) else {
- return Ok(());
- };
- for (layer_num, quads) in self.layers() {
- for quad in quads {
- let Some(mapped) = quad.transformed_clipped(transform, clip) else {
- continue;
- };
- let mapped = if opacity < 1.0 {
- mapped.with_opacity(opacity)
- } else {
- mapped
- };
- other.extend_with(layer_num, &mapped.to_vertices());
- }
- }
- metrics::histogram!("quad_buffer_apply_scaled").record(started.elapsed());
- Ok(())
- }
-
- /// Replay everything recorded before `mark`, in place.
- pub fn apply_before(
- &self,
- other: &mut TripleLayerQuadAllocator,
- mark: &HeapQuadMark,
- ) -> anyhow::Result<()> {
- for (layer_num, quads) in self.layers() {
- let end = Self::layer_bounds(mark, layer_num).min(quads.len());
- for quad in &quads[..end] {
- other.extend_with(layer_num, &quad.to_vertices());
- }
- }
- Ok(())
- }
-
- /// Replay everything recorded from `mark` onwards, in place.
- pub fn apply_after(
- &self,
- other: &mut TripleLayerQuadAllocator,
- mark: &HeapQuadMark,
- ) -> anyhow::Result<()> {
- for (layer_num, quads) in self.layers() {
- let begin = Self::layer_bounds(mark, layer_num).min(quads.len());
- for quad in &quads[begin..] {
- other.extend_with(layer_num, &quad.to_vertices());
- }
- }
- Ok(())
- }
-
- /// Replay `start..end`, shifted horizontally and clipped.
- ///
- /// The clip is a containment bound -- it stops the shifted quads escaping
- /// the surface they belong to -- and not a way to carve the frame into
- /// moving and stationary parts. Use the marks for that.
- pub fn apply_between(
- &self,
- other: &mut TripleLayerQuadAllocator,
- start: &HeapQuadMark,
- end: &HeapQuadMark,
- offset_x: f32,
- clip: QuadClipRect,
- ) -> anyhow::Result<()> {
- let started = std::time::Instant::now();
- for (layer_num, quads) in self.layers() {
- let begin = Self::layer_bounds(start, layer_num).min(quads.len());
- let finish = Self::layer_bounds(end, layer_num)
- .min(quads.len())
- .max(begin);
- for quad in &quads[begin..finish] {
- let Some(clipped) = quad.translated_clipped(offset_x, 0.0, clip) else {
- continue;
- };
- other.extend_with(layer_num, &clipped.to_vertices());
- }
- }
- metrics::histogram!("quad_buffer_translated_rect_clip_apply").record(started.elapsed());
- Ok(())
- }
-
- /// Replay every recorded quad into ONE sub-layer of `other`, shifted
- /// horizontally and cropped to `clip`.
- ///
- /// The sub-layer a quad was recorded in decides only *when* it is drawn:
- /// each layer's three buffers are submitted 0, 1, 2 whatever order they
- /// were filled in (see `render/draw.rs`). A surface that has to float
- /// over the terminal therefore cannot keep its own sub-layers -- the
- /// terminal's glyphs live in sub-buffer 2 and would draw straight through
- /// a panel background recorded in sub-buffer 0. Collapsing the recording
- /// into the last sub-buffer, in recorded order, keeps the surface's own
- /// back-to-front order and puts all of it above anything drawn earlier:
- /// the same arrangement the context menu gets by painting its panel into
- /// sub-layer 2 by hand.
- pub fn apply_to_single_layer(
- &self,
- other: &mut TripleLayerQuadAllocator,
- layer_num: usize,
- offset_x: f32,
- clip: QuadClipRect,
- ) -> anyhow::Result<()> {
- let started = std::time::Instant::now();
- for (_recorded_layer, quads) in self.layers() {
- for quad in quads {
- let Some(clipped) = quad.translated_clipped(offset_x, 0.0, clip) else {
- continue;
- };
- other.extend_with(layer_num, &clipped.to_vertices());
- }
- }
- metrics::histogram!("quad_buffer_single_layer_apply").record(started.elapsed());
- Ok(())
- }
-
- fn set_position_transform(&mut self, transform: Option<QuadPositionTransform>) {
- self.position_transform = transform;
- }
-}
-
-impl TripleLayerQuadAllocatorTrait for HeapQuadAllocator {
- fn allocate(&mut self, layer_num: usize) -> anyhow::Result<QuadImpl<'_>> {
- let position_transform = self.position_transform;
- let quads = match layer_num {
- 0 => &mut self.layer0,
- 1 => &mut self.layer1,
- 2 => &mut self.layer2,
- _ => unreachable!(),
- };
-
- quads.push(BoxedQuad::default());
-
- let quad = quads.last_mut().unwrap();
- Ok(match position_transform {
- Some(transform) => QuadImpl::TransformedBoxed(quad, transform),
- None => QuadImpl::Boxed(quad),
- })
- }
-
- fn extend_with(&mut self, layer_num: usize, vertices: &[Vertex]) {
- if vertices.is_empty() {
- return;
- }
-
- let position_transform = self.position_transform;
- let dest_quads = match layer_num {
- 0 => &mut self.layer0,
- 1 => &mut self.layer1,
- 2 => &mut self.layer2,
- _ => unreachable!(),
- };
-
- // This is logically equivalent to
- // https://doc.rust-lang.org/std/primitive.slice.html#method.as_chunks_unchecked
- // which is currently nightly-only
- assert_eq!(vertices.len() % VERTICES_PER_CELL, 0);
- let src_quads: &[[Vertex; VERTICES_PER_CELL]] =
- unsafe { std::slice::from_raw_parts(vertices.as_ptr().cast(), vertices.len() / 4) };
-
- for quad in src_quads {
- let mut quad = BoxedQuad::from_vertices(quad);
- if let Some(transform) = position_transform {
- let (left, top, right, bottom) = quad.position;
- quad.position = transform.map_position(left, top, right, bottom);
- }
- dest_quads.push(quad);
- }
- }
-}
pub enum TripleLayerQuadAllocator<'a> {
Gpu(BorrowedLayers),
@@ -1132,330 +77,3 @@ impl<'a> TripleLayerQuadAllocatorTrait for TripleLayerQuadAllocator<'a> {
}
}
}
-
-#[cfg(test)]
-const TEST_ORIGIN: Dimensions = Dimensions {
- pixel_width: 0,
- pixel_height: 0,
- dpi: 96,
-};
-
-#[cfg(test)]
-#[test]
-fn size() {
- assert_eq!(std::mem::size_of::<Vertex>() * VERTICES_PER_CELL, 272);
- assert_eq!(std::mem::size_of::<BoxedQuad>(), 96);
-}
-
-#[cfg(test)]
-#[test]
-fn boxed_quad_preserves_vertical_gradient_colors() {
- let top = LinearRgba::with_components(0.1, 0.2, 0.3, 1.0);
- let bottom = LinearRgba::with_components(0.4, 0.5, 0.6, 1.0);
- let mut quad = BoxedQuad::default();
- quad.set_vertical_gradient(top, bottom);
- let vertices = quad.to_vertices();
- let top: [f32; 4] = top.into();
- let bottom: [f32; 4] = bottom.into();
- assert_eq!(vertices[V_TOP_LEFT].fg_color, top);
- assert_eq!(vertices[V_TOP_RIGHT].fg_color, top);
- assert_eq!(vertices[V_BOT_LEFT].fg_color, bottom);
- assert_eq!(vertices[V_BOT_RIGHT].fg_color, bottom);
-}
-
-#[cfg(test)]
-#[test]
-fn boxed_quad_preserves_corner_gradient_colors() {
- let top_left = LinearRgba::with_components(0.1, 0.2, 0.3, 1.0);
- let top_right = LinearRgba::with_components(0.2, 0.3, 0.4, 1.0);
- let bottom_left = LinearRgba::with_components(0.3, 0.4, 0.5, 1.0);
- let bottom_right = LinearRgba::with_components(0.4, 0.5, 0.6, 1.0);
- let mut quad = BoxedQuad::default();
- quad.set_corner_gradient(top_left, top_right, bottom_left, bottom_right);
- let vertices = quad.to_vertices();
- assert_eq!(vertices[V_TOP_LEFT].fg_color, <[f32; 4]>::from(top_left));
- assert_eq!(vertices[V_TOP_RIGHT].fg_color, <[f32; 4]>::from(top_right));
- assert_eq!(vertices[V_BOT_LEFT].fg_color, <[f32; 4]>::from(bottom_left));
- assert_eq!(
- vertices[V_BOT_RIGHT].fg_color,
- <[f32; 4]>::from(bottom_right)
- );
-}
-
-#[cfg(test)]
-#[test]
-fn boxed_quad_keeps_solid_colors_inline() {
- let color = LinearRgba::with_components(0.1, 0.2, 0.3, 1.0);
- let mut quad = BoxedQuad::default();
- quad.set_fg_color(color);
- assert!(quad.fg_color_corners.is_none());
- quad.set_vertical_gradient(color, color);
- assert!(quad.fg_color_corners.is_none());
-}
-
-#[cfg(test)]
-#[test]
-fn boxed_quad_translation_and_clip_crop_position_texture_and_gradient_together() {
- let mut quad = BoxedQuad::default();
- quad.set_position(0.0, 0.0, 100.0, 80.0);
- quad.set_texture_discrete(0.1, 0.9, 0.2, 0.6);
- quad.set_corner_gradient(
- LinearRgba::with_components(0.0, 0.0, 0.0, 1.0),
- LinearRgba::with_components(1.0, 0.0, 0.0, 1.0),
- LinearRgba::with_components(0.0, 1.0, 0.0, 1.0),
- LinearRgba::with_components(1.0, 1.0, 0.0, 1.0),
- );
-
- let clip = QuadClipRect::from_top_left_pixels(35.0, 25.0, 85.0, 65.0, &TEST_ORIGIN);
- let clipped = quad.translated_clipped(10.0, 5.0, clip).unwrap();
- assert_eq!(clipped.position, (35.0, 25.0, 85.0, 65.0));
- for (actual, expected) in std::iter::zip(
- [clipped.tex.0, clipped.tex.1, clipped.tex.2, clipped.tex.3]
- .iter()
- .copied(),
- [0.3, 0.7, 0.3, 0.5].iter().copied(),
- ) {
- assert!((actual - expected).abs() < 0.000_001);
- }
- let colors = clipped.fg_color_corners.unwrap();
- assert_eq!(colors[V_TOP_LEFT], [0.25, 0.25, 0.0, 1.0]);
- assert_eq!(colors[V_TOP_RIGHT], [0.75, 0.25, 0.0, 1.0]);
- assert_eq!(colors[V_BOT_LEFT], [0.25, 0.75, 0.0, 1.0]);
- assert_eq!(colors[V_BOT_RIGHT], [0.75, 0.75, 0.0, 1.0]);
-}
-
-#[cfg(test)]
-#[test]
-fn heap_position_transform_maps_new_and_cached_quads_in_one_pass() {
- let source = QuadClipRect::from_top_left_pixels(0.0, 0.0, 100.0, 100.0, &TEST_ORIGIN);
- let target = QuadClipRect::from_top_left_pixels(10.0, 20.0, 210.0, 70.0, &TEST_ORIGIN);
- let mut heap = HeapQuadAllocator::default();
- {
- let mut layers = TripleLayerQuadAllocator::Heap(&mut heap);
- assert!(layers.set_heap_position_transform(Some((source, target))));
-
- let mut authored = layers.allocate(0).unwrap();
- authored.set_position(20.0, 10.0, 40.0, 50.0);
- drop(authored);
-
- let mut cached = BoxedQuad::default();
- cached.set_position(20.0, 10.0, 40.0, 50.0);
- layers.extend_with(1, &cached.to_vertices());
- assert!(layers.set_heap_position_transform(None));
- }
-
- assert_eq!(heap.layer0[0].position, (50.0, 25.0, 90.0, 45.0));
- assert_eq!(heap.layer1[0].position, (50.0, 25.0, 90.0, 45.0));
-}
-
-#[cfg(test)]
-#[test]
-fn single_layer_replay_flattens_three_sub_layers_in_recorded_order() {
- let mut heap = HeapQuadAllocator::default();
- {
- let mut layers = TripleLayerQuadAllocator::Heap(&mut heap);
- for (layer_num, x) in [(0usize, 0.0f32), (1, 100.0), (2, 200.0)] {
- let mut quad = layers.allocate(layer_num).unwrap();
- quad.set_position(x, 0.0, x + 50.0, 50.0);
- }
- }
-
- let mut target_heap = HeapQuadAllocator::default();
- {
- let mut target = TripleLayerQuadAllocator::Heap(&mut target_heap);
- let clip = QuadClipRect::from_top_left_pixels(-500.0, -500.0, 500.0, 500.0, &TEST_ORIGIN);
- heap.apply_to_single_layer(&mut target, 2, -10.0, clip)
- .unwrap();
- }
-
- assert!(target_heap.layer0.is_empty());
- assert!(target_heap.layer1.is_empty());
- assert_eq!(target_heap.layer2.len(), 3);
- // Recorded order 0 -> 1 -> 2 survives as draw order, shifted by -10.
- assert_eq!(target_heap.layer2[0].position, (-10.0, 0.0, 40.0, 50.0));
- assert_eq!(target_heap.layer2[1].position, (90.0, 0.0, 140.0, 50.0));
- assert_eq!(target_heap.layer2[2].position, (190.0, 0.0, 240.0, 50.0));
-}
-
-#[cfg(test)]
-#[test]
-fn single_layer_replay_drops_quads_the_shift_pushes_out_of_the_clip() {
- let mut heap = HeapQuadAllocator::default();
- {
- let mut layers = TripleLayerQuadAllocator::Heap(&mut heap);
- let mut quad = layers.allocate(0).unwrap();
- quad.set_position(0.0, 0.0, 50.0, 50.0);
- }
-
- let mut target_heap = HeapQuadAllocator::default();
- {
- let mut target = TripleLayerQuadAllocator::Heap(&mut target_heap);
- let clip = QuadClipRect::from_top_left_pixels(0.0, 0.0, 500.0, 500.0, &TEST_ORIGIN);
- // Shifted fully left of the clip: nothing lands.
- heap.apply_to_single_layer(&mut target, 2, -100.0, clip)
- .unwrap();
- }
- assert_eq!(target_heap.quad_count(), 0);
-}
-
-#[cfg(test)]
-#[test]
-fn boxed_quad_clip_rejects_outside_and_preserves_inside() {
- let mut quad = BoxedQuad::default();
- quad.set_position(10.0, 20.0, 30.0, 40.0);
- quad.set_texture_discrete(0.2, 0.6, 0.3, 0.7);
- let outside = QuadClipRect::from_top_left_pixels(30.0, 0.0, 50.0, 50.0, &TEST_ORIGIN);
- assert!(quad.translated_clipped(0.0, 0.0, outside).is_none());
- let full = QuadClipRect::from_top_left_pixels(0.0, 0.0, 50.0, 50.0, &TEST_ORIGIN);
- let inside = quad.translated_clipped(0.0, 0.0, full).unwrap();
- assert_eq!(inside.position, quad.position);
- assert_eq!(inside.tex, quad.tex);
-}
-
-#[cfg(test)]
-mod translated_clip_tests {
- use super::*;
-
- /// Fixtures below that predate the rebase work state their coordinates
- /// already centre-relative, so they convert against a zero-sized window.
- const ORIGIN: Dimensions = Dimensions {
- pixel_width: 0,
- pixel_height: 0,
- dpi: 96,
- };
-
- #[test]
- fn translated_rect_clip_moves_positions_and_crops_texture_coordinates_together() {
- let quad = BoxedQuad {
- position: (10.0, 2.0, 30.0, 8.0),
- tex: (0.2, 0.6, 0.1, 0.9),
- ..Default::default()
- };
- let clip = QuadClipRect::from_top_left_pixels(25.0, 3.0, 35.0, 7.0, &ORIGIN);
- let vertices = quad
- .translated_clipped(10.0, 0.0, clip)
- .expect("visible clip")
- .to_vertices();
-
- assert_eq!(vertices[V_TOP_LEFT].position, [25.0, 3.0]);
- assert_eq!(vertices[V_BOT_RIGHT].position, [35.0, 7.0]);
- assert!((vertices[V_TOP_LEFT].tex[0] - 0.3).abs() < 0.0001);
- assert!((vertices[V_TOP_RIGHT].tex[0] - 0.5).abs() < 0.0001);
- assert!((vertices[V_TOP_LEFT].tex[1] - (0.1 + 0.8 / 6.0)).abs() < 0.0001);
- assert!((vertices[V_BOT_LEFT].tex[1] - (0.9 - 0.8 / 6.0)).abs() < 0.0001);
- }
-
- /// Regression: the swipe transition built its clip rect straight from the
- /// sidebar's top-left layout geometry and handed it to the quad clipper,
- /// whose quads are window-centre relative. Every one of the ~300 quads
- /// failed the bounds test, so the sidebar drew nothing at all for the
- /// whole 220ms -- with correct-looking offsets in every log. Nothing about
- /// that is visible from inside the clipper, so pin the conversion here.
- #[test]
- fn a_clip_rect_is_useless_until_it_is_rebased_into_the_quads_own_space() {
- let window = Dimensions {
- pixel_width: 2560,
- pixel_height: 1600,
- dpi: 144,
- };
- // A window of zero size is the only way to express the old bug now.
- let no_window = Dimensions {
- pixel_width: 0,
- pixel_height: 0,
- dpi: 144,
- };
-
- // A sidebar row as a painter would emit it: laid out at top-left
- // pixels x 0..465, y 300..320, then written centre-relative.
- let row = QuadClipRect::from_top_left_pixels(0.0, 300.0, 465.0, 320.0, &window);
- let quad = BoxedQuad {
- position: (row.left(), row.top(), row.right(), row.bottom()),
- ..Default::default()
- };
-
- // The list viewport in the layout's own coordinates. Used as-is, it
- // silently discards a row that is plainly inside it.
- // `QuadClipRect` has private fields, so this is only expressible in a
- // test that reaches for the raw numbers on purpose.
- let unrebased = QuadClipRect::from_top_left_pixels(0.0, 204.0, 465.0, 1316.0, &no_window);
- assert!(
- quad.translated_clipped(0.0, 0.0, unrebased).is_none(),
- "an un-rebased clip rect drops everything -- this is the failure \
- mode, not a healthy result"
- );
-
- // Rebased against the real window, the row survives.
- let list = QuadClipRect::from_top_left_pixels(0.0, 204.0, 465.0, 1316.0, &window);
- assert!(quad.translated_clipped(0.0, 0.0, list).is_some());
- }
-
- /// Regression: the transition used to decide what slides by cutting the
- /// sidebar at a y coordinate. It cannot work. The bottom fade and the
- /// settings row are painted *over* the list on purpose, so any horizontal
- /// line drawn between "moving" and "stationary" runs straight through
- /// whichever list row happens to reach that far -- the row's top half slid
- /// away while its bottom half stayed put, already showing the destination.
- /// Splitting by paint order instead asks the question that has an answer.
- #[test]
- fn chrome_painted_over_the_list_stays_put_when_the_list_slides_under_it() {
- const WINDOW: Dimensions = Dimensions {
- pixel_width: 1000,
- pixel_height: 800,
- dpi: 96,
- };
- fn quad_at(left: f32, top: f32, right: f32, bottom: f32) -> BoxedQuad {
- let rect = QuadClipRect::from_top_left_pixels(left, top, right, bottom, &WINDOW);
- BoxedQuad {
- position: (rect.left(), rect.top(), rect.right(), rect.bottom()),
- ..Default::default()
- }
- }
- // Left edge of a top-left `x`, in the centre-relative space quads use.
- let at = |x: f32| x - WINDOW.pixel_width as f32 / 2.0;
-
- let mut frame = HeapQuadAllocator::default();
- // Chrome above the list.
- frame.layer2.push(quad_at(0.0, 0.0, 400.0, 100.0));
-
- let list_start = frame.mark();
- // A row reaching down into the band the footer chrome covers. Inset
- // from the sidebar edges so a horizontal shift is visible rather than
- // being cropped away by the containment clip.
- frame.layer2.push(quad_at(100.0, 600.0, 300.0, 660.0));
- let list_end = frame.mark();
-
- // The fade and the settings row: painted last, and deliberately
- // overlapping the row above.
- frame.layer2.push(quad_at(0.0, 620.0, 400.0, 700.0));
-
- let mut out = HeapQuadAllocator::default();
- let mut sink = TripleLayerQuadAllocator::Heap(&mut out);
- let clip = QuadClipRect::from_top_left_pixels(0.0, 0.0, 400.0, 800.0, &WINDOW);
- frame.apply_before(&mut sink, &list_start).unwrap();
- frame
- .apply_between(&mut sink, &list_start, &list_end, -50.0, clip)
- .unwrap();
- frame.apply_after(&mut sink, &list_end).unwrap();
- drop(sink);
-
- let left_edges: Vec<f32> = out.layer2.iter().map(|q| q.position.0).collect();
- assert_eq!(
- left_edges,
- vec![at(0.0), at(50.0), at(0.0)],
- "only the marked list span may move, and the chrome recorded after \
- it must still be replayed last so it keeps masking the row"
- );
- }
-
- #[test]
- fn translated_rect_clip_discards_quads_outside_the_sidebar_page() {
- let quad = BoxedQuad {
- position: (10.0, 2.0, 30.0, 8.0),
- ..Default::default()
- };
- let full = QuadClipRect::from_top_left_pixels(0.0, 0.0, 40.0, 10.0, &ORIGIN);
- let below = QuadClipRect::from_top_left_pixels(0.0, 20.0, 40.0, 30.0, &ORIGIN);
- assert!(quad.translated_clipped(-100.0, 0.0, full).is_none());
- assert!(quad.translated_clipped(0.0, 0.0, below).is_none());
- }
-}
diff --git a/wezterm-gui/src/renderstate.rs b/wezterm-gui/src/renderstate.rs
index b3c33421..188729d6 100644
--- a/wezterm-gui/src/renderstate.rs
+++ b/wezterm-gui/src/renderstate.rs
@@ -48,19 +48,36 @@ impl LoggedSrgbTexture2d {
impl Texture2d for LoggedSrgbTexture2d {
fn write(&self, rect: Rect, im: &dyn BitmapImage) {
- <SrgbTexture2d as Texture2d>::write(&self.inner, rect, im);
+ let (im_width, im_height) = im.image_dimensions();
+
+ let source = glium::texture::RawImage2d {
+ data: std::borrow::Cow::Borrowed(im.pixels()),
+ width: im_width as u32,
+ height: im_height as u32,
+ format: glium::texture::ClientFormat::U8U8U8U8,
+ };
+
+ self.inner.write(
+ glium::Rect {
+ left: rect.min_x() as u32,
+ bottom: rect.min_y() as u32,
+ width: rect.size.width as u32,
+ height: rect.size.height as u32,
+ },
+ source,
+ )
}
- fn read(&self, rect: Rect, im: &mut dyn BitmapImage) {
- <SrgbTexture2d as Texture2d>::read(&self.inner, rect, im);
+ fn read(&self, _rect: Rect, _im: &mut dyn BitmapImage) {
+ unimplemented!();
}
fn width(&self) -> usize {
- <SrgbTexture2d as Texture2d>::width(&self.inner)
+ self.inner.width() as usize
}
fn height(&self) -> usize {
- <SrgbTexture2d as Texture2d>::height(&self.inner)
+ self.inner.height() as usize
}
}
diff --git a/wezterm-gui/src/termwindow/render/draw.rs b/wezterm-gui/src/termwindow/render/draw.rs
index 1adeb5c7..602afc38 100644
--- a/wezterm-gui/src/termwindow/render/draw.rs
+++ b/wezterm-gui/src/termwindow/render/draw.rs
@@ -120,7 +120,7 @@ fn composite_quad_verts(
let v1 = (vis.max_y() - dest.min_y()) / dest.size.height;
let (x0, x1) = (vis.min_x() - half_w, vis.max_x() - half_w);
let (y0, y1) = (vis.min_y() - half_h, vis.max_y() - half_h);
- const IS_BG_IMAGE: f32 = 2.0;
+ use crate::quad::IS_BG_IMAGE;
let vert = |x: f32, y: f32, u: f32, v: f32| Vertex {
position: [x, y],
tex: [u, v],
@@ -599,17 +599,12 @@ impl crate::TermWindow {
}
fn call_draw_glium(&mut self, frame: &mut glium::Frame) -> anyhow::Result<()> {
- use window::glium::texture::SrgbTexture2d;
-
let gl_state = self.render_state.as_ref().unwrap();
let tex = gl_state.glyph_cache.borrow().atlas.texture();
- let tex = if let Some(tex) = tex.downcast_ref::<SrgbTexture2d>() {
- tex
- } else {
- tex.downcast_ref::<LoggedSrgbTexture2d>()
- .expect("OpenGL texture atlas")
- .inner()
- };
+ let tex = tex
+ .downcast_ref::<LoggedSrgbTexture2d>()
+ .expect("OpenGL texture atlas")
+ .inner();
frame.clear_color(0., 0., 0., 0.);
diff --git a/wezterm-gui/src/termwindow/webgpu.rs b/wezterm-gui/src/termwindow/webgpu.rs
index ec64d176..98f4233f 100644
--- a/wezterm-gui/src/termwindow/webgpu.rs
+++ b/wezterm-gui/src/termwindow/webgpu.rs
@@ -1,4 +1,4 @@
-use crate::quad::Vertex;
+use thinkterm_render::pipeline::Pipeline;
use anyhow::anyhow;
use config::{ConfigHandle, GpuInfo, WebGpuPowerPreference};
use std::cell::{Cell, RefCell};
@@ -21,17 +21,7 @@ fn gpu_debug(message: impl AsRef<str>) {
}
}
-#[repr(C)]
-#[derive(Copy, Clone, Default, Debug, bytemuck::Pod, bytemuck::Zeroable)]
-pub struct ShaderUniform {
- pub foreground_text_hsb: [f32; 3],
- pub milliseconds: u32,
- pub viewport_and_corner: [f32; 4],
- pub window_border: [f32; 4],
- pub projection: [[f32; 4]; 4],
- // sampler2D atlas_nearest_sampler;
- // sampler2D atlas_linear_sampler;
-}
+pub use thinkterm_render::pipeline::ShaderUniform;
/// A persistent uniform buffer plus its bind group. The buffer is written
/// at most once per frame, so a slot can be reused every frame without
@@ -88,21 +78,6 @@ pub struct RawHandlePair {
display: RawDisplayHandle,
}
-#[cfg(test)]
-mod shader_tests {
- #[test]
- fn main_wgsl_shader_parses_and_validates() {
- let module = wgpu::naga::front::wgsl::parse_str(include_str!("../shader.wgsl"))
- .expect("main WGSL shader should parse");
- wgpu::naga::valid::Validator::new(
- wgpu::naga::valid::ValidationFlags::all(),
- wgpu::naga::valid::Capabilities::all(),
- )
- .validate(&module)
- .expect("main WGSL shader should validate");
- }
-}
-
impl RawHandlePair {
fn new(window: &Window) -> Self {
Self {
@@ -663,114 +638,9 @@ impl WebGpuState {
));
surface.configure(&device, &config);
- 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 | wgpu::ShaderStages::FRAGMENT,
- 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: &[
- &shader_uniform_bind_group_layout,
- &texture_bind_group_layout,
- &texture_bind_group_layout,
- ],
- 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: Some("vs_main"),
- buffers: &[Vertex::desc()],
- compilation_options: wgpu::PipelineCompilationOptions::default(),
- },
- fragment: Some(wgpu::FragmentState {
- module: &shader,
- entry_point: Some("fs_main"),
- targets: &[Some(wgpu::ColorTargetState {
- format: config.format,
- blend: Some(wgpu::BlendState::ALPHA_BLENDING),
- write_mask: wgpu::ColorWrites::ALL,
- })],
- compilation_options: wgpu::PipelineCompilationOptions::default(),
- }),
-
- primitive: wgpu::PrimitiveState {
- topology: wgpu::PrimitiveTopology::TriangleList,
- strip_index_format: None,
- front_face: wgpu::FrontFace::Ccw,
- cull_mode: None,
- polygon_mode: wgpu::PolygonMode::Fill,
- unclipped_depth: false,
- conservative: false,
- },
- depth_stencil: None,
- multisample: wgpu::MultisampleState {
- count: 1,
- mask: !0,
- alpha_to_coverage_enabled: false,
- },
- multiview: None,
- cache: None,
- });
+ // The shader, layouts, samplers and pipeline are the shared
+ // renderer's; the browser builds the very same ones.
+ let pipeline = Pipeline::new(&device, config.format);
Ok(Self {
adapter_info,
@@ -780,12 +650,12 @@ impl WebGpuState {
queue,
config: RefCell::new(config),
dimensions: RefCell::new(dimensions),
- render_pipeline,
+ render_pipeline: pipeline.render_pipeline,
handle,
- shader_uniform_bind_group_layout,
- texture_bind_group_layout,
- texture_nearest_sampler,
- texture_linear_sampler,
+ shader_uniform_bind_group_layout: pipeline.uniform_layout,
+ texture_bind_group_layout: pipeline.texture_layout,
+ texture_nearest_sampler: pipeline.nearest_sampler,
+ texture_linear_sampler: pipeline.linear_sampler,
frame_uniforms: RefCell::new(FrameUniforms::default()),
atlas_bind_groups: RefCell::new(None),
pending_frame_latency: Cell::new(None),
diff --git a/window/Cargo.toml b/window/Cargo.toml
index e0daa750..31e5d250 100644
--- a/window/Cargo.toml
+++ b/window/Cargo.toml
@@ -26,23 +26,20 @@ async-trait.workspace = true
anyhow.workspace = true
bytes.workspace = true
config.workspace = true
-downcast-rs.workspace = true
thiserror.workspace = true
bitflags.workspace = true
euclid.workspace = true
-guillotiere.workspace = true
lazy_static.workspace = true
libloading.workspace = true
-line_drawing.workspace = true
log.workspace = true
metrics.workspace = true
promise.workspace = true
raw-window-handle.workspace = true
-resize.workspace = true
serde = {workspace=true, features = ["rc", "derive"]}
tiny-skia.workspace = true
glium.workspace = true
shlex.workspace = true
+thinkterm-render.workspace = true
url.workspace = true
wezterm-bidi.workspace = true
wezterm-color-types.workspace = true
diff --git a/window/src/bitmaps.rs b/window/src/bitmaps.rs
new file mode 100644
index 00000000..38c4e7e7
--- /dev/null
+++ b/window/src/bitmaps.rs
@@ -0,0 +1,7 @@
+//! Bitmaps, textures and the atlas live in `thinkterm-render` now; this
+//! module keeps the `window::bitmaps::*` paths the desktop uses.
+pub use thinkterm_render::bitmaps::*;
+
+pub mod atlas {
+ pub use thinkterm_render::atlas::*;
+}
diff --git a/window/src/lib.rs b/window/src/lib.rs
index baad068c..cf4c03f2 100644
--- a/window/src/lib.rs
+++ b/window/src/lib.rs
@@ -128,12 +128,7 @@ impl ClipboardContents {
}
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct Dimensions {
- pub pixel_width: usize,
- pub pixel_height: usize,
- pub dpi: usize,
-}
+pub use thinkterm_render::Dimensions;
#[derive(Debug, Clone, PartialEq)]
pub enum ContextMenuAction {
@@ -497,11 +492,7 @@ impl ContextMenuItem {
}
}
-pub type ULength = euclid::Length<usize, PixelUnit>;
-pub type Rect = euclid::Rect<isize, PixelUnit>;
-pub type RectF = euclid::Rect<f32, PixelUnit>;
-pub type Size = euclid::Size2D<isize, PixelUnit>;
-pub type SizeF = euclid::Size2D<f32, PixelUnit>;
+pub use thinkterm_render::geom::{Rect, RectF, Size, SizeF, ULength};
pub type ScreenRect = euclid::Rect<isize, ScreenPixelUnit>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]