Skip to main content

gpui/
vn_clip.rs

1//! vue-native fork: the CSS `clip-path` shapes that are no rounded rectangle,
2//! `polygon()` and `path()` (CSS Shapes 1 §3.1, CSS Masking 1 §5.1).
3//!
4//! A rounded shape (`inset()`, `circle()`, a box) is a content mask
5//! ([`crate::Style::vn_clip_mask`]), which every shader already applies. These
6//! are not: the element's painting goes into an isolated layer instead, an
7//! offscreen texture the renderer composites through the shape's coverage
8//! ([`crate::Scene::vn_push_isolation`]). The shape travels three ways:
9//!
10//! - [`VnPathVerb`]s, the parsed `path()` data (absolute, arcs as cubics), in
11//!   the style;
12//! - a [`VnClipOutline`], the shape laid out against its reference box in the
13//!   element's own frame, logical pixels;
14//! - a [`VnClipGeometry`], the outline flattened into line segments in WINDOW
15//!   device pixels, through the element's whole transform. The renderer
16//!   uploads its segments and evaluates the winding number and the distance
17//!   to the nearest edge per pixel; the hit test asks [`VnClipGeometry::contains`].
18//!   An affine map takes a Bézier's control points to the mapped curve's, so
19//!   the geometry is exact under rotation and skew too.
20
21use crate::{Bounds, ScaledPixels, TransformationMatrix, point, px, size};
22#[cfg(feature = "schemars")]
23use schemars::JsonSchema;
24use serde::{Deserialize, Serialize};
25use std::sync::Arc;
26
27/// vue-native fork: the `<fill-rule>` of a `polygon()` or `path()`.
28#[derive(Copy, Clone, Default, PartialEq, Eq, Debug, Serialize, Deserialize)]
29#[cfg_attr(feature = "schemars", derive(JsonSchema))]
30pub enum VnFillRule {
31    /// `nonzero`, the default: inside where the winding number is not zero.
32    #[default]
33    NonZero,
34    /// `evenodd`: inside where the winding number is odd.
35    EvenOdd,
36}
37
38/// vue-native fork: one verb of a `path()`, in absolute pixels from the
39/// reference box's top left corner. A parser resolves the relative commands,
40/// the `H`/`V` lines, the `S`/`T` reflections and the arcs
41/// ([`VnPathVerb::push_arc`]) into these five.
42#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
43#[cfg_attr(feature = "schemars", derive(JsonSchema))]
44pub enum VnPathVerb {
45    /// `M`: starts a subpath.
46    MoveTo([f32; 2]),
47    /// `L`, `H`, `V`.
48    LineTo([f32; 2]),
49    /// `Q`, `T`: a control point and the end.
50    QuadTo([f32; 2], [f32; 2]),
51    /// `C`, `S`, `A`: two control points and the end.
52    CubicTo([f32; 2], [f32; 2], [f32; 2]),
53    /// `Z`: closes the subpath. A fill closes every subpath anyway.
54    Close,
55}
56
57impl VnPathVerb {
58    /// Appends SVG's elliptical arc from `from` to `to` (SVG 2 §9.3.8 and
59    /// its appendix B.2.5: out-of-range radii scale up, a zero radius is a
60    /// line, an arc to its own start is nothing) as cubics.
61    pub fn push_arc(
62        out: &mut Vec<VnPathVerb>,
63        from: [f32; 2],
64        radii: [f32; 2],
65        x_rotation_degrees: f32,
66        large_arc: bool,
67        sweep: bool,
68        to: [f32; 2],
69    ) {
70        use lyon_path::geom::{Angle, ArcFlags, SvgArc, point as lpoint, vector};
71        if from == to {
72            return;
73        }
74        let arc = SvgArc {
75            from: lpoint(from[0], from[1]),
76            to: lpoint(to[0], to[1]),
77            radii: vector(radii[0].abs(), radii[1].abs()),
78            x_rotation: Angle::degrees(x_rotation_degrees),
79            flags: ArcFlags { large_arc, sweep },
80        };
81        if arc.is_straight_line() {
82            out.push(VnPathVerb::LineTo(to));
83            return;
84        }
85        arc.for_each_cubic_bezier(&mut |c| {
86            out.push(VnPathVerb::CubicTo([c.ctrl1.x, c.ctrl1.y], [c.ctrl2.x, c.ctrl2.y], [c.to.x, c.to.y]));
87        });
88        // The last cubic ends on `to` up to rounding; make it exact, so a
89        // following relative command starts where the arc was asked to end.
90        if let Some(VnPathVerb::CubicTo(_, _, end)) = out.last_mut() {
91            *end = to;
92        }
93    }
94}
95
96/// vue-native fork: a `polygon()` or `path()` laid out against its reference
97/// box, in the element's own frame and logical pixels
98/// ([`crate::Style::vn_clip_outline`]).
99#[derive(Clone, PartialEq, Debug, Default)]
100pub struct VnClipOutline {
101    /// How the winding number decides inside.
102    pub fill_rule: VnFillRule,
103    /// The shape.
104    pub verbs: Vec<VnPathVerb>,
105}
106
107impl VnClipOutline {
108    /// The bounding box of every point and control point, which holds the
109    /// shape (a Bézier lies in the hull of its control points). `None` for
110    /// an outline with no point.
111    pub fn control_bounds(&self) -> Option<Bounds<crate::Pixels>> {
112        let mut points = self.verbs.iter().flat_map(|v| match v {
113            VnPathVerb::MoveTo(a) | VnPathVerb::LineTo(a) => vec![*a],
114            VnPathVerb::QuadTo(a, b) => vec![*a, *b],
115            VnPathVerb::CubicTo(a, b, c) => vec![*a, *b, *c],
116            VnPathVerb::Close => vec![],
117        });
118        let first = points.next()?;
119        let (mut min, mut max) = (first, first);
120        for p in points {
121            min = [min[0].min(p[0]), min[1].min(p[1])];
122            max = [max[0].max(p[0]), max[1].max(p[1])];
123        }
124        Some(Bounds::from_corners(point(px(min[0]), px(min[1])), point(px(max[0]), px(max[1]))))
125    }
126}
127
128/// The largest distance, in device pixels, between a curve and the line
129/// segments that stand for it. A quarter pixel is below what the shader's
130/// one-pixel antialiased edge shows.
131pub const VN_CLIP_TOLERANCE: f32 = 0.25;
132
133/// Most segments one curve becomes, whatever its size.
134const MAX_CURVE_SEGMENTS: u32 = 128;
135
136/// vue-native fork: a clip shape flattened into line segments, in window
137/// device pixels. What the renderer evaluates per pixel and the hit test
138/// asks.
139#[derive(Clone, PartialEq, Debug, Default)]
140pub struct VnClipGeometry {
141    /// How the winding number decides inside.
142    pub fill_rule: VnFillRule,
143    /// The edges, `[x0, y0, x1, y1]`; every subpath is closed.
144    pub segments: Vec<[f32; 4]>,
145    /// The box around the segments.
146    pub bounds: Bounds<ScaledPixels>,
147}
148
149impl VnClipGeometry {
150    /// A rectangle, in window device pixels.
151    pub fn rect(bounds: Bounds<ScaledPixels>) -> Self {
152        let (left, top) = (bounds.origin.x.0, bounds.origin.y.0);
153        let (right, bottom) = (left + bounds.size.width.0, top + bounds.size.height.0);
154        Self {
155            fill_rule: VnFillRule::NonZero,
156            segments: vec![
157                [left, top, right, top],
158                [right, top, right, bottom],
159                [right, bottom, left, bottom],
160                [left, bottom, left, top],
161            ],
162            bounds,
163        }
164    }
165
166    /// Flattens `outline` (logical pixels, the element's own frame) into
167    /// window device pixels: scaled by `scale_factor`, then through
168    /// `transform` (a device-space matrix, as
169    /// [`crate::Window::element_transform`]). Curves are cut to
170    /// [`VN_CLIP_TOLERANCE`] in device pixels.
171    pub fn new(outline: &VnClipOutline, scale_factor: f32, transform: TransformationMatrix) -> Self {
172        let unit = transform.is_unit();
173        let map = |p: [f32; 2]| -> [f32; 2] {
174            let d = [p[0] * scale_factor, p[1] * scale_factor];
175            if unit {
176                return d;
177            }
178            let t = transform.apply(point(px(d[0]), px(d[1])));
179            [t.x.0, t.y.0]
180        };
181        let mut segments = Vec::new();
182        let mut start = [0.; 2];
183        let mut current = [0.; 2];
184        let mut open = false;
185        let mut close = |segments: &mut Vec<[f32; 4]>, current: [f32; 2], start: [f32; 2]| {
186            if current != start {
187                segments.push([current[0], current[1], start[0], start[1]]);
188            }
189        };
190        for verb in &outline.verbs {
191            match *verb {
192                VnPathVerb::MoveTo(p) => {
193                    if open {
194                        close(&mut segments, current, start);
195                    }
196                    start = map(p);
197                    current = start;
198                    open = true;
199                }
200                VnPathVerb::LineTo(p) => {
201                    let p = map(p);
202                    if p != current {
203                        segments.push([current[0], current[1], p[0], p[1]]);
204                    }
205                    current = p;
206                    open = true;
207                }
208                VnPathVerb::QuadTo(c, p) => {
209                    let (c, p) = (map(c), map(p));
210                    flatten_quad(&mut segments, current, c, p);
211                    current = p;
212                    open = true;
213                }
214                VnPathVerb::CubicTo(c1, c2, p) => {
215                    let (c1, c2, p) = (map(c1), map(c2), map(p));
216                    flatten_cubic(&mut segments, current, c1, c2, p);
217                    current = p;
218                    open = true;
219                }
220                VnPathVerb::Close => {
221                    if open {
222                        close(&mut segments, current, start);
223                    }
224                    // SVG: the next segment starts where the subpath did.
225                    current = start;
226                    open = false;
227                }
228            }
229        }
230        if open {
231            close(&mut segments, current, start);
232        }
233        let bounds = segment_bounds(&segments);
234        VnClipGeometry { fill_rule: outline.fill_rule, segments, bounds }
235    }
236
237    /// The winding number of the shape around `p` (device pixels): the
238    /// signed count of edges crossing the ray from `p` to the right, upward
239    /// edges counting one way and downward ones the other.
240    pub fn winding(&self, p: [f32; 2]) -> i32 {
241        let mut winding = 0;
242        for s in &self.segments {
243            let (a, b) = ([s[0], s[1]], [s[2], s[3]]);
244            // Half-open in y, so a vertex on the ray counts once.
245            if (a[1] <= p[1]) != (b[1] <= p[1]) {
246                let t = (p[1] - a[1]) / (b[1] - a[1]);
247                let x = a[0] + t * (b[0] - a[0]);
248                if p[0] < x {
249                    winding += if b[1] > a[1] { 1 } else { -1 };
250                }
251            }
252        }
253        winding
254    }
255
256    /// Whether `p` (device pixels) is inside the shape under its fill rule.
257    pub fn contains(&self, p: [f32; 2]) -> bool {
258        let w = self.winding(p);
259        match self.fill_rule {
260            VnFillRule::NonZero => w != 0,
261            VnFillRule::EvenOdd => w & 1 == 1,
262        }
263    }
264
265    /// The antialiased coverage at the pixel centre `p`, as the composite
266    /// shader computes it (`vn_layer_fragment` in gpui_windows'
267    /// shaders.hlsl): inside or outside by the fill rule, blended over one
268    /// pixel across the nearest edge.
269    pub fn coverage(&self, p: [f32; 2]) -> f32 {
270        let mut nearest = f32::MAX;
271        for s in &self.segments {
272            nearest = nearest.min(distance_to_segment(p, *s));
273        }
274        let d = if self.contains(p) { nearest } else { -nearest };
275        (0.5 + d).clamp(0., 1.)
276    }
277}
278
279/// An SVG feColorMatrix over unpremultiplied RGBA components.
280#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
281#[cfg_attr(feature = "schemars", derive(JsonSchema))]
282pub struct VnColorMatrix {
283    /// Stable identity of the filtered element within this window's scene.
284    /// Zero keeps independently composited layers for callers without an ID.
285    pub group_id: u64,
286    /// Four rows of five coefficients, in SVG order.
287    pub values: [f32; 20],
288    /// SVG filters use linear RGB unless color-interpolation-filters is sRGB.
289    pub linear_rgb: bool,
290}
291
292impl VnColorMatrix {
293    /// The identity transform.
294    pub const IDENTITY: [f32; 20] = [
295        1., 0., 0., 0., 0., 0., 1., 0., 0., 0.,
296        0., 0., 1., 0., 0., 0., 0., 0., 1., 0.,
297    ];
298
299    /// Four float4 coefficient rows followed by a float4 bias, for the GPU.
300    pub fn gpu_values(self) -> [f32; 20] {
301        let mut packed = [0.; 20];
302        for row in 0..4 {
303            packed[row * 4..row * 4 + 4].copy_from_slice(&self.values[row * 5..row * 5 + 4]);
304            packed[16 + row] = self.values[row * 5 + 4];
305        }
306        packed
307    }
308}
309
310/// vue-native fork: a clip shape in force, and the ones around it — what a
311/// hitbox, a deferred draw and the window's clip stack carry, so a press
312/// outside any of them misses (CSS Masking 1 §5).
313#[derive(Debug)]
314pub struct VnClipNode {
315    /// This clip's shape, in window device pixels.
316    pub geometry: Arc<VnClipGeometry>,
317    /// A color transform applied when this isolated layer is composited.
318    pub color_matrix: Option<VnColorMatrix>,
319    /// A captured group ([`crate::VnIsolation::capture`]); it has no parent.
320    pub capture: Option<crate::VnCaptureInfo>,
321    /// A CSS `mask` this layer composites through; it does not cut the hit test.
322    pub mask: Option<VnClipMask>,
323    /// The clip around this one, if any.
324    pub parent: Option<Arc<VnClipNode>>,
325}
326
327/// vue-native fork: a [`crate::VnMask`] with the border box and transform it
328/// paints at, so a deferred descendant can paint it again around its own layer.
329#[derive(Clone)]
330pub struct VnClipMask {
331    /// The mask.
332    pub mask: crate::VnMask,
333    /// The element's border box, in its own frame.
334    pub bounds: crate::Bounds<crate::Pixels>,
335    /// The element transform in force at the element.
336    pub transform: TransformationMatrix,
337}
338
339impl std::fmt::Debug for VnClipMask {
340    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341        f.debug_struct("VnClipMask").field("mask", &self.mask).field("bounds", &self.bounds).finish()
342    }
343}
344
345impl VnClipNode {
346    /// Whether the window device pixel `p` is inside this clip and every
347    /// one around it.
348    pub fn contains(&self, p: [f32; 2]) -> bool {
349        let mut node = Some(self);
350        while let Some(n) = node {
351            if n.mask.is_none() && !n.geometry.contains(p) {
352                return false;
353            }
354            node = n.parent.as_deref();
355        }
356        true
357    }
358
359    /// The chain from the outermost clip in.
360    pub fn outermost_first(this: &Arc<VnClipNode>) -> Vec<Arc<VnClipNode>> {
361        let mut chain = vec![this.clone()];
362        while let Some(parent) = chain.last().and_then(|n| n.parent.clone()) {
363            chain.push(parent);
364        }
365        chain.reverse();
366        chain
367    }
368
369    /// [`Self::outermost_first`] without the clips `base` is already inside
370    /// of: the layers a draw deferred from inside `base` reopens when it
371    /// paints within it.
372    pub fn inside_of(this: &Arc<VnClipNode>, base: Option<&Arc<VnClipNode>>) -> Vec<Arc<VnClipNode>> {
373        let chain = Self::outermost_first(this);
374        let Some(base) = base else { return chain };
375        let mut outer = Self::outermost_first(base).into_iter();
376        // A `color_filters` chain copies the nodes it keeps, sharing their geometry.
377        let same = |a: &Arc<VnClipNode>, b: &Arc<VnClipNode>| {
378            Arc::ptr_eq(a, b)
379                || (Arc::ptr_eq(&a.geometry, &b.geometry)
380                    && a.color_matrix == b.color_matrix
381                    && a.capture == b.capture)
382        };
383        let shared = chain
384            .iter()
385            .take_while(|node| outer.any(|o| same(&o, node)))
386            .count();
387        chain.into_iter().skip(shared).collect()
388    }
389
390    /// Fixed-position descendants can escape geometric clips, but remain in
391    /// their ancestors' color-filter groups until those groups composite.
392    pub fn color_filters(clip: &Option<Arc<VnClipNode>>) -> Option<Arc<VnClipNode>> {
393        let Some(clip) = clip else { return None };
394        let mut parent = None;
395        for node in Self::outermost_first(clip) {
396            if node.color_matrix.is_some() || node.capture.is_some() {
397                parent = Some(Arc::new(Self {
398                    geometry: node.geometry.clone(),
399                    color_matrix: node.color_matrix,
400                    capture: node.capture,
401                    mask: None,
402                    parent,
403                }));
404            }
405        }
406        parent
407    }
408
409    /// Two chains are the same clip: the same shapes, nested the same way.
410    pub fn same(a: &Option<Arc<VnClipNode>>, b: &Option<Arc<VnClipNode>>) -> bool {
411        match (a, b) {
412            (None, None) => true,
413            (Some(a), Some(b)) => {
414                Arc::ptr_eq(a, b)
415                    || (a.geometry == b.geometry
416                        && a.color_matrix == b.color_matrix
417                        && a.capture == b.capture
418                        && a.mask.as_ref().map(|m| &m.mask) == b.mask.as_ref().map(|m| &m.mask)
419                        && VnClipNode::same(&a.parent, &b.parent))
420            }
421            _ => false,
422        }
423    }
424}
425
426fn segment_bounds(segments: &[[f32; 4]]) -> Bounds<ScaledPixels> {
427    let Some(first) = segments.first() else {
428        return Bounds::default();
429    };
430    let (mut min, mut max) = ([first[0], first[1]], [first[0], first[1]]);
431    for s in segments {
432        for p in [[s[0], s[1]], [s[2], s[3]]] {
433            min = [min[0].min(p[0]), min[1].min(p[1])];
434            max = [max[0].max(p[0]), max[1].max(p[1])];
435        }
436    }
437    Bounds {
438        origin: point(ScaledPixels(min[0]), ScaledPixels(min[1])),
439        size: size(ScaledPixels(max[0] - min[0]), ScaledPixels(max[1] - min[1])),
440    }
441}
442
443fn distance_to_segment(p: [f32; 2], s: [f32; 4]) -> f32 {
444    let (ax, ay, bx, by) = (s[0], s[1], s[2], s[3]);
445    let (dx, dy) = (bx - ax, by - ay);
446    let len2 = dx * dx + dy * dy;
447    let t = if len2 > 0. { (((p[0] - ax) * dx + (p[1] - ay) * dy) / len2).clamp(0., 1.) } else { 0. };
448    let (qx, qy) = (ax + t * dx - p[0], ay + t * dy - p[1]);
449    (qx * qx + qy * qy).sqrt()
450}
451
452/// Wang's formula: the segments a Bézier of `degree` needs for its
453/// approximation to stay within the tolerance, from its largest second
454/// difference.
455fn segment_count(degree: f32, second_difference: f32) -> u32 {
456    let n = (degree * (degree - 1.) / 8. * second_difference / VN_CLIP_TOLERANCE).sqrt().ceil();
457    (n as u32).clamp(1, MAX_CURVE_SEGMENTS)
458}
459
460fn flatten_quad(out: &mut Vec<[f32; 4]>, p0: [f32; 2], p1: [f32; 2], p2: [f32; 2]) {
461    let dd = ((p0[0] - 2. * p1[0] + p2[0]).powi(2) + (p0[1] - 2. * p1[1] + p2[1]).powi(2)).sqrt();
462    let n = segment_count(2., dd);
463    let mut prev = p0;
464    for i in 1..=n {
465        let t = i as f32 / n as f32;
466        let u = 1. - t;
467        let p = if i == n {
468            p2
469        } else {
470            [u * u * p0[0] + 2. * u * t * p1[0] + t * t * p2[0], u * u * p0[1] + 2. * u * t * p1[1] + t * t * p2[1]]
471        };
472        if p != prev {
473            out.push([prev[0], prev[1], p[0], p[1]]);
474        }
475        prev = p;
476    }
477}
478
479fn flatten_cubic(out: &mut Vec<[f32; 4]>, p0: [f32; 2], p1: [f32; 2], p2: [f32; 2], p3: [f32; 2]) {
480    let d1 = ((p0[0] - 2. * p1[0] + p2[0]).powi(2) + (p0[1] - 2. * p1[1] + p2[1]).powi(2)).sqrt();
481    let d2 = ((p1[0] - 2. * p2[0] + p3[0]).powi(2) + (p1[1] - 2. * p2[1] + p3[1]).powi(2)).sqrt();
482    let n = segment_count(3., d1.max(d2));
483    let mut prev = p0;
484    for i in 1..=n {
485        let t = i as f32 / n as f32;
486        let u = 1. - t;
487        let p = if i == n {
488            p3
489        } else {
490            let (a, b, c, d) = (u * u * u, 3. * u * u * t, 3. * u * t * t, t * t * t);
491            [
492                a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0],
493                a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1],
494            ]
495        };
496        if p != prev {
497            out.push([prev[0], prev[1], p[0], p[1]]);
498        }
499        prev = p;
500    }
501}
502
503#[cfg(test)]
504mod tests {
505    use super::*;
506    use crate::{TransformationMatrix, point};
507
508    fn outline(fill_rule: VnFillRule, verbs: Vec<VnPathVerb>) -> VnClipOutline {
509        VnClipOutline { fill_rule, verbs }
510    }
511
512    fn square(x: f32, y: f32, side: f32, clockwise: bool) -> Vec<VnPathVerb> {
513        use VnPathVerb::*;
514        let mut v = vec![MoveTo([x, y])];
515        if clockwise {
516            v.extend([LineTo([x + side, y]), LineTo([x + side, y + side]), LineTo([x, y + side])]);
517        } else {
518            v.extend([LineTo([x, y + side]), LineTo([x + side, y + side]), LineTo([x + side, y])]);
519        }
520        v.push(Close);
521        v
522    }
523
524    #[test]
525    fn color_matrix_gpu_rows_and_bias_match_the_layer_shader() {
526        let matrix = VnColorMatrix {
527            group_id: 1,
528            values: std::array::from_fn(|index| index as f32),
529            linear_rgb: true,
530        };
531        assert_eq!(matrix.gpu_values(), [
532            0., 1., 2., 3., 5., 6., 7., 8., 10., 11., 12., 13., 15., 16., 17., 18.,
533            4., 9., 14., 19.,
534        ]);
535        assert_eq!(std::mem::size_of::<crate::VnLayer>(), 240);
536        assert_eq!(std::mem::offset_of!(crate::VnLayer, color_matrix), 32);
537        assert_eq!(std::mem::offset_of!(crate::VnLayer, bounds), 112);
538    }
539
540    #[test]
541    fn a_triangle_is_inside_where_it_is_and_closes_itself() {
542        use VnPathVerb::*;
543        // No `Z`: a fill closes the subpath.
544        let g = VnClipGeometry::new(
545            &outline(VnFillRule::NonZero, vec![MoveTo([0., 0.]), LineTo([100., 0.]), LineTo([0., 100.])]),
546            1.,
547            TransformationMatrix::unit(),
548        );
549        assert_eq!(g.segments.len(), 3);
550        assert!(g.contains([10., 10.]));
551        assert!(!g.contains([60., 60.]), "beyond the hypotenuse");
552        assert!(!g.contains([-1., 5.]));
553        assert_eq!(g.coverage([10.5, 10.5]), 1.);
554        assert_eq!(g.coverage([80.5, 80.5]), 0.);
555        // On the hypotenuse x + y = 100 the pixel is half covered.
556        assert!((g.coverage([50., 50.]) - 0.5).abs() < 0.01);
557        assert_eq!(
558            [g.bounds.origin.x.0, g.bounds.origin.y.0, g.bounds.size.width.0, g.bounds.size.height.0],
559            [0., 0., 100., 100.]
560        );
561    }
562
563    #[test]
564    fn the_fill_rule_decides_a_hole() {
565        // A square inside a square, both clockwise: winding 2 in the middle.
566        let mut verbs = square(0., 0., 100., true);
567        verbs.extend(square(25., 25., 50., true));
568        let nonzero = VnClipGeometry::new(&outline(VnFillRule::NonZero, verbs.clone()), 1., TransformationMatrix::unit());
569        let evenodd = VnClipGeometry::new(&outline(VnFillRule::EvenOdd, verbs), 1., TransformationMatrix::unit());
570        assert_eq!(nonzero.winding([50., 50.]).abs(), 2);
571        assert!(nonzero.contains([50., 50.]) && nonzero.contains([10., 10.]));
572        assert!(!evenodd.contains([50., 50.]) && evenodd.contains([10., 10.]));
573        // The inner one counter-clockwise: a hole under nonzero too.
574        let mut verbs = square(0., 0., 100., true);
575        verbs.extend(square(25., 25., 50., false));
576        let g = VnClipGeometry::new(&outline(VnFillRule::NonZero, verbs), 1., TransformationMatrix::unit());
577        assert!(!g.contains([50., 50.]) && g.contains([10., 10.]));
578    }
579
580    #[test]
581    fn curves_flatten_within_the_tolerance() {
582        use VnPathVerb::*;
583        // A circle of radius 40 from four cubics (k = 0.5523).
584        let (c, r, k) = (50., 40., 0.5523 * 40.);
585        let verbs = vec![
586            MoveTo([c + r, c]),
587            CubicTo([c + r, c + k], [c + k, c + r], [c, c + r]),
588            CubicTo([c - k, c + r], [c - r, c + k], [c - r, c]),
589            CubicTo([c - r, c - k], [c - k, c - r], [c, c - r]),
590            CubicTo([c + k, c - r], [c + r, c - k], [c + r, c]),
591            Close,
592        ];
593        let g = VnClipGeometry::new(&outline(VnFillRule::NonZero, verbs), 2., TransformationMatrix::unit());
594        // At scale 2 the radius is 80 device pixels: every vertex on it.
595        for s in &g.segments {
596            let d = ((s[0] - 100.).powi(2) + (s[1] - 100.).powi(2)).sqrt();
597            assert!((d - 80.).abs() < 0.1, "{d}");
598        }
599        // Few enough segments to evaluate per pixel, enough to be round.
600        assert!(g.segments.len() >= 16 && g.segments.len() <= 64, "{}", g.segments.len());
601        assert!(g.contains([100., 100.]) && !g.contains([100. + 80. * 0.75, 100. + 80. * 0.75]));
602        // A quadratic too.
603        let q = VnClipGeometry::new(
604            &outline(VnFillRule::NonZero, vec![MoveTo([0., 0.]), QuadTo([50., 100.], [100., 0.]), Close]),
605            1.,
606            TransformationMatrix::unit(),
607        );
608        assert!(q.contains([50., 40.]) && !q.contains([50., 60.]), "the apex is at y = 50");
609    }
610
611    #[test]
612    fn the_shape_follows_the_whole_transform() {
613        // A 90 degree rotation about the origin, then a translation: exact,
614        // where a rounded mask would fall back to its bounding box.
615        let rotate = TransformationMatrix::unit()
616            .translate(point(ScaledPixels(200.), ScaledPixels(0.)))
617            .rotate(crate::Radians(std::f32::consts::FRAC_PI_2));
618        use VnPathVerb::*;
619        let triangle = vec![MoveTo([0., 0.]), LineTo([100., 0.]), LineTo([0., 50.]), Close];
620        let g = VnClipGeometry::new(&outline(VnFillRule::NonZero, triangle.clone()), 1., rotate);
621        let probe = |p: [f32; 2]| {
622            let q = rotate.apply(point(px(p[0]), px(p[1])));
623            [q.x.0, q.y.0]
624        };
625        assert!(g.contains(probe([10., 10.])));
626        assert!(!g.contains(probe([90., 40.])));
627        assert!(!g.contains([10., 10.]), "not where the untransformed shape was");
628    }
629
630    #[test]
631    fn arcs_become_cubics_that_end_where_asked() {
632        let mut verbs = vec![VnPathVerb::MoveTo([0., 50.])];
633        // A half circle of radius 50 from (0, 50) to (100, 50), over the top.
634        VnPathVerb::push_arc(&mut verbs, [0., 50.], [50., 50.], 0., false, true, [100., 50.]);
635        assert!(verbs.len() >= 3, "{verbs:?}");
636        assert_eq!(verbs.last(), Some(&VnPathVerb::CubicTo(
637            match verbs.last() { Some(VnPathVerb::CubicTo(a, _, _)) => *a, _ => unreachable!() },
638            match verbs.last() { Some(VnPathVerb::CubicTo(_, b, _)) => *b, _ => unreachable!() },
639            [100., 50.],
640        )));
641        let g = VnClipGeometry::new(&outline(VnFillRule::NonZero, verbs), 1., TransformationMatrix::unit());
642        assert!(g.contains([50., 10.]), "the top of the half disc");
643        assert!(!g.contains([50., 60.]), "below the diameter");
644        assert!(!g.contains([5., 5.]), "outside the curve in the corner");
645        // A zero radius is a line; an arc to its own start is nothing.
646        let mut line = vec![];
647        VnPathVerb::push_arc(&mut line, [0., 0.], [0., 10.], 0., false, false, [10., 0.]);
648        assert_eq!(line, vec![VnPathVerb::LineTo([10., 0.])]);
649        let mut none = vec![];
650        VnPathVerb::push_arc(&mut none, [3., 3.], [10., 10.], 0., false, false, [3., 3.]);
651        assert!(none.is_empty());
652    }
653
654    #[test]
655    fn a_clip_chain_contains_what_every_link_does() {
656        let left = Arc::new(VnClipGeometry::new(
657            &outline(VnFillRule::NonZero, square(0., 0., 60., true)),
658            1.,
659            TransformationMatrix::unit(),
660        ));
661        let right = Arc::new(VnClipGeometry::new(
662            &outline(VnFillRule::NonZero, square(40., 0., 60., true)),
663            1.,
664            TransformationMatrix::unit(),
665        ));
666        let outer = Arc::new(VnClipNode { geometry: left.clone(), color_matrix: None, capture: None, mask: None, parent: None });
667        let inner = Arc::new(VnClipNode { geometry: right.clone(), color_matrix: None, capture: None, mask: None, parent: Some(outer.clone()) });
668        assert!(inner.contains([50., 10.]));
669        assert!(!inner.contains([10., 10.]) && !inner.contains([90., 10.]));
670        assert_eq!(VnClipNode::outermost_first(&inner).len(), 2);
671        assert!(Arc::ptr_eq(&VnClipNode::outermost_first(&inner)[0], &outer));
672        // The same shapes rebuilt are the same clip; a different one is not.
673        let rebuilt = Some(Arc::new(VnClipNode {
674            geometry: Arc::new((*right).clone()),
675            color_matrix: None,
676            capture: None,
677            mask: None,
678            parent: Some(Arc::new(VnClipNode { geometry: Arc::new((*left).clone()), color_matrix: None, capture: None, mask: None, parent: None })),
679        }));
680        assert!(VnClipNode::same(&Some(inner.clone()), &rebuilt));
681        assert!(!VnClipNode::same(&Some(inner), &Some(outer)));
682    }
683
684    #[test]
685    fn fixed_escapes_preserve_color_groups_while_dropping_geometric_clips() {
686        let geometry = Arc::new(VnClipGeometry::new(
687            &outline(VnFillRule::NonZero, square(0., 0., 100., true)),
688            1., TransformationMatrix::unit(),
689        ));
690        let clip = Arc::new(VnClipNode { geometry: geometry.clone(), color_matrix: None, capture: None, mask: None, parent: None });
691        let filter = Arc::new(VnClipNode {
692            geometry: geometry.clone(),
693            color_matrix: Some(VnColorMatrix { group_id: 7, values: VnColorMatrix::IDENTITY, linear_rgb: true }),
694            capture: None,
695            mask: None,
696            parent: Some(clip),
697        });
698        let inside = Some(Arc::new(VnClipNode { geometry, color_matrix: None, capture: None, mask: None, parent: Some(filter) }));
699        let retained = VnClipNode::color_filters(&inside).expect("filter retained");
700        assert_eq!(retained.color_matrix.expect("matrix").group_id, 7);
701        assert!(retained.parent.is_none(), "geometric clipping is escaped");
702    }
703
704}