From ffe0fa29e41ee16c948ccbc312edd304b9bf7a3f Mon Sep 17 00:00:00 2001 From: John Tur Date: Thu, 12 Nov 2026 08:19:30 +0000 Subject: [PATCH] gpui: Improve path rendering (#66809) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GPUI currently implements paths in two ways: - A remnant of a Loop-Blinn shader (which doesn't quite work because the winding accumulation is missing). - Tessellating paths on the CPU with `lyon` and uploading the triangles to the GPU. Tessellated triangles have no curve coordinates, so Loop-Blinn's analytic antialiasing doesn't help them. To antialias them, we used 4x MSAA instead. This was particularly problematic: - MSAA has an enormous bandwidth and memory cost relative to the quality of the result (5 coverage levels). - Many lower-end GPUs can't afford MSAA on the main render target. So, paths rendered into a separate MSAA target, which was resolved into an intermediate texture and then drawn onto the main target. These textures cost extra memory. - The MSAA draw and resolve happened per path batch. We didn't use a single path atlas, because in principle its memory use is unbounded. This dramatically magnifies the bandwidth cost of path rendering, especially on tile-based GPUs, since every batch switches render passes mid-frame. We present a new path renderer that computes analytic coverage per pixel from the winding number. Coverage is computed as in Eric Lengyel's Slug: we cast rays leftward and upward from the pixel and count crossings with the path's curves. Crossings within the pixel contribute partial winding. GPUI paths can be larger and more complex than glyphs. But since they're built at a fixed scale in screen space, we can do some of the spatial work on the CPU: - `PathBuilder` turns each contour into closed chains of monotone quadratic curves. - The curves are binned into square cells, where each cell lists only the curves near it. Cell size is picked per path to balance binning cost against shading cost. - For each cell, the CPU computes a *backdrop* value that encodes the winding contribution of all the curves it doesn't list. - Neighboring cells with the same curve list and backdrop merge into rectangular tiles. A large rectangle becomes nine tiles: four corners, four edges, and a solid interior with no listed curves. - Each tile is one GPU instance, and the shader loops only over that tile's curves. Tiles are drawn in the main render pass alongside every other primitive. There's no MSAA, no intermediate textures, no extra render passes or resolves, and no tessellation. --- Binning has a different cost profile from tessellation: - The tessellator's work happened almost entirely in `PathBuilder::build()`. Binning depends on the display scale, so it happens in `paint_path`. Code that caches and reuses `Path`s pays binning cost on every paint. However, this doesn't seem to be a common pattern, so mitigations are deferred. - In general, fills are about as fast as before or slightly faster, while strokes are 2–8× slower. `lyon` has a dedicated stroke tessellator that emits triangles directly along the stroke. We convert the stroke to an outline with `tiny-skia`, then bin it like any other fill. Long, sprawling strokes are the worst case (a 1,000-point scribble takes about 1.5ms now vs 0.2ms before). GPU time is, generally, reduced dramatically. Measured on an Intel HD 4600: | Scene | Before | After | Change | Pixel shader invocations | |---|---|---|---|---| | `painting` example | 9,257µs | 1,928µs | −79% | 1.81M → 1.50M (−17%) | | Git Graph | 19,669µs | 3,828µs | −81% | 3.21M → 3.13M (−2%) | --- Some breaking changes were made to the API: - `Path` is no longer generic and can only be built with `PathBuilder`. Use `PathBuilder`'s equivalents of `Path`'s builder methods. - `PathBuilder` can still be populated from `lyon` path builders, but the places where `lyon`'s tessellator leaked into the API were removed. `StrokeOptions` and `FillOptions` are now GPUI types with fewer options, and `PathBuilder::build_path` is gone. - Since paths now render with analytic antialiasing, you may see conflation artifacts where MSAA didn't have any. Release Notes: - Reduced GPU usage - [GPUI] Improved path rendering performance. `Path` is no longer generic and must be built with `PathBuilder` --------- Co-authored-by: Anthony Eid --- Cargo.lock | 56 +- crates/gpui/Cargo.toml | 5 +- crates/gpui/examples/painting.rs | 73 +- crates/gpui/examples/paths_bench.rs | 2 +- crates/gpui/src/gpui.rs | 2 + crates/gpui/src/path_builder.rs | 454 ++++++++--- crates/gpui/src/path_winding.rs | 842 ++++++++++++++++++++ crates/gpui/src/randomized_element_tree.rs | 11 +- crates/gpui/src/scene.rs | 268 +++---- crates/gpui/src/window.rs | 19 +- crates/gpui_apple/build.rs | 10 +- crates/gpui_apple/src/metal_renderer.rs | 721 +++-------------- crates/gpui_apple/src/shaders.metal | 276 ++++--- crates/gpui_macos/src/gpui_macos.rs | 2 +- crates/gpui_platform/benches/primitives.rs | 41 +- crates/gpui_wgpu/src/shaders.wgsl | 236 ++++-- crates/gpui_wgpu/src/shaders_storage.wgsl | 18 +- crates/gpui_wgpu/src/shaders_webgl.wgsl | 40 +- crates/gpui_wgpu/src/wgpu_renderer.rs | 717 ++++++----------- crates/gpui_windows/build.rs | 3 +- crates/gpui_windows/src/directx_renderer.rs | 567 ++++--------- crates/gpui_windows/src/shaders.hlsl | 229 ++++-- crates/title_bar/src/collab.rs | 19 +- 23 files changed, 2493 insertions(+), 2118 deletions(-) create mode 100644 crates/gpui/src/path_winding.rs diff --git a/Cargo.lock b/Cargo.lock index e35f4cf7de5..9b448ce1144 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6367,12 +6367,6 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d" -[[package]] -name = "float_next_after" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" - [[package]] name = "fluent-uri" version = "0.4.1" @@ -7385,7 +7379,8 @@ dependencies = [ "itertools 0.14.0", "libc", "log", - "lyon", + "lyon_extra", + "lyon_path", "num_cpus", "objc2 0.6.3", "objc2-core-foundation", @@ -7419,6 +7414,7 @@ dependencies = [ "sum_tree", "taffy", "thiserror 2.0.17", + "tiny-skia-path", "ttf-parser", "unicode-segmentation", "url", @@ -10456,42 +10452,21 @@ dependencies = [ "workspace", ] -[[package]] -name = "lyon" -version = "1.0.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbcb7d54d54c8937364c9d41902d066656817dce1e03a44e5533afebd1ef4352" -dependencies = [ - "lyon_algorithms", - "lyon_extra", - "lyon_tessellation", -] - -[[package]] -name = "lyon_algorithms" -version = "1.0.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4c0829e28c4f336396f250d850c3987e16ce6db057ffe047ce0dd54aab6b647" -dependencies = [ - "lyon_path", - "num-traits", -] - [[package]] name = "lyon_extra" -version = "1.0.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ca94c7bf1e2557c2798989c43416822c12fc5dcc5e17cc3307ef0e71894a955" +checksum = "7755f08423275157ad1680aaecc9ccb7e0cc633da3240fea2d1522935cc15c72" dependencies = [ "lyon_path", - "thiserror 1.0.69", + "thiserror 2.0.17", ] [[package]] name = "lyon_geom" -version = "1.0.17" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e16770d760c7848b0c1c2d209101e408207a65168109509f8483837a36cf2e7" +checksum = "4336502e29e32af93cf2dad2214ed6003c17ceb5bd499df77b1de663b9042b92" dependencies = [ "arrayvec", "euclid", @@ -10500,25 +10475,14 @@ dependencies = [ [[package]] name = "lyon_path" -version = "1.0.16" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aeca86bcfd632a15984ba029b539ffb811e0a70bf55e814ef8b0f54f506fdeb" +checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e" dependencies = [ "lyon_geom", "num-traits", ] -[[package]] -name = "lyon_tessellation" -version = "1.0.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3f586142e1280335b1bc89539f7c97dd80f08fc43e9ab1b74ef0a42b04aa353" -dependencies = [ - "float_next_after", - "lyon_path", - "num-traits", -] - [[package]] name = "mac-notification-sys" version = "0.6.15" diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.toml index f215c006fd6..3300a445059 100644 --- a/crates/gpui/Cargo.toml +++ b/crates/gpui/Cargo.toml @@ -119,9 +119,10 @@ unicode-segmentation.workspace = true gpui_util.workspace = true hdrhistogram = { workspace = true, optional = true } waker-fn = "1.2.0" -lyon = "1.0" +lyon_path = "1.0.19" pin-project = "1.1.10" spin.workspace = true +tiny-skia-path = "0.11" url.workspace = true uuid = { workspace = true, features = ["v4"] } web-time = { workspace = true, optional = true } @@ -181,7 +182,7 @@ postage = { workspace = true, features = ["blocking"] } web-time.workspace = true gpui_platform = { workspace = true, features = ["font-kit", "wayland", "x11"] } gpui_util.workspace = true -lyon = { version = "1.0", features = ["extra"] } +lyon_extra = "1.1.0" rand = { workspace = true, default-features = true } scheduler = { workspace = true, features = ["test-support"] } util_macros.workspace = true diff --git a/crates/gpui/examples/painting.rs b/crates/gpui/examples/painting.rs index 3d89b0ff522..63ec07d9aab 100644 --- a/crates/gpui/examples/painting.rs +++ b/crates/gpui/examples/painting.rs @@ -4,14 +4,14 @@ mod example_support; use gpui::{ - Background, Bounds, ColorSpace, Context, MouseDownEvent, Path, PathBuilder, PathStyle, Pixels, - Point, Render, StrokeOptions, Window, WindowOptions, canvas, div, linear_color_stop, - linear_gradient, point, prelude::*, px, quad, rgb, size, + Background, Bounds, ColorSpace, Context, LineJoin, MouseDownEvent, Path, PathBuilder, + PathStyle, Pixels, Point, Render, StrokeOptions, Window, WindowOptions, canvas, div, + linear_color_stop, linear_gradient, point, prelude::*, px, quad, rgb, size, }; use gpui_platform::application; struct PaintingViewer { - default_lines: Vec<(Path, Background)>, + default_lines: Vec<(Path, Background)>, background_quads: Vec<(Bounds, Background)>, lines: Vec>>, start: Point, @@ -154,8 +154,8 @@ impl PaintingViewer { lines.push((path, red2.into())); // draw a Rust logo - let mut builder = lyon::path::Path::svg_builder(); - lyon::extra::rust_logo::build_logo_path(&mut builder); + let mut builder = lyon_path::Path::svg_builder(); + lyon_extra::rust_logo::build_logo_path(&mut builder); // move down the Path let mut builder: PathBuilder = builder.into(); builder.translate(point(px(10.), px(200.))); @@ -273,9 +273,11 @@ impl PaintingViewer { } // draw a wave - let options = StrokeOptions::default() - .with_line_width(1.) - .with_line_join(lyon::path::LineJoin::Bevel); + let options = StrokeOptions { + line_width: 1., + line_join: LineJoin::Bevel, + ..Default::default() + }; let mut builder = PathBuilder::stroke(px(1.)).with_style(PathStyle::Stroke(options)); builder.move_to(point(px(40.), px(420.))); for i in 1..50 { @@ -301,6 +303,57 @@ impl PaintingViewer { self.lines.clear(); cx.notify(); } + + /// Fill the canvas with a deterministic scribble, for benchmarking. + fn stress_scribble(&mut self, cx: &mut Context) { + self.lines.clear(); + let mut state: u32 = 0x9E3779B9; + let mut random = move || { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + state as f32 / u32::MAX as f32 + }; + for _ in 0..30 { + let mut x = 40.0 + random() * 860.0; + let mut y = 80.0 + random() * 440.0; + let mut angle = random() * std::f32::consts::TAU; + let mut points = Vec::with_capacity(121); + points.push(point(px(x), px(y))); + for _ in 0..120 { + angle += (random() - 0.5) * 1.2; + x += angle.cos() * 12.0; + y += angle.sin() * 12.0; + if !(40.0..=900.0).contains(&x) { + angle = std::f32::consts::PI - angle; + x = x.clamp(40.0, 900.0); + } + if !(80.0..=520.0).contains(&y) { + angle = -angle; + y = y.clamp(80.0, 520.0); + } + points.push(point(px(x), px(y))); + } + self.lines.push(points); + } + cx.notify(); + } + + /// Fill the canvas with a grid of strokes, for benchmarking. + fn stress_grid(&mut self, cx: &mut Context) { + self.lines.clear(); + for i in 0..55 { + let y = 80.0 + i as f32 * 8.0; + self.lines + .push(vec![point(px(40.0), px(y)), point(px(900.0), px(y))]); + } + for i in 0..108 { + let x = 40.0 + i as f32 * 8.0; + self.lines + .push(vec![point(px(x), px(80.0)), point(px(x), px(520.0))]); + } + cx.notify(); + } } fn button( @@ -349,6 +402,8 @@ impl Render for PaintingViewer { cx, move |this, _| this.dashed = !dashed, )) + .child(button("Scribble", cx, |this, cx| this.stress_scribble(cx))) + .child(button("Grid", cx, |this, cx| this.stress_grid(cx))) .child(button("Clear", cx, |this, cx| this.clear(cx))), ), ) diff --git a/crates/gpui/examples/paths_bench.rs b/crates/gpui/examples/paths_bench.rs index 236e70e9fcc..6f931995604 100644 --- a/crates/gpui/examples/paths_bench.rs +++ b/crates/gpui/examples/paths_bench.rs @@ -14,7 +14,7 @@ const DEFAULT_WINDOW_WIDTH: Pixels = px(1024.0); const DEFAULT_WINDOW_HEIGHT: Pixels = px(768.0); struct PaintingViewer { - default_lines: Vec<(Path, Background)>, + default_lines: Vec<(Path, Background)>, _painting: bool, } diff --git a/crates/gpui/src/gpui.rs b/crates/gpui/src/gpui.rs index 5b31a3557fb..abd966d750a 100644 --- a/crates/gpui/src/gpui.rs +++ b/crates/gpui/src/gpui.rs @@ -44,6 +44,7 @@ mod interactive; mod key_dispatch; mod keymap; mod path_builder; +mod path_winding; mod platform; mod platform_scheduler; mod scene; @@ -134,6 +135,7 @@ pub use inspector::*; pub use interactive::*; pub use keymap::*; pub use path_builder::*; +pub(crate) use path_winding::*; pub use platform::*; pub use profiler::*; pub use refineable::*; diff --git a/crates/gpui/src/path_builder.rs b/crates/gpui/src/path_builder.rs index 40a6e71e0a1..0e54d0bfd3d 100644 --- a/crates/gpui/src/path_builder.rs +++ b/crates/gpui/src/path_builder.rs @@ -1,17 +1,15 @@ -use anyhow::Error; +use anyhow::{Error, bail}; use etagere::euclid::{Point2D, Vector2D}; -use lyon::geom::Angle; -use lyon::math::{Vector, vector}; -use lyon::path::traits::SvgPathBuilder; -use lyon::path::{ArcFlags, Polygon}; -use lyon::tessellation::{ - BuffersBuilder, FillTessellator, FillVertex, StrokeTessellator, StrokeVertex, VertexBuffers, -}; +use lyon_path::geom::{Angle, CubicBezierSegment, QuadraticBezierSegment}; +use lyon_path::math::{Vector, vector}; +use lyon_path::traits::SvgPathBuilder; +use lyon_path::{ArcFlags, Event, Polygon}; -pub use lyon::math::Transform; -pub use lyon::tessellation::{FillOptions, FillRule, StrokeOptions}; +pub use lyon_path::math::Transform; +pub use lyon_path::{FillRule, LineCap, LineJoin}; -use crate::{Path, Pixels, Point, point, px}; +use crate::{PathCurve, PathTiles, Pixels, Point, point, px}; +use std::sync::Arc; /// Style of the PathBuilder pub enum PathStyle { @@ -21,17 +19,57 @@ pub enum PathStyle { Fill(FillOptions), } +/// How to stroke a path. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StrokeOptions { + /// Width of the stroke. + pub line_width: f32, + /// Shape of the ends of open subpaths and dashes. + pub line_cap: LineCap, + /// Shape of corners. + pub line_join: LineJoin, + /// How long a miter join may get, as a multiple of the line width, + /// before it is beveled instead. + pub miter_limit: f32, +} + +impl Default for StrokeOptions { + fn default() -> Self { + Self { + line_width: 1.0, + line_cap: LineCap::Butt, + line_join: LineJoin::Miter, + miter_limit: 4.0, + } + } +} + +/// How to fill a path. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FillOptions { + /// How overlapping contours combine into the filled region. + pub fill_rule: FillRule, +} + +impl Default for FillOptions { + fn default() -> Self { + Self { + fill_rule: FillRule::EvenOdd, + } + } +} + /// A [`Path`] builder. pub struct PathBuilder { - raw: lyon::path::builder::WithSvg, - transform: Option, + raw: lyon_path::builder::WithSvg, + transform: Option, /// PathStyle of the PathBuilder pub style: PathStyle, dash_array: Option>, } -impl From for PathBuilder { - fn from(builder: lyon::path::Builder) -> Self { +impl From for PathBuilder { + fn from(builder: lyon_path::Builder) -> Self { Self { raw: builder.with_svg(), ..Default::default() @@ -39,8 +77,8 @@ impl From for PathBuilder { } } -impl From> for PathBuilder { - fn from(raw: lyon::path::builder::WithSvg) -> Self { +impl From> for PathBuilder { + fn from(raw: lyon_path::builder::WithSvg) -> Self { Self { raw, ..Default::default() @@ -48,15 +86,15 @@ impl From> for PathBuilder } } -impl From for Point { - fn from(p: lyon::math::Point) -> Self { +impl From for Point { + fn from(p: lyon_path::math::Point) -> Self { point(px(p.x), px(p.y)) } } -impl From> for lyon::math::Point { +impl From> for lyon_path::math::Point { fn from(p: Point) -> Self { - lyon::math::point(p.x.0, p.y.0) + lyon_path::math::point(p.x.0, p.y.0) } } @@ -75,7 +113,7 @@ impl From> for Point2D { impl Default for PathBuilder { fn default() -> Self { Self { - raw: lyon::path::Path::builder().with_svg(), + raw: lyon_path::Path::builder().with_svg(), style: PathStyle::Fill(FillOptions::default()), transform: None, dash_array: None, @@ -87,7 +125,10 @@ impl PathBuilder { /// Creates a new [`PathBuilder`] to build a Stroke path. pub fn stroke(width: Pixels) -> Self { Self { - style: PathStyle::Stroke(StrokeOptions::default().with_line_width(width.0)), + style: PathStyle::Stroke(StrokeOptions { + line_width: width.0, + ..Default::default() + }), ..Self::default() } } @@ -102,7 +143,7 @@ impl PathBuilder { Self { style, ..self } } - /// Sets the dash array of the [`PathBuilder`]. + /// Sets the dash array of the [`PathBuilder`]. Fills ignore it. /// /// [MDN](https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Attribute/stroke-dasharray) pub fn dash_array(mut self, dash_array: &[Pixels]) -> Self { @@ -240,108 +281,297 @@ impl PathBuilder { } /// Builds into a [`Path`]. - #[inline] - pub fn build(self) -> Result, Error> { + pub fn build(self) -> Result { + let (curves, fill_rule) = self.outline()?; + Ok(Path::from_curves(curves, fill_rule)) + } + + /// The closed contours to fill, and the rule to fill them by. + pub(crate) fn outline(self) -> Result<(Vec, FillRule), Error> { let path = if let Some(transform) = self.transform { self.raw.build().transformed(&transform) } else { self.raw.build() }; - match self.style { - PathStyle::Stroke(options) => Self::tessellate_stroke(self.dash_array, &path, &options), - PathStyle::Fill(options) => Self::tessellate_fill(&path, &options), - } + Ok(match self.style { + PathStyle::Stroke(options) => ( + Self::stroke_outline(&path, &options, self.dash_array.as_deref())?, + FillRule::NonZero, + ), + PathStyle::Fill(options) => (Self::fill_outline(&path)?, options.fill_rule), + }) } - fn tessellate_fill( - path: &lyon::path::Path, - options: &FillOptions, - ) -> Result, Error> { - // Will contain the result of the tessellation. - let mut buf: VertexBuffers = VertexBuffers::new(); - let mut tessellator = FillTessellator::new(); - - // Compute the tessellation. - tessellator.tessellate_path( - path, - options, - &mut BuffersBuilder::new(&mut buf, |vertex: FillVertex| vertex.position()), - )?; - - Ok(Self::build_path(buf)) - } - - fn tessellate_stroke( - dash_array: Option>, - path: &lyon::path::Path, + fn stroke_outline( + path: &lyon_path::Path, options: &StrokeOptions, - ) -> Result, Error> { - let path = if let Some(dash_array) = dash_array { - let measurements = lyon::algorithms::measure::PathMeasurements::from_path(path, 0.01); - let mut sampler = measurements - .create_sampler(path, lyon::algorithms::measure::SampleType::Normalized); - let mut builder = lyon::path::Path::builder(); - - let total_length = sampler.length(); - let dash_array_len = dash_array.len(); - let mut pos = 0.; - let mut dash_index = 0; - while pos < total_length { - let dash_length = dash_array[dash_index % dash_array_len].0; - let next_pos = (pos + dash_length).min(total_length); - if dash_index % 2 == 0 { - let start = pos / total_length; - let end = next_pos / total_length; - sampler.split_range(start..end, &mut builder); + dash_array: Option<&[Pixels]>, + ) -> Result, Error> { + let outline = skia_path(path) + .map(|skia_path| match dash_array { + Some(dash_array) => { + let array = dash_array.iter().map(|length| length.0).collect(); + match tiny_skia_path::StrokeDash::new(array, 0.0) { + Some(dash) => skia_path + .dash(&dash, STROKE_RESOLUTION_SCALE) + .unwrap_or(skia_path), + // An invalid dash array strokes undashed, as in SVG. + None => skia_path, + } } - pos = next_pos; - dash_index += 1; - } - - &builder.build() - } else { - path + None => skia_path, + }) + .and_then(|skia_path| { + skia_path.stroke( + &tiny_skia_path::Stroke { + width: options.line_width, + miter_limit: options.miter_limit, + line_cap: match options.line_cap { + LineCap::Butt => tiny_skia_path::LineCap::Butt, + LineCap::Square => tiny_skia_path::LineCap::Square, + LineCap::Round => tiny_skia_path::LineCap::Round, + }, + line_join: match options.line_join { + LineJoin::Miter => tiny_skia_path::LineJoin::Miter, + LineJoin::MiterClip => tiny_skia_path::LineJoin::MiterClip, + LineJoin::Round => tiny_skia_path::LineJoin::Round, + LineJoin::Bevel => tiny_skia_path::LineJoin::Bevel, + }, + dash: None, + }, + STROKE_RESOLUTION_SCALE, + ) + }); + let Some(outline) = outline else { + return Ok(Vec::new()); }; - // Will contain the result of the tessellation. - let mut buf: VertexBuffers = VertexBuffers::new(); - let mut tessellator = StrokeTessellator::new(); - - // Compute the tessellation. - tessellator.tessellate_path( - path, - options, - &mut BuffersBuilder::new(&mut buf, |vertex: StrokeVertex| vertex.position()), - )?; - - Ok(Self::build_path(buf)) + let mut output = Outline::default(); + let at = |p: tiny_skia_path::Point| point(p.x, p.y); + for segment in outline.segments() { + match segment { + tiny_skia_path::PathSegment::MoveTo(p) => output.move_to(at(p)), + tiny_skia_path::PathSegment::LineTo(p) => output.line_to(at(p)), + tiny_skia_path::PathSegment::QuadTo(ctrl, p) => output.curve_to(at(p), at(ctrl)), + tiny_skia_path::PathSegment::CubicTo(ctrl1, ctrl2, p) => { + output.cubic_to(at(p), at(ctrl1), at(ctrl2)) + } + tiny_skia_path::PathSegment::Close => output.close(), + } + } + output.into_curves() } - /// Builds a [`Path`] from a [`lyon::tessellation::VertexBuffers`]. - pub fn build_path(buf: VertexBuffers) -> Path { - if buf.vertices.is_empty() { - return Path::new(Point::default()); + /// Convert a lyon path into a fill, closing every subpath. + fn fill_outline(path: &lyon_path::Path) -> Result, Error> { + let mut output = Outline::default(); + let at = |p: lyon_path::math::Point| point(p.x, p.y); + for event in path.iter() { + match event { + Event::Begin { at: p } => output.move_to(at(p)), + Event::Line { to, .. } => output.line_to(at(to)), + Event::Quadratic { ctrl, to, .. } => output.curve_to(at(to), at(ctrl)), + Event::Cubic { + ctrl1, ctrl2, to, .. + } => output.cubic_to(at(to), at(ctrl1), at(ctrl2)), + Event::End { .. } => output.close(), + } } - - let first_point = buf.vertices[0]; - - let mut path = Path::new(first_point.into()); - for i in 0..buf.indices.len() / 3 { - let i0 = buf.indices[i * 3] as usize; - let i1 = buf.indices[i * 3 + 1] as usize; - let i2 = buf.indices[i * 3 + 2] as usize; - - let v0 = buf.vertices[i0]; - let v1 = buf.vertices[i1]; - let v2 = buf.vertices[i2]; - - path.push_triangle( - (v0.into(), v1.into(), v2.into()), - (point(0., 1.), point(0., 1.), point(0., 1.)), - ); - } - - path + output.into_curves() } } + +/// A filled path, ready to paint. Build one with [`PathBuilder`]. +#[derive(Clone, Debug)] +pub struct Path { + /// Closed contours of monotone curves, in logical pixels. + curves: Arc<[PathCurve]>, + even_odd: bool, +} + +impl Path { + pub(crate) fn from_curves(curves: Vec, fill_rule: FillRule) -> Self { + Self { + curves: curves.into(), + even_odd: matches!(fill_rule, FillRule::EvenOdd), + } + } + + pub(crate) fn even_odd(&self) -> bool { + self.even_odd + } + + /// Bin the curves into tiles in device pixels, for painting at the given + /// display scale. + pub(crate) fn bin(&self, scale: f32) -> PathTiles { + crate::path_winding::bin(&self.curves, self.even_odd, scale) + } +} + +/// A path's contours as monotone curves, collected by [`PathBuilder`]. +#[derive(Default)] +pub(crate) struct Outline { + curves: Vec, + start: Point, + current: Point, + non_finite: bool, +} + +impl Outline { + /// Whether segments through these points can be added. + fn accepts(&mut self, points: &[Point]) -> bool { + self.non_finite |= !points + .iter() + .all(|point| point.x.is_finite() && point.y.is_finite()); + !self.non_finite + } + + /// Close the current contour and start a new one at the given point. + pub(crate) fn move_to(&mut self, to: Point) { + if !self.accepts(&[to]) { + return; + } + self.close(); + self.start = to; + self.current = to; + } + + pub(crate) fn line_to(&mut self, to: Point) { + if self.accepts(&[to]) && to != self.current { + self.curves.push(PathCurve::line(self.current, to)); + self.current = to; + } + } + + pub(crate) fn curve_to(&mut self, to: Point, ctrl: Point) { + if !self.accepts(&[to, ctrl]) || (to == self.current && ctrl == self.current) { + return; + } + PathCurve::push_monotone(&mut self.curves, self.current, ctrl, to); + self.current = to; + } + + pub(crate) fn cubic_to(&mut self, to: Point, ctrl1: Point, ctrl2: Point) { + /// Maximum error, in logical pixels. + const TOLERANCE: f32 = 0.25; + if !self.accepts(&[to, ctrl1, ctrl2]) { + return; + } + let lyon_point = |p: Point| lyon_path::math::point(p.x, p.y); + let cubic = CubicBezierSegment { + from: lyon_point(self.current), + ctrl1: lyon_point(ctrl1), + ctrl2: lyon_point(ctrl2), + to: lyon_point(to), + }; + cubic.for_each_quadratic_bezier(TOLERANCE, &mut |quadratic| { + self.curve_to( + point(quadratic.to.x, quadratic.to.y), + point(quadratic.ctrl.x, quadratic.ctrl.y), + ); + }); + } + + /// Close the current contour with a straight line back to its start. + pub(crate) fn close(&mut self) { + let start = self.start; + self.line_to(start); + } + + /// The curves, with every contour closed. + pub(crate) fn into_curves(mut self) -> Result, Error> { + if self.non_finite { + bail!("path has a non-finite point"); + } + self.close(); + Ok(self.curves) + } +} + +impl PathCurve { + fn new(p0: Point, ctrl: Point, p1: Point, sign: f32) -> Self { + Self { + p0, + p1, + a: point(p0.x - 2.0 * ctrl.x + p1.x, p0.y - 2.0 * ctrl.y + p1.y), + b: point(2.0 * (ctrl.x - p0.x), 2.0 * (ctrl.y - p0.y)), + sign, + pad: 0, + } + } + + /// A line, with exactly zero quadratic terms. + fn line(from: Point, to: Point) -> Self { + let (p0, p1, sign) = downward(from, to); + Self { + p0, + p1, + a: point(0.0, 0.0), + b: point(p1.x - p0.x, p1.y - p0.y), + sign, + pad: 0, + } + } + + /// Split a quadratic segment at its extrema into xy-monotone curves. + fn push_monotone(curves: &mut Vec, p0: Point, ctrl: Point, p1: Point) { + let curve = QuadraticBezierSegment { + from: lyon_path::math::point(p0.x, p0.y), + ctrl: lyon_path::math::point(ctrl.x, ctrl.y), + to: lyon_path::math::point(p1.x, p1.y), + }; + // Unlike `split_range`, this also clamps each piece's control point + // back into its endpoint box when rounding pushes it out. + curve.for_each_monotonic(&mut |monotone| { + let from = point(monotone.from.x, monotone.from.y); + let to = point(monotone.to.x, monotone.to.y); + if from == to { + return; + } + // Horizontal curves are kept: upward rays cross them. + let (p0, p1, sign) = downward(from, to); + let ctrl = point( + monotone.ctrl.x.clamp(p0.x.min(p1.x), p0.x.max(p1.x)), + monotone.ctrl.y.clamp(p0.y, p1.y), + ); + curves.push(Self::new(p0, ctrl, p1, sign)); + }); + } +} + +fn downward(from: Point, to: Point) -> (Point, Point, f32) { + if from.y > to.y { + (to, from, -1.0) + } else { + (from, to, 1.0) + } +} + +/// Strokes are expanded in logical pixels. tiny-skia keeps offset curves +/// within `0.25 / STROKE_RESOLUTION_SCALE` of exact, a quarter device pixel at +/// 2x, and flattens curves to within `0.5 / STROKE_RESOLUTION_SCALE` to measure +/// dashes. Round joins and caps ignore it: their arcs are approximated to 0.25 +/// logical pixels. +const STROKE_RESOLUTION_SCALE: f32 = 2.0; + +/// Returns [`None`] for empty geometry. +fn skia_path(path: &lyon_path::Path) -> Option { + let mut builder = tiny_skia_path::PathBuilder::new(); + for event in path.iter() { + match event { + Event::Begin { at } => builder.move_to(at.x, at.y), + Event::Line { to, .. } => builder.line_to(to.x, to.y), + Event::Quadratic { ctrl, to, .. } => builder.quad_to(ctrl.x, ctrl.y, to.x, to.y), + Event::Cubic { + ctrl1, ctrl2, to, .. + } => builder.cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y), + Event::End { close, .. } => { + if close { + builder.close(); + } + } + } + } + builder.finish() +} diff --git a/crates/gpui/src/path_winding.rs b/crates/gpui/src/path_winding.rs new file mode 100644 index 00000000000..5fe10dc197a --- /dev/null +++ b/crates/gpui/src/path_winding.rs @@ -0,0 +1,842 @@ +//! Path fills by per-pixel winding. +//! +//! [`PathBuilder`](crate::PathBuilder) turns contours into closed chains of +//! monotone quadratic curves. To paint the resulting [`Path`](crate::Path), we compute the +//! winding number at each pixel on the GPU, as in Eric Lengyel's Slug: we +//! cast rays leftward and upward from the pixel and count crossings with the +//! path's curves. Crossings within the pixel contribute partial winding to +//! approximate coverage across its area. Coverage is then determined by the +//! fill rule. +//! +//! To reduce the number of curves tested against each ray, we preprocess the +//! path on the CPU, binning its curves into square cells. Each cell lists the +//! curves intersecting or near it. The cell size is chosen per path to balance +//! the cost of binning against the cost of shading (see `cell_size`). +//! +//! Curves outside a cell's list cannot contribute partial winding, so the +//! binner sums their winding contributions along a leftward ray from the +//! cell's top-left corner into a *backdrop*. For each pixel, the shader starts +//! with this backdrop and adds the contributions of the listed curves. It also +//! corrects the backdrop to account for unlisted curves' contribution between the +//! corner and the pixel. +//! +//! Neighboring cells with the same curve list and backdrop are merged into +//! rectangular [`PathTile`]s, which are uploaded to and drawn by the GPU. For +//! example, a large rectangle can become nine tiles: four corners, four edges, +//! and an interior. + +use crate::{Bounds, PathCurve, PathTile, Point, ScaledPixels, point}; +use std::cell::RefCell; + +/// A tile lists every curve within this distance of its bounds. Any other curve +/// is more than half a pixel away from the tile, so it cannot contribute partial winding. +/// The extra 1/256 covers the rasterizer snapping tile edges to its subpixel grid. +const MARGIN: f32 = 0.5 + 1.0 / 256.0; + +/// `f32::min`, `max` and `clamp` without IEEE-compliant NaN handling, which costs a +/// compare and blend per call on x86-64's baseline target. +trait FastFloat { + fn fast_min(self, other: f32) -> f32; + fn fast_max(self, other: f32) -> f32; + fn fast_clamp(self, min: f32, max: f32) -> f32; +} + +impl FastFloat for f32 { + #[inline(always)] + fn fast_min(self, other: f32) -> f32 { + if self < other { self } else { other } + } + + #[inline(always)] + fn fast_max(self, other: f32) -> f32 { + if self > other { self } else { other } + } + + #[inline(always)] + fn fast_clamp(self, min: f32, max: f32) -> f32 { + self.fast_max(min).fast_min(max) + } +} + +/// A path's curves binned into tiles for one display scale. +#[derive(Debug, Default)] +pub(crate) struct PathTiles { + bounds: Bounds, + tiles: Vec, + /// Every tile's curve list, concatenated. + curves: Vec, +} + +impl PathTiles { + pub(crate) fn bounds(&self) -> Bounds { + self.bounds + } + + pub(crate) fn painted_bounds(&self) -> Bounds { + if self.tiles.is_empty() { + return self.bounds; + } + self.bounds.dilate(ScaledPixels(MARGIN)) + } + + pub(crate) fn tiles(&self) -> &[PathTile] { + &self.tiles + } + + pub(crate) fn curves(&self) -> &[PathCurve] { + &self.curves + } + + /// Drops the tiles that lie entirely outside `mask`. + pub(crate) fn retain_visible(&mut self, mask: Bounds) { + self.tiles.retain(|tile| { + tile.top_left.x < mask.right().0 + && tile.top_left.y < mask.bottom().0 + && tile.bottom_right.x > mask.origin.x.0 + && tile.bottom_right.y > mask.origin.y.0 + }); + } +} + +pub(crate) fn bin(curves: &[PathCurve], even_odd: bool, scale: f32) -> PathTiles { + debug_assert!(scale > 0.0 && scale.is_finite(), "invalid scale {scale}"); + if curves.is_empty() { + return PathTiles::default(); + } + BINNER.with_borrow_mut(|binner| { + let (min, max, length) = binner.scale(curves, scale); + let Some(grid) = Grid::covering(min, max, curves.len(), length) else { + log::warn!("path spanning {min:?} to {max:?} device pixels overflows; skipping"); + return PathTiles::default(); + }; + binner.find_spans(&grid); + binner.fill_cells(); + let (tiles, curves) = binner.merge_cells(&grid, even_odd); + let device = |p: Point| point(ScaledPixels(p.x), ScaledPixels(p.y)); + PathTiles { + bounds: Bounds::from_corners(device(min), device(max)), + tiles, + curves, + } + }) +} + +/// Picks the power-of-two cell size that minimizes the estimated time spent +/// binning and shading. Smaller cells list each curve in more cells, which +/// costs CPU time. Larger cells make the shader evaluate each listed curve at +/// more pixels, which costs GPU time. +/// +/// We estimate the binning and shading time by the following cost model, +/// expressed in terms of shader evaluations of one curve at one pixel: +/// +/// ```text +/// cost = listings * (LISTING_CPU_COST + area) + empty_cells * EMPTY_CELL_CPU_COST +/// ``` +fn cell_size(curves: f32, length: f32, size: Point) -> f32 { + // The CPU time of a listing and an empty cell, in shader evaluations, + // measured about 634 and 207 on a desktop (RX 6600) and 68 and 21 on an + // integrated GPU (HD 4600). Of the values in between, these lost the least + // on either machine, measuring CPU and GPU time on realistic paths. Walking + // a cell that lists curves has no cost: giving it one made dashed lines use + // larger cells, which cost far more GPU time than it saved on the CPU. + const LISTING_CPU_COST: f32 = 320.0; + const EMPTY_CELL_CPU_COST: f32 = 95.0; + // Smaller cells save GPU time, but on realistic paths they measured + // costing more CPU time than they saved, on both machines. + const MIN_CELL_SIZE: f32 = 16.0; + // Limits the grid's memory and walking time when the estimate undercounts + // empty cells, as when most curves crowd into a few cells of a large path. + const MAX_GRID_CELLS: f32 = 4096.0; + + let grid_cells = |cell_size: f32| { + ((size.x / cell_size).floor() + 1.0) * ((size.y / cell_size).floor() + 1.0) + }; + let extent = size.x.fast_max(size.y); + let mut cell_size = MIN_CELL_SIZE; + while grid_cells(cell_size) > MAX_GRID_CELLS { + cell_size *= 2.0; + } + let mut best = (f32::INFINITY, cell_size); + loop { + let listings = if cell_size >= extent { + curves + } else { + // Since curves are monotone, each crosses about `(w + h) / cell_size` grid lines. + curves + length / cell_size + }; + let area = cell_size.fast_min(size.x) * cell_size.fast_min(size.y) / 2.0; + let empty_cells = (grid_cells(cell_size) - listings).fast_max(0.0); + let cost = listings * (LISTING_CPU_COST + area) + empty_cells * EMPTY_CELL_CPU_COST; + if cost < best.0 { + best = (cost, cell_size); + } + if cell_size >= extent { + return best.1; + } + cell_size *= 2.0; + } +} + +fn fills(winding: i32, even_odd: bool) -> bool { + if even_odd { + winding % 2 != 0 + } else { + winding != 0 + } +} + +#[derive(Default)] +struct Binner { + /// The path's curves, scaled into device pixels. + input: Vec, + spans: Vec, + /// Per cell, where its list ends in `keys`. Reused while binning, as in a + /// counting sort: `find_spans` stores each cell's count here, and + /// `fill_cells` turns the counts into starts and advances them as it + /// fills each list. + cell_ends: Vec, + /// Per cell, the winding steps of curves crossing its row's top to its + /// left, other than those it lists. + steps: Vec, + /// Each cell's listings: a curve's leftmost x above its index. + keys: Vec, + /// The current row's runs. + runs: Vec, + /// The previous row's runs, whose tiles the current row can extend down. + above: Vec, +} + +thread_local! { + static BINNER: RefCell = Default::default(); +} + +/// A curve's run of consecutive cells within a row. +struct Span { + cell: usize, + count: usize, + key: u64, +} + +impl Binner { + fn scale(&mut self, curves: &[PathCurve], scale: f32) -> (Point, Point, f32) { + let mut min = point(f32::INFINITY, f32::INFINITY); + let mut max = point(f32::NEG_INFINITY, f32::NEG_INFINITY); + let mut length = 0.0; + self.input.clear(); + self.input.extend(curves.iter().map(|curve| { + let curve = curve.scaled(scale); + // The extents of a monotone curve can be computed from its endpoints. + min.x = min.x.fast_min(curve.min_x()); + max.x = max.x.fast_max(curve.max_x()); + min.y = min.y.fast_min(curve.p0.y); + max.y = max.y.fast_max(curve.p1.y); + length += curve.max_x() - curve.min_x() + curve.p1.y - curve.p0.y; + curve + })); + (min, max, length) + } + + fn find_spans(&mut self, grid: &Grid) { + let cells = grid.rows * grid.columns; + self.spans.clear(); + self.cell_ends.clear(); + self.cell_ends.resize(cells, 0); + self.steps.clear(); + self.steps.resize(cells, 0); + for (index, curve) in self.input.iter().enumerate() { + // This key sorts curves by leftmost x, which is used by the shader's early exit; + // then by index, so that curves are totally ordered. + let key = u64::from(ordered_bits(curve.min_x())) << 32 | index as u64; + for row in grid.row_of(curve.p0.y - MARGIN)..=grid.row_of(curve.p1.y + MARGIN) { + let row_top = grid.y(row); + let (low, high) = curve.x_range(row_top - MARGIN, grid.y(row + 1) + MARGIN); + let first = grid.column_of(low - MARGIN); + let last = grid.column_of(high + MARGIN); + let cell = row * grid.columns + first; + let count = last + 1 - first; + self.spans.push(Span { cell, count, key }); + for listings in self + .cell_ends + .get_mut(cell..cell + count) + .unwrap_or_default() + { + *listings += 1; + } + + // If this curve contributes to cell backdrops, record its contribution + // in the first cell to the right of its span. + if curve.crosses(row_top) + && last + 1 < grid.columns + && let Some(step) = self.steps.get_mut(cell + count) + { + *step += curve.step(); + } + } + } + } + + fn fill_cells(&mut self) { + let mut total = 0; + for end in self.cell_ends.iter_mut() { + let count = *end; + *end = total; + total += count; + } + self.keys.clear(); + self.keys.resize(total, 0); + for span in &self.spans { + for cursor in self + .cell_ends + .get_mut(span.cell..span.cell + span.count) + .unwrap_or_default() + { + if let Some(key) = self.keys.get_mut(*cursor) { + *key = span.key; + } + *cursor += 1; + } + } + let mut start = 0; + for &end in &self.cell_ends { + self.keys + .get_mut(start..end) + .unwrap_or_default() + .sort_unstable(); + start = end; + } + } + + fn merge_cells(&mut self, grid: &Grid, even_odd: bool) -> (Vec, Vec) { + let Binner { + input, + steps, + cell_ends, + keys, + runs, + above, + .. + } = self; + let mut tiles: Vec = Vec::new(); + // Each listing is copied at most once. + let mut curves = Vec::with_capacity(keys.len()); + above.clear(); + let mut cell_start = 0; + for row in 0..grid.rows { + runs.clear(); + let mut backdrop = 0; + for column in 0..grid.columns { + let index = row * grid.columns + column; + backdrop += steps.get(index).copied().unwrap_or(0); + let cell_end = cell_ends.get(index).copied().unwrap_or(cell_start); + let list = (cell_start, cell_end); + cell_start = cell_end; + + let cell = grid.cell(column, row); + let quad = if list.0 == list.1 { + fills(backdrop, even_odd).then(|| (cell.top_left(), cell.bottom_right())) + } else { + let mut measure = Measure::new(cell, backdrop); + for curve in listed(keys, input, list) { + measure.add(curve); + } + measure.quad(even_odd) + }; + let Some((top_left, bottom_right)) = quad else { + continue; + }; + let run = Run { + start: column, + end: column + 1, + backdrop, + list, + top_left, + bottom_right, + tile: 0, + }; + match runs.last_mut() { + Some(last) if last.end == run.start && last.shades_like(&run, keys) => { + last.end = run.end; + extend_quad(&mut last.top_left, &mut last.bottom_right, &run); + } + _ => runs.push(run), + } + } + + // Both rows' runs are in column order. + let mut above_runs = above.iter().peekable(); + for run in runs.iter_mut() { + while above_runs + .next_if(|other| other.start < run.start) + .is_some() + {} + let matching = above_runs.next_if(|other| { + other.start == run.start && other.end == run.end && other.shades_like(run, keys) + }); + run.tile = match matching { + Some(above_run) => { + if let Some(tile) = tiles.get_mut(above_run.tile) { + extend_quad(&mut tile.top_left, &mut tile.bottom_right, run); + } + above_run.tile + } + None => { + let curve_start = curves.len(); + // Tiles are trimmed to their curves' extents, so the path is known to be + // filled for pixels outside this box. + let mut curves_top_left = point(f32::INFINITY, f32::INFINITY); + let mut curves_bottom_right = point(f32::NEG_INFINITY, f32::NEG_INFINITY); + for curve in listed(keys, input, run.list) { + // The rasterizer snaps tile edges to its subpixel grid, so it can + // shade a pixel just outside a tile. Where the tile is trimmed, that + // pixel would also be outside the box, and be wrongly filled. Dilate + // the box by more than the largest snapping error to prevent this. + const BOX_MARGIN: f32 = MARGIN + 1.0 / 16.0; + + curves_top_left.x = + curves_top_left.x.fast_min(curve.min_x() - BOX_MARGIN); + curves_top_left.y = curves_top_left.y.fast_min(curve.p0.y - BOX_MARGIN); + curves_bottom_right.x = + curves_bottom_right.x.fast_max(curve.max_x() + BOX_MARGIN); + curves_bottom_right.y = + curves_bottom_right.y.fast_max(curve.p1.y + BOX_MARGIN); + curves.push(*curve); + } + tiles.push(PathTile { + paint: 0, + curve_start: curve_start as u32, + curve_count: (curves.len() - curve_start) as u32, + top_left: run.top_left, + bottom_right: run.bottom_right, + reference: grid.cell(run.start, row).top_left(), + backdrop: run.backdrop, + curves_top_left, + curves_bottom_right, + }); + tiles.len() - 1 + } + }; + } + std::mem::swap(above, runs); + } + (tiles, curves) + } +} + +/// Maps finite floats to integers in the same order. +fn ordered_bits(x: f32) -> u32 { + let bits = x.to_bits(); + if bits >> 31 == 1 { + !bits + } else { + bits | 1 << 31 + } +} + +/// Consecutive cells in a row, over columns `start..end`, that would be +/// shaded identically. +#[derive(Clone, Copy)] +struct Run { + start: usize, + end: usize, + backdrop: i32, + /// The cells' list, as a range of `keys`. + list: (usize, usize), + top_left: Point, + bottom_right: Point, + tile: usize, +} + +impl Run { + /// Whether the two have the same backdrop and list the same curves. + fn shades_like(&self, other: &Run, keys: &[u64]) -> bool { + self.backdrop == other.backdrop + && keys.get(self.list.0..self.list.1) == keys.get(other.list.0..other.list.1) + } +} + +/// Grows a quad to cover a run's quad. +fn extend_quad(top_left: &mut Point, bottom_right: &mut Point, run: &Run) { + top_left.x = top_left.x.fast_min(run.top_left.x); + top_left.y = top_left.y.fast_min(run.top_left.y); + bottom_right.x = bottom_right.x.fast_max(run.bottom_right.x); + bottom_right.y = bottom_right.y.fast_max(run.bottom_right.y); +} + +/// The curves in a range of `keys`. +fn listed<'a>( + keys: &'a [u64], + input: &'a [PathCurve], + list: (usize, usize), +) -> impl Iterator { + keys.get(list.0..list.1) + .unwrap_or_default() + .iter() + .filter_map(move |&key| input.get(key as u32 as usize)) +} + +struct Grid { + left: f32, + top: f32, + cell_size: f32, + columns: usize, + rows: usize, +} + +impl Grid { + fn covering(min: Point, max: Point, curves: usize, length: f32) -> Option { + let left = (min.x - MARGIN).floor(); + let top = (min.y - MARGIN).floor(); + let size = point(max.x + MARGIN - left, max.y + MARGIN - top); + if !(size.x.is_finite() && size.y.is_finite()) { + return None; + } + let cell_size = cell_size(curves as f32, length, size); + Some(Self { + left, + top, + cell_size, + columns: (size.x / cell_size) as usize + 1, + rows: (size.y / cell_size) as usize + 1, + }) + } + + fn column_of(&self, x: f32) -> usize { + let column = (x - self.left) / self.cell_size; + column.fast_clamp(0.0, (self.columns - 1) as f32) as u32 as usize + } + + fn row_of(&self, y: f32) -> usize { + let row = (y - self.top) / self.cell_size; + row.fast_clamp(0.0, (self.rows - 1) as f32) as u32 as usize + } + + fn x(&self, column: usize) -> f32 { + self.left + column as f32 * self.cell_size + } + + fn y(&self, row: usize) -> f32 { + self.top + row as f32 * self.cell_size + } + + fn cell(&self, column: usize, row: usize) -> Cell { + Cell { + left: self.x(column), + top: self.y(row), + right: self.x(column + 1), + bottom: self.y(row + 1), + } + } +} + +#[derive(Clone, Copy)] +struct Cell { + left: f32, + top: f32, + right: f32, + bottom: f32, +} + +impl Cell { + fn top_left(self) -> Point { + point(self.left, self.top) + } + + fn bottom_right(self) -> Point { + point(self.right, self.bottom) + } +} + +/// Accumulates the bounds and windings of a cell's curves, to trim its quad. +struct Measure { + cell: Cell, + backdrop: i32, + min: Point, + max: Point, + /// Left of and above every curve, no correction applies, so the winding + /// is the backdrop. Right of every curve, it is the backdrop plus the + /// curves crossing the cell's top; below every curve, the backdrop + /// corrected for the endpoints beside the cell's left edge. + right_winding: i32, + bottom_winding: i32, +} + +impl Measure { + fn new(cell: Cell, backdrop: i32) -> Self { + Self { + cell, + backdrop, + min: point(f32::INFINITY, f32::INFINITY), + max: point(f32::NEG_INFINITY, f32::NEG_INFINITY), + right_winding: backdrop, + bottom_winding: backdrop, + } + } + + #[inline(always)] + fn add(&mut self, curve: &PathCurve) { + let cell = self.cell; + self.min.x = self.min.x.fast_min(curve.min_x()); + self.max.x = self.max.x.fast_max(curve.max_x()); + self.min.y = self.min.y.fast_min(curve.p0.y); + self.max.y = self.max.y.fast_max(curve.p1.y); + if curve.crosses(cell.top) { + self.right_winding += curve.step(); + } + for (endpoint, step) in curve.endpoints() { + if endpoint.x <= cell.left && endpoint.y > cell.top { + self.bottom_winding -= step; + } + } + } + + /// The top-left and bottom-right corners of the quad to shade, if any: + /// the cell, trimmed to within `MARGIN` of the curves on each side where + /// the winding beyond them leaves pixels unfilled. + #[inline(always)] + fn quad(&self, even_odd: bool) -> Option<(Point, Point)> { + let cell = self.cell; + let clamp_x = |x: f32| x.fast_clamp(cell.left, cell.right); + let clamp_y = |y: f32| y.fast_clamp(cell.top, cell.bottom); + let unfilled = !fills(self.backdrop, even_odd); + let left = if unfilled { + clamp_x(self.min.x - MARGIN) + } else { + cell.left + }; + let top = if unfilled { + clamp_y(self.min.y - MARGIN) + } else { + cell.top + }; + let right = if fills(self.right_winding, even_odd) { + cell.right + } else { + clamp_x(self.max.x + MARGIN) + }; + let bottom = if fills(self.bottom_winding, even_odd) { + cell.bottom + } else { + clamp_y(self.max.y + MARGIN) + }; + (left < right && top < bottom).then(|| (point(left, top), point(right, bottom))) + } +} + +impl PathCurve { + fn scaled(&self, scale: f32) -> Self { + let scale_point = |p: Point| point(p.x * scale, p.y * scale); + Self { + p0: scale_point(self.p0), + p1: scale_point(self.p1), + a: scale_point(self.a), + b: scale_point(self.b), + sign: self.sign, + pad: 0, + } + } + + fn min_x(&self) -> f32 { + self.p0.x.fast_min(self.p1.x) + } + + fn max_x(&self) -> f32 { + self.p0.x.fast_max(self.p1.x) + } + + fn step(&self) -> i32 { + if self.sign < 0.0 { -1 } else { 1 } + } + + /// Whether the curve crosses the horizontal line at `y`. It's half-open, + /// so where two curves meet on the line, exactly one of them crosses it. + fn crosses(&self, y: f32) -> bool { + self.p0.y <= y && y < self.p1.y + } + + /// Each endpoint with the step the shader corrects for it. + fn endpoints(&self) -> [(Point, i32); 2] { + [(self.p0, self.step()), (self.p1, -self.step())] + } + + /// The curve's x extent between two heights. + fn x_range(&self, top: f32, bottom: f32) -> (f32, f32) { + let top = top.fast_max(self.p0.y); + let bottom = bottom.fast_min(self.p1.y); + let x_top = if top <= self.p0.y { + self.p0.x + } else { + self.x_at_y(top) + }; + let x_bottom = if bottom >= self.p1.y { + self.p1.x + } else { + self.x_at_y(bottom) + }; + // Clamped so rounding can't carry the range past the curve's extent. + ( + x_top.fast_min(x_bottom).fast_max(self.min_x()), + x_top.fast_max(x_bottom).fast_min(self.max_x()), + ) + } + + fn x_at_y(&self, y: f32) -> f32 { + if self.a.y == 0.0 { + if self.b.y == 0.0 { + return self.p0.x; + } + let t = ((y - self.p0.y) / self.b.y).fast_clamp(0.0, 1.0); + return (self.a.x * t + self.b.x) * t + self.p0.x; + } + let t = monotone_quadratic_root(self.a.y, self.b.y, self.p0.y - y, 1.0); + (self.a.x * t + self.b.x) * t + self.p0.x + } +} + +/// Solves a*t^2 + b*t + c = 0 for the root in [0, 1] on a monotone piece. +fn monotone_quadratic_root(a: f32, b: f32, c: f32, direction: f32) -> f32 { + let discriminant = (b * b - 4.0 * a * c).fast_max(0.0); + let denominator = b + direction * discriminant.sqrt(); + if denominator == 0.0 { + return 0.0; + } + (-2.0 * c / denominator).fast_clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + ContentMask, Outline, PaintedPath, Path, PathBuilder, Pixels, Scene, black, px, size, + }; + + /// A rectangle spanning many cells is four edge strips, four corners and + /// one interior, however many cells it covers. + #[test] + fn rectangle_is_nine_tiles() { + let path = square(100., 40., 900., 600.); + assert_eq!(path.bin(1.25).tiles().len(), 9); + } + + /// A path far larger than the window is binned coarsely, and painting it + /// keeps only the tiles its clip shows. + #[test] + fn huge_path_paints_only_visible_tiles() { + let path = square(-20000., -20000., 20000., 20000.); + let tile_count = path.bin(1.5).tiles().len(); + assert!(tile_count < 10_000, "{tile_count} tiles"); + + let mask = Bounds { + origin: point(px(300.), px(200.)), + size: size(px(120.), px(90.)), + }; + let mut scene = Scene::default(); + scene.insert_primitive(PaintedPath::new( + path, + 1.5, + ContentMask { bounds: mask }, + black().into(), + )); + scene.finish(); + let painted: usize = scene.paths.iter().map(PaintedPath::tile_count).sum(); + assert!(painted > 0 && painted < 20, "{painted} tiles"); + } + + /// A path whose size overflows, at some scale or at any, is skipped. + #[test] + fn overflowing_paths_are_skipped() { + let radius = f32::MAX / 4.0; + let path = square(-radius, -radius, radius, radius); + assert!(!path.bin(1.0).tiles().is_empty()); + assert!(path.bin(4.0).tiles().is_empty()); + let radius = f32::MAX * 0.75; + let path = square(-radius, -radius, radius, radius); + assert!(path.bin(1.0).tiles().is_empty()); + } + + /// A non-finite point fails the whole path. Dropping only its segments + /// would leave its contour open. + #[test] + fn non_finite_point_fails_path() { + // Built directly, since lyon asserts its points are finite in debug + // builds. + let mut outline = Outline::default(); + outline.move_to(point(0., 0.)); + outline.line_to(point(10., 0.)); + outline.line_to(point(10., 10.)); + outline.move_to(point(20., 0.)); + outline.line_to(point(f32::NAN, 5.)); + outline.line_to(point(30., 10.)); + assert!(outline.into_curves().is_err()); + } + + /// The shader's backdrop corrections need curves that meet to share + /// bit-identical endpoints. A break shows up as streaks, not as a + /// failure, so check it directly. + #[test] + fn endpoints_balance() { + let mut curved_fill = PathBuilder::fill(); + curved_fill.move_to(point(px(450.3), px(280.7))); + curved_fill.curve_to(point(px(530.3), px(230.7)), point(px(450.3), px(230.7))); + curved_fill.arc_to( + point(px(30.), px(30.)), + px(0.), + false, + false, + point(px(590.3), px(230.7)), + ); + curved_fill.close(); + + let mut stroke = PathBuilder::stroke(px(2.)); + stroke.move_to(point(px(80.3), px(500.7))); + stroke.cubic_bezier_to( + point(px(900.), px(250.)), + point(px(300.), px(50.)), + point(px(700.), px(800.)), + ); + + let mut dashed = PathBuilder::stroke(px(3.)).dash_array(&[px(9.), px(4.)]); + dashed.move_to(point(px(50.3), px(10.7))); + dashed.arc_to( + point(px(40.), px(40.)), + px(0.), + false, + true, + point(px(90.3), px(50.7)), + ); + + for (name, builder) in [ + ("curved fill", curved_fill), + ("stroke", stroke), + ("dashed stroke", dashed), + ] { + let (curves, _) = builder.outline().unwrap(); + let mut balance = collections::HashMap::<(u32, u32), i32>::default(); + for curve in &curves { + for (endpoint, step) in curve.endpoints() { + *balance + .entry((endpoint.x.to_bits(), endpoint.y.to_bits())) + .or_default() += step; + } + } + assert!(!balance.is_empty(), "{name} produced no curves"); + for ((x, y), sum) in balance { + assert_eq!( + sum, + 0, + "{name}: endpoints at ({}, {}) do not balance", + f32::from_bits(x), + f32::from_bits(y), + ); + } + } + } + + fn square(left: f32, top: f32, right: f32, bottom: f32) -> Path { + let mut builder = PathBuilder::fill(); + let corners = [(left, top), (right, top), (right, bottom), (left, bottom)]; + let points: Vec> = + corners.iter().map(|&(x, y)| point(px(x), px(y))).collect(); + builder.add_polygon(&points, true); + builder.build().unwrap() + } +} diff --git a/crates/gpui/src/randomized_element_tree.rs b/crates/gpui/src/randomized_element_tree.rs index 6b2ad69c8be..412aa063f59 100644 --- a/crates/gpui/src/randomized_element_tree.rs +++ b/crates/gpui/src/randomized_element_tree.rs @@ -1699,8 +1699,8 @@ mod tests { #[derive(Debug, PartialEq)] struct SceneSnapshot { quads: Vec, - /// Every other primitive kind, formatted without the per-window atlas tile and - /// path IDs, which differ between two windows drawing the same scene. + /// Every other primitive kind, formatted without the per-window atlas tile + /// IDs, which differ between two windows drawing the same scene. other_primitives: Vec, element_ids: BTreeSet, } @@ -1718,12 +1718,7 @@ mod tests { .iter() .map(|underline| format!("{underline:?}")), ) - .chain(scene.paths.iter().map(|path| { - format!( - "path {} {:?} {:?} {:?} {:?}", - path.order, path.bounds, path.content_mask, path.color, path.vertices - ) - })) + .chain(scene.paths.iter().map(|path| format!("{path:?}"))) .chain(scene.monochrome_sprites.iter().map(|sprite| { format!( "monochrome {} {:?} {:?} {:?} {:?}", diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs index a4116aa5251..458301fdcf5 100644 --- a/crates/gpui/src/scene.rs +++ b/crates/gpui/src/scene.rs @@ -5,19 +5,10 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::{ - AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, Hsla, Pixels, - Point, Radians, ScaledPixels, Size, bounds_tree::BoundsTree, point, + AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, Hsla, Path, + PathTiles, Pixels, Point, Radians, ScaledPixels, Size, bounds_tree::BoundsTree, }; -use std::{ - fmt::Debug, - iter::Peekable, - ops::{Add, Range, Sub}, - slice, -}; - -#[allow(non_camel_case_types, unused)] -#[expect(missing_docs)] -pub type PathVertex_ScaledPixels = PathVertex; +use std::{fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice}; #[expect(missing_docs)] pub type DrawOrder = u32; @@ -36,6 +27,13 @@ impl From for PaddedBool32 { } } +impl PaddedBool32 { + /// The wrapped boolean. + pub fn as_bool(self) -> bool { + self.0 != 0 + } +} + #[derive(Default)] #[expect(missing_docs)] pub struct Scene { @@ -44,7 +42,7 @@ pub struct Scene { layer_stack: Vec, pub shadows: Vec, pub quads: Vec, - pub paths: Vec>, + pub paths: Vec, pub underlines: Vec, pub monochrome_sprites: Vec, pub subpixel_sprites: Vec, @@ -110,7 +108,6 @@ impl Scene { } Primitive::Path(path) => { path.order = order; - path.id = PathId(self.paths.len()); self.paths.push(path.clone()); } Primitive::Underline(underline) => { @@ -222,7 +219,7 @@ pub(crate) enum PaintOperation { pub enum Primitive { Shadow(Shadow), Quad(Quad), - Path(Path), + Path(PaintedPath), Underline(Underline), MonochromeSprite(MonochromeSprite), SubpixelSprite(SubpixelSprite), @@ -249,7 +246,7 @@ impl Primitive { match self { Primitive::Shadow(shadow) => &shadow.content_mask, Primitive::Quad(quad) => &quad.content_mask, - Primitive::Path(path) => &path.content_mask, + Primitive::Path(path) => &path.paint.content_mask, Primitive::Underline(underline) => &underline.content_mask, Primitive::MonochromeSprite(sprite) => &sprite.content_mask, Primitive::SubpixelSprite(sprite) => &sprite.content_mask, @@ -272,7 +269,7 @@ struct BatchIterator<'a> { quads_start: usize, quads_iter: Peekable>, paths_start: usize, - paths_iter: Peekable>>, + paths_iter: Peekable>, underlines_start: usize, underlines_iter: Peekable>, monochrome_sprites_start: usize, @@ -295,7 +292,10 @@ impl<'a> Iterator for BatchIterator<'a> { PrimitiveKind::Shadow, ), (self.quads_iter.peek().map(|q| q.order), PrimitiveKind::Quad), - (self.paths_iter.peek().map(|q| q.order), PrimitiveKind::Path), + ( + self.paths_iter.peek().map(|path| path.order), + PrimitiveKind::Path, + ), ( self.underlines_iter.peek().map(|u| u.order), PrimitiveKind::Underline, @@ -779,171 +779,105 @@ impl From for Primitive { } } -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq)] +#[repr(C)] #[expect(missing_docs)] -pub struct PathId(pub usize); +pub struct PathCurve { + pub p0: Point, + pub p1: Point, + pub a: Point, + pub b: Point, + pub sign: f32, + pub pad: u32, // align to 8 bytes +} + +#[derive(Clone, Copy, Debug)] +#[repr(C)] +#[expect(missing_docs)] +pub struct PathPaint { + /// The path's bounds, in device pixels. + pub bounds: Bounds, + pub content_mask: ContentMask, + pub color: Background, + pub even_odd: PaddedBool32, + pub pad: u32, // align to 8 bytes +} + +#[derive(Clone, Copy, Debug, PartialEq)] +#[repr(C)] +#[expect(missing_docs)] +pub struct PathTile { + pub paint: u32, + pub curve_start: u32, + pub curve_count: u32, + pub backdrop: i32, + pub top_left: Point, + pub bottom_right: Point, + pub reference: Point, + pub curves_top_left: Point, + pub curves_bottom_right: Point, +} -/// A line made up of a series of vertices and control points. #[derive(Clone, Debug)] #[expect(missing_docs)] -pub struct Path { - pub id: PathId, - pub order: DrawOrder, - pub bounds: Bounds

, - pub content_mask: ContentMask

, - pub vertices: Vec>, - pub color: Background, - start: Point

, - current: Point

, - contour_count: usize, +pub struct PaintedPath { + order: DrawOrder, + bounds: Bounds, + tiles: Rc, + paint: PathPaint, } -impl Path { - /// Create a new path with the given starting point. - pub fn new(start: Point) -> Self { +#[expect(missing_docs)] +impl PaintedPath { + /// Bins `path` into tiles, to be filled with `color` within `content_mask`. + pub fn new( + path: Path, + scale_factor: f32, + content_mask: ContentMask, + color: Background, + ) -> Self { + let content_mask = content_mask.scale(scale_factor); + let mut tiles = path.bin(scale_factor); + tiles.retain_visible(content_mask.bounds); + let paint = PathPaint { + bounds: tiles.bounds(), + content_mask, + color, + even_odd: path.even_odd().into(), + pad: 0, + }; Self { - id: PathId(0), - order: DrawOrder::default(), - vertices: Vec::new(), - start, - current: start, - bounds: Bounds { - origin: start, - size: Default::default(), - }, - content_mask: Default::default(), - color: Default::default(), - contour_count: 0, + order: 0, + bounds: tiles.painted_bounds(), + tiles: Rc::new(tiles), + paint, } } - /// Scale this path by the given factor. - pub fn scale(&self, factor: f32) -> Path { - Path { - id: self.id, - order: self.order, - bounds: self.bounds.scale(factor), - content_mask: self.content_mask.scale(factor), - vertices: self - .vertices - .iter() - .map(|vertex| vertex.scale(factor)) - .collect(), - start: self.start.map(|start| start.scale(factor)), - current: self.current.scale(factor), - contour_count: self.contour_count, - color: self.color, - } + pub fn tile_count(&self) -> usize { + self.tiles.tiles().len() } - /// Move the start, current point to the given point. - pub fn move_to(&mut self, to: Point) { - self.contour_count += 1; - self.start = to; - self.current = to; - } - - /// Draw a straight line from the current point to the given point. - pub fn line_to(&mut self, to: Point) { - self.contour_count += 1; - if self.contour_count > 1 { - self.push_triangle( - (self.start, self.current, to), - (point(0., 1.), point(0., 1.), point(0., 1.)), - ); - } - self.current = to; - } - - /// Draw a curve from the current point to the given point, using the given control point. - pub fn curve_to(&mut self, to: Point, ctrl: Point) { - self.contour_count += 1; - if self.contour_count > 1 { - self.push_triangle( - (self.start, self.current, to), - (point(0., 1.), point(0., 1.), point(0., 1.)), - ); - } - - self.push_triangle( - (self.current, ctrl, to), - (point(0., 0.), point(0.5, 0.), point(1., 1.)), - ); - self.current = to; - } - - /// Push a triangle to the Path. - pub fn push_triangle( - &mut self, - xy: (Point, Point, Point), - st: (Point, Point, Point), + pub fn append_to( + &self, + paints: &mut Vec, + curves: &mut Vec, + tiles: &mut Vec, ) { - self.bounds = self - .bounds - .union(&Bounds { - origin: xy.0, - size: Default::default(), - }) - .union(&Bounds { - origin: xy.1, - size: Default::default(), - }) - .union(&Bounds { - origin: xy.2, - size: Default::default(), - }); - - self.vertices.push(PathVertex { - xy_position: xy.0, - st_position: st.0, - content_mask: Default::default(), - }); - self.vertices.push(PathVertex { - xy_position: xy.1, - st_position: st.1, - content_mask: Default::default(), - }); - self.vertices.push(PathVertex { - xy_position: xy.2, - st_position: st.2, - content_mask: Default::default(), - }); + let paint_index = paints.len() as u32; + let curve_start = curves.len() as u32; + paints.push(self.paint); + curves.extend_from_slice(self.tiles.curves()); + tiles.extend(self.tiles.tiles().iter().map(|tile| PathTile { + paint: paint_index, + curve_start: curve_start + tile.curve_start, + ..*tile + })); } } -impl Path -where - T: Clone + Debug + Default + PartialEq + PartialOrd + Add + Sub, -{ - #[allow(unused)] - #[expect(missing_docs)] - pub fn clipped_bounds(&self) -> Bounds { - self.bounds.intersect(&self.content_mask.bounds) - } -} - -impl From> for Primitive { - fn from(path: Path) -> Self { +impl From for Primitive { + fn from(path: PaintedPath) -> Self { Primitive::Path(path) } } - -#[derive(Clone, Debug)] -#[repr(C)] -#[expect(missing_docs)] -pub struct PathVertex { - pub xy_position: Point

, - pub st_position: Point, - pub content_mask: ContentMask

, -} - -#[expect(missing_docs)] -impl PathVertex { - pub fn scale(&self, factor: f32) -> PathVertex { - PathVertex { - xy_position: self.xy_position.scale(factor), - st_position: self.st_position, - content_mask: self.content_mask.scale(factor), - } - } -} diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index ba3f41af87a..c6c2eab384d 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -14,9 +14,9 @@ use crate::{ EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs, Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent, - MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, - PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, - PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, + MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, PaintedPath, Path, + Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, + Point, PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style, SubpixelSprite, Subscription, SystemWindowTab, @@ -5095,18 +5095,19 @@ impl Window { /// Paint the given `Path` into the scene for the next frame at the current z-index. /// /// This method should only be called as part of the paint phase of element drawing. - pub fn paint_path(&mut self, mut path: Path, color: impl Into) { + pub fn paint_path(&mut self, path: Path, color: impl Into) { self.invalidator.debug_assert_paint(); let scale_factor = self.scale_factor(); let content_mask = self.content_mask(); let opacity = self.element_opacity(); - path.content_mask = content_mask; let color: Background = color.into(); - path.color = color.opacity(opacity); - self.next_frame - .scene - .insert_primitive(path.scale(scale_factor)); + self.next_frame.scene.insert_primitive(PaintedPath::new( + path, + scale_factor, + content_mask, + color.opacity(opacity), + )); } /// Paint an underline into the scene for the next frame at the current z-index. diff --git a/crates/gpui_apple/build.rs b/crates/gpui_apple/build.rs index a29d01be664..47c0e41fb25 100644 --- a/crates/gpui_apple/build.rs +++ b/crates/gpui_apple/build.rs @@ -42,14 +42,15 @@ mod apple_build { "Edges".into(), "Size".into(), "Pixels".into(), - "PointF".into(), "Hsla".into(), "ContentMask".into(), "Uniforms".into(), "AtlasTile".into(), - "PathRasterizationInputIndex".into(), - "PathVertex_ScaledPixels".into(), - "PathRasterizationVertex".into(), + "GlobalInputIndex".into(), + "PathTileInputIndex".into(), + "PathTile".into(), + "PathCurve".into(), + "PathPaint".into(), "ShadowInputIndex".into(), "Shadow".into(), "QuadInputIndex".into(), @@ -60,7 +61,6 @@ mod apple_build { "SpriteInputIndex".into(), "MonochromeSprite".into(), "PolychromeSprite".into(), - "PathSprite".into(), "SurfaceInputIndex".into(), "SurfaceBounds".into(), "TransformationMatrix".into(), diff --git a/crates/gpui_apple/src/metal_renderer.rs b/crates/gpui_apple/src/metal_renderer.rs index 076494a3d45..732fa31def0 100644 --- a/crates/gpui_apple/src/metal_renderer.rs +++ b/crates/gpui_apple/src/metal_renderer.rs @@ -2,8 +2,8 @@ use crate::metal_atlas::MetalAtlas; use anyhow::{Context as _, Result}; use block2::RcBlock; use gpui::{ - AtlasTextureId, Background, Bounds, ContentMask, DevicePixels, PaintSurface, Path, Point, - PrimitiveBatch, ScaledPixels, Scene, Size, point, size, + AtlasTextureId, Bounds, ContentMask, DevicePixels, PaintSurface, PaintedPath, PrimitiveBatch, + ScaledPixels, Scene, Size, size, }; #[cfg(any(test, feature = "bench-support", feature = "test-support"))] use image::RgbaImage; @@ -23,26 +23,22 @@ use objc2_metal::{ MTLCommandEncoder, MTLCommandQueue, MTLCreateSystemDefaultDevice, MTLDevice, MTLDrawable, MTLGPUFamily, MTLLibrary, MTLLoadAction, MTLPixelFormat, MTLPrimitiveType, MTLRenderCommandEncoder, MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, - MTLRenderPipelineState, MTLResourceOptions, MTLStorageMode, MTLStoreAction, MTLTexture, - MTLTextureDescriptor, MTLTextureType, MTLTextureUsage, MTLViewport, + MTLRenderPipelineState, MTLResourceOptions, MTLStoreAction, MTLTexture, MTLViewport, }; #[cfg(any(test, feature = "bench-support", feature = "test-support"))] -use objc2_metal::{MTLBlitCommandEncoder, MTLOrigin, MTLRegion, MTLSize}; +use objc2_metal::{ + MTLBlitCommandEncoder, MTLOrigin, MTLRegion, MTLSize, MTLStorageMode, MTLTextureDescriptor, + MTLTextureUsage, +}; use objc2_quartz_core::{CAMetalDrawable, CAMetalLayer}; use parking_lot::Mutex; use std::{cell::Cell, mem, mem::MaybeUninit, ops::Range, ptr, slice, sync::Arc}; -// Exported to metal -pub(crate) type PointF = gpui::Point; - #[cfg(not(feature = "runtime_shaders"))] const SHADERS_METALLIB: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/shaders.metallib")); #[cfg(feature = "runtime_shaders")] const SHADERS_SOURCE_FILE: &str = include_str!(concat!(env!("OUT_DIR"), "/stitched_shaders.metal")); -// Use 4x MSAA, all devices support it. -// https://developer.apple.com/documentation/metal/mtldevice/1433355-supportstexturesamplecount -const PATH_SAMPLE_COUNT: u32 = 4; /// Metal requires the offset a buffer is bound at to be 256-byte aligned. const INSTANCE_BUFFER_ALIGNMENT: usize = 256; const MAX_INSTANCE_BUFFER_SIZE: usize = 256 * 1024 * 1024; @@ -128,6 +124,7 @@ enum DisplayLinkMode { pub struct MetalRenderer { device: Retained>, layer: Option>, + #[cfg(any(test, feature = "bench-support", feature = "test-support"))] is_apple_gpu: bool, is_unified_memory: bool, presents_with_transaction: bool, @@ -135,35 +132,22 @@ pub struct MetalRenderer { /// For headless rendering, tracks whether output should be opaque opaque: bool, command_queue: Retained>, - paths_rasterization_pipeline_state: Retained>, - path_sprites_pipeline_state: Retained>, + path_tiles_pipeline_state: Retained>, shadows_pipeline_state: Retained>, quads_pipeline_state: Retained>, underlines_pipeline_state: Retained>, monochrome_sprites_pipeline_state: Retained>, polychrome_sprites_pipeline_state: Retained>, surfaces_pipeline_state: Retained>, - unit_vertices: Retained>, instance_buffer_pool: Arc>, sprite_atlas: Arc, core_video_texture_cache: CFRetained, - path_intermediate_texture: Option>>, - path_intermediate_msaa_texture: Option>>, - path_sample_count: u32, /// Offscreen render target reused across `render_scene` calls when /// rendering headlessly without reading pixels back. #[cfg(any(test, feature = "bench-support", feature = "test-support"))] headless_render_target: Option>>, } -#[repr(C)] -pub struct PathRasterizationVertex { - pub xy_position: Point, - pub st_position: Point, - pub color: Background, - pub bounds: Bounds, -} - impl MetalRenderer { /// Creates a new MetalRenderer with a CAMetalLayer for window-based rendering. pub fn new( @@ -287,62 +271,21 @@ impl MetalRenderer { )) .context("loading Metal library")?; - fn to_float2_bits(point: PointF) -> u64 { - let mut output = point.y.to_bits() as u64; - output <<= 32; - output |= point.x.to_bits() as u64; - output - } - // Shared memory can be used only if CPU and GPU share the same memory space. // https://developer.apple.com/documentation/metal/setting-resource-storage-modes // iOS does not support managed resources. Its simulator may report a // non-unified host GPU even though resources must still use shared storage. let is_unified_memory = cfg!(target_os = "ios") || device.hasUnifiedMemory(); - // Apple GPU families support memoryless textures, which can significantly reduce - // memory usage by keeping render targets in on-chip tile memory instead of - // allocating backing store in system memory. + // Only Apple GPUs can create shared-storage textures on macOS. // https://developer.apple.com/documentation/metal/mtlgpufamily let is_apple_gpu = device.supportsFamily(MTLGPUFamily::Apple1); - let unit_vertices = [ - to_float2_bits(point(0., 0.)), - to_float2_bits(point(1., 0.)), - to_float2_bits(point(0., 1.)), - to_float2_bits(point(0., 1.)), - to_float2_bits(point(1., 0.)), - to_float2_bits(point(1., 1.)), - ]; - // SAFETY: Metal copies the live array using its exact byte length. - let unit_vertices = unsafe { - device.newBufferWithBytes_length_options( - ptr::NonNull::from(&unit_vertices).cast(), - mem::size_of_val(&unit_vertices), - if is_unified_memory { - MTLResourceOptions::StorageModeShared - | MTLResourceOptions::CPUCacheModeWriteCombined - } else { - MTLResourceOptions::StorageModeManaged - }, - ) - } - .context("allocating unit vertex buffer")?; - - let paths_rasterization_pipeline_state = build_path_rasterization_pipeline_state( + let path_tiles_pipeline_state = build_pipeline_state( &device, &library, - "paths_rasterization", - "path_rasterization_vertex", - "path_rasterization_fragment", - MTLPixelFormat::BGRA8Unorm, - PATH_SAMPLE_COUNT, - )?; - let path_sprites_pipeline_state = build_path_sprite_pipeline_state( - &device, - &library, - "path_sprites", - "path_sprite_vertex", - "path_sprite_fragment", + "path_tiles", + "path_tile_vertex", + "path_tile_fragment", MTLPixelFormat::BGRA8Unorm, )?; let shadows_pipeline_state = build_pipeline_state( @@ -419,25 +362,21 @@ impl MetalRenderer { layer, presents_with_transaction: false, display_link_mode: DisplayLinkMode::Detached, + #[cfg(any(test, feature = "bench-support", feature = "test-support"))] is_apple_gpu, is_unified_memory, opaque, command_queue, - paths_rasterization_pipeline_state, - path_sprites_pipeline_state, + path_tiles_pipeline_state, shadows_pipeline_state, quads_pipeline_state, underlines_pipeline_state, monochrome_sprites_pipeline_state, polychrome_sprites_pipeline_state, surfaces_pipeline_state, - unit_vertices, instance_buffer_pool, sprite_atlas, core_video_texture_cache, - path_intermediate_texture: None, - path_intermediate_msaa_texture: None, - path_sample_count: PATH_SAMPLE_COUNT, #[cfg(any(test, feature = "bench-support", feature = "test-support"))] headless_render_target: None, }) @@ -517,75 +456,6 @@ impl MetalRenderer { if let Some(layer) = &self.layer { layer.setDrawableSize(CGSize::new(size.width.0 as f64, size.height.0 as f64)); } - if let Err(error) = self.update_path_intermediate_textures(size) { - log::error!("failed to resize path textures: {error:#}"); - } - } - - fn update_path_intermediate_textures(&mut self, size: Size) -> Result<()> { - // We are uncertain when this happens, but sometimes size can be 0 here. Most likely before - // the layout pass on window creation. Zero-sized texture creation causes SIGABRT. - // https://github.com/zed-industries/zed/issues/36229 - if size.width.0 <= 0 || size.height.0 <= 0 { - self.path_intermediate_texture = None; - self.path_intermediate_msaa_texture = None; - return Ok(()); - } - - if self - .path_intermediate_texture - .as_ref() - .is_some_and(|texture| { - texture.width() == size.width.0 as usize - && texture.height() == size.height.0 as usize - }) - { - return Ok(()); - } - - self.path_intermediate_texture = None; - self.path_intermediate_msaa_texture = None; - let texture_descriptor = MTLTextureDescriptor::new(); - // SAFETY: The dimensions are positive and this descriptor creates a 2D texture. - unsafe { - texture_descriptor.setWidth(size.width.0 as usize); - texture_descriptor.setHeight(size.height.0 as usize); - } - texture_descriptor.setPixelFormat(MTLPixelFormat::BGRA8Unorm); - texture_descriptor.setStorageMode(MTLStorageMode::Private); - texture_descriptor.setUsage(MTLTextureUsage::RenderTarget | MTLTextureUsage::ShaderRead); - let intermediate_texture = self - .device - .newTextureWithDescriptor(&texture_descriptor) - .context("allocating path intermediate texture")?; - - let msaa_texture = if self.path_sample_count > 1 { - // https://developer.apple.com/documentation/metal/choosing-a-resource-storage-mode-for-apple-gpus - // Rendering MSAA textures are done in a single pass, so we can use memory-less storage on Apple Silicon - let storage_mode = if self.is_apple_gpu { - MTLStorageMode::Memoryless - } else { - MTLStorageMode::Private - }; - - let msaa_descriptor = texture_descriptor; - msaa_descriptor.setTextureType(MTLTextureType::Type2DMultisample); - msaa_descriptor.setStorageMode(storage_mode); - // SAFETY: The multisample texture uses the same sample count as its render pipeline. - unsafe { - msaa_descriptor.setSampleCount(self.path_sample_count as _); - } - Some( - self.device - .newTextureWithDescriptor(&msaa_descriptor) - .context("allocating multisample path texture")?, - ) - } else { - None - }; - self.path_intermediate_texture = Some(intermediate_texture); - self.path_intermediate_msaa_texture = msaa_texture; - Ok(()) } pub fn update_transparency(&mut self, transparent: bool) { @@ -660,9 +530,6 @@ impl MetalRenderer { texture: &ProtocolObject, viewport_size: Size, ) -> Result>> { - if self.path_intermediate_texture.is_none() { - self.update_path_intermediate_textures(viewport_size)?; - } let mut writer = InstanceBufferWriter::new( &self.device, &self.instance_buffer_pool, @@ -684,7 +551,6 @@ impl MetalRenderer { let command_buffer = self.draw_primitives_to_texture( scene, &instance_bindings, - &mut writer, texture, viewport_size, &mut surface_textures, @@ -745,10 +611,7 @@ impl MetalRenderer { // Headless callers do not have a Cocoa event-loop pool to release // autoreleased command buffers and render-pass descriptors. - objc2::rc::autoreleasepool(|_| { - self.update_path_intermediate_textures(size)?; - self.render_offscreen(scene, size) - }) + objc2::rc::autoreleasepool(|_| self.render_offscreen(scene, size)) } /// Renders a scene into a new offscreen texture of `size` and reads it @@ -813,8 +676,6 @@ impl MetalRenderer { } objc2::rc::autoreleasepool(|_| { - self.update_path_intermediate_textures(size)?; - let needs_new_target = self.headless_render_target.as_ref().is_none_or(|texture| { texture.width() != size.width.0 as usize || texture.height() != size.height.0 as usize @@ -853,7 +714,6 @@ impl MetalRenderer { &mut self, scene: &Scene, instance_bindings: &InstanceBindings, - writer: &mut InstanceBufferWriter, texture: &ProtocolObject, viewport_size: Size, surface_textures: &mut Vec>, @@ -864,65 +724,56 @@ impl MetalRenderer { .context("creating command buffer")?; let alpha = if self.opaque { 1. } else { 0. }; - let mut command_encoder = new_command_encoder_for_texture( + let command_encoder = new_command_encoder_for_texture( &command_buffer, texture, viewport_size, - Some(MTLClearColor { + MTLClearColor { red: 0., green: 0., blue: 0., alpha, - }), + }, )?; + // SAFETY: Metal copies the viewport bytes, which match every vertex + // shader's `GlobalInputIndex_ViewportSize` argument. + unsafe { + command_encoder.setVertexBytes_length_atIndex( + ptr::NonNull::from(&viewport_size).cast(), + mem::size_of_val(&viewport_size), + GlobalInputIndex::ViewportSize as usize, + ); + } + let mut path_tile_cursor = 0; for batch in scene.batches() { match batch { PrimitiveBatch::Shadows(range) => { - self.draw_shadows(range, instance_bindings, viewport_size, &command_encoder) + self.draw_shadows(range, instance_bindings, &command_encoder) } PrimitiveBatch::Quads(range) => { - self.draw_quads(range, instance_bindings, viewport_size, &command_encoder) + self.draw_quads(range, instance_bindings, &command_encoder) } PrimitiveBatch::Paths(range) => { - let paths = &scene.paths[range]; - command_encoder.endEncoding(); - - let did_draw = self.draw_paths_to_intermediate( - paths, - writer, - viewport_size, - &command_buffer, - )?; - - command_encoder = new_command_encoder_for_texture( - &command_buffer, - texture, - viewport_size, - None, - )?; - - if did_draw { - if let Err(error) = self.draw_paths_from_intermediate( - paths, - writer, - viewport_size, - &command_encoder, - ) { - command_encoder.endEncoding(); - return Err(error); - } - } + let tiles_start = path_tile_cursor; + path_tile_cursor += scene.paths[range] + .iter() + .map(PaintedPath::tile_count) + .sum::(); + self.draw_path_tiles( + tiles_start..path_tile_cursor, + instance_bindings, + &command_encoder, + ) } PrimitiveBatch::Underlines(range) => { - self.draw_underlines(range, instance_bindings, viewport_size, &command_encoder) + self.draw_underlines(range, instance_bindings, &command_encoder) } PrimitiveBatch::MonochromeSprites { texture_id, range } => self .draw_monochrome_sprites( texture_id, range, instance_bindings, - viewport_size, &command_encoder, ), PrimitiveBatch::PolychromeSprites { texture_id, range } => self @@ -930,7 +781,6 @@ impl MetalRenderer { texture_id, range, instance_bindings, - viewport_size, &command_encoder, ), PrimitiveBatch::Surfaces(range) => { @@ -938,7 +788,6 @@ impl MetalRenderer { &scene.surfaces[range.clone()], range.start, instance_bindings, - viewport_size, &command_encoder, surface_textures, ) { @@ -955,95 +804,59 @@ impl MetalRenderer { Ok(command_buffer) } - fn draw_paths_to_intermediate( + fn draw_path_tiles( &self, - paths: &[Path], - writer: &mut InstanceBufferWriter, - viewport_size: Size, - command_buffer: &ProtocolObject, - ) -> Result { - if paths.is_empty() { - return Ok(false); - } - let intermediate_texture = self - .path_intermediate_texture - .as_ref() - .context("missing path intermediate texture")?; - - let mut vertices = Vec::new(); - for path in paths { - vertices.extend(path.vertices.iter().map(|v| PathRasterizationVertex { - xy_position: v.xy_position, - st_position: v.st_position, - color: path.color, - bounds: path.bounds.intersect(&path.content_mask.bounds), - })); - } - let vertex_instance_bindings = writer.write(&vertices)?; - - let render_pass_descriptor = MTLRenderPassDescriptor::new(); - // SAFETY: Index zero is within the render pass's color attachment array. - let color_attachment = unsafe { - render_pass_descriptor - .colorAttachments() - .objectAtIndexedSubscript(0) - }; - color_attachment.setLoadAction(MTLLoadAction::Clear); - color_attachment.setClearColor(MTLClearColor { - red: 0., - green: 0., - blue: 0., - alpha: 0., - }); - - if let Some(msaa_texture) = &self.path_intermediate_msaa_texture { - color_attachment.setTexture(Some(msaa_texture)); - color_attachment.setResolveTexture(Some(intermediate_texture)); - color_attachment.setStoreAction(MTLStoreAction::MultisampleResolve); - } else { - color_attachment.setTexture(Some(intermediate_texture)); - color_attachment.setStoreAction(MTLStoreAction::Store); + tiles: Range, + instance_bindings: &InstanceBindings, + command_encoder: &ProtocolObject, + ) { + if tiles.is_empty() { + return; } - let command_encoder = command_buffer - .renderCommandEncoderWithDescriptor(&render_pass_descriptor) - .context("creating path render command encoder")?; - command_encoder.setRenderPipelineState(&self.paths_rasterization_pipeline_state); - // SAFETY: The binding contains vertices.len() shader-compatible vertices at an aligned offset. - // Metal retains the buffer, and writer.finish publishes CPU writes before submission. - // The viewport bytes are copied from a live value into the matching shader slot. + command_encoder.setRenderPipelineState(&self.path_tiles_pipeline_state); + // SAFETY: The scene's tile range and its curves and paints match the uploaded shader layouts and slots. + // Metal retains the buffers, and writer.finish publishes their writes. unsafe { command_encoder.setVertexBuffer_offset_atIndex( - Some(&vertex_instance_bindings.buffer), - vertex_instance_bindings.offset, - PathRasterizationInputIndex::Vertices as usize, + Some(&instance_bindings.path_tiles.buffer), + instance_bindings.path_tiles.offset, + PathTileInputIndex::Tiles as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - PathRasterizationInputIndex::ViewportSize as usize, + command_encoder.setVertexBuffer_offset_atIndex( + Some(&instance_bindings.path_paints.buffer), + instance_bindings.path_paints.offset, + PathTileInputIndex::Paints as usize, ); command_encoder.setFragmentBuffer_offset_atIndex( - Some(&vertex_instance_bindings.buffer), - vertex_instance_bindings.offset, - PathRasterizationInputIndex::Vertices as usize, + Some(&instance_bindings.path_tiles.buffer), + instance_bindings.path_tiles.offset, + PathTileInputIndex::Tiles as usize, ); - command_encoder.drawPrimitives_vertexStart_vertexCount( - MTLPrimitiveType::Triangle, + command_encoder.setFragmentBuffer_offset_atIndex( + Some(&instance_bindings.path_curves.buffer), + instance_bindings.path_curves.offset, + PathTileInputIndex::Curves as usize, + ); + command_encoder.setFragmentBuffer_offset_atIndex( + Some(&instance_bindings.path_paints.buffer), + instance_bindings.path_paints.offset, + PathTileInputIndex::Paints as usize, + ); + command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( + MTLPrimitiveType::TriangleStrip, 0, - vertices.len(), + 4, + tiles.len(), + tiles.start, ); } - - command_encoder.endEncoding(); - Ok(true) } fn draw_shadows( &self, shadows: Range, instance_bindings: &InstanceBindings, - viewport_size: Size, command_encoder: &ProtocolObject, ) { if shadows.is_empty() { @@ -1051,14 +864,9 @@ impl MetalRenderer { } command_encoder.setRenderPipelineState(&self.shadows_pipeline_state); - // SAFETY: Six unit vertices and the scene's shadow range match the uploaded shader layouts and slots. - // Metal retains the buffers, writer.finish publishes their writes, and viewport bytes are copied. + // SAFETY: The scene's shadow range matches the uploaded shader layouts and slots. + // Metal retains the buffers, and writer.finish publishes their writes. unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - ShadowInputIndex::Vertices as usize, - ); command_encoder.setVertexBuffer_offset_atIndex( Some(&instance_bindings.shadows.buffer), instance_bindings.shadows.offset, @@ -1069,15 +877,10 @@ impl MetalRenderer { instance_bindings.shadows.offset, ShadowInputIndex::Shadows as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - ShadowInputIndex::ViewportSize as usize, - ); command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::Triangle, + MTLPrimitiveType::TriangleStrip, 0, - 6, + 4, shadows.len(), shadows.start, ); @@ -1088,7 +891,6 @@ impl MetalRenderer { &self, quads: Range, instance_bindings: &InstanceBindings, - viewport_size: Size, command_encoder: &ProtocolObject, ) { if quads.is_empty() { @@ -1096,14 +898,9 @@ impl MetalRenderer { } command_encoder.setRenderPipelineState(&self.quads_pipeline_state); - // SAFETY: Six unit vertices and the scene's quad range match the uploaded shader layouts and slots. - // Metal retains the buffers, writer.finish publishes their writes, and viewport bytes are copied. + // SAFETY: The scene's quad range matches the uploaded shader layouts and slots. + // Metal retains the buffers, and writer.finish publishes their writes. unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - QuadInputIndex::Vertices as usize, - ); command_encoder.setVertexBuffer_offset_atIndex( Some(&instance_bindings.quads.buffer), instance_bindings.quads.offset, @@ -1114,103 +911,20 @@ impl MetalRenderer { instance_bindings.quads.offset, QuadInputIndex::Quads as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - QuadInputIndex::ViewportSize as usize, - ); command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::Triangle, + MTLPrimitiveType::TriangleStrip, 0, - 6, + 4, quads.len(), quads.start, ); } } - fn draw_paths_from_intermediate( - &self, - paths: &[Path], - writer: &mut InstanceBufferWriter, - viewport_size: Size, - command_encoder: &ProtocolObject, - ) -> Result<()> { - let (Some(first_path), Some(last_path)) = (paths.first(), paths.last()) else { - return Ok(()); - }; - let intermediate_texture = self - .path_intermediate_texture - .as_ref() - .context("missing path intermediate texture")?; - - command_encoder.setRenderPipelineState(&self.path_sprites_pipeline_state); - // SAFETY: The shader slots match the unit vertices, copied viewport, and retained path texture. - // The preceding render pass writes this tracked texture before it is sampled. - unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - SpriteInputIndex::Vertices as usize, - ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - SpriteInputIndex::ViewportSize as usize, - ); - command_encoder.setFragmentTexture_atIndex( - Some(intermediate_texture), - SpriteInputIndex::AtlasTexture as usize, - ); - } - - // When copying paths from the intermediate texture to the drawable, - // each pixel must only be copied once, in case of transparent paths. - // - // If all paths have the same draw order, then their bounds are all - // disjoint, so we can copy each path's bounds individually. If this - // batch combines different draw orders, we perform a single copy - // for a minimal spanning rect. - let sprites; - if last_path.order == first_path.order { - sprites = paths - .iter() - .map(|path| PathSprite { - bounds: path.clipped_bounds(), - }) - .collect(); - } else { - let mut bounds = first_path.clipped_bounds(); - for path in paths.iter().skip(1) { - bounds = bounds.union(&path.clipped_bounds()); - } - sprites = vec![PathSprite { bounds }]; - } - - let sprite_instance_bindings = writer.write(&sprites)?; - // SAFETY: The draw uses six unit vertices and exactly the sprites written at this aligned binding. - // Metal retains the buffer, and writer.finish publishes CPU writes before submission. - unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&sprite_instance_bindings.buffer), - sprite_instance_bindings.offset, - SpriteInputIndex::Sprites as usize, - ); - command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount( - MTLPrimitiveType::Triangle, - 0, - 6, - sprites.len(), - ); - } - Ok(()) - } - fn draw_underlines( &self, underlines: Range, instance_bindings: &InstanceBindings, - viewport_size: Size, command_encoder: &ProtocolObject, ) { if underlines.is_empty() { @@ -1218,14 +932,9 @@ impl MetalRenderer { } command_encoder.setRenderPipelineState(&self.underlines_pipeline_state); - // SAFETY: Six unit vertices and the scene's underline range match the uploaded shader layouts and slots. - // Metal retains the buffers, writer.finish publishes their writes, and viewport bytes are copied. + // SAFETY: The scene's underline range matches the uploaded shader layouts and slots. + // Metal retains the buffers, and writer.finish publishes their writes. unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - UnderlineInputIndex::Vertices as usize, - ); command_encoder.setVertexBuffer_offset_atIndex( Some(&instance_bindings.underlines.buffer), instance_bindings.underlines.offset, @@ -1236,15 +945,10 @@ impl MetalRenderer { instance_bindings.underlines.offset, UnderlineInputIndex::Underlines as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - UnderlineInputIndex::ViewportSize as usize, - ); command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::Triangle, + MTLPrimitiveType::TriangleStrip, 0, - 6, + 4, underlines.len(), underlines.start, ); @@ -1256,7 +960,6 @@ impl MetalRenderer { texture_id: AtlasTextureId, sprites: Range, instance_bindings: &InstanceBindings, - viewport_size: Size, command_encoder: &ProtocolObject, ) { if sprites.is_empty() { @@ -1271,24 +974,14 @@ impl MetalRenderer { DevicePixels(texture.height() as i32), ); command_encoder.setRenderPipelineState(&self.monochrome_sprites_pipeline_state); - // SAFETY: The scene's sprite range, six unit vertices, and copied sizes match the shader layouts and slots. + // SAFETY: The scene's sprite range and copied sizes match the shader layouts and slots. // Metal retains the buffers and texture, and writer.finish publishes the instance writes. unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - SpriteInputIndex::Vertices as usize, - ); command_encoder.setVertexBuffer_offset_atIndex( Some(&instance_bindings.monochrome_sprites.buffer), instance_bindings.monochrome_sprites.offset, SpriteInputIndex::Sprites as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - SpriteInputIndex::ViewportSize as usize, - ); command_encoder.setVertexBytes_length_atIndex( ptr::NonNull::from(&texture_size).cast(), mem::size_of_val(&texture_size), @@ -1304,9 +997,9 @@ impl MetalRenderer { SpriteInputIndex::AtlasTexture as usize, ); command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::Triangle, + MTLPrimitiveType::TriangleStrip, 0, - 6, + 4, sprites.len(), sprites.start, ); @@ -1318,7 +1011,6 @@ impl MetalRenderer { texture_id: AtlasTextureId, sprites: Range, instance_bindings: &InstanceBindings, - viewport_size: Size, command_encoder: &ProtocolObject, ) { if sprites.is_empty() { @@ -1333,24 +1025,14 @@ impl MetalRenderer { DevicePixels(texture.height() as i32), ); command_encoder.setRenderPipelineState(&self.polychrome_sprites_pipeline_state); - // SAFETY: The scene's sprite range, six unit vertices, and copied sizes match the shader layouts and slots. + // SAFETY: The scene's sprite range and copied sizes match the shader layouts and slots. // Metal retains the buffers and texture, and writer.finish publishes the instance writes. unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - SpriteInputIndex::Vertices as usize, - ); command_encoder.setVertexBuffer_offset_atIndex( Some(&instance_bindings.polychrome_sprites.buffer), instance_bindings.polychrome_sprites.offset, SpriteInputIndex::Sprites as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - SpriteInputIndex::ViewportSize as usize, - ); command_encoder.setVertexBytes_length_atIndex( ptr::NonNull::from(&texture_size).cast(), mem::size_of_val(&texture_size), @@ -1366,9 +1048,9 @@ impl MetalRenderer { SpriteInputIndex::AtlasTexture as usize, ); command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::Triangle, + MTLPrimitiveType::TriangleStrip, 0, - 6, + 4, sprites.len(), sprites.start, ); @@ -1380,7 +1062,6 @@ impl MetalRenderer { surfaces: &[PaintSurface], first_surface: usize, instance_bindings: &InstanceBindings, - viewport_size: Size, command_encoder: &ProtocolObject, surface_textures: &mut Vec>, ) -> Result<()> { @@ -1389,24 +1070,14 @@ impl MetalRenderer { } command_encoder.setRenderPipelineState(&self.surfaces_pipeline_state); - // SAFETY: The unit vertices, SurfaceBounds instances, and copied viewport match the shader layouts and slots. + // SAFETY: The SurfaceBounds instances match the shader layout and slot. // Metal retains the buffers, and writer.finish publishes CPU writes before submission. unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - SurfaceInputIndex::Vertices as usize, - ); command_encoder.setVertexBuffer_offset_atIndex( Some(&instance_bindings.surfaces.buffer), instance_bindings.surfaces.offset, SurfaceInputIndex::Surfaces as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - SurfaceInputIndex::ViewportSize as usize, - ); } for (index, surface) in surfaces.iter().enumerate() { @@ -1475,12 +1146,12 @@ impl MetalRenderer { } surface_textures.extend([y_texture, cb_cr_texture]); - // SAFETY: Six unit vertices draw one instance within the uploaded scene's surface range. + // SAFETY: This draws one instance within the uploaded scene's surface range. unsafe { command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::Triangle, + MTLPrimitiveType::TriangleStrip, 0, - 6, + 4, 1, first_surface + index, ); @@ -1494,7 +1165,7 @@ fn new_command_encoder_for_texture( command_buffer: &ProtocolObject, texture: &ProtocolObject, viewport_size: Size, - clear_color: Option, + clear_color: MTLClearColor, ) -> Result>> { let render_pass_descriptor = MTLRenderPassDescriptor::new(); // SAFETY: Index zero is within the render pass's color attachment array. @@ -1505,12 +1176,8 @@ fn new_command_encoder_for_texture( }; color_attachment.setTexture(Some(texture)); color_attachment.setStoreAction(MTLStoreAction::Store); - if let Some(clear_color) = clear_color { - color_attachment.setLoadAction(MTLLoadAction::Clear); - color_attachment.setClearColor(clear_color); - } else { - color_attachment.setLoadAction(MTLLoadAction::Load); - } + color_attachment.setLoadAction(MTLLoadAction::Clear); + color_attachment.setClearColor(clear_color); let command_encoder = command_buffer .renderCommandEncoderWithDescriptor(&render_pass_descriptor) @@ -1593,81 +1260,6 @@ fn build_pipeline_state( .with_context(|| format!("creating {label} render pipeline")) } -fn build_path_sprite_pipeline_state( - device: &ProtocolObject, - library: &ProtocolObject, - label: &str, - vertex_fn_name: &str, - fragment_fn_name: &str, - pixel_format: MTLPixelFormat, -) -> Result>> { - let vertex_fn = library - .newFunctionWithName(&NSString::from_str(vertex_fn_name)) - .with_context(|| format!("locating vertex function {vertex_fn_name}"))?; - let fragment_fn = library - .newFunctionWithName(&NSString::from_str(fragment_fn_name)) - .with_context(|| format!("locating fragment function {fragment_fn_name}"))?; - - let descriptor = MTLRenderPipelineDescriptor::new(); - descriptor.setLabel(Some(&NSString::from_str(label))); - descriptor.setVertexFunction(Some(vertex_fn.as_ref())); - descriptor.setFragmentFunction(Some(fragment_fn.as_ref())); - // SAFETY: Index zero is within the pipeline's color attachment array. - let color_attachment = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }; - color_attachment.setPixelFormat(pixel_format); - color_attachment.setBlendingEnabled(true); - color_attachment.setRgbBlendOperation(MTLBlendOperation::Add); - color_attachment.setAlphaBlendOperation(MTLBlendOperation::Add); - color_attachment.setSourceRGBBlendFactor(MTLBlendFactor::One); - color_attachment.setSourceAlphaBlendFactor(MTLBlendFactor::One); - color_attachment.setDestinationRGBBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); - color_attachment.setDestinationAlphaBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); - - device - .newRenderPipelineStateWithDescriptor_error(&descriptor) - .with_context(|| format!("creating {label} render pipeline")) -} - -fn build_path_rasterization_pipeline_state( - device: &ProtocolObject, - library: &ProtocolObject, - label: &str, - vertex_fn_name: &str, - fragment_fn_name: &str, - pixel_format: MTLPixelFormat, - path_sample_count: u32, -) -> Result>> { - let vertex_fn = library - .newFunctionWithName(&NSString::from_str(vertex_fn_name)) - .with_context(|| format!("locating vertex function {vertex_fn_name}"))?; - let fragment_fn = library - .newFunctionWithName(&NSString::from_str(fragment_fn_name)) - .with_context(|| format!("locating fragment function {fragment_fn_name}"))?; - - let descriptor = MTLRenderPipelineDescriptor::new(); - descriptor.setLabel(Some(&NSString::from_str(label))); - descriptor.setVertexFunction(Some(vertex_fn.as_ref())); - descriptor.setFragmentFunction(Some(fragment_fn.as_ref())); - if path_sample_count > 1 { - descriptor.setRasterSampleCount(path_sample_count as _); - descriptor.setAlphaToCoverageEnabled(false); - } - // SAFETY: Index zero is within the pipeline's color attachment array. - let color_attachment = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }; - color_attachment.setPixelFormat(pixel_format); - color_attachment.setBlendingEnabled(true); - color_attachment.setRgbBlendOperation(MTLBlendOperation::Add); - color_attachment.setAlphaBlendOperation(MTLBlendOperation::Add); - color_attachment.setSourceRGBBlendFactor(MTLBlendFactor::One); - color_attachment.setSourceAlphaBlendFactor(MTLBlendFactor::One); - color_attachment.setDestinationRGBBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); - color_attachment.setDestinationAlphaBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); - - device - .newRenderPipelineStateWithDescriptor_error(&descriptor) - .with_context(|| format!("creating {label} render pipeline")) -} - #[derive(Clone)] struct InstanceBinding { buffer: Retained>, @@ -1676,6 +1268,9 @@ struct InstanceBinding { struct InstanceBindings { quads: InstanceBinding, + path_tiles: InstanceBinding, + path_curves: InstanceBinding, + path_paints: InstanceBinding, shadows: InstanceBinding, underlines: InstanceBinding, monochrome_sprites: InstanceBinding, @@ -1684,8 +1279,17 @@ struct InstanceBindings { } fn write_instances(scene: &Scene, writer: &mut InstanceBufferWriter) -> Result { + let mut path_paints = Vec::with_capacity(scene.paths.len()); + let mut path_curves = Vec::new(); + let mut path_tiles = Vec::new(); + for path in &scene.paths { + path.append_to(&mut path_paints, &mut path_curves, &mut path_tiles); + } Ok(InstanceBindings { quads: writer.write(&scene.quads)?, + path_tiles: writer.write(&path_tiles)?, + path_curves: writer.write(&path_curves)?, + path_paints: writer.write(&path_paints)?, shadows: writer.write(&scene.shadows)?, underlines: writer.write(&scene.underlines)?, monochrome_sprites: writer.write(&scene.monochrome_sprites)?, @@ -1834,56 +1438,48 @@ impl InstanceBufferWriter { } } +/// Vertex buffer slots bound once per render pass and shared by every +/// pipeline. Each primitive's own slots start after these. +#[repr(C)] +enum GlobalInputIndex { + ViewportSize = 0, +} + #[repr(C)] enum ShadowInputIndex { - Vertices = 0, Shadows = 1, - ViewportSize = 2, } #[repr(C)] enum QuadInputIndex { - Vertices = 0, Quads = 1, - ViewportSize = 2, } #[repr(C)] enum UnderlineInputIndex { - Vertices = 0, Underlines = 1, - ViewportSize = 2, } #[repr(C)] enum SpriteInputIndex { - Vertices = 0, Sprites = 1, - ViewportSize = 2, - AtlasTextureSize = 3, - AtlasTexture = 4, + AtlasTextureSize = 2, + AtlasTexture = 3, } #[repr(C)] enum SurfaceInputIndex { - Vertices = 0, Surfaces = 1, - ViewportSize = 2, - TextureSize = 3, - YTexture = 4, - CbCrTexture = 5, + TextureSize = 2, + YTexture = 3, + CbCrTexture = 4, } #[repr(C)] -enum PathRasterizationInputIndex { - Vertices = 0, - ViewportSize = 1, -} - -#[derive(Clone, Debug, Eq, PartialEq)] -#[repr(C)] -pub struct PathSprite { - pub bounds: Bounds, +enum PathTileInputIndex { + Tiles = 1, + Curves = 2, + Paints = 3, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -1929,6 +1525,7 @@ impl gpui::PlatformHeadlessRenderer for MetalHeadlessRenderer { #[cfg(test)] mod tests { use super::*; + use gpui::Point; use objc2_core_foundation::{CFDictionary, CFType}; use objc2_core_video::{ CVPixelBufferCreate, CVPixelBufferGetBaseAddressOfPlane, @@ -1937,60 +1534,6 @@ mod tests { }; use objc2_metal::MTLCommandBufferStatus; - #[test] - fn path_intermediate_textures_are_reused_until_resize() -> Result<()> { - let mut renderer = MetalRenderer::new_headless(Default::default())?; - let initial_size = size(DevicePixels(64), DevicePixels(64)); - renderer.update_path_intermediate_textures(initial_size)?; - let initial_texture = renderer - .path_intermediate_texture - .clone() - .context("missing path intermediate texture")?; - let initial_msaa_texture = renderer.path_intermediate_msaa_texture.clone(); - - renderer.update_path_intermediate_textures(initial_size)?; - assert!(ptr::eq( - &*initial_texture, - renderer - .path_intermediate_texture - .as_deref() - .context("missing reused texture")?, - )); - assert_eq!( - initial_msaa_texture.as_ref().map(Retained::as_ptr), - renderer - .path_intermediate_msaa_texture - .as_ref() - .map(Retained::as_ptr), - ); - - renderer.update_path_intermediate_textures(size(DevicePixels(128), DevicePixels(64)))?; - let resized_texture = renderer - .path_intermediate_texture - .as_deref() - .context("missing resized texture")?; - assert_eq!( - (resized_texture.width(), resized_texture.height()), - (128, 64) - ); - assert!(!ptr::eq(&*initial_texture, resized_texture)); - if let Some(texture) = &renderer.path_intermediate_msaa_texture { - assert_eq!((texture.width(), texture.height()), (128, 64)); - } - - for (width, height) in [(0, 64), (64, 0), (-1, 64), (64, -1)] { - renderer.update_path_intermediate_textures(size( - DevicePixels(width), - DevicePixels(height), - ))?; - assert!(renderer.path_intermediate_texture.is_none()); - assert!(renderer.path_intermediate_msaa_texture.is_none()); - renderer.update_path_intermediate_textures(initial_size)?; - assert!(renderer.path_intermediate_texture.is_some()); - } - Ok(()) - } - #[test] fn render_to_image_rejects_zero_sized_layer() -> Result<()> { let mut renderer = MetalRenderer::new(Default::default(), false, false)?; diff --git a/crates/gpui_apple/src/shaders.metal b/crates/gpui_apple/src/shaders.metal index ad227801a38..5a5f2793bd2 100644 --- a/crates/gpui_apple/src/shaders.metal +++ b/crates/gpui_apple/src/shaders.metal @@ -67,15 +67,12 @@ struct QuadFragmentInput { PreparedBackground background; }; -vertex QuadFragmentInput quad_vertex(uint unit_vertex_id [[vertex_id]], - uint quad_id [[instance_id]], - constant float2 *unit_vertices - [[buffer(QuadInputIndex_Vertices)]], - constant Quad *quads - [[buffer(QuadInputIndex_Quads)]], - constant Size_DevicePixels *viewport_size - [[buffer(QuadInputIndex_ViewportSize)]]) { - float2 unit_vertex = unit_vertices[unit_vertex_id]; +vertex QuadFragmentInput quad_vertex( + uint vertex_id [[vertex_id]], uint quad_id [[instance_id]], + constant Quad *quads [[buffer(QuadInputIndex_Quads)]], + constant Size_DevicePixels *viewport_size + [[buffer(GlobalInputIndex_ViewportSize)]]) { + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); Quad quad = quads[quad_id]; ClippedVertex clipped = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask.bounds); @@ -439,12 +436,11 @@ struct ShadowFragmentInput { }; vertex ShadowFragmentInput shadow_vertex( - uint unit_vertex_id [[vertex_id]], uint shadow_id [[instance_id]], - constant float2 *unit_vertices [[buffer(ShadowInputIndex_Vertices)]], + uint vertex_id [[vertex_id]], uint shadow_id [[instance_id]], constant Shadow *shadows [[buffer(ShadowInputIndex_Shadows)]], constant Size_DevicePixels *viewport_size - [[buffer(ShadowInputIndex_ViewportSize)]]) { - float2 unit_vertex = unit_vertices[unit_vertex_id]; + [[buffer(GlobalInputIndex_ViewportSize)]]) { + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); Shadow shadow = shadows[shadow_id]; Bounds_ScaledPixels bounds; @@ -539,12 +535,11 @@ struct UnderlineFragmentInput { }; vertex UnderlineFragmentInput underline_vertex( - uint unit_vertex_id [[vertex_id]], uint underline_id [[instance_id]], - constant float2 *unit_vertices [[buffer(UnderlineInputIndex_Vertices)]], + uint vertex_id [[vertex_id]], uint underline_id [[instance_id]], constant Underline *underlines [[buffer(UnderlineInputIndex_Underlines)]], constant Size_DevicePixels *viewport_size - [[buffer(ShadowInputIndex_ViewportSize)]]) { - float2 unit_vertex = unit_vertices[unit_vertex_id]; + [[buffer(GlobalInputIndex_ViewportSize)]]) { + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); Underline underline = underlines[underline_id]; ClippedVertex clipped = clip_to_mask(unit_vertex, underline.bounds, underline.content_mask.bounds); @@ -596,14 +591,13 @@ struct MonochromeSpriteFragmentInput { }; vertex MonochromeSpriteFragmentInput monochrome_sprite_vertex( - uint unit_vertex_id [[vertex_id]], uint sprite_id [[instance_id]], - constant float2 *unit_vertices [[buffer(SpriteInputIndex_Vertices)]], + uint vertex_id [[vertex_id]], uint sprite_id [[instance_id]], constant MonochromeSprite *sprites [[buffer(SpriteInputIndex_Sprites)]], constant Size_DevicePixels *viewport_size - [[buffer(SpriteInputIndex_ViewportSize)]], + [[buffer(GlobalInputIndex_ViewportSize)]], constant Size_DevicePixels *atlas_size [[buffer(SpriteInputIndex_AtlasTextureSize)]]) { - float2 unit_vertex = unit_vertices[unit_vertex_id]; + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); MonochromeSprite sprite = sprites[sprite_id]; float4 device_position = to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation, viewport_size); @@ -643,15 +637,13 @@ struct PolychromeSpriteFragmentInput { }; vertex PolychromeSpriteFragmentInput polychrome_sprite_vertex( - uint unit_vertex_id [[vertex_id]], uint sprite_id [[instance_id]], - constant float2 *unit_vertices [[buffer(SpriteInputIndex_Vertices)]], + uint vertex_id [[vertex_id]], uint sprite_id [[instance_id]], constant PolychromeSprite *sprites [[buffer(SpriteInputIndex_Sprites)]], constant Size_DevicePixels *viewport_size - [[buffer(SpriteInputIndex_ViewportSize)]], + [[buffer(GlobalInputIndex_ViewportSize)]], constant Size_DevicePixels *atlas_size [[buffer(SpriteInputIndex_AtlasTextureSize)]]) { - - float2 unit_vertex = unit_vertices[unit_vertex_id]; + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); PolychromeSprite sprite = sprites[sprite_id]; ClippedVertex clipped = clip_to_mask(unit_vertex, sprite.bounds, sprite.content_mask.bounds); @@ -693,106 +685,157 @@ fragment float4 polychrome_sprite_fragment( return color; } -struct PathRasterizationVertexOutput { +struct PathTileFragmentInput { float4 position [[position]]; - float2 st_position; - uint vertex_id [[flat]]; - float clip_rect_distance [[clip_distance]][4]; + uint tile_id [[flat]]; + float4 curve_box [[flat]]; + PreparedBackground background; }; -struct PathRasterizationFragmentInput { - float4 position [[position]]; - float2 st_position; - uint vertex_id [[flat]]; -}; +vertex PathTileFragmentInput path_tile_vertex( + uint vertex_id [[vertex_id]], uint tile_id [[instance_id]], + constant PathTile *tiles [[buffer(PathTileInputIndex_Tiles)]], + constant PathPaint *paints [[buffer(PathTileInputIndex_Paints)]], + constant Size_DevicePixels *viewport_size + [[buffer(GlobalInputIndex_ViewportSize)]]) { + PathTile tile = tiles[tile_id]; + PathPaint paint = paints[tile.paint]; -vertex PathRasterizationVertexOutput path_rasterization_vertex( - uint vertex_id [[vertex_id]], - constant PathRasterizationVertex *vertices [[buffer(PathRasterizationInputIndex_Vertices)]], - constant Size_DevicePixels *atlas_size [[buffer(PathRasterizationInputIndex_ViewportSize)]] -) { - PathRasterizationVertex v = vertices[vertex_id]; - float2 vertex_position = float2(v.xy_position.x, v.xy_position.y); - float4 position = float4( - vertex_position * float2(2. / atlas_size->width, -2. / atlas_size->height) + float2(-1., 1.), - 0., - 1. - ); - return PathRasterizationVertexOutput{ - position, - float2(v.st_position.x, v.st_position.y), - vertex_id, - { - v.xy_position.x - v.bounds.origin.x, - v.bounds.origin.x + v.bounds.size.width - v.xy_position.x, - v.xy_position.y - v.bounds.origin.y, - v.bounds.origin.y + v.bounds.size.height - v.xy_position.y - } - }; + float2 mask_top_left = float2(paint.content_mask.bounds.origin.x, + paint.content_mask.bounds.origin.y); + float2 mask_bottom_right = + mask_top_left + float2(paint.content_mask.bounds.size.width, + paint.content_mask.bounds.size.height); + float2 top_left = clamp(float2(tile.top_left.x, tile.top_left.y), + mask_top_left, mask_bottom_right); + float2 bottom_right = clamp(float2(tile.bottom_right.x, tile.bottom_right.y), + top_left, mask_bottom_right); + float2 position = + float2((vertex_id & 1u) != 0u ? bottom_right.x : top_left.x, + (vertex_id & 2u) != 0u ? bottom_right.y : top_left.y); + + return PathTileFragmentInput{ + to_device_position_impl(position, viewport_size), + tile_id, + float4(tile.curves_top_left.x, tile.curves_top_left.y, + tile.curves_bottom_right.x, tile.curves_bottom_right.y), + prepare_background(paint.color)}; } -fragment float4 path_rasterization_fragment( - PathRasterizationFragmentInput input [[stage_in]], - constant PathRasterizationVertex *vertices [[buffer(PathRasterizationInputIndex_Vertices)]] -) { - float2 dx = dfdx(input.st_position); - float2 dy = dfdy(input.st_position); +// Solves a*t^2 + b*t + c = 0 for the root in [0, 1] on a monotone piece. +float monotone_quadratic_root(float a, float b, float c, float direction) { + float discriminant = max(b * b - 4.0 * a * c, 0.0); + float denominator = b + direction * sqrt(discriminant); + if (denominator == 0.0) { + return 0.0; + } + return saturate(-2.0 * c / denominator); +} - PathRasterizationVertex v = vertices[input.vertex_id]; - Background background = v.color; - Bounds_ScaledPixels path_bounds = v.bounds; - float alpha; - if (length(float2(dx.x, dy.x)) < 0.001) { - alpha = 1.0; - } else { - float2 gradient = float2( - (2. * input.st_position.x) * dx.x - dx.y, - (2. * input.st_position.x) * dy.x - dy.y - ); - float f = (input.st_position.x * input.st_position.x) - input.st_position.y; - float distance = f / length(gradient); - alpha = saturate(0.5 - distance); +// Coverage estimate adapted from https://github.com/EricLengyel/Slug/blob/be3c13eb7d63f9e8aa5c583e42d92c374cb91d98/SlugPixelShader.hlsl +// Copyright (c) 2017 Eric Lengyel. +// Licensed under the MIT license. + +// Accumulates the curve's winding along the pixel's leftward and upward rays. +// Like Slug, a crossing within half a pixel of the center counts fractionally. +void add_curve_winding(PathCurve curve, float2 center, thread float2 &winding, + thread float2 &weight) { + float2 p0 = float2(curve.p0.x, curve.p0.y); + float2 p1 = float2(curve.p1.x, curve.p1.y); + float2 a = float2(curve.a.x, curve.a.y); + float2 b = float2(curve.b.x, curve.b.y); + float min_x = min(p0.x, p1.x); + float max_x = max(p0.x, p1.x); + + if (p0.y <= center.y && center.y < p1.y) { + if (max_x <= center.x - 0.5) { + winding.x += curve.sign; + } else { + float t = monotone_quadratic_root(a.y, b.y, p0.y - center.y, 1.0); + float x = (a.x * t + b.x) * t + p0.x; + float distance = center.x - x; + winding.x += curve.sign * saturate(distance + 0.5); + weight.x = max(weight.x, saturate(1.0 - 2.0 * abs(distance))); + } } - float4 color = background_color(prepare_background(background), background, - path_bounds, input.position.xy); - return float4(color.rgb * color.a * alpha, alpha * color.a); + if (min_x <= center.x && center.x < max_x) { + float direction = p1.x > p0.x ? 1.0 : -1.0; + if (p1.y <= center.y - 0.5) { + winding.y -= curve.sign * direction; + } else if (p0.y < center.y + 0.5) { + float t = monotone_quadratic_root(a.x, b.x, p0.x - center.x, direction); + float y = (a.y * t + b.y) * t + p0.y; + float distance = center.y - y; + winding.y -= curve.sign * direction * saturate(distance + 0.5); + weight.y = max(weight.y, saturate(1.0 - 2.0 * abs(distance))); + } + } } -struct PathSpriteVertexOutput { - float4 position [[position]]; - float2 texture_coords; -}; - -vertex PathSpriteVertexOutput path_sprite_vertex( - uint unit_vertex_id [[vertex_id]], - uint sprite_id [[instance_id]], - constant float2 *unit_vertices [[buffer(SpriteInputIndex_Vertices)]], - constant PathSprite *sprites [[buffer(SpriteInputIndex_Sprites)]], - constant Size_DevicePixels *viewport_size [[buffer(SpriteInputIndex_ViewportSize)]] -) { - float2 unit_vertex = unit_vertices[unit_vertex_id]; - PathSprite sprite = sprites[sprite_id]; - // Don't apply content mask because it was already accounted for when - // rasterizing the path. - float4 device_position = - to_device_position(unit_vertex, sprite.bounds, viewport_size); - - float2 screen_position = float2(sprite.bounds.origin.x, sprite.bounds.origin.y) + unit_vertex * float2(sprite.bounds.size.width, sprite.bounds.size.height); - float2 texture_coords = screen_position / float2(viewport_size->width, viewport_size->height); - - return PathSpriteVertexOutput{ - device_position, - texture_coords - }; +// The backdrop gives the unlisted curves' winding along a leftward ray from +// the tile's reference corner. We need it at the current pixel, along both +// leftward and upward rays. Because paths are closed, chains of unlisted +// curves can only begin or end where a listed curve does. So, we can compute +// the winding at the current pixel by correcting the backdrop for each listed +// endpoint between its ray and the pixel. +void correct_for_endpoint(float2 endpoint, float step, float2 reference, + float2 center, thread float2 &winding) { + if (endpoint.x <= reference.x) { + winding.x -= step * (float(endpoint.y <= center.y) - + float(endpoint.y <= reference.y)); + } + if (endpoint.y <= reference.y && endpoint.x <= center.x) { + winding.y += step; + } } -fragment float4 path_sprite_fragment( - PathSpriteVertexOutput input [[stage_in]], - texture2d intermediate_texture [[texture(SpriteInputIndex_AtlasTexture)]] -) { - constexpr sampler intermediate_texture_sampler(mag_filter::linear, min_filter::linear); - return intermediate_texture.sample(intermediate_texture_sampler, input.texture_coords); +fragment float4 path_tile_fragment( + PathTileFragmentInput input [[stage_in]], + constant PathTile *tiles [[buffer(PathTileInputIndex_Tiles)]], + constant PathCurve *curves [[buffer(PathTileInputIndex_Curves)]], + constant PathPaint *paints [[buffer(PathTileInputIndex_Paints)]]) { + float2 center = floor(input.position.xy) + 0.5; + if (input.background.tag == 0u && + (any(center < input.curve_box.xy) || any(center > input.curve_box.zw))) { + return input.background.color0; + } + PathTile tile = tiles[input.tile_id]; + PathPaint paint = paints[tile.paint]; + float2 reference = float2(tile.reference.x, tile.reference.y); + + float2 winding = float2(float(tile.backdrop)); + float2 weight = float2(0.0); + for (uint i = 0u; i < tile.curve_count; i++) { + PathCurve curve = curves[tile.curve_start + i]; + float2 p0 = float2(curve.p0.x, curve.p0.y); + float2 p1 = float2(curve.p1.x, curve.p1.y); + if (min(p0.x, p1.x) >= center.x + 0.5) { + break; + } + if (p0.y < center.y + 0.5) { + add_curve_winding(curve, center, winding, weight); + correct_for_endpoint(p0, curve.sign, reference, center, winding); + correct_for_endpoint(p1, -curve.sign, reference, center, winding); + } + } + + // Weight the winding computed by each ray by its nearest crossing's distance + // from the pixel center, using Slug's technique. + float coverage = + max(abs(dot(winding, weight)) / max(weight.x + weight.y, 1.0 / 65536.0), + min(abs(winding.x), abs(winding.y))); + coverage = paint.even_odd != 0u + ? 1.0 - abs(1.0 - fract(coverage * 0.5) * 2.0) + : saturate(coverage); + + if (coverage == 0.0) { + return float4(0.0); + } + + float4 color = background_color(input.background, paint.color, + paint.bounds, input.position.xy); + return float4(color.rgb, color.a * coverage); } struct SurfaceVertexOutput { @@ -806,14 +849,13 @@ struct SurfaceFragmentInput { }; vertex SurfaceVertexOutput surface_vertex( - uint unit_vertex_id [[vertex_id]], uint surface_id [[instance_id]], - constant float2 *unit_vertices [[buffer(SurfaceInputIndex_Vertices)]], + uint vertex_id [[vertex_id]], uint surface_id [[instance_id]], constant SurfaceBounds *surfaces [[buffer(SurfaceInputIndex_Surfaces)]], constant Size_DevicePixels *viewport_size - [[buffer(SurfaceInputIndex_ViewportSize)]], + [[buffer(GlobalInputIndex_ViewportSize)]], constant Size_DevicePixels *texture_size [[buffer(SurfaceInputIndex_TextureSize)]]) { - float2 unit_vertex = unit_vertices[unit_vertex_id]; + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); SurfaceBounds surface = surfaces[surface_id]; ClippedVertex clipped = clip_to_mask(unit_vertex, surface.bounds, surface.content_mask.bounds); diff --git a/crates/gpui_macos/src/gpui_macos.rs b/crates/gpui_macos/src/gpui_macos.rs index 8732badd321..7f1f124a682 100644 --- a/crates/gpui_macos/src/gpui_macos.rs +++ b/crates/gpui_macos/src/gpui_macos.rs @@ -17,7 +17,7 @@ mod screen_capture; use gpui_apple::metal_renderer as renderer; pub mod metal_renderer { - pub use gpui_apple::metal_renderer::{PathRasterizationVertex, PathSprite, SurfaceBounds}; + pub use gpui_apple::metal_renderer::SurfaceBounds; #[cfg(any(test, feature = "bench-support", feature = "test-support"))] pub use gpui_apple::metal_renderer::MetalHeadlessRenderer; diff --git a/crates/gpui_platform/benches/primitives.rs b/crates/gpui_platform/benches/primitives.rs index 4b19618675f..1f1e129210c 100644 --- a/crates/gpui_platform/benches/primitives.rs +++ b/crates/gpui_platform/benches/primitives.rs @@ -12,9 +12,9 @@ use std::{fmt, rc::Rc, time::Duration}; use gpui::{ App, AtlasTextureId, AtlasTextureKind, AtlasTile, Background, BenchAppContext, Bounds, - BoxShadow, Context, Corners, DevicePixels, Hsla, IntoElement, Path, PathBuilder, Pixels, - Render, Scene, SharedString, Styled, TextAlign, TextRun, TileId, TransformationMatrix, - UnderlineStyle, Window, canvas, fill, hsla, point, + BoxShadow, ContentMask, Context, Corners, DevicePixels, Hsla, IntoElement, PaintedPath, Path, + PathBuilder, Pixels, Render, Scene, SharedString, Styled, TextAlign, TextRun, TileId, + TransformationMatrix, UnderlineStyle, Window, canvas, fill, hsla, point, private::rand::{Rng as _, SeedableRng as _, rngs::StdRng}, px, size, }; @@ -80,9 +80,12 @@ enum Kind { Quad, Shadow, Underline, - /// Tessellated before timing: path tessellation is measured by the tree benchmarks, - /// and would otherwise dominate what these cases are for. - Path(Path), + /// Built and binned before timing, since binning would otherwise dominate what these + /// cases are for. The window paints `path`, and the scene takes a copy of `painted`. + Path { + path: Path, + painted: PaintedPath, + }, Text(SharedString), } @@ -113,7 +116,10 @@ fn random_rectangles(seed: u64, count: usize, extent: f32) -> Rc<[Rectangle]> { 0..9 => Kind::Quad, 9..11 => Kind::Shadow, 11..13 => Kind::Underline, - 13..16 => triangle(bounds).map_or(Kind::Quad, Kind::Path), + 13..16 => triangle(bounds).map_or(Kind::Quad, |path| Kind::Path { + painted: PaintedPath::new(path.clone(), 1., scene_content_mask(), color.into()), + path, + }), _ => { let length = rng.random_range(1..12); Kind::Text("Ag3 Wq7 fixture"[..length].to_string().into()) @@ -130,7 +136,7 @@ fn random_rectangles(seed: u64, count: usize, extent: f32) -> Rc<[Rectangle]> { .into() } -fn triangle(bounds: Bounds) -> Option> { +fn triangle(bounds: Bounds) -> Option { let mut path = PathBuilder::fill(); path.move_to(bounds.origin); path.line_to(bounds.top_right()); @@ -236,7 +242,7 @@ fn paint(rectangle: &Rectangle, window: &mut Window, cx: &mut App) { wavy: false, }, ), - Kind::Path(path) => window.paint_path(path.clone(), rectangle.color), + Kind::Path { path, .. } => window.paint_path(path.clone(), rectangle.color), // Shaped every frame, as the text element does; the line layout cache makes // repeated shaping a lookup. Kind::Text(text) => { @@ -283,11 +289,15 @@ fn glyph_tile(index: usize) -> AtlasTile { } } +fn scene_content_mask() -> ContentMask { + ContentMask { + bounds: Bounds::new(point(px(0.), px(0.)), size(px(1_024.), px(1_024.))), + } +} + fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { scene.clear(); - let content_mask = gpui::ContentMask { - bounds: Bounds::new(point(px(0.), px(0.)), size(px(1_024.), px(1_024.))).scale(1.), - }; + let content_mask = scene_content_mask().scale(1.); for (index, rectangle) in rectangles.iter().enumerate() { let bounds = rectangle.bounds.scale(1.); match &rectangle.kind { @@ -322,12 +332,7 @@ fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { thickness: bounds.size.height.min(gpui::ScaledPixels(4.)), wavy: Default::default(), }), - Kind::Path(path) => { - let mut path = path.scale(1.); - path.content_mask = content_mask; - path.color = rectangle.background; - scene.insert_primitive(path); - } + Kind::Path { painted, .. } => scene.insert_primitive(painted.clone()), Kind::Text(text) => { let glyph_size = bounds.size.height.min(gpui::ScaledPixels(32.)); for glyph in 0..text.len() { diff --git a/crates/gpui_wgpu/src/shaders.wgsl b/crates/gpui_wgpu/src/shaders.wgsl index 34129856744..f62cf8240eb 100644 --- a/crates/gpui_wgpu/src/shaders.wgsl +++ b/crates/gpui_wgpu/src/shaders.wgsl @@ -79,10 +79,12 @@ fn apply_contrast_and_gamma_correction3(sample: vec3, color: vec3, enh struct GlobalParams { viewport_size: vec2, - premultiplied_alpha: u32, - pad: u32, + path_paint_base: u32, + path_curve_base: u32, } +override PREMULTIPLIED_ALPHA: bool = false; + struct GammaParams { gamma_ratios: vec4, grayscale_enhanced_contrast: f32, @@ -404,7 +406,7 @@ fn quad_sdf_impl(corner_center_to_point: vec2, corner_radius: f32) -> f32 { // target alpha compositing mode. fn blend_color(color: vec4, alpha_factor: f32) -> vec4 { let alpha = color.a * alpha_factor; - let multiplier = select(1.0, alpha, globals.premultiplied_alpha != 0u); + let multiplier = select(1.0, alpha, PREMULTIPLIED_ALPHA); return vec4(color.rgb * multiplier, alpha); } @@ -1054,97 +1056,177 @@ fn fs_shadow(input: ShadowVarying) -> @location(0) vec4 { return blend_color(input.color, alpha); } -// --- path rasterization --- // +// --- path tiles --- // -struct PathRasterizationVertex { - xy_position: vec2, - st_position: vec2, - color: Background, - bounds: Bounds, +struct PathTile { + paint: u32, + curve_start: u32, + curve_count: u32, + backdrop: i32, + top_left: vec2, + bottom_right: vec2, + reference: vec2, + curves_top_left: vec2, + curves_bottom_right: vec2, } +struct PathCurve { + p0: vec2, + p1: vec2, + a: vec2, + b: vec2, + sign: f32, + pad: u32, +} +struct PathPaint { + bounds: Bounds, + content_mask: Bounds, + color: Background, + even_odd: u32, + pad: u32, +} -struct PathRasterizationVarying { +struct PathTileVarying { @builtin(position) position: vec4, - @location(0) st_position: vec2, - @location(1) @interpolate(flat) vertex_id: u32, - //TODO: use `clip_distance` once Naga supports it - @location(3) clip_distances: vec4, + @location(0) @interpolate(flat) tile_id: u32, + // Inter-stage values can't be structs, so `PreparedBackground` is flattened. + @location(1) @interpolate(flat) background_color0: vec4, + @location(2) @interpolate(flat) background_color1: vec4, + @location(3) @interpolate(flat) background_tag: u32, + @location(4) @interpolate(flat) curve_box: vec4, } @vertex -fn vs_path_rasterization(@builtin(vertex_index) vertex_id: u32) -> PathRasterizationVarying { - let v = load_path_vertex(vertex_id); +fn vs_path_tile(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PathTileVarying { + let tile = load_path_tile(instance_id); + let paint = load_path_paint(tile.paint); - var out = PathRasterizationVarying(); - out.position = to_device_position_impl(v.xy_position); - out.st_position = v.st_position; - out.vertex_id = vertex_id; - out.clip_distances = distance_from_clip_rect_impl(v.xy_position, v.bounds); + let mask_top_left = paint.content_mask.origin; + let mask_bottom_right = paint.content_mask.origin + paint.content_mask.size; + let top_left = clamp(tile.top_left, mask_top_left, mask_bottom_right); + let bottom_right = clamp(tile.bottom_right, top_left, mask_bottom_right); + let position = vec2( + select(top_left.x, bottom_right.x, (vertex_id & 1u) != 0u), + select(top_left.y, bottom_right.y, (vertex_id & 2u) != 0u), + ); + + var out = PathTileVarying(); + out.position = to_device_position_impl(position); + out.tile_id = instance_id; + out.curve_box = vec4(tile.curves_top_left, tile.curves_bottom_right); + let background = prepare_background(paint.color); + out.background_color0 = background.color0; + out.background_color1 = background.color1; + out.background_tag = background.tag; return out; } +// Solves a*t^2 + b*t + c = 0 for the root in [0, 1] on a monotone piece. +fn monotone_quadratic_root(a: f32, b: f32, c: f32, direction: f32) -> f32 { + let discriminant = max(b * b - 4.0 * a * c, 0.0); + let denominator = b + direction * sqrt(discriminant); + if (denominator == 0.0) { + return 0.0; + } + return saturate(-2.0 * c / denominator); +} + +// Coverage estimate adapted from https://github.com/EricLengyel/Slug/blob/be3c13eb7d63f9e8aa5c583e42d92c374cb91d98/SlugPixelShader.hlsl +// Copyright (c) 2017 Eric Lengyel. +// Licensed under the MIT license. + +// Accumulates the curve's winding along the pixel's leftward and upward rays. Like Slug, a crossing +// within half a pixel of the center counts fractionally. +fn add_curve_winding(curve: PathCurve, center: vec2, winding: ptr>, + weight: ptr>) { + let min_x = min(curve.p0.x, curve.p1.x); + let max_x = max(curve.p0.x, curve.p1.x); + + if (curve.p0.y <= center.y && center.y < curve.p1.y) { + if (max_x <= center.x - 0.5) { + (*winding).x += curve.sign; + } else { + let t = monotone_quadratic_root(curve.a.y, curve.b.y, curve.p0.y - center.y, 1.0); + let x = (curve.a.x * t + curve.b.x) * t + curve.p0.x; + let distance = center.x - x; + (*winding).x += curve.sign * saturate(distance + 0.5); + (*weight).x = max((*weight).x, saturate(1.0 - 2.0 * abs(distance))); + } + } + + if (min_x <= center.x && center.x < max_x) { + let direction = select(-1.0, 1.0, curve.p1.x > curve.p0.x); + if (curve.p1.y <= center.y - 0.5) { + (*winding).y -= curve.sign * direction; + } else if (curve.p0.y < center.y + 0.5) { + let t = monotone_quadratic_root(curve.a.x, curve.b.x, curve.p0.x - center.x, direction); + let y = (curve.a.y * t + curve.b.y) * t + curve.p0.y; + let distance = center.y - y; + (*winding).y -= curve.sign * direction * saturate(distance + 0.5); + (*weight).y = max((*weight).y, saturate(1.0 - 2.0 * abs(distance))); + } + } +} + +// The backdrop gives the unlisted curves' winding along a leftward ray from the tile's reference +// corner. We need it at the current pixel, along both leftward and upward rays. Because paths are +// closed, chains of unlisted curves can only begin or end where a listed curve does. So, we can +// compute the winding at the current pixel by correcting the backdrop for each listed endpoint +// between its ray and the pixel. +fn correct_for_endpoint(endpoint: vec2, step: f32, reference: vec2, center: vec2, + winding: ptr>) { + if (endpoint.x <= reference.x) { + (*winding).x -= step * (f32(endpoint.y <= center.y) - f32(endpoint.y <= reference.y)); + } + if (endpoint.y <= reference.y && endpoint.x <= center.x) { + (*winding).y += step; + } +} + @fragment -fn fs_path_rasterization(input: PathRasterizationVarying) -> @location(0) vec4 { - let dx = dpdx(input.st_position); - let dy = dpdy(input.st_position); - if (any(input.clip_distances < vec4(0.0))) { +fn fs_path_tile(input: PathTileVarying) -> @location(0) vec4 { + let center = floor(input.position.xy) + 0.5; + if (input.background_tag == 0u + && (any(center < input.curve_box.xy) || any(center > input.curve_box.zw))) { + return blend_color(input.background_color0, 1.0); + } + let tile = load_path_tile(input.tile_id); + let paint = load_path_paint(tile.paint); + + var winding = vec2(f32(tile.backdrop)); + var weight = vec2(0.0); + for (var i = 0u; i < tile.curve_count; i++) { + let curve = load_path_curve(tile.curve_start + i); + if (min(curve.p0.x, curve.p1.x) >= center.x + 0.5) { + break; + } + if (curve.p0.y < center.y + 0.5) { + add_curve_winding(curve, center, &winding, &weight); + correct_for_endpoint(curve.p0, curve.sign, tile.reference, center, &winding); + correct_for_endpoint(curve.p1, -curve.sign, tile.reference, center, &winding); + } + } + + // Weight the winding computed by each ray by its nearest crossing's distance from the pixel center, + // using Slug's technique. + var coverage = max( + abs(dot(winding, weight)) / max(weight.x + weight.y, 1.0 / 65536.0), + min(abs(winding.x), abs(winding.y))); + if (paint.even_odd != 0u) { + coverage = 1.0 - abs(1.0 - fract(coverage * 0.5) * 2.0); + } else { + coverage = saturate(coverage); + } + + if (coverage == 0.0) { return vec4(0.0); } - let v = load_path_vertex(input.vertex_id); - let background = v.color; - let bounds = v.bounds; - - var alpha: f32; - if (length(vec2(dx.x, dy.x)) < 0.001) { - // If the gradient is too small, return a solid color. - alpha = 1.0; - } else { - let gradient = 2.0 * input.st_position.xx * vec2(dx.x, dy.x) - vec2(dx.y, dy.y); - let f = input.st_position.x * input.st_position.x - input.st_position.y; - let distance = f / length(gradient); - alpha = saturate(0.5 - distance); - } - let color = background_color(prepare_background(background), background, bounds, - input.position.xy); - return vec4(color.rgb * color.a * alpha, color.a * alpha); -} - -// --- paths --- // - -struct PathSprite { - bounds: Bounds, -} - - -struct PathVarying { - @builtin(position) position: vec4, - @location(0) texture_coords: vec2, -} - -@vertex -fn vs_path(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PathVarying { - let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); - let sprite = load_path_sprite(instance_id); - // Don't apply content mask because it was already accounted for when rasterizing the path. - let device_position = to_device_position(unit_vertex, sprite.bounds); - // For screen-space intermediate texture, convert screen position to texture coordinates - let screen_position = sprite.bounds.origin + unit_vertex * sprite.bounds.size; - let texture_coords = screen_position / globals.viewport_size; - - var out = PathVarying(); - out.position = device_position; - out.texture_coords = texture_coords; - - return out; -} - -@fragment -fn fs_path(input: PathVarying) -> @location(0) vec4 { - let sample = textureSample(t_sprite, s_sprite, input.texture_coords); - return sample; + let prepared = PreparedBackground(input.background_color0, input.background_color1, + input.background_tag); + let color = background_color(prepared, paint.color, paint.bounds, input.position.xy); + return blend_color(color, coverage); } // --- underlines --- // diff --git a/crates/gpui_wgpu/src/shaders_storage.wgsl b/crates/gpui_wgpu/src/shaders_storage.wgsl index 55b80802e6c..08d31698157 100644 --- a/crates/gpui_wgpu/src/shaders_storage.wgsl +++ b/crates/gpui_wgpu/src/shaders_storage.wgsl @@ -7,8 +7,6 @@ @group(1) @binding(0) var b_quads: array; @group(1) @binding(0) var b_shadows: array; -@group(1) @binding(0) var b_path_vertices: array; -@group(1) @binding(0) var b_path_sprites: array; @group(1) @binding(0) var b_underlines: array; @group(1) @binding(0) var b_mono_sprites: array; @group(1) @binding(0) var b_poly_sprites: array; @@ -21,12 +19,20 @@ fn load_shadow(instance_id: u32) -> Shadow { return b_shadows[instance_id]; } -fn load_path_vertex(vertex_id: u32) -> PathRasterizationVertex { - return b_path_vertices[vertex_id]; +@group(1) @binding(0) var b_path_tiles: array; +@group(1) @binding(1) var b_path_curves: array; +@group(1) @binding(2) var b_path_paints: array; + +fn load_path_tile(instance_id: u32) -> PathTile { + return b_path_tiles[instance_id]; } -fn load_path_sprite(instance_id: u32) -> PathSprite { - return b_path_sprites[instance_id]; +fn load_path_curve(index: u32) -> PathCurve { + return b_path_curves[index]; +} + +fn load_path_paint(index: u32) -> PathPaint { + return b_path_paints[index]; } fn load_underline(instance_id: u32) -> Underline { diff --git a/crates/gpui_wgpu/src/shaders_webgl.wgsl b/crates/gpui_wgpu/src/shaders_webgl.wgsl index e28a56568c6..66f95950772 100644 --- a/crates/gpui_wgpu/src/shaders_webgl.wgsl +++ b/crates/gpui_wgpu/src/shaders_webgl.wgsl @@ -206,19 +206,43 @@ fn load_shadow(instance_id: u32) -> Shadow { ); } -fn load_path_vertex(vertex_id: u32) -> PathRasterizationVertex { - var cursor = instance_cursor(vertex_id * 26u); - return PathRasterizationVertex( +fn load_path_tile(instance_id: u32) -> PathTile { + var cursor = instance_cursor(instance_id * 14u); + return PathTile( + read_word(&cursor), + read_word(&cursor), + read_word(&cursor), + read_i32(&cursor), + read_vec2_f32(&cursor), + read_vec2_f32(&cursor), + read_vec2_f32(&cursor), read_vec2_f32(&cursor), read_vec2_f32(&cursor), - read_background(&cursor), - read_bounds(&cursor), ); } -fn load_path_sprite(instance_id: u32) -> PathSprite { - var cursor = instance_cursor(instance_id * 4u); - return PathSprite(read_bounds(&cursor)); +// Tiles index this frame's paint and curve arrays, which start at the bases in `globals`. +fn load_path_curve(index: u32) -> PathCurve { + var cursor = instance_cursor((globals.path_curve_base + index) * 10u); + return PathCurve( + read_vec2_f32(&cursor), + read_vec2_f32(&cursor), + read_vec2_f32(&cursor), + read_vec2_f32(&cursor), + read_f32(&cursor), + read_word(&cursor), + ); +} + +fn load_path_paint(index: u32) -> PathPaint { + var cursor = instance_cursor((globals.path_paint_base + index) * 28u); + return PathPaint( + read_bounds(&cursor), + read_bounds(&cursor), + read_background(&cursor), + read_word(&cursor), + read_word(&cursor), + ); } fn load_underline(instance_id: u32) -> Underline { diff --git a/crates/gpui_wgpu/src/wgpu_renderer.rs b/crates/gpui_wgpu/src/wgpu_renderer.rs index 46f9ffdb989..73fa8e2a3d1 100644 --- a/crates/gpui_wgpu/src/wgpu_renderer.rs +++ b/crates/gpui_wgpu/src/wgpu_renderer.rs @@ -3,8 +3,8 @@ use anyhow::{Context as _, Result}; use bytemuck::{Pod, Zeroable}; use collections::FxHashMap; use gpui::{ - AtlasTextureId, Background, Bounds, DevicePixels, GpuSpecs, Path, Point, PrimitiveBatch, - ScaledPixels, Scene, Size, get_gamma_correction_ratios, + AtlasTextureId, Bounds, DevicePixels, GpuSpecs, PaintedPath, PrimitiveBatch, ScaledPixels, + Scene, Size, get_gamma_correction_ratios, }; use log::warn; #[cfg(not(target_family = "wasm"))] @@ -59,8 +59,8 @@ fn least_common_multiple(left: u64, right: u64) -> u64 { #[derive(Clone, Copy, Pod, Zeroable)] struct GlobalParams { viewport_size: [f32; 2], - premultiplied_alpha: u32, - pad: u32, + path_paint_base: u32, + path_curve_base: u32, } #[repr(C)] @@ -96,21 +96,6 @@ struct GammaParams { _pad: u32, } -#[derive(Clone, Debug)] -#[repr(C)] -struct PathSprite { - bounds: Bounds, -} - -#[derive(Clone, Debug)] -#[repr(C)] -struct PathRasterizationVertex { - xy_position: Point, - st_position: Point, - color: Background, - bounds: Bounds, -} - pub struct WgpuSurfaceConfig { pub size: Size, pub transparent: bool, @@ -126,8 +111,7 @@ pub struct WgpuSurfaceConfig { struct WgpuPipelines { quads: wgpu::RenderPipeline, shadows: wgpu::RenderPipeline, - path_rasterization: wgpu::RenderPipeline, - paths: wgpu::RenderPipeline, + path_tiles: wgpu::RenderPipeline, underlines: wgpu::RenderPipeline, mono_sprites: wgpu::RenderPipeline, subpixel_sprites: Option, @@ -147,9 +131,23 @@ struct InstanceBinding { first_instance: u32, } +struct PathTileBinding { + tiles: InstanceBinding, + paint_base: u32, + curve_base: u32, +} + +/// Where one array of instance data was written this frame. +struct InstanceAllocation { + offset: u64, + size: u64, + first_instance: u32, +} + struct InstanceBindings { quads: InstanceBinding, shadows: InstanceBinding, + path_tiles: PathTileBinding, underlines: InstanceBinding, monochrome_sprites: InstanceBinding, subpixel_sprites: InstanceBinding, @@ -159,6 +157,7 @@ struct InstanceBindings { struct WgpuBindGroupLayouts { globals: wgpu::BindGroupLayout, instances: wgpu::BindGroupLayout, + path_tiles: wgpu::BindGroupLayout, texture: wgpu::BindGroupLayout, surfaces: wgpu::BindGroupLayout, } @@ -188,12 +187,7 @@ struct WgpuResources { atlas_texture_bind_groups: FxHashMap, globals_buffer: wgpu::Buffer, globals_bind_group: wgpu::BindGroup, - path_globals_bind_group: wgpu::BindGroup, instance_data: InstanceData, - path_intermediate_texture: Option, - path_intermediate_view: Option, - path_msaa_texture: Option, - path_msaa_view: Option, } struct CachedTextureBindGroup { @@ -201,19 +195,9 @@ struct CachedTextureBindGroup { bind_group: wgpu::BindGroup, } -impl WgpuResources { - fn invalidate_intermediate_textures(&mut self) { - self.path_intermediate_texture = None; - self.path_intermediate_view = None; - self.path_msaa_texture = None; - self.path_msaa_view = None; - } -} - struct WgpuRendererCore { resources: WgpuResources, atlas: Arc, - path_globals_offset: u64, gamma_offset: u64, instance_data_capacity: u64, max_instance_data_size: u64, @@ -223,6 +207,11 @@ struct WgpuRendererCore { is_bgr: bool, dual_source_blending: bool, adapter_info: wgpu::AdapterInfo, + /// Read by the headless renderer to create its render target. + #[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") + ))] target_format: wgpu::TextureFormat, max_texture_size: u32, } @@ -579,6 +568,30 @@ impl WgpuRendererCore { entries: &[instance_data_entry], }); + // Path tiles read their curves and paints too. The texture transport + // reads all three from the one instance texture. + let path_tiles = if uses_webgl_instance_data { + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("path_tiles_layout"), + entries: &[instance_data_entry], + }) + } else { + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("path_tiles_layout"), + entries: &[ + instance_data_entry, + wgpu::BindGroupLayoutEntry { + binding: 1, + ..instance_data_entry + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + ..instance_data_entry + }, + ], + }) + }; + let texture = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("texture_layout"), entries: &[ @@ -648,6 +661,7 @@ impl WgpuRendererCore { WgpuBindGroupLayouts { globals, instances, + path_tiles, texture, surfaces, } @@ -696,7 +710,6 @@ impl WgpuRendererCore { layouts: &WgpuBindGroupLayouts, surface_format: wgpu::TextureFormat, alpha_mode: wgpu::CompositeAlphaMode, - path_sample_count: u32, dual_source_blending: bool, uses_webgl_instance_data: bool, ) -> WgpuPipelines { @@ -742,11 +755,15 @@ impl WgpuRendererCore { None }; - let blend_mode = match alpha_mode { - wgpu::CompositeAlphaMode::PreMultiplied => { - wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING - } - _ => wgpu::BlendState::ALPHA_BLENDING, + let premultiplied_alpha = alpha_mode == wgpu::CompositeAlphaMode::PreMultiplied; + let blend_mode = if premultiplied_alpha { + wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING + } else { + wgpu::BlendState::ALPHA_BLENDING + }; + let compilation_options = wgpu::PipelineCompilationOptions { + constants: &[("PREMULTIPLIED_ALPHA", f64::from(premultiplied_alpha as u8))], + ..Default::default() }; let color_target = wgpu::ColorTargetState { @@ -780,13 +797,13 @@ impl WgpuRendererCore { module, entry_point: Some(vs_entry), buffers: &[], - compilation_options: wgpu::PipelineCompilationOptions::default(), + compilation_options: compilation_options.clone(), }, fragment: Some(wgpu::FragmentState { module, entry_point: Some(fs_entry), targets: color_targets, - compilation_options: wgpu::PipelineCompilationOptions::default(), + compilation_options: compilation_options.clone(), }), primitive: wgpu::PrimitiveState { topology, @@ -834,36 +851,15 @@ impl WgpuRendererCore { &shader_module, ); - let path_rasterization = create_pipeline( - "path_rasterization", - "vs_path_rasterization", - "fs_path_rasterization", + let path_tiles = create_pipeline( + "path_tiles", + "vs_path_tile", + "fs_path_tile", &layouts.globals, - &layouts.instances, + &layouts.path_tiles, None, - wgpu::PrimitiveTopology::TriangleList, - &[Some(wgpu::ColorTargetState { - format: surface_format, - blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), - write_mask: wgpu::ColorWrites::ALL, - })], - path_sample_count, - &shader_module, - ); - - let paths = create_pipeline( - "paths", - "vs_path", - "fs_path", - &layouts.globals, - &layouts.instances, - Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, - &[Some(wgpu::ColorTargetState { - format: surface_format, - blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), - write_mask: wgpu::ColorWrites::ALL, - })], + &[Some(color_target.clone())], 1, &shader_module, ); @@ -957,8 +953,7 @@ impl WgpuRendererCore { WgpuPipelines { quads, shadows, - path_rasterization, - paths, + path_tiles, underlines, mono_sprites, subpixel_sprites, @@ -966,58 +961,6 @@ impl WgpuRendererCore { surfaces, } } - - fn create_path_intermediate( - device: &wgpu::Device, - format: wgpu::TextureFormat, - width: u32, - height: u32, - ) -> (wgpu::Texture, wgpu::TextureView) { - let texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some("path_intermediate"), - size: wgpu::Extent3d { - width: width.max(1), - height: height.max(1), - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, - view_formats: &[], - }); - let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); - (texture, view) - } - - fn create_msaa_if_needed( - device: &wgpu::Device, - format: wgpu::TextureFormat, - width: u32, - height: u32, - sample_count: u32, - ) -> Option<(wgpu::Texture, wgpu::TextureView)> { - if sample_count <= 1 { - return None; - } - let texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some("path_msaa"), - size: wgpu::Extent3d { - width: width.max(1), - height: height.max(1), - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count, - dimension: wgpu::TextureDimension::D2, - format, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, - view_formats: &[], - }); - let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); - Some((texture, view)) - } } impl WgpuRenderer { @@ -1043,32 +986,6 @@ impl WgpuRenderer { self.surface_config.width = clamped_width.max(1); self.surface_config.height = clamped_height.max(1); - let Some(core) = self.core_mut() else { - return; - }; - let resources = &mut core.resources; - - // Wait for any in-flight GPU work to complete before destroying textures - if let Err(e) = resources.device.poll(wgpu::PollType::Wait { - submission_index: None, - timeout: None, - }) { - warn!("Failed to poll device during resize: {e:?}"); - } - - // Destroy old textures before allocating new ones to avoid GPU memory spikes - if let Some(ref texture) = resources.path_intermediate_texture { - texture.destroy(); - } - if let Some(ref texture) = resources.path_msaa_texture { - texture.destroy(); - } - - // Invalidate intermediate textures - they will be lazily recreated - // in draw() after we confirm the surface is healthy. This avoids - // panics when the device/surface is in an invalid state during resize. - resources.invalidate_intermediate_textures(); - if let RendererState::Ready { surface, core } = &self.state { surface.configure(&core.resources.device, &self.surface_config); } @@ -1096,16 +1013,7 @@ impl WgpuRenderer { let Some(core) = self.core_mut() else { return; }; - let resources = &mut core.resources; - resources.pipelines = WgpuRendererCore::create_pipelines( - &resources.device, - &resources.bind_group_layouts, - format, - new_alpha_mode, - core.rendering_params.path_sample_count, - core.dual_source_blending, - core.uses_webgl_instance_data, - ); + core.rebuild_pipelines(format, new_alpha_mode); if let RendererState::Ready { surface, core } = &self.state { surface.configure(&core.resources.device, &self.surface_config); @@ -1178,7 +1086,6 @@ impl WgpuRenderer { if self.failed_frame_count > 10 { panic!("Too many consecutive GPU errors. Last error: {error}"); } else if self.failed_frame_count > 5 { - core.resources.invalidate_intermediate_textures(); self.atlas.clear(); self.needs_redraw = true; self.failed_frame_count = 0; @@ -1218,15 +1125,7 @@ impl WgpuRenderer { let frame_view = frame .texture .create_view(&wgpu::TextureViewDescriptor::default()); - let premultiplied_alpha = - self.surface_config.alpha_mode == wgpu::CompositeAlphaMode::PreMultiplied; - if let Err(error) = core.render_frame( - scene, - &frame_view, - size, - premultiplied_alpha, - wgpu::Color::TRANSPARENT, - ) { + if let Err(error) = core.render_frame(scene, &frame_view, size, wgpu::Color::TRANSPARENT) { log::error!("{error:#}"); return false; } @@ -1245,7 +1144,7 @@ impl WgpuRendererCore { ) -> Self { let device = Arc::clone(&context.device); let queue = Arc::clone(&context.queue); - let rendering_params = RenderingParameters::new(&context.adapter, target_format); + let rendering_params = RenderingParameters::new(); let uses_webgl_instance_data = context.uses_webgl_instance_data(); let dual_source_blending = context.supports_dual_source_blending() && !uses_webgl_instance_data; @@ -1255,7 +1154,6 @@ impl WgpuRendererCore { &bind_group_layouts, target_format, alpha_mode, - rendering_params.path_sample_count, dual_source_blending, uses_webgl_instance_data, ); @@ -1268,8 +1166,7 @@ impl WgpuRendererCore { let uniform_alignment = device.limits().min_uniform_buffer_offset_alignment as u64; let globals_size = std::mem::size_of::() as u64; let gamma_size = std::mem::size_of::() as u64; - let path_globals_offset = globals_size.next_multiple_of(uniform_alignment); - let gamma_offset = (path_globals_offset + globals_size).next_multiple_of(uniform_alignment); + let gamma_offset = globals_size.next_multiple_of(uniform_alignment); let globals_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("globals_buffer"), size: gamma_offset + gamma_size, @@ -1337,28 +1234,6 @@ impl WgpuRendererCore { }, ], }); - let path_globals_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("path_globals_bind_group"), - layout: &bind_group_layouts.globals, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { - buffer: &globals_buffer, - offset: path_globals_offset, - size: NonZeroU64::new(globals_size), - }), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { - buffer: &globals_buffer, - offset: gamma_offset, - size: NonZeroU64::new(gamma_size), - }), - }, - ], - }); let max_texture_size = device.limits().max_texture_dimension_2d; Self { @@ -1371,15 +1246,9 @@ impl WgpuRendererCore { atlas_texture_bind_groups: FxHashMap::default(), globals_buffer, globals_bind_group, - path_globals_bind_group, instance_data, - path_intermediate_texture: None, - path_intermediate_view: None, - path_msaa_texture: None, - path_msaa_view: None, }, atlas, - path_globals_offset, gamma_offset, instance_data_capacity, max_instance_data_size, @@ -1389,6 +1258,10 @@ impl WgpuRendererCore { is_bgr: false, dual_source_blending, adapter_info: context.adapter.get_info(), + #[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") + ))] target_format, max_texture_size, } @@ -1398,44 +1271,23 @@ impl WgpuRendererCore { &self.resources } - fn resources_mut(&mut self) -> &mut WgpuResources { - &mut self.resources + fn rebuild_pipelines( + &mut self, + surface_format: wgpu::TextureFormat, + alpha_mode: wgpu::CompositeAlphaMode, + ) { + self.resources.pipelines = Self::create_pipelines( + &self.resources.device, + &self.resources.bind_group_layouts, + surface_format, + alpha_mode, + self.dual_source_blending, + self.uses_webgl_instance_data, + ); } - /// Path rendering goes through an intermediate texture that must match the frame - /// target's dimensions, so the textures are keyed by size and rebuilt on mismatch. - fn ensure_intermediate_textures(&mut self, size: Size) { - let width = size.width.0 as u32; - let height = size.height.0 as u32; - if self - .resources - .path_intermediate_texture - .as_ref() - .is_some_and(|texture| texture.width() == width && texture.height() == height) - { - return; - } - - let format = self.target_format; - let path_sample_count = self.rendering_params.path_sample_count; - let resources = &mut self.resources; - - let (texture, view) = - Self::create_path_intermediate(&resources.device, format, width, height); - resources.path_intermediate_texture = Some(texture); - resources.path_intermediate_view = Some(view); - - let (path_msaa_texture, path_msaa_view) = Self::create_msaa_if_needed( - &resources.device, - format, - width, - height, - path_sample_count, - ) - .map(|(texture, view)| (Some(texture), Some(view))) - .unwrap_or((None, None)); - resources.path_msaa_texture = path_msaa_texture; - resources.path_msaa_view = path_msaa_view; + fn resources_mut(&mut self) -> &mut WgpuResources { + &mut self.resources } fn render_frame( @@ -1443,7 +1295,6 @@ impl WgpuRendererCore { scene: &Scene, target_view: &wgpu::TextureView, size: Size, - premultiplied_alpha: bool, clear_color: wgpu::Color, ) -> Result { anyhow::ensure!( @@ -1458,7 +1309,6 @@ impl WgpuRendererCore { ); self.atlas.before_frame(); - self.ensure_intermediate_textures(size); let gamma_params = GammaParams { gamma_ratios: self.rendering_params.gamma_ratios, @@ -1467,32 +1317,13 @@ impl WgpuRendererCore { is_bgr: self.is_bgr as u32, _pad: 0, }; - let globals = GlobalParams { - viewport_size: [size.width.0 as f32, size.height.0 as f32], - premultiplied_alpha: premultiplied_alpha as u32, - pad: 0, - }; - let path_globals = GlobalParams { - premultiplied_alpha: 0, - ..globals - }; - self.resources.queue.write_buffer( - &self.resources.globals_buffer, - 0, - bytemuck::bytes_of(&globals), - ); - self.resources.queue.write_buffer( - &self.resources.globals_buffer, - self.path_globals_offset, - bytemuck::bytes_of(&path_globals), - ); self.resources.queue.write_buffer( &self.resources.globals_buffer, self.gamma_offset, bytemuck::bytes_of(&gamma_params), ); - self.record_frame(scene, target_view, clear_color) + self.record_frame(scene, target_view, size, clear_color) .inspect_err(|_| { // Queue writes are staged before encoding; flush them even if the frame fails. self.resources.queue.submit(std::iter::empty()); @@ -1503,6 +1334,7 @@ impl WgpuRendererCore { &mut self, scene: &Scene, frame_view: &wgpu::TextureView, + size: Size, clear_color: wgpu::Color, ) -> Result { let mut instance_offset = 0; @@ -1520,6 +1352,16 @@ impl WgpuRendererCore { scene.polychrome_sprites.len(), ) })?; + let globals = GlobalParams { + viewport_size: [size.width.0 as f32, size.height.0 as f32], + path_paint_base: instance_bindings.path_tiles.paint_base, + path_curve_base: instance_bindings.path_tiles.curve_base, + }; + self.resources().queue.write_buffer( + &self.resources().globals_buffer, + 0, + bytemuck::bytes_of(&globals), + ); self.prepare_texture_bind_groups(scene); let mut encoder = @@ -1544,7 +1386,9 @@ impl WgpuRendererCore { depth_stencil_attachment: None, ..Default::default() }); + pass.set_bind_group(0, &self.resources().globals_bind_group, &[]); + let mut path_tile_cursor = 0; for batch in scene.batches() { match batch { PrimitiveBatch::Quads(range) => self.draw_instances( @@ -1560,40 +1404,17 @@ impl WgpuRendererCore { &mut pass, ), PrimitiveBatch::Paths(range) => { - let paths = &scene.paths[range]; - if paths.is_empty() { - continue; - } - - drop(pass); - let rasterized = self.draw_paths_to_intermediate( - &mut encoder, - paths, - &mut instance_offset, - )?; - - pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("main_pass_continued"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: frame_view, - resolve_target: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Load, - store: wgpu::StoreOp::Store, - }, - depth_slice: None, - })], - depth_stencil_attachment: None, - ..Default::default() - }); - - if rasterized { - self.draw_paths_from_intermediate( - paths, - &mut instance_offset, - &mut pass, - )?; - } + let tiles_start = path_tile_cursor; + path_tile_cursor += scene.paths[range] + .iter() + .map(PaintedPath::tile_count) + .sum::(); + self.draw_instances( + &instance_bindings.path_tiles.tiles, + &self.resources().pipelines.path_tiles, + instance_range(tiles_start..path_tile_cursor), + &mut pass, + ) } PrimitiveBatch::Underlines(range) => self.draw_instances( &instance_bindings.underlines, @@ -1663,6 +1484,7 @@ impl WgpuRendererCore { instance_offset, &scene.shadows, )?, + path_tiles: self.write_path_tiles(scene, instance_offset)?, underlines: self.write_instance_binding( "underlines_bind_group", instance_offset, @@ -1767,7 +1589,6 @@ impl WgpuRendererCore { return; } pass.set_pipeline(pipeline); - pass.set_bind_group(0, &self.resources().globals_bind_group, &[]); pass.set_bind_group(1, &instances.bind_group, &[]); pass.draw( 0..4, @@ -1793,7 +1614,6 @@ impl WgpuRendererCore { return Ok(()); }; pass.set_pipeline(pipeline); - pass.set_bind_group(0, &resources.globals_bind_group, &[]); pass.set_bind_group(1, &sprite_instances.bind_group, &[]); pass.set_bind_group(2, &texture.bind_group, &[]); pass.draw( @@ -1813,132 +1633,13 @@ impl WgpuRendererCore { } } - fn draw_paths_from_intermediate( - &mut self, - paths: &[Path], - instance_offset: &mut u64, - pass: &mut wgpu::RenderPass<'_>, - ) -> Result<()> { - let first_path = &paths[0]; - let sprites: Vec = if paths.last().map(|p| &p.order) == Some(&first_path.order) - { - paths - .iter() - .map(|p| PathSprite { - bounds: p.clipped_bounds(), - }) - .collect() - } else { - let mut bounds = first_path.clipped_bounds(); - for path in paths.iter().skip(1) { - bounds = bounds.union(&path.clipped_bounds()); - } - vec![PathSprite { bounds }] - }; - - let Some(path_intermediate_view) = self.resources().path_intermediate_view.clone() else { - return Ok(()); - }; - let instances = - self.write_instance_binding("path_sprites_bind_group", instance_offset, &sprites)?; - let texture = self.create_texture_bind_group( - "path_intermediate_texture_bind_group", - &path_intermediate_view, - ); - let resources = self.resources(); - pass.set_pipeline(&resources.pipelines.paths); - pass.set_bind_group(0, &resources.globals_bind_group, &[]); - pass.set_bind_group(1, &instances.bind_group, &[]); - pass.set_bind_group(2, &texture, &[]); - pass.draw( - 0..4, - instances.first_instance..instances.first_instance + sprites.len() as u32, - ); - Ok(()) - } - - fn draw_paths_to_intermediate( - &mut self, - encoder: &mut wgpu::CommandEncoder, - paths: &[Path], - instance_offset: &mut u64, - ) -> Result { - let mut vertices = Vec::new(); - for path in paths { - let bounds = path.clipped_bounds(); - vertices.extend(path.vertices.iter().map(|v| PathRasterizationVertex { - xy_position: v.xy_position, - st_position: v.st_position, - color: path.color, - bounds, - })); - } - - if vertices.is_empty() { - return Ok(false); - } - - let vertex_binding = self.write_instance_binding( - "path_rasterization_bind_group", - instance_offset, - &vertices, - )?; - - let resources = self.resources(); - let Some(path_intermediate_view) = resources.path_intermediate_view.as_ref() else { - return Ok(false); - }; - - let (target_view, resolve_target) = if let Some(ref msaa_view) = resources.path_msaa_view { - (msaa_view, Some(path_intermediate_view)) - } else { - (path_intermediate_view, None) - }; - - { - let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("path_rasterization_pass"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: target_view, - resolve_target, - ops: wgpu::Operations { - load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), - store: wgpu::StoreOp::Store, - }, - depth_slice: None, - })], - depth_stencil_attachment: None, - ..Default::default() - }); - - pass.set_pipeline(&resources.pipelines.path_rasterization); - pass.set_bind_group(0, &resources.path_globals_bind_group, &[]); - pass.set_bind_group(1, &vertex_binding.bind_group, &[]); - // The path rasterization shader loads records by vertex index - // rather than instance index, so the allocation's base shifts the - // vertex range here. - pass.draw( - vertex_binding.first_instance - ..vertex_binding.first_instance + vertices.len() as u32, - 0..1, - ); - } - - Ok(true) - } - - fn write_instance_binding( - &mut self, - label: &str, - instance_offset: &mut u64, - instances: &[T], - ) -> Result { - let data = unsafe { Self::instance_bytes(instances) }; + /// The alignment of an allocation of `byte_len` bytes of `stride`-sized + /// records, and the bytes it takes up from that aligned offset. + fn instance_allocation_layout(&self, stride: u64, byte_len: u64) -> (u64, u64) { // wgpu rejects zero-sized bindings, so empty primitive arrays still // reserve the 16-byte minimum. - let size = (data.len() as u64).max(16); - let stride = (std::mem::size_of::() as u64).max(1); - let (alignment, allocation_size) = if self.uses_webgl_instance_data { + let size = byte_len.max(16); + if self.uses_webgl_instance_data { // The texture transport has no binding offset: the shader indexes // the instance texture absolutely, so each allocation must start on // a whole instance (a stride multiple) and a whole texel, and must @@ -1950,7 +1651,36 @@ impl WgpuRendererCore { ) } else { (self.instance_data_alignment.max(1), size) - }; + } + } + + /// The most space `instances` can take up, including alignment padding. + fn instance_allocation_bound(&self, instances: &[T]) -> u64 { + let stride = (std::mem::size_of::() as u64).max(1); + let (alignment, allocation_size) = + self.instance_allocation_layout(stride, std::mem::size_of_val(instances) as u64); + alignment + allocation_size + } + + /// Grows the instance data up front if `size` more bytes won't fit, so the + /// allocations that follow land in the same buffer or texture. + fn reserve_instance_data(&mut self, instance_offset: &mut u64, size: u64) -> Result<()> { + if *instance_offset + size > self.instance_data_capacity { + self.grow_instance_data(size)?; + *instance_offset = 0; + } + Ok(()) + } + + fn write_instance_data( + &mut self, + instance_offset: &mut u64, + instances: &[T], + ) -> Result { + let data = unsafe { Self::instance_bytes(instances) }; + let stride = (std::mem::size_of::() as u64).max(1); + let (alignment, allocation_size) = + self.instance_allocation_layout(stride, data.len() as u64); let mut offset = (*instance_offset).next_multiple_of(alignment); if offset + allocation_size > self.instance_data_capacity { self.grow_instance_data(allocation_size)?; @@ -1973,6 +1703,35 @@ impl WgpuRendererCore { } } } + Ok(InstanceAllocation { + offset, + size: (data.len() as u64).max(16), + first_instance, + }) + } + + fn instance_binding_resource( + &self, + allocation: &InstanceAllocation, + ) -> wgpu::BindingResource<'_> { + match &self.resources().instance_data { + InstanceData::Storage(buffer) => wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer, + offset: allocation.offset, + size: NonZeroU64::new(allocation.size), + }), + InstanceData::Texture { view, .. } => wgpu::BindingResource::TextureView(view), + } + } + + fn write_instance_binding( + &mut self, + label: &str, + instance_offset: &mut u64, + instances: &[T], + ) -> Result { + let allocation = self.write_instance_data(instance_offset, instances)?; + let resources = self.resources(); let bind_group = resources .device .create_bind_group(&wgpu::BindGroupDescriptor { @@ -1980,23 +1739,79 @@ impl WgpuRendererCore { layout: &resources.bind_group_layouts.instances, entries: &[wgpu::BindGroupEntry { binding: 0, - resource: match &resources.instance_data { - InstanceData::Storage(buffer) => { - wgpu::BindingResource::Buffer(wgpu::BufferBinding { - buffer, - offset, - size: NonZeroU64::new(size), - }) - } - InstanceData::Texture { view, .. } => { - wgpu::BindingResource::TextureView(view) - } - }, + resource: self.instance_binding_resource(&allocation), }], }); Ok(InstanceBinding { bind_group, - first_instance, + first_instance: allocation.first_instance, + }) + } + + fn write_path_tiles( + &mut self, + scene: &Scene, + instance_offset: &mut u64, + ) -> Result { + let mut paint_data = Vec::with_capacity(scene.paths.len()); + let mut curve_data = Vec::new(); + let mut tile_data = Vec::new(); + for path in &scene.paths { + path.append_to(&mut paint_data, &mut curve_data, &mut tile_data); + } + + // All three arrays are bound together, so they must not be split by a + // grow partway through. + let reserved = self.instance_allocation_bound(&paint_data) + + self.instance_allocation_bound(&curve_data) + + self.instance_allocation_bound(&tile_data); + self.reserve_instance_data(instance_offset, reserved)?; + + let paints = self.write_instance_data(instance_offset, &paint_data)?; + let curves = self.write_instance_data(instance_offset, &curve_data)?; + let tiles = self.write_instance_data(instance_offset, &tile_data)?; + + let resources = self.resources(); + let bind_group = if self.uses_webgl_instance_data { + resources + .device + .create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("path_tiles_bind_group"), + layout: &resources.bind_group_layouts.path_tiles, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: self.instance_binding_resource(&tiles), + }], + }) + } else { + resources + .device + .create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("path_tiles_bind_group"), + layout: &resources.bind_group_layouts.path_tiles, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: self.instance_binding_resource(&tiles), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: self.instance_binding_resource(&curves), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: self.instance_binding_resource(&paints), + }, + ], + }) + }; + Ok(PathTileBinding { + tiles: InstanceBinding { + bind_group, + first_instance: tiles.first_instance, + }, + paint_base: paints.first_instance, + curve_base: curves.first_instance, }) } @@ -2144,10 +1959,6 @@ impl WgpuRenderer { } state @ (RendererState::Unconfigured { .. } | RendererState::Released) => state, }; - // Drop intermediate textures since they reference the old surface size. - if let Some(core) = self.core_mut() { - core.resources.invalidate_intermediate_textures(); - } } /// Replace the wgpu surface with a new one (e.g. after Android destroys @@ -2179,6 +1990,7 @@ impl WgpuRenderer { } else { self.opaque_alpha_mode }; + let alpha_mode_changed = alpha_mode != self.surface_config.alpha_mode; self.surface_config.width = width; self.surface_config.height = height; @@ -2200,8 +2012,10 @@ impl WgpuRenderer { anyhow::bail!("Cannot replace the surface: GPU resources have been released") } }; + if alpha_mode_changed { + core.rebuild_pipelines(self.surface_config.format, alpha_mode); + } surface.configure(&core.resources.device, &self.surface_config); - core.resources.invalidate_intermediate_textures(); self.state = RendererState::Ready { surface, core }; Ok(()) @@ -2436,7 +2250,7 @@ impl WgpuHeadlessRenderer { .view .clone(); self.core - .render_frame(scene, &view, size, false, wgpu::Color::BLACK)?; + .render_frame(scene, &view, size, wgpu::Color::BLACK)?; Ok(()) } @@ -2596,22 +2410,15 @@ fn create_surface( } struct RenderingParameters { - path_sample_count: u32, gamma_ratios: [f32; 4], grayscale_enhanced_contrast: f32, subpixel_enhanced_contrast: f32, } impl RenderingParameters { - fn new(adapter: &wgpu::Adapter, surface_format: wgpu::TextureFormat) -> Self { + fn new() -> Self { use std::env; - let format_features = adapter.get_texture_format_features(surface_format); - let path_sample_count = [4, 2, 1] - .into_iter() - .find(|&n| format_features.flags.sample_count_supported(n)) - .unwrap_or(1); - let gamma = env::var("ZED_FONTS_GAMMA") .ok() .and_then(|v| v.parse().ok()) @@ -2632,7 +2439,6 @@ impl RenderingParameters { .max(0.0); Self { - path_sample_count, gamma_ratios, grayscale_enhanced_contrast, subpixel_enhanced_contrast, @@ -2644,9 +2450,9 @@ impl RenderingParameters { mod tests { use super::*; use gpui::{ - BorderStyle, ColorSpace, ContentMask, Corners, Edges, Hsla, MonochromeSprite, - PolychromeSprite, Quad, Shadow, Size, SubpixelSprite, Underline, linear_color_stop, - linear_gradient, + BorderStyle, ColorSpace, ContentMask, Corners, Edges, Hsla, MonochromeSprite, PathCurve, + PathPaint, PathTile, Point, PolychromeSprite, Quad, Shadow, Size, SubpixelSprite, + Underline, linear_color_stop, linear_gradient, }; #[cfg(target_os = "linux")] use gpui::{DevicePixels, PlatformHeadlessRenderer, Scene}; @@ -2831,8 +2637,9 @@ mod tests { fn webgl_record_sizes_match_shader_word_strides() { assert_eq!(std::mem::size_of::(), 40 * 4); assert_eq!(std::mem::size_of::(), 28 * 4); - assert_eq!(std::mem::size_of::(), 26 * 4); - assert_eq!(std::mem::size_of::(), 4 * 4); + assert_eq!(std::mem::size_of::(), 14 * 4); + assert_eq!(std::mem::size_of::(), 10 * 4); + assert_eq!(std::mem::size_of::(), 28 * 4); assert_eq!(std::mem::size_of::(), 16 * 4); assert_eq!(std::mem::size_of::(), 28 * 4); assert_eq!(std::mem::size_of::(), 28 * 4); diff --git a/crates/gpui_windows/build.rs b/crates/gpui_windows/build.rs index a544f6cf904..bbef5316e2d 100644 --- a/crates/gpui_windows/build.rs +++ b/crates/gpui_windows/build.rs @@ -34,8 +34,7 @@ mod shader_compilation { let modules = [ "quad", "shadow", - "path_rasterization", - "path_sprite", + "path_tile", "underline", "monochrome_sprite", "subpixel_sprite", diff --git a/crates/gpui_windows/src/directx_renderer.rs b/crates/gpui_windows/src/directx_renderer.rs index 4cce3e06cdc..2b364d49319 100644 --- a/crates/gpui_windows/src/directx_renderer.rs +++ b/crates/gpui_windows/src/directx_renderer.rs @@ -1,4 +1,5 @@ use std::{ + ops::Range, slice, sync::{Arc, OnceLock}, }; @@ -25,8 +26,6 @@ use gpui::*; pub(crate) const DISABLE_DIRECT_COMPOSITION: &str = "GPUI_DISABLE_DIRECT_COMPOSITION"; const RENDER_TARGET_FORMAT: DXGI_FORMAT = DXGI_FORMAT_B8G8R8A8_UNORM; -// This configuration is used for MSAA rendering on paths only, and it's guaranteed to be supported by DirectX 11. -const PATH_MULTISAMPLE_COUNT: u32 = 4; const MAX_INSTANCE_BUFFER_SIZE: usize = 256 * 1024 * 1024; pub(crate) struct FontInfo { @@ -73,12 +72,6 @@ struct DirectXResources { render_target: Option, render_target_view: Option, - // Path intermediate textures (with MSAA) - path_intermediate_texture: ID3D11Texture2D, - path_intermediate_srv: Option, - path_intermediate_msaa_texture: ID3D11Texture2D, - path_intermediate_msaa_view: Option, - // Cached viewport viewport: D3D11_VIEWPORT, } @@ -86,8 +79,9 @@ struct DirectXResources { struct DirectXRenderPipelines { shadow_pipeline: PipelineState, quad_pipeline: PipelineState, - path_rasterization_pipeline: PipelineState, - path_sprite_pipeline: PipelineState, + path_tile_pipeline: PipelineState, + path_curves: StructuredBuffer, + path_paints: StructuredBuffer, underline_pipeline: PipelineState, mono_sprites: PipelineState, subpixel_sprites: PipelineState, @@ -362,6 +356,7 @@ impl DirectXRenderer { .as_ref() .and_then(|devices| devices.annotation.clone()) .filter(|annotation| unsafe { annotation.GetStatus().as_bool() }); + let mut path_tile_cursor = 0; for batch in scene.batches() { let _annotation = annotation .as_ref() @@ -370,9 +365,12 @@ impl DirectXRenderer { PrimitiveBatch::Shadows(range) => self.draw_shadows(range.start, range.len()), PrimitiveBatch::Quads(range) => self.draw_quads(range.start, range.len()), PrimitiveBatch::Paths(range) => { - let paths = &scene.paths[range]; - self.draw_paths_to_intermediate(paths)?; - self.draw_paths_from_intermediate(paths) + let tiles_start = path_tile_cursor; + path_tile_cursor += scene.paths[range] + .iter() + .map(PaintedPath::tile_count) + .sum::(); + self.draw_paths(tiles_start..path_tile_cursor) } PrimitiveBatch::Underlines(range) => self.draw_underlines(range.start, range.len()), PrimitiveBatch::MonochromeSprites { texture_id, range } => { @@ -545,6 +543,39 @@ impl DirectXRenderer { )?; } + if !scene.paths.is_empty() { + let mut paints = Vec::with_capacity(scene.paths.len()); + let mut curves = Vec::new(); + let mut tiles = Vec::new(); + for path in &scene.paths { + path.append_to(&mut paints, &mut curves, &mut tiles); + } + + self.pipelines.path_tile_pipeline.update_buffer( + &devices.device, + &devices.device_context, + &tiles, + )?; + self.pipelines + .path_curves + .write(&devices.device, &devices.device_context, &curves)?; + self.pipelines + .path_paints + .write(&devices.device, &devices.device_context, &paints)?; + let buffers = [ + self.pipelines.path_curves.view.clone(), + self.pipelines.path_paints.view.clone(), + ]; + unsafe { + devices + .device_context + .VSSetShaderResources(2, Some(&buffers)); + devices + .device_context + .PSSetShaderResources(2, Some(&buffers)); + } + } + if !scene.underlines.is_empty() { self.pipelines.underline_pipeline.update_buffer( &devices.device, @@ -612,110 +643,19 @@ impl DirectXRenderer { ) } - fn draw_paths_to_intermediate(&mut self, paths: &[Path]) -> Result<()> { - if paths.is_empty() { + fn draw_paths(&mut self, tile_range: Range) -> Result<()> { + if tile_range.is_empty() { return Ok(()); } - let devices = self.devices.as_ref().context("devices missing")?; - let resources = self.resources.as_ref().context("resources missing")?; - // Clear intermediate MSAA texture - unsafe { - devices.device_context.ClearRenderTargetView( - resources.path_intermediate_msaa_view.as_ref().unwrap(), - &[0.0; 4], - ); - // Set intermediate MSAA texture as render target - devices.device_context.OMSetRenderTargets( - Some(slice::from_ref(&resources.path_intermediate_msaa_view)), - None, - ); - } - - // Collect all vertices and sprites for a single draw call - let mut vertices = Vec::new(); - - for path in paths { - vertices.extend(path.vertices.iter().map(|v| PathRasterizationSprite { - xy_position: v.xy_position, - st_position: v.st_position, - color: path.color, - bounds: path.clipped_bounds(), - })); - } - - self.pipelines.path_rasterization_pipeline.update_buffer( - &devices.device, + self.pipelines.path_tile_pipeline.draw_range( &devices.device_context, - &vertices, - )?; - - self.pipelines.path_rasterization_pipeline.draw( - &devices.device_context, - D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, - vertices.len() as u32, - 1, - )?; - - // Resolve MSAA to non-MSAA intermediate texture - unsafe { - devices.device_context.ResolveSubresource( - &resources.path_intermediate_texture, - 0, - &resources.path_intermediate_msaa_texture, - 0, - RENDER_TARGET_FORMAT, - ); - // Restore main render target - devices - .device_context - .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None); - } - - Ok(()) - } - - fn draw_paths_from_intermediate(&mut self, paths: &[Path]) -> Result<()> { - let Some(first_path) = paths.first() else { - return Ok(()); - }; - - // When copying paths from the intermediate texture to the drawable, - // each pixel must only be copied once, in case of transparent paths. - // - // If all paths have the same draw order, then their bounds are all - // disjoint, so we can copy each path's bounds individually. If this - // batch combines different draw orders, we perform a single copy - // for a minimal spanning rect. - let sprites = if paths.last().unwrap().order == first_path.order { - paths - .iter() - .map(|path| PathSprite { - bounds: path.clipped_bounds(), - }) - .collect::>() - } else { - let mut bounds = first_path.clipped_bounds(); - for path in paths.iter().skip(1) { - bounds = bounds.union(&path.clipped_bounds()); - } - vec![PathSprite { bounds }] - }; - - let devices = self.devices.as_ref().context("devices missing")?; - let resources = self.resources.as_ref().context("resources missing")?; - self.pipelines.path_sprite_pipeline.update_buffer( - &devices.device, - &devices.device_context, - &sprites, - )?; - - // Draw the sprites with the path texture - self.pipelines.path_sprite_pipeline.draw_with_texture( - &devices.device_context, - slice::from_ref(&resources.path_intermediate_srv), - slice::from_ref(&self.globals.sampler), - sprites.len() as u32, + self.globals + .batch_params_buffer + .as_ref() + .context("batch params buffer missing")?, + tile_range.start as u32, + tile_range.len() as u32, ) } @@ -889,25 +829,14 @@ impl DirectXResources { )? }; - let ( - render_target, - render_target_view, - path_intermediate_texture, - path_intermediate_srv, - path_intermediate_msaa_texture, - path_intermediate_msaa_view, - viewport, - ) = create_resources(devices, &swap_chain, width, height)?; + let (render_target, render_target_view, viewport) = + create_resources(devices, &swap_chain, width, height)?; set_rasterizer_state(&devices.device, &devices.device_context)?; Ok(Self { swap_chain, render_target: Some(render_target), render_target_view, - path_intermediate_texture, - path_intermediate_msaa_texture, - path_intermediate_msaa_view, - path_intermediate_srv, viewport, }) } @@ -919,21 +848,10 @@ impl DirectXResources { width: u32, height: u32, ) -> Result<()> { - let ( - render_target, - render_target_view, - path_intermediate_texture, - path_intermediate_srv, - path_intermediate_msaa_texture, - path_intermediate_msaa_view, - viewport, - ) = create_resources(devices, &self.swap_chain, width, height)?; + let (render_target, render_target_view, viewport) = + create_resources(devices, &self.swap_chain, width, height)?; self.render_target = Some(render_target); self.render_target_view = render_target_view; - self.path_intermediate_texture = path_intermediate_texture; - self.path_intermediate_msaa_texture = path_intermediate_msaa_texture; - self.path_intermediate_msaa_view = path_intermediate_msaa_view; - self.path_intermediate_srv = path_intermediate_srv; self.viewport = viewport; Ok(()) } @@ -955,20 +873,15 @@ impl DirectXRenderPipelines { 64, create_blend_state(device)?, )?; - let path_rasterization_pipeline = PipelineState::new( + let path_tile_pipeline = PipelineState::new( device, - "path_rasterization_pipeline", - ShaderModule::PathRasterization, - 32, - create_blend_state_for_path_rasterization(device)?, - )?; - let path_sprite_pipeline = PipelineState::new( - device, - "path_sprite_pipeline", - ShaderModule::PathSprite, - 4, - create_blend_state_for_path_sprite(device)?, + "path_tile_pipeline", + ShaderModule::PathTile, + 64, + create_blend_state(device)?, )?; + let path_curves = StructuredBuffer::new(device, "path_curves", 256)?; + let path_paints = StructuredBuffer::new(device, "path_paints", 64)?; let underline_pipeline = PipelineState::new( device, "underline_pipeline", @@ -1001,8 +914,9 @@ impl DirectXRenderPipelines { Ok(Self { shadow_pipeline, quad_pipeline, - path_rasterization_pipeline, - path_sprite_pipeline, + path_tile_pipeline, + path_curves, + path_paints, underline_pipeline, mono_sprites, subpixel_sprites, @@ -1083,17 +997,70 @@ struct BatchParams { _padding: [u32; 3], } -const _: () = assert!(std::mem::size_of::() == 16); +struct StructuredBuffer { + label: &'static str, + buffer: ID3D11Buffer, + capacity: usize, + view: Option, + _marker: std::marker::PhantomData, +} + +impl StructuredBuffer { + fn new(device: &ID3D11Device, label: &'static str, capacity: usize) -> Result { + let buffer = create_buffer(device, std::mem::size_of::(), capacity)?; + let view = create_buffer_view(device, &buffer)?; + Ok(StructuredBuffer { + label, + buffer, + capacity, + view, + _marker: std::marker::PhantomData, + }) + } + + fn write( + &mut self, + device: &ID3D11Device, + device_context: &ID3D11DeviceContext, + data: &[T], + ) -> Result<()> { + self.ensure_capacity(device, data.len())?; + update_buffer(device_context, &self.buffer, data) + } + + fn ensure_capacity(&mut self, device: &ID3D11Device, len: usize) -> Result<()> { + if self.capacity < len { + let element_size = std::mem::size_of::().max(1); + let required_size = len.checked_mul(element_size); + anyhow::ensure!( + required_size.is_some_and(|size| size <= MAX_INSTANCE_BUFFER_SIZE), + "{} buffer needs {len} elements of {element_size} bytes, above the maximum of {MAX_INSTANCE_BUFFER_SIZE} bytes", + self.label + ); + let new_capacity = len + .next_power_of_two() + .min(MAX_INSTANCE_BUFFER_SIZE / element_size); + log::debug!( + "Updating {} buffer size from {} to {}", + self.label, + self.capacity, + new_capacity + ); + let buffer = create_buffer(device, std::mem::size_of::(), new_capacity)?; + let view = create_buffer_view(device, &buffer)?; + self.buffer = buffer; + self.view = view; + self.capacity = new_capacity; + } + Ok(()) + } +} struct PipelineState { - label: &'static str, vertex: ID3D11VertexShader, fragment: ID3D11PixelShader, - buffer: ID3D11Buffer, - buffer_size: usize, - view: Option, + instances: StructuredBuffer, blend_state: ID3D11BlendState, - _marker: std::marker::PhantomData, } impl PipelineState { @@ -1112,18 +1079,12 @@ impl PipelineState { let raw_shader = RawShaderBytes::new(shader_module, ShaderTarget::Fragment)?; create_fragment_shader(device, raw_shader.as_bytes())? }; - let buffer = create_buffer(device, std::mem::size_of::(), buffer_size)?; - let view = create_buffer_view(device, &buffer)?; Ok(PipelineState { - label, vertex, fragment, - buffer, - buffer_size, - view, + instances: StructuredBuffer::new(device, label, buffer_size)?, blend_state, - _marker: std::marker::PhantomData, }) } @@ -1133,77 +1094,7 @@ impl PipelineState { device_context: &ID3D11DeviceContext, data: &[T], ) -> Result<()> { - if self.buffer_size < data.len() { - let element_size = std::mem::size_of::(); - let required_size = std::mem::size_of_val(data); - anyhow::ensure!( - required_size <= MAX_INSTANCE_BUFFER_SIZE, - "{} buffer needs {required_size} bytes, above the maximum of {MAX_INSTANCE_BUFFER_SIZE}", - self.label - ); - let new_buffer_size = data - .len() - .next_power_of_two() - .min(MAX_INSTANCE_BUFFER_SIZE / element_size); - log::debug!( - "Updating {} buffer size from {} to {}", - self.label, - self.buffer_size, - new_buffer_size - ); - let buffer = create_buffer(device, std::mem::size_of::(), new_buffer_size)?; - let view = create_buffer_view(device, &buffer)?; - self.buffer = buffer; - self.view = view; - self.buffer_size = new_buffer_size; - } - update_buffer(device_context, &self.buffer, data) - } - - fn draw( - &self, - device_context: &ID3D11DeviceContext, - topology: D3D_PRIMITIVE_TOPOLOGY, - vertex_count: u32, - instance_count: u32, - ) -> Result<()> { - set_pipeline_state( - device_context, - slice::from_ref(&self.view), - topology, - &self.vertex, - &self.fragment, - &self.blend_state, - ); - unsafe { - device_context.DrawInstanced(vertex_count, instance_count, 0, 0); - } - Ok(()) - } - - fn draw_with_texture( - &self, - device_context: &ID3D11DeviceContext, - texture: &[Option], - sampler: &[Option], - instance_count: u32, - ) -> Result<()> { - set_pipeline_state( - device_context, - slice::from_ref(&self.view), - D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, - &self.vertex, - &self.fragment, - &self.blend_state, - ); - unsafe { - device_context.PSSetSamplers(0, Some(sampler)); - device_context.VSSetShaderResources(0, Some(texture)); - device_context.PSSetShaderResources(0, Some(texture)); - - device_context.DrawInstanced(4, instance_count, 0, 0); - } - Ok(()) + self.instances.write(device, device_context, data) } fn draw_range( @@ -1213,15 +1104,11 @@ impl PipelineState { first_instance: u32, instance_count: u32, ) -> Result<()> { - anyhow::ensure!( - first_instance as usize + instance_count as usize <= self.buffer_size, - "DirectX instance range exceeds the {} buffer", - self.label - ); + self.ensure_range(first_instance, instance_count)?; update_batch_start(device_context, batch_params_buffer, first_instance)?; set_pipeline_state( device_context, - slice::from_ref(&self.view), + slice::from_ref(&self.instances.view), D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, &self.vertex, &self.fragment, @@ -1242,15 +1129,11 @@ impl PipelineState { first_instance: u32, instance_count: u32, ) -> Result<()> { - anyhow::ensure!( - first_instance as usize + instance_count as usize <= self.buffer_size, - "DirectX instance range exceeds the {} buffer", - self.label - ); + self.ensure_range(first_instance, instance_count)?; update_batch_start(device_context, batch_params_buffer, first_instance)?; set_pipeline_state( device_context, - slice::from_ref(&self.view), + slice::from_ref(&self.instances.view), D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, &self.vertex, &self.fragment, @@ -1264,21 +1147,15 @@ impl PipelineState { } Ok(()) } -} -#[derive(Clone, Copy)] -#[repr(C)] -struct PathRasterizationSprite { - xy_position: Point, - st_position: Point, - color: Background, - bounds: Bounds, -} - -#[derive(Clone, Copy)] -#[repr(C)] -struct PathSprite { - bounds: Bounds, + fn ensure_range(&self, first_instance: u32, instance_count: u32) -> Result<()> { + anyhow::ensure!( + first_instance as usize + instance_count as usize <= self.instances.capacity, + "DirectX instance range exceeds the {} buffer", + self.instances.label + ); + Ok(()) + } } impl Drop for DirectXRenderer { @@ -1359,37 +1236,14 @@ fn create_resources( width: u32, height: u32, ) -> Result<( - ID3D11Texture2D, - Option, - ID3D11Texture2D, - Option, ID3D11Texture2D, Option, D3D11_VIEWPORT, )> { let (render_target, render_target_view) = create_render_target_and_its_view(swap_chain, &devices.device)?; - let (path_intermediate_texture, path_intermediate_srv) = - create_path_intermediate_texture(&devices.device, width, height)?; - let (path_intermediate_msaa_texture, path_intermediate_msaa_view) = - create_path_intermediate_msaa_texture_and_view(&devices.device, width, height)?; - let viewport = D3D11_VIEWPORT { - TopLeftX: 0.0, - TopLeftY: 0.0, - Width: width as f32, - Height: height as f32, - MinDepth: 0.0, - MaxDepth: 1.0, - }; - Ok(( - render_target, - render_target_view, - path_intermediate_texture, - path_intermediate_srv, - path_intermediate_msaa_texture, - path_intermediate_msaa_view, - viewport, - )) + let viewport = set_viewport(&devices.device_context, width as f32, height as f32); + Ok((render_target, render_target_view, viewport)) } #[inline] @@ -1404,67 +1258,17 @@ fn create_render_target_and_its_view( } #[inline] -fn create_path_intermediate_texture( - device: &ID3D11Device, - width: u32, - height: u32, -) -> Result<(ID3D11Texture2D, Option)> { - let texture = unsafe { - let mut output = None; - let desc = D3D11_TEXTURE2D_DESC { - Width: width, - Height: height, - MipLevels: 1, - ArraySize: 1, - Format: RENDER_TARGET_FORMAT, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Usage: D3D11_USAGE_DEFAULT, - BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32, - CPUAccessFlags: 0, - MiscFlags: 0, - }; - device.CreateTexture2D(&desc, None, Some(&mut output))?; - output.unwrap() - }; - - let mut shader_resource_view = None; - unsafe { device.CreateShaderResourceView(&texture, None, Some(&mut shader_resource_view))? }; - - Ok((texture, Some(shader_resource_view.unwrap()))) -} - -#[inline] -fn create_path_intermediate_msaa_texture_and_view( - device: &ID3D11Device, - width: u32, - height: u32, -) -> Result<(ID3D11Texture2D, Option)> { - let msaa_texture = unsafe { - let mut output = None; - let desc = D3D11_TEXTURE2D_DESC { - Width: width, - Height: height, - MipLevels: 1, - ArraySize: 1, - Format: RENDER_TARGET_FORMAT, - SampleDesc: DXGI_SAMPLE_DESC { - Count: PATH_MULTISAMPLE_COUNT, - Quality: D3D11_STANDARD_MULTISAMPLE_PATTERN.0 as u32, - }, - Usage: D3D11_USAGE_DEFAULT, - BindFlags: D3D11_BIND_RENDER_TARGET.0 as u32, - CPUAccessFlags: 0, - MiscFlags: 0, - }; - device.CreateTexture2D(&desc, None, Some(&mut output))?; - output.unwrap() - }; - let mut msaa_view = None; - unsafe { device.CreateRenderTargetView(&msaa_texture, None, Some(&mut msaa_view))? }; - Ok((msaa_texture, Some(msaa_view.unwrap()))) +fn set_viewport(device_context: &ID3D11DeviceContext, width: f32, height: f32) -> D3D11_VIEWPORT { + let viewport = [D3D11_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: width, + Height: height, + MinDepth: 0.0, + MaxDepth: 1.0, + }]; + unsafe { device_context.RSSetViewports(Some(&viewport)) }; + viewport[0] } #[inline] @@ -1530,46 +1334,6 @@ fn create_blend_state_for_subpixel_rendering(device: &ID3D11Device) -> Result Result { - // If the feature level is set to greater than D3D_FEATURE_LEVEL_9_3, the display - // device performs the blend in linear space, which is ideal. - let mut desc = D3D11_BLEND_DESC::default(); - desc.RenderTarget[0].BlendEnable = true.into(); - desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; - desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; - desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; - desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; - desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; - desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; - desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8; - unsafe { - let mut state = None; - device.CreateBlendState(&desc, Some(&mut state))?; - Ok(state.unwrap()) - } -} - -#[inline] -fn create_blend_state_for_path_sprite(device: &ID3D11Device) -> Result { - // If the feature level is set to greater than D3D_FEATURE_LEVEL_9_3, the display - // device performs the blend in linear space, which is ideal. - let mut desc = D3D11_BLEND_DESC::default(); - desc.RenderTarget[0].BlendEnable = true.into(); - desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; - desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; - desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; - desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; - desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; - desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; - desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8; - unsafe { - let mut state = None; - device.CreateBlendState(&desc, Some(&mut state))?; - Ok(state.unwrap()) - } -} - #[inline] fn create_vertex_shader(device: &ID3D11Device, bytes: &[u8]) -> Result { unsafe { @@ -1610,13 +1374,18 @@ fn create_buffer( element_size: usize, buffer_size: usize, ) -> Result { + let byte_width = element_size + .checked_mul(buffer_size) + .and_then(|size| u32::try_from(size).ok()) + .context("structured buffer size overflows u32")?; let desc = D3D11_BUFFER_DESC { - ByteWidth: (element_size * buffer_size) as u32, + ByteWidth: byte_width, Usage: D3D11_USAGE_DYNAMIC, BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32, CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32, MiscFlags: D3D11_RESOURCE_MISC_BUFFER_STRUCTURED.0 as u32, - StructureByteStride: element_size as u32, + StructureByteStride: u32::try_from(element_size) + .context("structured buffer stride overflows u32")?, }; let mut buffer = None; unsafe { device.CreateBuffer(&desc, None, Some(&mut buffer)) }?; @@ -1711,8 +1480,7 @@ pub(crate) mod shader_resources { Quad, Shadow, Underline, - PathRasterization, - PathSprite, + PathTile, MonochromeSprite, SubpixelSprite, PolychromeSprite, @@ -1769,13 +1537,9 @@ pub(crate) mod shader_resources { ShaderTarget::Vertex => UNDERLINE_VERTEX_BYTES, ShaderTarget::Fragment => UNDERLINE_FRAGMENT_BYTES, }, - ShaderModule::PathRasterization => match target { - ShaderTarget::Vertex => PATH_RASTERIZATION_VERTEX_BYTES, - ShaderTarget::Fragment => PATH_RASTERIZATION_FRAGMENT_BYTES, - }, - ShaderModule::PathSprite => match target { - ShaderTarget::Vertex => PATH_SPRITE_VERTEX_BYTES, - ShaderTarget::Fragment => PATH_SPRITE_FRAGMENT_BYTES, + ShaderModule::PathTile => match target { + ShaderTarget::Vertex => PATH_TILE_VERTEX_BYTES, + ShaderTarget::Fragment => PATH_TILE_FRAGMENT_BYTES, }, ShaderModule::MonochromeSprite => match target { ShaderTarget::Vertex => MONOCHROME_SPRITE_VERTEX_BYTES, @@ -1864,8 +1628,7 @@ pub(crate) mod shader_resources { ShaderModule::Quad => "quad", ShaderModule::Shadow => "shadow", ShaderModule::Underline => "underline", - ShaderModule::PathRasterization => "path_rasterization", - ShaderModule::PathSprite => "path_sprite", + ShaderModule::PathTile => "path_tile", ShaderModule::MonochromeSprite => "monochrome_sprite", ShaderModule::SubpixelSprite => "subpixel_sprite", ShaderModule::PolychromeSprite => "polychrome_sprite", diff --git a/crates/gpui_windows/src/shaders.hlsl b/crates/gpui_windows/src/shaders.hlsl index d370a44181d..90136902c55 100644 --- a/crates/gpui_windows/src/shaders.hlsl +++ b/crates/gpui_windows/src/shaders.hlsl @@ -938,102 +938,179 @@ float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET { /* ** -** Path Rasterization +** Path Tiles ** */ -struct PathRasterizationSprite { - float2 xy_position; - float2 st_position; - Background color; +struct PathCurve { + float2 p0; + float2 p1; + float2 a; + float2 b; + float sign; + uint pad; +}; + +struct PathTile { + uint paint; + uint curve_start; + uint curve_count; + int backdrop; + float2 top_left; + float2 bottom_right; + float2 reference; + float2 curves_top_left; + float2 curves_bottom_right; +}; + +struct PathPaint { Bounds bounds; + Bounds content_mask; + Background color; + uint even_odd; + uint pad; }; -StructuredBuffer path_rasterization_sprites: register(t1); +StructuredBuffer path_tiles: register(t1); +StructuredBuffer path_curves: register(t2); +StructuredBuffer path_paints: register(t3); -struct PathVertexOutput { +struct PathTileFragmentInput { float4 position: SV_Position; - float2 st_position: TEXCOORD0; - nointerpolation uint vertex_id: TEXCOORD1; - float4 clip_distance: SV_ClipDistance; + nointerpolation uint tile_id: TEXCOORD0; + nointerpolation float4 curve_box: TEXCOORD1; + PreparedBackground background; }; -struct PathFragmentInput { - float4 position: SV_Position; - float2 st_position: TEXCOORD0; - nointerpolation uint vertex_id: TEXCOORD1; -}; +PathTileFragmentInput path_tile_vertex(uint vertex_id: SV_VertexID, uint tile_id: SV_InstanceID) { + uint tile_index = batch_start_index + tile_id; + PathTile tile = path_tiles[tile_index]; + PathPaint paint = path_paints[tile.paint]; -PathVertexOutput path_rasterization_vertex(uint vertex_id: SV_VertexID) { - PathRasterizationSprite sprite = path_rasterization_sprites[vertex_id]; - - PathVertexOutput output; - output.position = to_device_position_impl(sprite.xy_position); - output.st_position = sprite.st_position; - output.vertex_id = vertex_id; - output.clip_distance = distance_from_clip_rect_impl(sprite.xy_position, sprite.bounds); + // Neighboring tiles store their shared edge as the same number, so clipping each corner on its + // own gives them bit-identical edges, which the rasterizer neither overlaps nor leaves gaps + // between. Interpolating from an origin and a size would not. + float2 mask_top_left = paint.content_mask.origin; + float2 mask_bottom_right = paint.content_mask.origin + paint.content_mask.size; + float2 top_left = clamp(tile.top_left, mask_top_left, mask_bottom_right); + float2 bottom_right = clamp(tile.bottom_right, top_left, mask_bottom_right); + float2 position = float2( + (vertex_id & 1u) != 0u ? bottom_right.x : top_left.x, + (vertex_id & 2u) != 0u ? bottom_right.y : top_left.y); + PathTileFragmentInput output; + output.position = to_device_position_impl(position); + output.tile_id = tile_index; + output.curve_box = float4(tile.curves_top_left, tile.curves_bottom_right); + output.background = prepare_background(paint.color); return output; } -float4 path_rasterization_fragment(PathFragmentInput input): SV_Target { - float2 dx = ddx(input.st_position); - float2 dy = ddy(input.st_position); - PathRasterizationSprite sprite = path_rasterization_sprites[input.vertex_id]; +// Solves a*t^2 + b*t + c = 0 for the root in [0, 1] on a monotone piece. +float monotone_quadratic_root(float a, float b, float c, float direction) { + float discriminant = max(b * b - 4.0 * a * c, 0.0); + float denominator = b + direction * sqrt(discriminant); + if (denominator == 0.0) { + return 0.0; + } + return saturate(-2.0 * c / denominator); +} - Background background = sprite.color; - Bounds bounds = sprite.bounds; +// Coverage estimate adapted from https://github.com/EricLengyel/Slug/blob/be3c13eb7d63f9e8aa5c583e42d92c374cb91d98/SlugPixelShader.hlsl +// Copyright (c) 2017 Eric Lengyel. +// Licensed under the MIT license. - float alpha; - if (length(float2(dx.x, dy.x))) { - alpha = 1.0; - } else { - float2 gradient = 2.0 * input.st_position.xx * float2(dx.x, dy.x) - float2(dx.y, dy.y); - float f = input.st_position.x * input.st_position.x - input.st_position.y; - float distance = f / length(gradient); - alpha = saturate(0.5 - distance); +// Accumulates the curve's winding along the pixel's leftward and upward rays. Like Slug, a crossing +// within half a pixel of the center counts fractionally. +void add_curve_winding(PathCurve curve, float2 center, inout float2 winding, inout float2 weight) { + float min_x = min(curve.p0.x, curve.p1.x); + float max_x = max(curve.p0.x, curve.p1.x); + + [branch] + if (curve.p0.y <= center.y && center.y < curve.p1.y) { + [branch] + if (max_x <= center.x - 0.5) { + winding.x += curve.sign; + } else { + float t = monotone_quadratic_root(curve.a.y, curve.b.y, curve.p0.y - center.y, 1.0); + float x = (curve.a.x * t + curve.b.x) * t + curve.p0.x; + float distance = center.x - x; + winding.x += curve.sign * saturate(distance + 0.5); + weight.x = max(weight.x, saturate(1.0 - 2.0 * abs(distance))); + } + } + + [branch] + if (min_x <= center.x && center.x < max_x) { + float direction = curve.p1.x > curve.p0.x ? 1.0 : -1.0; + [branch] + if (curve.p1.y <= center.y - 0.5) { + winding.y -= curve.sign * direction; + } else if (curve.p0.y < center.y + 0.5) { + float t = monotone_quadratic_root(curve.a.x, curve.b.x, curve.p0.x - center.x, direction); + float y = (curve.a.y * t + curve.b.y) * t + curve.p0.y; + float distance = center.y - y; + winding.y -= curve.sign * direction * saturate(distance + 0.5); + weight.y = max(weight.y, saturate(1.0 - 2.0 * abs(distance))); + } + } +} + +// The backdrop gives the unlisted curves' winding along a leftward ray from the tile's reference +// corner. We need it at the current pixel, along both leftward and upward rays. Because paths are +// closed, chains of unlisted curves can only begin or end where a listed curve does. So, we can +// compute the winding at the current pixel by correcting the backdrop for each listed endpoint +// between its ray and the pixel. +void correct_for_endpoint(float2 endpoint, float step, float2 reference, float2 center, + inout float2 winding) { + if (endpoint.x <= reference.x) { + winding.x -= step * (float(endpoint.y <= center.y) - float(endpoint.y <= reference.y)); + } + if (endpoint.y <= reference.y && endpoint.x <= center.x) { + winding.y += step; + } +} + +float4 path_tile_fragment(PathTileFragmentInput input): SV_Target { + float2 center = floor(input.position.xy) + 0.5; + if (input.background.tag == 0u + && (any(center < input.curve_box.xy) || any(center > input.curve_box.zw))) { + return input.background.color0; + } + PathTile tile = path_tiles[input.tile_id]; + PathPaint paint = path_paints[tile.paint]; + + float2 winding = float(tile.backdrop); + float2 weight = float2(0.0, 0.0); + [loop] + for (uint i = 0u; i < tile.curve_count; i++) { + PathCurve curve = path_curves[tile.curve_start + i]; + if (min(curve.p0.x, curve.p1.x) >= center.x + 0.5) { + break; + } + if (curve.p0.y < center.y + 0.5) { + add_curve_winding(curve, center, winding, weight); + correct_for_endpoint(curve.p0, curve.sign, tile.reference, center, winding); + correct_for_endpoint(curve.p1, -curve.sign, tile.reference, center, winding); + } + } + + // Weight the winding computed by each ray by its nearest crossing's distance from the pixel center, + // using Slug's technique. + float coverage = max( + abs(dot(winding, weight)) / max(weight.x + weight.y, 1.0 / 65536.0), + min(abs(winding.x), abs(winding.y))); + coverage = paint.even_odd != 0u + ? 1.0 - abs(1.0 - frac(coverage * 0.5) * 2.0) + : saturate(coverage); + + if (coverage == 0.0) { + return float4(0.0, 0.0, 0.0, 0.0); } float4 color = - background_color(prepare_background(background), background, bounds, input.position.xy); - return float4(color.rgb * color.a * alpha, alpha * color.a); -} - -/* -** -** Path Sprites -** -*/ - -struct PathSprite { - Bounds bounds; -}; - -struct PathSpriteVertexOutput { - float4 position: SV_Position; - float2 texture_coords: TEXCOORD0; -}; - -StructuredBuffer path_sprites: register(t1); - -PathSpriteVertexOutput path_sprite_vertex(uint vertex_id: SV_VertexID, uint sprite_id: SV_InstanceID) { - float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); - PathSprite sprite = path_sprites[sprite_id]; - - // Don't apply content mask because it was already accounted for when rasterizing the path - float4 device_position = to_device_position(unit_vertex, sprite.bounds); - - float2 screen_position = sprite.bounds.origin + unit_vertex * sprite.bounds.size; - float2 texture_coords = screen_position / global_viewport_size; - - PathSpriteVertexOutput output; - output.position = device_position; - output.texture_coords = texture_coords; - return output; -} - -float4 path_sprite_fragment(PathSpriteVertexOutput input): SV_Target { - return t_sprite.Sample(s_sprite, input.texture_coords); + background_color(input.background, paint.color, paint.bounds, input.position.xy); + return float4(color.rgb, color.a * coverage); } /* diff --git a/crates/title_bar/src/collab.rs b/crates/title_bar/src/collab.rs index fe418bef36d..42c617ecea2 100644 --- a/crates/title_bar/src/collab.rs +++ b/crates/title_bar/src/collab.rs @@ -5,8 +5,8 @@ use call::{ActiveCall, Room}; use channel::ChannelStore; use client::{User, proto::PeerId}; use gpui::{ - AnyElement, Empty, Hsla, IntoElement, MouseButton, Path, ScreenCaptureSource, Styled, TaskExt, - WeakEntity, canvas, point, + AnyElement, Empty, Hsla, IntoElement, MouseButton, PathBuilder, ScreenCaptureSource, Styled, + TaskExt, WeakEntity, canvas, point, }; use gpui::{App, Task, Window}; use icons::IconName; @@ -123,18 +123,21 @@ fn render_color_ribbon(color: Hsla) -> impl Element { let height = bounds.size.height; let horizontal_offset = height; let vertical_offset = height / 2.0; - let mut path = Path::new(bounds.bottom_left()); - path.curve_to( + let mut builder = PathBuilder::fill(); + builder.move_to(bounds.bottom_left()); + builder.curve_to( bounds.origin + point(horizontal_offset, vertical_offset), bounds.origin + point(px(0.0), vertical_offset), ); - path.line_to(bounds.top_right() + point(-horizontal_offset, vertical_offset)); - path.curve_to( + builder.line_to(bounds.top_right() + point(-horizontal_offset, vertical_offset)); + builder.curve_to( bounds.bottom_right(), bounds.top_right() + point(px(0.0), vertical_offset), ); - path.line_to(bounds.bottom_left()); - window.paint_path(path, color); + builder.close(); + if let Ok(path) = builder.build() { + window.paint_path(path, color); + } }, ) .h_1()