mirror of
https://github.com/zed-industries/zed.git
synced 2026-12-03 05:51:27 +01:00
gpui: Improve path rendering (#66809)
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 <hello@anthonyeid.me>
This commit is contained in:
Generated
+10
-46
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<Pixels>, Background)>,
|
||||
default_lines: Vec<(Path, Background)>,
|
||||
background_quads: Vec<(Bounds<Pixels>, Background)>,
|
||||
lines: Vec<Vec<Point<Pixels>>>,
|
||||
start: Point<Pixels>,
|
||||
@@ -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>) {
|
||||
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>) {
|
||||
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))),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -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<Pixels>, Background)>,
|
||||
default_lines: Vec<(Path, Background)>,
|
||||
_painting: bool,
|
||||
}
|
||||
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
+342
-112
@@ -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<lyon::path::BuilderImpl>,
|
||||
transform: Option<lyon::math::Transform>,
|
||||
raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>,
|
||||
transform: Option<lyon_path::math::Transform>,
|
||||
/// PathStyle of the PathBuilder
|
||||
pub style: PathStyle,
|
||||
dash_array: Option<Vec<Pixels>>,
|
||||
}
|
||||
|
||||
impl From<lyon::path::Builder> for PathBuilder {
|
||||
fn from(builder: lyon::path::Builder) -> Self {
|
||||
impl From<lyon_path::Builder> for PathBuilder {
|
||||
fn from(builder: lyon_path::Builder) -> Self {
|
||||
Self {
|
||||
raw: builder.with_svg(),
|
||||
..Default::default()
|
||||
@@ -39,8 +77,8 @@ impl From<lyon::path::Builder> for PathBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<lyon::path::builder::WithSvg<lyon::path::BuilderImpl>> for PathBuilder {
|
||||
fn from(raw: lyon::path::builder::WithSvg<lyon::path::BuilderImpl>) -> Self {
|
||||
impl From<lyon_path::builder::WithSvg<lyon_path::BuilderImpl>> for PathBuilder {
|
||||
fn from(raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>) -> Self {
|
||||
Self {
|
||||
raw,
|
||||
..Default::default()
|
||||
@@ -48,15 +86,15 @@ impl From<lyon::path::builder::WithSvg<lyon::path::BuilderImpl>> for PathBuilder
|
||||
}
|
||||
}
|
||||
|
||||
impl From<lyon::math::Point> for Point<Pixels> {
|
||||
fn from(p: lyon::math::Point) -> Self {
|
||||
impl From<lyon_path::math::Point> for Point<Pixels> {
|
||||
fn from(p: lyon_path::math::Point) -> Self {
|
||||
point(px(p.x), px(p.y))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Point<Pixels>> for lyon::math::Point {
|
||||
impl From<Point<Pixels>> for lyon_path::math::Point {
|
||||
fn from(p: Point<Pixels>) -> 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<Point<Pixels>> for Point2D<f32, Pixels> {
|
||||
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<Path<Pixels>, Error> {
|
||||
pub fn build(self) -> Result<Path, Error> {
|
||||
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<PathCurve>, 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<Path<Pixels>, Error> {
|
||||
// Will contain the result of the tessellation.
|
||||
let mut buf: VertexBuffers<lyon::math::Point, u16> = 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<Vec<Pixels>>,
|
||||
path: &lyon::path::Path,
|
||||
fn stroke_outline(
|
||||
path: &lyon_path::Path,
|
||||
options: &StrokeOptions,
|
||||
) -> Result<Path<Pixels>, 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<Vec<PathCurve>, 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<lyon::math::Point, u16> = 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<lyon::math::Point, u16>) -> Path<Pixels> {
|
||||
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<Vec<PathCurve>, 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<PathCurve>, 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<PathCurve>,
|
||||
start: Point<f32>,
|
||||
current: Point<f32>,
|
||||
non_finite: bool,
|
||||
}
|
||||
|
||||
impl Outline {
|
||||
/// Whether segments through these points can be added.
|
||||
fn accepts(&mut self, points: &[Point<f32>]) -> 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<f32>) {
|
||||
if !self.accepts(&[to]) {
|
||||
return;
|
||||
}
|
||||
self.close();
|
||||
self.start = to;
|
||||
self.current = to;
|
||||
}
|
||||
|
||||
pub(crate) fn line_to(&mut self, to: Point<f32>) {
|
||||
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<f32>, ctrl: Point<f32>) {
|
||||
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<f32>, ctrl1: Point<f32>, ctrl2: Point<f32>) {
|
||||
/// Maximum error, in logical pixels.
|
||||
const TOLERANCE: f32 = 0.25;
|
||||
if !self.accepts(&[to, ctrl1, ctrl2]) {
|
||||
return;
|
||||
}
|
||||
let lyon_point = |p: Point<f32>| 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<Vec<PathCurve>, Error> {
|
||||
if self.non_finite {
|
||||
bail!("path has a non-finite point");
|
||||
}
|
||||
self.close();
|
||||
Ok(self.curves)
|
||||
}
|
||||
}
|
||||
|
||||
impl PathCurve {
|
||||
fn new(p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>, 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<f32>, to: Point<f32>) -> 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<Self>, p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>) {
|
||||
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<f32>, to: Point<f32>) -> (Point<f32>, Point<f32>, 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<tiny_skia_path::Path> {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -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<ScaledPixels>,
|
||||
tiles: Vec<PathTile>,
|
||||
/// Every tile's curve list, concatenated.
|
||||
curves: Vec<PathCurve>,
|
||||
}
|
||||
|
||||
impl PathTiles {
|
||||
pub(crate) fn bounds(&self) -> Bounds<ScaledPixels> {
|
||||
self.bounds
|
||||
}
|
||||
|
||||
pub(crate) fn painted_bounds(&self) -> Bounds<ScaledPixels> {
|
||||
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<ScaledPixels>) {
|
||||
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<f32>| 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>) -> 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<PathCurve>,
|
||||
spans: Vec<Span>,
|
||||
/// 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<usize>,
|
||||
/// Per cell, the winding steps of curves crossing its row's top to its
|
||||
/// left, other than those it lists.
|
||||
steps: Vec<i32>,
|
||||
/// Each cell's listings: a curve's leftmost x above its index.
|
||||
keys: Vec<u64>,
|
||||
/// The current row's runs.
|
||||
runs: Vec<Run>,
|
||||
/// The previous row's runs, whose tiles the current row can extend down.
|
||||
above: Vec<Run>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static BINNER: RefCell<Binner> = 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<f32>, Point<f32>, 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<PathTile>, Vec<PathCurve>) {
|
||||
let Binner {
|
||||
input,
|
||||
steps,
|
||||
cell_ends,
|
||||
keys,
|
||||
runs,
|
||||
above,
|
||||
..
|
||||
} = self;
|
||||
let mut tiles: Vec<PathTile> = 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<f32>,
|
||||
bottom_right: Point<f32>,
|
||||
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<f32>, bottom_right: &mut Point<f32>, 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<Item = &'a PathCurve> {
|
||||
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<f32>, max: Point<f32>, curves: usize, length: f32) -> Option<Self> {
|
||||
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<f32> {
|
||||
point(self.left, self.top)
|
||||
}
|
||||
|
||||
fn bottom_right(self) -> Point<f32> {
|
||||
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<f32>,
|
||||
max: Point<f32>,
|
||||
/// 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<f32>, Point<f32>)> {
|
||||
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<f32>| 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<f32>, 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<Point<Pixels>> =
|
||||
corners.iter().map(|&(x, y)| point(px(x), px(y))).collect();
|
||||
builder.add_polygon(&points, true);
|
||||
builder.build().unwrap()
|
||||
}
|
||||
}
|
||||
@@ -1699,8 +1699,8 @@ mod tests {
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct SceneSnapshot {
|
||||
quads: Vec<QuadSnapshot>,
|
||||
/// 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<String>,
|
||||
element_ids: BTreeSet<u64>,
|
||||
}
|
||||
@@ -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 {} {:?} {:?} {:?} {:?}",
|
||||
|
||||
+101
-167
@@ -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<ScaledPixels>;
|
||||
use std::{fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice};
|
||||
|
||||
#[expect(missing_docs)]
|
||||
pub type DrawOrder = u32;
|
||||
@@ -36,6 +27,13 @@ impl From<bool> 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<DrawOrder>,
|
||||
pub shadows: Vec<Shadow>,
|
||||
pub quads: Vec<Quad>,
|
||||
pub paths: Vec<Path<ScaledPixels>>,
|
||||
pub paths: Vec<PaintedPath>,
|
||||
pub underlines: Vec<Underline>,
|
||||
pub monochrome_sprites: Vec<MonochromeSprite>,
|
||||
pub subpixel_sprites: Vec<SubpixelSprite>,
|
||||
@@ -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<ScaledPixels>),
|
||||
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<slice::Iter<'a, Quad>>,
|
||||
paths_start: usize,
|
||||
paths_iter: Peekable<slice::Iter<'a, Path<ScaledPixels>>>,
|
||||
paths_iter: Peekable<slice::Iter<'a, PaintedPath>>,
|
||||
underlines_start: usize,
|
||||
underlines_iter: Peekable<slice::Iter<'a, Underline>>,
|
||||
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<PaintSurface> 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<f32>,
|
||||
pub p1: Point<f32>,
|
||||
pub a: Point<f32>,
|
||||
pub b: Point<f32>,
|
||||
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<ScaledPixels>,
|
||||
pub content_mask: ContentMask<ScaledPixels>,
|
||||
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<f32>,
|
||||
pub bottom_right: Point<f32>,
|
||||
pub reference: Point<f32>,
|
||||
pub curves_top_left: Point<f32>,
|
||||
pub curves_bottom_right: Point<f32>,
|
||||
}
|
||||
|
||||
/// A line made up of a series of vertices and control points.
|
||||
#[derive(Clone, Debug)]
|
||||
#[expect(missing_docs)]
|
||||
pub struct Path<P: Clone + Debug + Default + PartialEq> {
|
||||
pub id: PathId,
|
||||
pub order: DrawOrder,
|
||||
pub bounds: Bounds<P>,
|
||||
pub content_mask: ContentMask<P>,
|
||||
pub vertices: Vec<PathVertex<P>>,
|
||||
pub color: Background,
|
||||
start: Point<P>,
|
||||
current: Point<P>,
|
||||
contour_count: usize,
|
||||
pub struct PaintedPath {
|
||||
order: DrawOrder,
|
||||
bounds: Bounds<ScaledPixels>,
|
||||
tiles: Rc<PathTiles>,
|
||||
paint: PathPaint,
|
||||
}
|
||||
|
||||
impl Path<Pixels> {
|
||||
/// Create a new path with the given starting point.
|
||||
pub fn new(start: Point<Pixels>) -> 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<Pixels>,
|
||||
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<ScaledPixels> {
|
||||
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<Pixels>) {
|
||||
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<Pixels>) {
|
||||
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<Pixels>, ctrl: Point<Pixels>) {
|
||||
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<Pixels>, Point<Pixels>, Point<Pixels>),
|
||||
st: (Point<f32>, Point<f32>, Point<f32>),
|
||||
pub fn append_to(
|
||||
&self,
|
||||
paints: &mut Vec<PathPaint>,
|
||||
curves: &mut Vec<PathCurve>,
|
||||
tiles: &mut Vec<PathTile>,
|
||||
) {
|
||||
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<T> Path<T>
|
||||
where
|
||||
T: Clone + Debug + Default + PartialEq + PartialOrd + Add<T, Output = T> + Sub<Output = T>,
|
||||
{
|
||||
#[allow(unused)]
|
||||
#[expect(missing_docs)]
|
||||
pub fn clipped_bounds(&self) -> Bounds<T> {
|
||||
self.bounds.intersect(&self.content_mask.bounds)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Path<ScaledPixels>> for Primitive {
|
||||
fn from(path: Path<ScaledPixels>) -> Self {
|
||||
impl From<PaintedPath> for Primitive {
|
||||
fn from(path: PaintedPath) -> Self {
|
||||
Primitive::Path(path)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[repr(C)]
|
||||
#[expect(missing_docs)]
|
||||
pub struct PathVertex<P: Clone + Debug + Default + PartialEq> {
|
||||
pub xy_position: Point<P>,
|
||||
pub st_position: Point<f32>,
|
||||
pub content_mask: ContentMask<P>,
|
||||
}
|
||||
|
||||
#[expect(missing_docs)]
|
||||
impl PathVertex<Pixels> {
|
||||
pub fn scale(&self, factor: f32) -> PathVertex<ScaledPixels> {
|
||||
PathVertex {
|
||||
xy_position: self.xy_position.scale(factor),
|
||||
st_position: self.st_position,
|
||||
content_mask: self.content_mask.scale(factor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Pixels>, color: impl Into<Background>) {
|
||||
pub fn paint_path(&mut self, path: Path, color: impl Into<Background>) {
|
||||
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.
|
||||
|
||||
@@ -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(),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+159
-117
@@ -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<float> 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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<Pixels>),
|
||||
/// 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<Pixels>) -> Option<Path<Pixels>> {
|
||||
fn triangle(bounds: Bounds<Pixels>) -> Option<Path> {
|
||||
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<Pixels> {
|
||||
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() {
|
||||
|
||||
@@ -79,10 +79,12 @@ fn apply_contrast_and_gamma_correction3(sample: vec3<f32>, color: vec3<f32>, enh
|
||||
|
||||
struct GlobalParams {
|
||||
viewport_size: vec2<f32>,
|
||||
premultiplied_alpha: u32,
|
||||
pad: u32,
|
||||
path_paint_base: u32,
|
||||
path_curve_base: u32,
|
||||
}
|
||||
|
||||
override PREMULTIPLIED_ALPHA: bool = false;
|
||||
|
||||
struct GammaParams {
|
||||
gamma_ratios: vec4<f32>,
|
||||
grayscale_enhanced_contrast: f32,
|
||||
@@ -404,7 +406,7 @@ fn quad_sdf_impl(corner_center_to_point: vec2<f32>, corner_radius: f32) -> f32 {
|
||||
// target alpha compositing mode.
|
||||
fn blend_color(color: vec4<f32>, alpha_factor: f32) -> vec4<f32> {
|
||||
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<f32>(color.rgb * multiplier, alpha);
|
||||
}
|
||||
|
||||
@@ -1054,97 +1056,177 @@ fn fs_shadow(input: ShadowVarying) -> @location(0) vec4<f32> {
|
||||
return blend_color(input.color, alpha);
|
||||
}
|
||||
|
||||
// --- path rasterization --- //
|
||||
// --- path tiles --- //
|
||||
|
||||
struct PathRasterizationVertex {
|
||||
xy_position: vec2<f32>,
|
||||
st_position: vec2<f32>,
|
||||
color: Background,
|
||||
bounds: Bounds,
|
||||
struct PathTile {
|
||||
paint: u32,
|
||||
curve_start: u32,
|
||||
curve_count: u32,
|
||||
backdrop: i32,
|
||||
top_left: vec2<f32>,
|
||||
bottom_right: vec2<f32>,
|
||||
reference: vec2<f32>,
|
||||
curves_top_left: vec2<f32>,
|
||||
curves_bottom_right: vec2<f32>,
|
||||
}
|
||||
|
||||
struct PathCurve {
|
||||
p0: vec2<f32>,
|
||||
p1: vec2<f32>,
|
||||
a: vec2<f32>,
|
||||
b: vec2<f32>,
|
||||
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<f32>,
|
||||
@location(0) st_position: vec2<f32>,
|
||||
@location(1) @interpolate(flat) vertex_id: u32,
|
||||
//TODO: use `clip_distance` once Naga supports it
|
||||
@location(3) clip_distances: vec4<f32>,
|
||||
@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<f32>,
|
||||
@location(2) @interpolate(flat) background_color1: vec4<f32>,
|
||||
@location(3) @interpolate(flat) background_tag: u32,
|
||||
@location(4) @interpolate(flat) curve_box: vec4<f32>,
|
||||
}
|
||||
|
||||
@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<f32>(
|
||||
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<f32>(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<f32>, winding: ptr<function, vec2<f32>>,
|
||||
weight: ptr<function, vec2<f32>>) {
|
||||
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<f32>, step: f32, reference: vec2<f32>, center: vec2<f32>,
|
||||
winding: ptr<function, vec2<f32>>) {
|
||||
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<f32> {
|
||||
let dx = dpdx(input.st_position);
|
||||
let dy = dpdy(input.st_position);
|
||||
if (any(input.clip_distances < vec4<f32>(0.0))) {
|
||||
fn fs_path_tile(input: PathTileVarying) -> @location(0) vec4<f32> {
|
||||
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>(f32(tile.backdrop));
|
||||
var weight = vec2<f32>(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<f32>(0.0);
|
||||
}
|
||||
|
||||
let v = load_path_vertex(input.vertex_id);
|
||||
let background = v.color;
|
||||
let bounds = v.bounds;
|
||||
|
||||
var alpha: f32;
|
||||
if (length(vec2<f32>(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<f32>(dx.x, dy.x) - vec2<f32>(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<f32>(color.rgb * color.a * alpha, color.a * alpha);
|
||||
}
|
||||
|
||||
// --- paths --- //
|
||||
|
||||
struct PathSprite {
|
||||
bounds: Bounds,
|
||||
}
|
||||
|
||||
|
||||
struct PathVarying {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) texture_coords: vec2<f32>,
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_path(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PathVarying {
|
||||
let unit_vertex = vec2<f32>(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<f32> {
|
||||
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 --- //
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
|
||||
@group(1) @binding(0) var<storage, read> b_quads: array<Quad>;
|
||||
@group(1) @binding(0) var<storage, read> b_shadows: array<Shadow>;
|
||||
@group(1) @binding(0) var<storage, read> b_path_vertices: array<PathRasterizationVertex>;
|
||||
@group(1) @binding(0) var<storage, read> b_path_sprites: array<PathSprite>;
|
||||
@group(1) @binding(0) var<storage, read> b_underlines: array<Underline>;
|
||||
@group(1) @binding(0) var<storage, read> b_mono_sprites: array<MonochromeSprite>;
|
||||
@group(1) @binding(0) var<storage, read> b_poly_sprites: array<PolychromeSprite>;
|
||||
@@ -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<storage, read> b_path_tiles: array<PathTile>;
|
||||
@group(1) @binding(1) var<storage, read> b_path_curves: array<PathCurve>;
|
||||
@group(1) @binding(2) var<storage, read> b_path_paints: array<PathPaint>;
|
||||
|
||||
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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -34,8 +34,7 @@ mod shader_compilation {
|
||||
let modules = [
|
||||
"quad",
|
||||
"shadow",
|
||||
"path_rasterization",
|
||||
"path_sprite",
|
||||
"path_tile",
|
||||
"underline",
|
||||
"monochrome_sprite",
|
||||
"subpixel_sprite",
|
||||
|
||||
@@ -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<ID3D11Texture2D>,
|
||||
render_target_view: Option<ID3D11RenderTargetView>,
|
||||
|
||||
// Path intermediate textures (with MSAA)
|
||||
path_intermediate_texture: ID3D11Texture2D,
|
||||
path_intermediate_srv: Option<ID3D11ShaderResourceView>,
|
||||
path_intermediate_msaa_texture: ID3D11Texture2D,
|
||||
path_intermediate_msaa_view: Option<ID3D11RenderTargetView>,
|
||||
|
||||
// Cached viewport
|
||||
viewport: D3D11_VIEWPORT,
|
||||
}
|
||||
@@ -86,8 +79,9 @@ struct DirectXResources {
|
||||
struct DirectXRenderPipelines {
|
||||
shadow_pipeline: PipelineState<Shadow>,
|
||||
quad_pipeline: PipelineState<Quad>,
|
||||
path_rasterization_pipeline: PipelineState<PathRasterizationSprite>,
|
||||
path_sprite_pipeline: PipelineState<PathSprite>,
|
||||
path_tile_pipeline: PipelineState<PathTile>,
|
||||
path_curves: StructuredBuffer<PathCurve>,
|
||||
path_paints: StructuredBuffer<PathPaint>,
|
||||
underline_pipeline: PipelineState<Underline>,
|
||||
mono_sprites: PipelineState<MonochromeSprite>,
|
||||
subpixel_sprites: PipelineState<SubpixelSprite>,
|
||||
@@ -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::<usize>();
|
||||
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<ScaledPixels>]) -> Result<()> {
|
||||
if paths.is_empty() {
|
||||
fn draw_paths(&mut self, tile_range: Range<usize>) -> 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<ScaledPixels>]) -> 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::<Vec<_>>()
|
||||
} 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::<BatchParams>() == 16);
|
||||
struct StructuredBuffer<T> {
|
||||
label: &'static str,
|
||||
buffer: ID3D11Buffer,
|
||||
capacity: usize,
|
||||
view: Option<ID3D11ShaderResourceView>,
|
||||
_marker: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> StructuredBuffer<T> {
|
||||
fn new(device: &ID3D11Device, label: &'static str, capacity: usize) -> Result<Self> {
|
||||
let buffer = create_buffer(device, std::mem::size_of::<T>(), 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::<T>().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::<T>(), new_capacity)?;
|
||||
let view = create_buffer_view(device, &buffer)?;
|
||||
self.buffer = buffer;
|
||||
self.view = view;
|
||||
self.capacity = new_capacity;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct PipelineState<T> {
|
||||
label: &'static str,
|
||||
vertex: ID3D11VertexShader,
|
||||
fragment: ID3D11PixelShader,
|
||||
buffer: ID3D11Buffer,
|
||||
buffer_size: usize,
|
||||
view: Option<ID3D11ShaderResourceView>,
|
||||
instances: StructuredBuffer<T>,
|
||||
blend_state: ID3D11BlendState,
|
||||
_marker: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> PipelineState<T> {
|
||||
@@ -1112,18 +1079,12 @@ impl<T> PipelineState<T> {
|
||||
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::<T>(), 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<T> PipelineState<T> {
|
||||
device_context: &ID3D11DeviceContext,
|
||||
data: &[T],
|
||||
) -> Result<()> {
|
||||
if self.buffer_size < data.len() {
|
||||
let element_size = std::mem::size_of::<T>();
|
||||
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::<T>(), 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<ID3D11ShaderResourceView>],
|
||||
sampler: &[Option<ID3D11SamplerState>],
|
||||
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<T> PipelineState<T> {
|
||||
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<T> PipelineState<T> {
|
||||
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<T> PipelineState<T> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
#[repr(C)]
|
||||
struct PathRasterizationSprite {
|
||||
xy_position: Point<ScaledPixels>,
|
||||
st_position: Point<f32>,
|
||||
color: Background,
|
||||
bounds: Bounds<ScaledPixels>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
#[repr(C)]
|
||||
struct PathSprite {
|
||||
bounds: Bounds<ScaledPixels>,
|
||||
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<ID3D11RenderTargetView>,
|
||||
ID3D11Texture2D,
|
||||
Option<ID3D11ShaderResourceView>,
|
||||
ID3D11Texture2D,
|
||||
Option<ID3D11RenderTargetView>,
|
||||
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<ID3D11ShaderResourceView>)> {
|
||||
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<ID3D11RenderTargetView>)> {
|
||||
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<ID
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn create_blend_state_for_path_rasterization(device: &ID3D11Device) -> Result<ID3D11BlendState> {
|
||||
// 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<ID3D11BlendState> {
|
||||
// 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<ID3D11VertexShader> {
|
||||
unsafe {
|
||||
@@ -1610,13 +1374,18 @@ fn create_buffer(
|
||||
element_size: usize,
|
||||
buffer_size: usize,
|
||||
) -> Result<ID3D11Buffer> {
|
||||
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",
|
||||
|
||||
@@ -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<PathRasterizationSprite> path_rasterization_sprites: register(t1);
|
||||
StructuredBuffer<PathTile> path_tiles: register(t1);
|
||||
StructuredBuffer<PathCurve> path_curves: register(t2);
|
||||
StructuredBuffer<PathPaint> 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<PathSprite> 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);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user