Skip to main content

valo_geometry/
path.rs

1use std::sync::Arc;
2
3use crate::{Matrix, Point, Rect};
4
5/// `FillRule` determines which regions of overlapping contours are filled.
6#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8pub enum FillRule {
9    /// `NonZero` fills regions whose signed winding count is nonzero.
10    #[default]
11    NonZero,
12    /// `EvenOdd` fills regions crossed an odd number of times.
13    EvenOdd,
14}
15
16/// `Winding` selects the traversal direction of a closed contour.
17///
18/// Direction matters wherever traversal carries meaning: under the nonzero fill
19/// rule two overlapping contours cancel when their windings oppose and add
20/// when they agree, and dashing walks a contour in order.
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
22#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
23pub enum Winding {
24    /// `Clockwise` traverses in the clockwise direction on Valo's y-down plane.
25    #[default]
26    Clockwise,
27    /// `CounterClockwise` traverses in the counterclockwise direction.
28    CounterClockwise,
29}
30
31// Serialize ONLY (the serde feature is a debug dump): a deserializer would
32// let malformed verb/point/weight counts reach flatten() and index out of
33// bounds.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize))]
36enum Verb {
37    Move,
38    Line,
39    Quad,
40    /// A rational quadratic: control point, end point, and a weight drawn
41    /// from the side channel `weights`. Weights are strictly positive and
42    /// finite — `conic_to` lowers everything else.
43    Conic,
44    Cubic,
45    Close,
46}
47
48/// `Contour` is one path contour flattened into a polyline.
49///
50/// Closed contours repeat their first point at the end so measurement and
51/// dashing include the closing edge. Closure remains explicit metadata rather
52/// than being inferred from coincident endpoints.
53#[derive(Clone, Debug, PartialEq)]
54pub struct Contour {
55    /// `points` contains the flattened polyline in traversal order.
56    pub points: Vec<Point>,
57    /// `closed` indicates whether the source contour ended with `close`.
58    pub closed: bool,
59    /// `has_segments` distinguishes drawn zero-length contours from a lone move.
60    ///
61    /// A close or explicit zero-length segment counts; a bare `move_to` does not.
62    pub has_segments: bool,
63}
64
65/// `PathElement` is one step of a [`Path`], as [`Path::elements`] walks it.
66///
67/// Points are absolute. A `Conic` carries its weight; feed the elements to a
68/// [`PathBuilder`] in order to rebuild an equal path.
69#[derive(Clone, Copy, Debug, PartialEq)]
70pub enum PathElement {
71    MoveTo(Point),
72    LineTo(Point),
73    QuadTo(Point, Point),
74    ConicTo(Point, Point, f32),
75    CubicTo(Point, Point, Point),
76    Close,
77}
78
79/// `Path` is an immutable collection of line and Bézier contours.
80///
81/// Build paths with [`PathBuilder`]. Display lists retain shared [`Arc`] handles,
82/// so recording and nesting do not copy path data.
83#[derive(Clone, Debug, PartialEq)]
84#[cfg_attr(feature = "serde", derive(serde::Serialize))]
85pub struct Path {
86    verbs: Vec<Verb>,
87    points: Vec<Point>,
88    /// One entry per `Verb::Conic`, consumed in verb order. Positive weights
89    /// keep the curve inside its control hull, so `bounds` stays sound.
90    weights: Vec<f32>,
91    /// Control-point bounds: conservative (curves stay inside their hull),
92    /// which is exactly what the record-time oracle wants.
93    bounds: Rect,
94    /// What the path was built as, when it was built as nothing but an oval
95    /// or a rounded rectangle.
96    shape: BuiltShape,
97}
98
99/// `BuiltShape` is what a path was built as, known by construction as
100/// Skia's path knows it (`SkPathIsAType`): an oval or a rounded rectangle
101/// added to an empty builder, with nothing added after it. Any other path is
102/// `General`, whatever its outline happens to trace.
103#[derive(Clone, Copy, Debug, Default, PartialEq)]
104#[cfg_attr(feature = "serde", derive(serde::Serialize))]
105enum BuiltShape {
106    #[default]
107    General,
108    /// An oval filling the rect.
109    Oval(Rect),
110    /// A rounded rectangle with its constrained per-corner radii, clockwise
111    /// from the top-left, each `[x, y]`; never all zero.
112    RoundRect { rect: Rect, radii: [[f32; 2]; 4] },
113}
114
115impl BuiltShape {
116    /// `of_round_rect` is what a rounded rectangle over `rect` with
117    /// constrained `radii` was built as, simplified as Skia's
118    /// `SkPathPriv::SimplifyRRect` does: a rectangle, which is `General` and
119    /// which [`PathBuilder::rect`] would equally build, when every radius is
120    /// zero; an oval when every corner's radii are half the rect's sides.
121    fn of_round_rect(rect: Rect, radii: [[f32; 2]; 4]) -> Self {
122        let halves = [rect.width * 0.5, rect.height * 0.5];
123        if radii.iter().all(|corner| *corner == [0.0; 2]) {
124            BuiltShape::General
125        } else if radii.iter().all(|corner| *corner == halves) {
126            BuiltShape::Oval(rect)
127        } else {
128            BuiltShape::RoundRect { rect, radii }
129        }
130    }
131
132    /// `transformed` is what a path built as this shape is once `transform`
133    /// maps its points: the same kind of shape under a transform that keeps
134    /// rectangles rectangles, a general path under any other, as Skia's
135    /// `SkPathBuilder::transform` keeps `isOval` and `isRRect` only when the
136    /// matrix `rectStaysRect` (its other condition, points that only ever
137    /// move along one axis, holds for every oval and rounded rectangle a
138    /// builder traces).
139    fn transformed(self, transform: &Matrix) -> Self {
140        if !transform.rect_stays_rect() {
141            return BuiltShape::General;
142        }
143        match self {
144            BuiltShape::General => BuiltShape::General,
145            BuiltShape::Oval(rect) => BuiltShape::Oval(transform.map_rect(&rect)),
146            BuiltShape::RoundRect { rect, radii } => BuiltShape::of_round_rect(
147                transform.map_rect(&rect),
148                transformed_radii(&rect, radii, transform),
149            ),
150        }
151    }
152}
153
154/// `transformed_radii` is where the per-corner `radii` of a rounded
155/// rectangle over `rect` land under `transform`, which keeps rectangles
156/// rectangles: each corner goes to the corner of the mapped rectangle its
157/// point lands on, its radii scaled by the axis lengths, and swapped by a
158/// quarter turn, which carries each axis onto the other.
159fn transformed_radii(rect: &Rect, radii: [[f32; 2]; 4], transform: &Matrix) -> [[f32; 2]; 4] {
160    let [a, b, c, d, ..] = transform.to_affine();
161    let quarter_turn = a == 0.0 && d == 0.0;
162    let mapped = transform.map_rect(rect);
163    let centre = Point::new(
164        mapped.x + mapped.width * 0.5,
165        mapped.y + mapped.height * 0.5,
166    );
167    let corners = [
168        Point::new(rect.x, rect.y),
169        Point::new(rect.right(), rect.y),
170        Point::new(rect.right(), rect.bottom()),
171        Point::new(rect.x, rect.bottom()),
172    ];
173    let mut moved = [[0.0; 2]; 4];
174    for (corner, [x, y]) in corners.into_iter().zip(radii) {
175        let landed = transform.map_point(corner);
176        let index = match (landed.x < centre.x, landed.y < centre.y) {
177            (true, true) => 0,
178            (false, true) => 1,
179            (false, false) => 2,
180            (true, false) => 3,
181        };
182        moved[index] = if quarter_turn {
183            [y * c.abs(), x * b.abs()]
184        } else {
185            [x * a.abs(), y * d.abs()]
186        };
187    }
188    moved
189}
190
191impl Path {
192    /// `as_oval` is the rect the path's oval fills, when the path was built
193    /// as nothing but an oval: one [`PathBuilder::circle`], or a rounded
194    /// rectangle whose radii fill its rect, added to an empty builder, as
195    /// Skia's `SkPath::isOval` knows it by construction.
196    pub fn as_oval(&self) -> Option<Rect> {
197        match self.shape {
198            BuiltShape::Oval(rect) => Some(rect),
199            _ => None,
200        }
201    }
202
203    /// `as_round_rect` is the rect and the per-corner `[x, y]` radii,
204    /// clockwise from the top-left, of the rounded rectangle the path was
205    /// built as, when it was built as nothing but one, added to an empty
206    /// builder, as Skia's `SkPath::isRRect` knows it by construction. One
207    /// whose radii are all zero is a rectangle, and one whose radii fill its
208    /// rect an oval ([`Self::as_oval`]), as Skia simplifies them.
209    pub fn as_round_rect(&self) -> Option<(Rect, [[f32; 2]; 4])> {
210        match self.shape {
211            BuiltShape::RoundRect { rect, radii } => Some((rect, radii)),
212            _ => None,
213        }
214    }
215
216    /// `transformed` is this path with every point mapped by `transform`:
217    /// Skia's `SkPath::makeTransform`, which dart:ui's `Path.shift` and
218    /// `Path.transform` run.
219    ///
220    /// A path built as an oval or a rounded rectangle ([`Self::as_oval`],
221    /// [`Self::as_round_rect`]) stays one under a transform that keeps
222    /// rectangles rectangles — a translation, a scale, a mirror, a quarter
223    /// turn, or any of them together — and is a general path under any
224    /// other, as Skia keeps it. [`PathBuilder::append`] is Skia's `addPath`
225    /// instead, which makes a general path whatever it appends. Under
226    /// perspective the control points are mapped as `append` maps them.
227    pub fn transformed(&self, transform: &Matrix) -> Arc<Path> {
228        let points: Vec<Point> = self
229            .points
230            .iter()
231            .map(|point| transform.map_point(*point))
232            .collect();
233        Arc::new(Path {
234            verbs: self.verbs.clone(),
235            bounds: control_point_bounds(&points),
236            points,
237            weights: self.weights.clone(),
238            shape: self.shape.transformed(transform),
239        })
240    }
241
242    /// `elements` walks the path's verbs with their points, for a consumer that
243    /// serializes or re-encodes it rather than flattens it.
244    pub fn elements(&self) -> impl Iterator<Item = PathElement> + '_ {
245        let mut point = 0;
246        let mut weight = 0;
247        self.verbs.iter().map(move |verb| {
248            let element = match verb {
249                Verb::Move => PathElement::MoveTo(self.points[point]),
250                Verb::Line => PathElement::LineTo(self.points[point]),
251                Verb::Quad => PathElement::QuadTo(self.points[point], self.points[point + 1]),
252                Verb::Conic => {
253                    let element = PathElement::ConicTo(
254                        self.points[point],
255                        self.points[point + 1],
256                        self.weights[weight],
257                    );
258                    weight += 1;
259                    element
260                }
261                Verb::Cubic => PathElement::CubicTo(
262                    self.points[point],
263                    self.points[point + 1],
264                    self.points[point + 2],
265                ),
266                Verb::Close => PathElement::Close,
267            };
268            point += match verb {
269                Verb::Move | Verb::Line => 1,
270                Verb::Quad | Verb::Conic => 2,
271                Verb::Cubic => 3,
272                Verb::Close => 0,
273            };
274            element
275        })
276    }
277
278    /// `bounds` returns conservative control-point bounds.
279    pub fn bounds(&self) -> Rect {
280        self.bounds
281    }
282
283    /// `tight_bounds` returns exact axis-aligned curve bounds.
284    pub fn tight_bounds(&self) -> Rect {
285        let mut bounds = TightBounds::default();
286        let mut point_index = 0usize;
287        let mut weight_index = 0usize;
288        let mut cursor = Point::ZERO;
289        let mut contour_start = Point::ZERO;
290        for verb in &self.verbs {
291            match verb {
292                Verb::Move => {
293                    cursor = self.points[point_index];
294                    contour_start = cursor;
295                    point_index += 1;
296                    bounds.include(cursor);
297                }
298                Verb::Line => {
299                    cursor = self.points[point_index];
300                    point_index += 1;
301                    bounds.include(cursor);
302                }
303                Verb::Quad => {
304                    let control = self.points[point_index];
305                    let end = self.points[point_index + 1];
306                    point_index += 2;
307                    include_quadratic_extrema(&mut bounds, cursor, control, end);
308                    cursor = end;
309                }
310                Verb::Conic => {
311                    let control = self.points[point_index];
312                    let end = self.points[point_index + 1];
313                    let weight = self.weights[weight_index];
314                    point_index += 2;
315                    weight_index += 1;
316                    include_conic_extrema(&mut bounds, cursor, control, end, weight);
317                    cursor = end;
318                }
319                Verb::Cubic => {
320                    let first = self.points[point_index];
321                    let second = self.points[point_index + 1];
322                    let end = self.points[point_index + 2];
323                    point_index += 3;
324                    include_cubic_extrema(&mut bounds, cursor, first, second, end);
325                    cursor = end;
326                }
327                Verb::Close => {
328                    cursor = contour_start;
329                    bounds.include(cursor);
330                }
331            }
332        }
333        bounds.rect()
334    }
335
336    /// `is_empty` reports whether the path contains no commands.
337    pub fn is_empty(&self) -> bool {
338        self.verbs.is_empty()
339    }
340
341    /// `heap_bytes` returns an estimate of owned path storage.
342    pub fn heap_bytes(&self) -> usize {
343        self.points.len() * std::mem::size_of::<Point>()
344            + self.weights.len() * std::mem::size_of::<f32>()
345            + self.verbs.len()
346    }
347
348    /// `contains` reports whether a point lies inside the filled path.
349    ///
350    /// The query evaluates the original curves, implicitly closes open contours,
351    /// and treats points on the outline as inside.
352    pub fn contains(&self, point: Point, fill_rule: FillRule) -> bool {
353        if !self.bounds.contains_inclusive(point) {
354            return false;
355        }
356        let crossings = self.walk_crossings(point);
357        match fill_rule {
358            FillRule::NonZero => crossings.is_inside_non_zero(),
359            FillRule::EvenOdd => crossings.is_inside_even_odd(),
360        }
361    }
362
363    /// Ray-cast the whole path, one segment at a time.
364    fn walk_crossings(&self, point: Point) -> crate::winding::Crossings {
365        let mut crossings = crate::winding::Crossings::default();
366        let mut index = 0usize;
367        let mut weight_index = 0usize;
368        let mut cursor = Point::ZERO;
369        let mut contour_start = Point::ZERO;
370        let mut contour_open = false;
371        for verb in &self.verbs {
372            match verb {
373                Verb::Move => {
374                    // A new contour closes the previous one: fills always see
375                    // that last→first edge, whether or not Close was recorded.
376                    if contour_open {
377                        crossings.line(cursor, contour_start, point);
378                    }
379                    contour_open = true;
380                    contour_start = self.points[index];
381                    cursor = contour_start;
382                    index += 1;
383                }
384                Verb::Line => {
385                    crossings.line(cursor, self.points[index], point);
386                    cursor = self.points[index];
387                    index += 1;
388                }
389                Verb::Quad => {
390                    crossings.quad(cursor, self.points[index], self.points[index + 1], point);
391                    cursor = self.points[index + 1];
392                    index += 2;
393                }
394                Verb::Conic => {
395                    crossings.conic(
396                        cursor,
397                        self.points[index],
398                        self.points[index + 1],
399                        self.weights[weight_index],
400                        point,
401                    );
402                    cursor = self.points[index + 1];
403                    index += 2;
404                    weight_index += 1;
405                }
406                Verb::Cubic => {
407                    crossings.cubic(
408                        cursor,
409                        self.points[index],
410                        self.points[index + 1],
411                        self.points[index + 2],
412                        point,
413                    );
414                    cursor = self.points[index + 2];
415                    index += 3;
416                }
417                Verb::Close => {
418                    crossings.line(cursor, contour_start, point);
419                    cursor = contour_start;
420                    contour_open = false;
421                }
422            }
423        }
424        if contour_open {
425            crossings.line(cursor, contour_start, point);
426        }
427        crossings
428    }
429
430    /// `measure` returns an arc-length measurement for each nonempty contour.
431    ///
432    /// `tolerance` is the maximum flattening deviation in path coordinates.
433    pub fn measure(&self, tolerance: f32) -> Vec<crate::ContourMeasure> {
434        self.flatten(tolerance)
435            .iter()
436            .filter_map(crate::ContourMeasure::of)
437            .collect()
438    }
439
440    /// `flatten` approximates curves with polygonal contours.
441    ///
442    /// `tolerance` is the maximum deviation in path coordinates. Fill
443    /// operations implicitly close every contour; stroke operations use
444    /// [`Contour::closed`].
445    pub fn flatten(&self, tolerance: f32) -> Vec<Contour> {
446        let mut out = Flattener::new(tolerance.max(1e-4));
447        let mut i = 0usize;
448        let mut weight_index = 0usize;
449        for verb in &self.verbs {
450            match verb {
451                Verb::Move => {
452                    out.move_to(self.points[i]);
453                    i += 1;
454                }
455                Verb::Line => {
456                    out.line_to(self.points[i]);
457                    i += 1;
458                }
459                Verb::Quad => {
460                    out.quad_to(self.points[i], self.points[i + 1]);
461                    i += 2;
462                }
463                Verb::Conic => {
464                    out.conic_to(
465                        self.points[i],
466                        self.points[i + 1],
467                        self.weights[weight_index],
468                    );
469                    i += 2;
470                    weight_index += 1;
471                }
472                Verb::Cubic => {
473                    out.cubic_to(self.points[i], self.points[i + 1], self.points[i + 2]);
474                    i += 3;
475                }
476                Verb::Close => out.close(),
477            }
478        }
479        out.finish()
480    }
481}
482
483#[derive(Default)]
484struct TightBounds(Option<(f32, f32, f32, f32)>);
485
486impl TightBounds {
487    fn include(&mut self, point: Point) {
488        self.0 = Some(match self.0 {
489            Some((left, top, right, bottom)) => (
490                left.min(point.x),
491                top.min(point.y),
492                right.max(point.x),
493                bottom.max(point.y),
494            ),
495            None => (point.x, point.y, point.x, point.y),
496        });
497    }
498
499    fn rect(self) -> Rect {
500        self.0
501            .map_or_else(Rect::default, |(left, top, right, bottom)| {
502                Rect::from_ltrb(left, top, right, bottom)
503            })
504    }
505}
506
507fn include_quadratic_extrema(bounds: &mut TightBounds, start: Point, control: Point, end: Point) {
508    bounds.include(start);
509    bounds.include(end);
510    for (start_axis, control_axis, end_axis) in
511        [(start.x, control.x, end.x), (start.y, control.y, end.y)]
512    {
513        let denominator = start_axis as f64 - 2.0 * control_axis as f64 + end_axis as f64;
514        if denominator == 0.0 {
515            continue;
516        }
517        let parameter = ((start_axis as f64 - control_axis as f64) / denominator) as f32;
518        if parameter > 0.0 && parameter < 1.0 {
519            bounds.include(eval_quad(start, control, end, parameter));
520        }
521    }
522}
523
524fn include_cubic_extrema(
525    bounds: &mut TightBounds,
526    start: Point,
527    first: Point,
528    second: Point,
529    end: Point,
530) {
531    bounds.include(start);
532    bounds.include(end);
533    for (start_axis, first_axis, second_axis, end_axis) in [
534        (start.x, first.x, second.x, end.x),
535        (start.y, first.y, second.y, end.y),
536    ] {
537        for parameter in cubic_extrema(start_axis, first_axis, second_axis, end_axis)
538            .into_iter()
539            .flatten()
540        {
541            if parameter > 0.0 && parameter < 1.0 {
542                bounds.include(eval_cubic(start, first, second, end, parameter));
543            }
544        }
545    }
546}
547
548fn include_conic_extrema(
549    bounds: &mut TightBounds,
550    start: Point,
551    control: Point,
552    end: Point,
553    weight: f32,
554) {
555    bounds.include(start);
556    bounds.include(end);
557    for (start_axis, control_axis, end_axis) in
558        [(start.x, control.x, end.x), (start.y, control.y, end.y)]
559    {
560        for parameter in conic_derivative_roots(start_axis, control_axis, end_axis, weight) {
561            let p = eval_conic(start, control, end, weight, parameter);
562            // A positive-weight conic never leaves its control hull; a root
563            // that lands a float ulp inside an endpoint must not let eval
564            // noise widen the bounds past it.
565            let clamp = |v: f32, a: f32, b: f32, c: f32| v.clamp(a.min(b).min(c), a.max(b).max(c));
566            bounds.include(Point::new(
567                clamp(p.x, start.x, control.x, end.x),
568                clamp(p.y, start.y, control.y, end.y),
569            ));
570        }
571    }
572}
573
574/// Parameters in (0, 1) where one coordinate of the conic turns around.
575///
576/// With numerator `N(t) = At² + Bt + C` and denominator `D(t) = at² − at + 1`
577/// (`a = 2 − 2w`), the extremum condition `N′D − ND′ = 0` collapses — the
578/// cubic terms cancel — to the quadratic `−a(A+B)t² + 2(A − aC)t + (B + aC)`.
579pub(crate) fn conic_derivative_roots(
580    start: f32,
581    control: f32,
582    end: f32,
583    weight: f32,
584) -> impl Iterator<Item = f32> {
585    // In point DIFFERENCES, Skia's `conic_find_extrema` form: substituting
586    // p10 = control − start and p20 = end − start collapses the quadratic
587    // above (divided by 2) to the coefficients below. The absolute-coordinate
588    // form subtracts near-equal products and loses every significant digit
589    // for curves far from the origin; the difference form does not, and f64
590    // covers what remains.
591    let w = weight as f64;
592    let p10 = control as f64 - start as f64;
593    let p20 = end as f64 - start as f64;
594    let quadratic = (w - 1.0) * p20;
595    let linear = p20 - 2.0 * w * p10;
596    let constant = w * p10;
597
598    let mut roots = [None, None];
599    if quadratic == 0.0 {
600        roots[0] = unit_root(-constant, linear);
601    } else {
602        let discriminant = linear * linear - 4.0 * quadratic * constant;
603        if discriminant >= 0.0 && discriminant.is_finite() {
604            // The same stable pairing as `cubic_extrema`: never subtract two
605            // near-equal numbers.
606            let root = discriminant.sqrt();
607            let q = -0.5 * (linear + root.copysign(linear));
608            roots[0] = unit_root(q, quadratic);
609            roots[1] = unit_root(constant, q).filter(|value| roots[0] != Some(*value));
610        }
611    }
612    roots.into_iter().flatten()
613}
614
615/// The conic (rational quadratic) point at `t`.
616pub(crate) fn eval_conic(start: Point, control: Point, end: Point, weight: f32, t: f32) -> Point {
617    let u = 1.0 - t;
618    let b0 = u * u;
619    let b1 = 2.0 * weight * u * t;
620    let b2 = t * t;
621    let d = b0 + b1 + b2;
622    Point::new(
623        (b0 * start.x + b1 * control.x + b2 * end.x) / d,
624        (b0 * start.y + b1 * control.y + b2 * end.y) / d,
625    )
626}
627
628fn cubic_extrema(start: f32, first: f32, second: f32, end: f32) -> [Option<f32>; 2] {
629    let start = start as f64;
630    let first = first as f64;
631    let second = second as f64;
632    let end = end as f64;
633    let quadratic = -start + 3.0 * first - 3.0 * second + end;
634    let linear = 2.0 * (start - 2.0 * first + second);
635    let constant = first - start;
636    if quadratic == 0.0 {
637        return [unit_root(-constant, linear), None];
638    }
639    let discriminant = linear * linear - 4.0 * quadratic * constant;
640    if discriminant < 0.0 || !discriminant.is_finite() {
641        return [None, None];
642    }
643
644    // Numerical Recipes / Skia: Q/A and C/Q avoid the cancellation in the
645    // ordinary (-B ± sqrt(D)) / 2A formula when one root is much smaller.
646    let root = discriminant.sqrt();
647    let q = -0.5 * (linear + root.copysign(linear));
648    let first_root = unit_root(q, quadratic);
649    let second_root = unit_root(constant, q).filter(|value| Some(*value) != first_root);
650    [first_root, second_root]
651}
652
653fn unit_root(numerator: f64, denominator: f64) -> Option<f32> {
654    if denominator == 0.0 {
655        return None;
656    }
657    let value = numerator / denominator;
658    (value.is_finite() && value > 0.0 && value < 1.0).then_some(value as f32)
659}
660
661/// `PathBuilder` records commands used to create an immutable [`Path`].
662#[derive(Clone, Default)]
663pub struct PathBuilder {
664    verbs: Vec<Verb>,
665    points: Vec<Point>,
666    weights: Vec<f32>,
667    bounds: Option<Rect>,
668    /// Where a segment recorded after a `close` resumes.
669    ///
670    /// It OUTLIVES the close — that is the whole point. Without it
671    /// `M10,10 L30,10 Z L30,30` loses its diagonal, because the line would
672    /// start at its own destination. Skia does the same in `ensureMove`
673    /// (`moveTo(fPts[fLastMoveIndex])` when the last verb was a close), and
674    /// Impeller inherits it by building on `SkPathBuilder`.
675    ///
676    /// NOT always the contour's origin, which is why it is not called that.
677    /// For `close` it is. For `rect` and `roundRect` WHATWG names the point
678    /// separately — "create a new subpath with the point (x, y)" — and for a
679    /// rounded rectangle `(x, y)` is a bounding-box corner the outline never
680    /// touches, since the walk begins at the top-left tangent. The two
681    /// coincide only at radius zero.
682    resume_point: Option<Point>,
683    contour_open: bool,
684    /// What the path is built as so far; any point added resets it to
685    /// `General`, and only the oval and rounded-rect helpers set it, after
686    /// their own points, on a builder that had no segment before them.
687    shape: BuiltShape,
688}
689
690impl PathBuilder {
691    /// `new` creates an empty path builder.
692    pub fn new() -> Self {
693        Self::default()
694    }
695
696    /// `move_to` starts a new contour at `p`.
697    pub fn move_to(&mut self, p: impl Into<Point>) -> &mut Self {
698        let p = p.into();
699        self.verbs.push(Verb::Move);
700        self.push_point(p);
701        self.resume_point = Some(p);
702        self.contour_open = true;
703        self
704    }
705
706    /// `line_to` adds a straight segment to `p`.
707    pub fn line_to(&mut self, p: impl Into<Point>) -> &mut Self {
708        let p = p.into();
709        self.ensure_contour(p);
710        self.verbs.push(Verb::Line);
711        self.push_point(p);
712        self
713    }
714
715    /// `quad_to` adds a quadratic Bézier through control point `c` to `p`.
716    pub fn quad_to(&mut self, c: impl Into<Point>, p: impl Into<Point>) -> &mut Self {
717        let (c, p) = (c.into(), p.into());
718        self.ensure_contour(c);
719        self.verbs.push(Verb::Quad);
720        self.push_point(c);
721        self.push_point(p);
722        self
723    }
724
725    /// `conic_to` adds a rational quadratic (a conic) through control point
726    /// `c` to `p`.
727    ///
728    /// A weight of 1 is an ordinary quadratic; `cos(θ/2)` traces a circular
729    /// arc of sweep `θ` exactly, which is what the arc and rounded-rect
730    /// helpers rely on. Stored weights are restricted to positive finite
731    /// values so every curve stays inside its control hull — the invariant
732    /// the record-time bounds rely on. Everything else lowers: a nonpositive
733    /// weight draws a line, a non-finite weight the control polygon (the
734    /// curve's limit as the weight grows). Skia, by contrast, records
735    /// negative weights as-is; nothing in valo's builders or Canvas2D
736    /// produces one.
737    pub fn conic_to(&mut self, c: impl Into<Point>, p: impl Into<Point>, weight: f32) -> &mut Self {
738        let (c, p) = (c.into(), p.into());
739        if !weight.is_finite() {
740            return self.line_to(c).line_to(p);
741        }
742        if weight <= 0.0 {
743            return self.line_to(p);
744        }
745        if weight == 1.0 {
746            return self.quad_to(c, p);
747        }
748        self.ensure_contour(c);
749        self.verbs.push(Verb::Conic);
750        self.push_point(c);
751        self.push_point(p);
752        self.weights.push(weight);
753        self
754    }
755
756    /// `cubic_to` adds a cubic Bézier through two control points to `p`.
757    pub fn cubic_to(
758        &mut self,
759        c1: impl Into<Point>,
760        c2: impl Into<Point>,
761        p: impl Into<Point>,
762    ) -> &mut Self {
763        let (c1, c2, p) = (c1.into(), c2.into(), p.into());
764        self.ensure_contour(c1);
765        self.verbs.push(Verb::Cubic);
766        self.push_point(c1);
767        self.push_point(c2);
768        self.push_point(p);
769        self
770    }
771
772    /// `close` adds a segment back to the current contour's starting point.
773    ///
774    /// It has no effect when no contour is open.
775    pub fn close(&mut self) -> &mut Self {
776        if self.contour_open {
777            self.verbs.push(Verb::Close);
778            self.contour_open = false;
779        }
780        self
781    }
782
783    // ── shape helpers (the common vocabulary) ──────────────────────────────
784
785    /// `rect` adds a closed rectangular contour.
786    pub fn rect(&mut self, r: Rect) -> &mut Self {
787        self.move_to((r.x, r.y))
788            .line_to((r.right(), r.y))
789            .line_to((r.right(), r.bottom()))
790            .line_to((r.x, r.bottom()))
791            .close();
792        // WHATWG's separate closing step: "create a new subpath with the
793        // point (x, y)". Stated here rather than inherited from the traversal
794        // above, so reordering the walk cannot move it.
795        self.resume_point = Some(Point::new(r.x, r.y));
796        self
797    }
798
799    /// `rrect` adds a closed rounded rectangle with one corner radius.
800    pub fn rrect(&mut self, r: Rect, radius: f32) -> &mut Self {
801        self.rrect_radii(r, [radius; 4])
802    }
803
804    /// `rrect_radii` adds a rounded rectangle with circular corner radii.
805    ///
806    /// `radii` is ordered clockwise from the top-left.
807    pub fn rrect_radii(&mut self, r: Rect, radii: [f32; 4]) -> &mut Self {
808        self.rrect_radii_elliptical(r, radii.map(|radius| [radius; 2]))
809    }
810
811    /// `rrect_radii_elliptical` adds per-corner elliptical radii.
812    ///
813    /// Each corner is `[x_radius, y_radius]`, starting at the top-left. Radii
814    /// are proportionally reduced when adjacent corners would overlap.
815    pub fn rrect_radii_elliptical(
816        &mut self,
817        r: impl Into<Rect>,
818        radii: [[f32; 2]; 4],
819    ) -> &mut Self {
820        self.rrect_radii_elliptical_wound(r, radii, Winding::Clockwise)
821    }
822
823    /// `rrect_radii_elliptical_wound` adds a rounded rectangle with explicit winding.
824    ///
825    /// Opposing contours cancel under [`FillRule::NonZero`], and dashing follows
826    /// this traversal order.
827    pub fn rrect_radii_elliptical_wound(
828        &mut self,
829        r: impl Into<Rect>,
830        radii: [[f32; 2]; 4],
831        winding: Winding,
832    ) -> &mut Self {
833        let r = r.into();
834        let [tl, tr, br, bl] = constrain_radii_elliptical(&r, radii);
835        let built_alone = self.has_no_segment();
836        self.trace_rrect(r, [tl, tr, br, bl], winding);
837        if built_alone {
838            self.shape = BuiltShape::of_round_rect(r, [tl, tr, br, bl]);
839        }
840        self
841    }
842
843    /// `trace_rrect` adds the outline of the rounded rectangle `r` with
844    /// constrained `radii`, wound by `winding`.
845    fn trace_rrect(&mut self, r: Rect, radii: [[f32; 2]; 4], winding: Winding) {
846        let [tl, tr, br, bl] = radii;
847        let (l, t, rr, b) = (r.x, r.y, r.right(), r.bottom());
848        if [tl, tr, br, bl].iter().all(|[x, y]| *x == 0.0 && *y == 0.0) {
849            match winding {
850                Winding::Clockwise => self.rect(r),
851                Winding::CounterClockwise => self
852                    .move_to((l, t))
853                    .line_to((l, b))
854                    .line_to((rr, b))
855                    .line_to((rr, t))
856                    .close(),
857            };
858            self.resume_point = Some(Point::new(l, t));
859            return;
860        }
861        // Each corner is one conic: a quarter ELLIPSE, exactly — the control
862        // point is the box corner and the weight is cos(45°). Impeller's
863        // rounded rect uses the identical construction (`round_rect.cc`).
864        let w = std::f32::consts::FRAC_1_SQRT_2;
865        match winding {
866            Winding::Clockwise => self
867                .move_to((l + tl[0], t))
868                .line_to((rr - tr[0], t))
869                .conic_to((rr, t), (rr, t + tr[1]), w)
870                .line_to((rr, b - br[1]))
871                .conic_to((rr, b), (rr - br[0], b), w)
872                .line_to((l + bl[0], b))
873                .conic_to((l, b), (l, b - bl[1]), w)
874                .line_to((l, t + tl[1]))
875                .conic_to((l, t), (l + tl[0], t), w)
876                .close(),
877            // The same anchors in reverse around the same control points —
878            // so the two directions are the identical outline and differ
879            // only in traversal.
880            Winding::CounterClockwise => self
881                .move_to((l + tl[0], t))
882                .conic_to((l, t), (l, t + tl[1]), w)
883                .line_to((l, b - bl[1]))
884                .conic_to((l, b), (l + bl[0], b), w)
885                .line_to((rr - br[0], b))
886                .conic_to((rr, b), (rr, b - br[1]), w)
887                .line_to((rr, t + tr[1]))
888                .conic_to((rr, t), (rr - tr[0], t), w)
889                .line_to((l + tl[0], t))
890                .close(),
891        };
892        // WHATWG step 14, SEPARATE from the outline that step 12 walks:
893        // "create a new subpath with the point (x, y)". For a rounded
894        // rectangle that corner is not on the outline at all — the walk
895        // begins at the top-left tangent — so this cannot be inherited from
896        // the traversal the way `close`'s resumption point is. Blink does the
897        // same explicitly, chaining `.MoveTo(x, y)` after its rounded-rect
898        // builder (`canvas_path.cc`).
899        //
900        // Verified against the spec text and current Blink source rather than
901        // by probing a browser. This corner of Canvas2D has already produced
902        // two places where the prose and every implementation disagree, so
903        // that distinction is worth keeping in view.
904        self.resume_point = Some(Point::new(l, t));
905    }
906
907    /// `rsuperellipse` adds a rounded superellipse with one corner radius.
908    ///
909    /// The corner profile is the iOS "squircle": circular near the diagonal,
910    /// blending into the straight edges along a superellipse instead of
911    /// meeting them abruptly the way a circular [`Self::rrect`] corner does.
912    pub fn rsuperellipse(&mut self, r: Rect, radius: f32) -> &mut Self {
913        self.rsuperellipse_radii(r, [[radius; 2]; 4])
914    }
915
916    /// `rsuperellipse_radii` adds a rounded superellipse with per-corner
917    /// elliptical radii.
918    ///
919    /// Each corner is `[x_radius, y_radius]`, clockwise from the top-left.
920    /// Radii are proportionally reduced when adjacent corners would overlap.
921    pub fn rsuperellipse_radii(&mut self, r: Rect, radii: [[f32; 2]; 4]) -> &mut Self {
922        crate::superellipse::RoundSuperellipse::new(r, radii).emit(self);
923        self.resume_point = Some(Point::new(r.x, r.y));
924        self
925    }
926
927    /// `arc` adds a circular arc.
928    ///
929    /// Angles are radians clockwise from +x in Valo's y-down coordinates.
930    /// Sweeps are limited to one full turn.
931    pub fn arc(
932        &mut self,
933        center: impl Into<Point>,
934        radius: f32,
935        start_angle: f32,
936        sweep_angle: f32,
937    ) -> &mut Self {
938        self.ellipse(center, [radius; 2], 0.0, start_angle, sweep_angle)
939    }
940
941    /// `ellipse` adds an elliptical arc.
942    ///
943    /// `radii` are the x and y half-extents, `x_axis_rotation` turns the
944    /// ellipse, and angles are radians clockwise from +x. An active contour is
945    /// connected to the arc's first point. Sweeps are limited to one full turn.
946    ///
947    /// Non-finite input is ignored. Negative radii trigger a debug assertion
948    /// and are ignored in release builds.
949    pub fn ellipse(
950        &mut self,
951        center: impl Into<Point>,
952        radii: [f32; 2],
953        x_axis_rotation: f32,
954        start_angle: f32,
955        sweep_angle: f32,
956    ) -> &mut Self {
957        let center = center.into();
958        let [radius_x, radius_y] = radii;
959        // Every input, not just the radii: a NaN centre flows into NaN points,
960        // and `f32::min`/`max` drop those from the bounds accumulator without
961        // complaint — an under-reported box silently breaks culling and
962        // hit-testing later.
963        let finite = center.x.is_finite()
964            && center.y.is_finite()
965            && radius_x.is_finite()
966            && radius_y.is_finite()
967            && x_axis_rotation.is_finite()
968            && start_angle.is_finite()
969            && sweep_angle.is_finite();
970        debug_assert!(
971            radius_x >= 0.0 && radius_y >= 0.0,
972            "negative radii draw nothing; Canvas2D throws here"
973        );
974        if !finite || radius_x < 0.0 || radius_y < 0.0 {
975            return self;
976        }
977
978        // Canvas2D stops at one full turn, and Skia routes full sweeps to an
979        // oval. Without this, `sweep = 1e20` passes the finite check above and
980        // asks for ~1e19 cubic pieces — an allocation the process does not
981        // survive, reachable by any embedder forwarding user input.
982        let full_turn = std::f32::consts::TAU;
983        let sweep_angle = sweep_angle.clamp(-full_turn, full_turn);
984
985        let unit_circle_to_ellipse = unit_circle_map(center, radii, x_axis_rotation);
986        let first = unit_circle_to_ellipse.map_point(unit_circle_point(start_angle));
987        // Canvas2D runs a straight line in to the arc's start when a contour
988        // is live. A CLOSED contour still counts as live for this: it resumes
989        // at its origin and then runs the line, so an arc after `closePath`
990        // stays connected to the seam. Only a path with no contour at all
991        // starts at the arc.
992        if self.contour_open || self.resume_point.is_some() {
993            self.ensure_contour(first);
994            self.line_to(first);
995        } else {
996            self.move_to(first);
997        }
998        if sweep_angle != 0.0 {
999            self.push_arc_conics(&unit_circle_to_ellipse, start_angle, sweep_angle);
1000        }
1001        // A whole turn ends where it began: close it, so the stroker joins the
1002        // seam instead of capping it (Skia's full sweeps produce a closed oval).
1003        if sweep_angle.abs() >= full_turn {
1004            self.close();
1005        }
1006        self
1007    }
1008
1009    /// `arc_to` rounds the corner between the current point, `corner`, and `next`.
1010    ///
1011    /// Zero or negative radius, coincident points, and straight-through corners
1012    /// fall back to a line ending at `corner`.
1013    pub fn arc_to(
1014        &mut self,
1015        corner: impl Into<Point>,
1016        next: impl Into<Point>,
1017        radius: f32,
1018    ) -> &mut Self {
1019        let (corner, next) = (corner.into(), next.into());
1020        self.ensure_contour(corner);
1021        let start = *self.points.last().expect("ensure_contour opened a contour");
1022
1023        // Skia's construction, in f64: the tangent length follows from the
1024        // half-angle at the corner, and the centre sits one radius along the
1025        // inward normal of the incoming edge.
1026        let incoming = normalize(
1027            corner.x as f64 - start.x as f64,
1028            corner.y as f64 - start.y as f64,
1029        );
1030        let outgoing = normalize(
1031            next.x as f64 - corner.x as f64,
1032            next.y as f64 - corner.y as f64,
1033        );
1034        let (Some(incoming), Some(outgoing)) = (incoming, outgoing) else {
1035            return self.line_to(corner);
1036        };
1037        let cosine = incoming.0 * outgoing.0 + incoming.1 * outgoing.1;
1038        let sine = incoming.0 * outgoing.1 - incoming.1 * outgoing.0;
1039        if radius <= 0.0 || !radius.is_finite() || sine.abs() < 1.0 / (1 << 12) as f64 {
1040            return self.line_to(corner);
1041        }
1042
1043        let tangent_length = (radius as f64 * (1.0 - cosine) / sine).abs();
1044        let entry = Point::new(
1045            corner.x - (tangent_length * incoming.0) as f32,
1046            corner.y - (tangent_length * incoming.1) as f32,
1047        );
1048        // The turn's sign puts the centre on the side the arc bends toward.
1049        let turn = sine.signum() as f32;
1050        let center = Point::new(
1051            entry.x + radius * turn * -(incoming.1 as f32),
1052            entry.y + radius * turn * incoming.0 as f32,
1053        );
1054        let exit = Point::new(
1055            corner.x + (tangent_length * outgoing.0) as f32,
1056            corner.y + (tangent_length * outgoing.1) as f32,
1057        );
1058
1059        let start_angle = (entry.y - center.y).atan2(entry.x - center.x);
1060        let end_angle = (exit.y - center.y).atan2(exit.x - center.x);
1061        let sweep = shortest_sweep(start_angle, end_angle, turn);
1062
1063        self.line_to(entry);
1064        let map = unit_circle_map(center, [radius; 2], 0.0);
1065        self.push_arc_conics(&map, start_angle, sweep);
1066        self
1067    }
1068
1069    /// `circle` adds a closed circular contour.
1070    ///
1071    /// Four conic quarters trace the circle exactly; the control points are
1072    /// the bounding box's corners.
1073    pub fn circle(&mut self, center: impl Into<Point>, radius: f32) -> &mut Self {
1074        let c = center.into();
1075        let r = radius;
1076        let w = std::f32::consts::FRAC_1_SQRT_2;
1077        let built_alone = self.has_no_segment();
1078        self.move_to((c.x + r, c.y))
1079            .conic_to((c.x + r, c.y + r), (c.x, c.y + r), w)
1080            .conic_to((c.x - r, c.y + r), (c.x - r, c.y), w)
1081            .conic_to((c.x - r, c.y - r), (c.x, c.y - r), w)
1082            .conic_to((c.x + r, c.y - r), (c.x + r, c.y), w)
1083            .close();
1084        if built_alone && r > 0.0 {
1085            self.shape = BuiltShape::Oval(Rect::new(c.x - r, c.y - r, 2.0 * r, 2.0 * r));
1086        }
1087        self
1088    }
1089
1090    /// `append` adds a transformed copy of another path.
1091    ///
1092    /// The appended path's final contour becomes the current contour for
1093    /// subsequent commands.
1094    pub fn append(&mut self, path: &Path, transform: &Matrix) -> &mut Self {
1095        if path.verbs.is_empty() {
1096            // Appending nothing must change nothing — in particular it must
1097            // not close this builder's open contour.
1098            return self;
1099        }
1100        let mut point = path.points.iter();
1101        let mut weight = path.weights.iter();
1102        let mut cursor = Point::ZERO;
1103        let mut contour_start = Point::ZERO;
1104        for verb in &path.verbs {
1105            let count = match verb {
1106                Verb::Move | Verb::Line => 1,
1107                Verb::Quad | Verb::Conic => 2,
1108                Verb::Cubic => 3,
1109                Verb::Close => 0,
1110            };
1111            self.verbs.push(*verb);
1112            for _ in 0..count {
1113                let Some(&p) = point.next() else {
1114                    return self;
1115                };
1116                cursor = transform.map_point(p);
1117                self.push_point(cursor);
1118            }
1119            if matches!(verb, Verb::Conic) {
1120                // Weights survive affine transforms unchanged. (A projective
1121                // transform would need to reweigh them — but it would also
1122                // need more than control-point mapping for quads and cubics,
1123                // so every verb shares that limitation.)
1124                let Some(&w) = weight.next() else {
1125                    return self;
1126                };
1127                self.weights.push(w);
1128            }
1129            match verb {
1130                Verb::Move => contour_start = cursor,
1131                Verb::Close => cursor = contour_start,
1132                _ => {}
1133            }
1134        }
1135        // WHATWG's `Path2D.addPath` ends by "creating a new subpath with the
1136        // last point in path", which is what lets a following `line_to`
1137        // continue from where the source stopped. A source ending mid-contour
1138        // already leaves this builder there; one ending in `close` does not,
1139        // and without the reopen the next segment would start at its own
1140        // endpoint and the connecting edge would vanish.
1141        //
1142        // The reopen leaves a lone-point contour when nothing follows. That
1143        // costs no pixels here: it sits exactly on the closed contour's seam,
1144        // which the fill and the stroke's join already cover.
1145        if matches!(path.verbs.last(), Some(Verb::Close)) {
1146            self.move_to(cursor);
1147        } else {
1148            // The appended contour is this builder's contour now, origin and
1149            // all — leaving the receiver's own origin in place would send a
1150            // later `close` + segment back to the wrong seam.
1151            self.resume_point = Some(contour_start);
1152            self.contour_open = true;
1153        }
1154        self
1155    }
1156
1157    /// `build` consumes the builder and returns a shared immutable path.
1158    pub fn build(self) -> Arc<Path> {
1159        Arc::new(Path {
1160            verbs: self.verbs,
1161            points: self.points,
1162            weights: self.weights,
1163            bounds: self.bounds.unwrap_or_default(),
1164            shape: self.shape,
1165        })
1166    }
1167
1168    // ── internals ──────────────────────────────────────────────────────────
1169
1170    /// `push_arc_conics` traces an arc with conic pieces of at most 90°.
1171    ///
1172    /// Each piece is exact: a conic of weight `cos(θ/2)` whose control point
1173    /// sits where the endpoint tangents meet IS the circular arc of sweep
1174    /// `θ`. The current point must already be at the arc's start.
1175    fn push_arc_conics(&mut self, map: &Matrix, start_angle: f32, sweep_angle: f32) {
1176        let piece_count = (sweep_angle.abs() / std::f32::consts::FRAC_PI_2)
1177            .ceil()
1178            .max(1.0);
1179        let step = sweep_angle / piece_count;
1180        let weight = (step / 2.0).cos();
1181
1182        let mut angle = start_angle;
1183        for _ in 0..piece_count as u32 {
1184            let mid = unit_circle_point(angle + step / 2.0);
1185            let control = Point::new(mid.x / weight, mid.y / weight);
1186            let to = unit_circle_point(angle + step);
1187            self.conic_to(map.map_point(control), map.map_point(to), weight);
1188            angle += step;
1189        }
1190    }
1191
1192    /// `ensure_contour` guarantees an open contour before recording a segment.
1193    ///
1194    /// After a `close` the path resumes at the CLOSED contour's origin — the
1195    /// spec's "new subpath with the last point", and Skia's `ensureMove`.
1196    /// Resuming at the incoming point instead silently deletes the segment
1197    /// from the seam, which is the whole bug this exists to prevent.
1198    ///
1199    /// A path that never had a contour starts at the incoming point: Skia's
1200    /// implicit `moveTo(0, 0)` there is a footgun valo does not copy.
1201    fn ensure_contour(&mut self, p: Point) {
1202        if self.contour_open {
1203            return;
1204        }
1205        self.move_to(self.resume_point.unwrap_or(p));
1206    }
1207
1208    /// `has_no_segment` reports whether nothing but moves has been added, as
1209    /// Skia's builder asks before it marks a path an oval or a rounded rect.
1210    fn has_no_segment(&self) -> bool {
1211        self.verbs.iter().all(|verb| matches!(verb, Verb::Move))
1212    }
1213
1214    fn push_point(&mut self, p: Point) {
1215        self.shape = BuiltShape::General;
1216        self.points.push(p);
1217        self.bounds = Some(grown_bounds(self.bounds, p));
1218    }
1219}
1220
1221/// `grown_bounds` is `bounds` grown to hold `p`, or the point itself when
1222/// there are none yet. Plain min/max accumulation — a zero-size seed rect is
1223/// a valid bound, wherever it sits (a rect-union "empty = identity" rule
1224/// would drop a first point at the origin).
1225fn grown_bounds(bounds: Option<Rect>, p: Point) -> Rect {
1226    match bounds {
1227        Some(b) => Rect::from_ltrb(
1228            b.x.min(p.x),
1229            b.y.min(p.y),
1230            b.right().max(p.x),
1231            b.bottom().max(p.y),
1232        ),
1233        None => Rect::new(p.x, p.y, 0.0, 0.0),
1234    }
1235}
1236
1237/// `control_point_bounds` is the bounds of `points`, as a builder
1238/// accumulates them; the default rect when there are none.
1239fn control_point_bounds(points: &[Point]) -> Rect {
1240    points
1241        .iter()
1242        .fold(None, |bounds, point| Some(grown_bounds(bounds, *point)))
1243        .unwrap_or_default()
1244}
1245
1246/// `unit_circle_point` returns the point at `angle` on the unit circle.
1247fn unit_circle_point(angle: f32) -> Point {
1248    let (sine, cosine) = angle.sin_cos();
1249    Point::new(cosine, sine)
1250}
1251
1252/// `unit_circle_map` creates the transform from a unit circle to an ellipse.
1253fn unit_circle_map(center: Point, radii: [f32; 2], rotation: f32) -> Matrix {
1254    let [radius_x, radius_y] = radii;
1255    let (sine, cosine) = rotation.sin_cos();
1256    Matrix::from_affine(
1257        radius_x * cosine,
1258        radius_x * sine,
1259        -radius_y * sine,
1260        radius_y * cosine,
1261        center.x,
1262        center.y,
1263    )
1264}
1265
1266/// `shortest_sweep` returns the sub-turn sweep matching `direction`.
1267fn shortest_sweep(start: f32, end: f32, direction: f32) -> f32 {
1268    let mut sweep = end - start;
1269    let turn = std::f32::consts::TAU;
1270    while sweep > 0.0 && direction < 0.0 {
1271        sweep -= turn;
1272    }
1273    while sweep < 0.0 && direction > 0.0 {
1274        sweep += turn;
1275    }
1276    sweep
1277}
1278
1279/// `normalize` returns a unit vector or `None` when no finite direction exists.
1280fn normalize(x: f64, y: f64) -> Option<(f64, f64)> {
1281    let length = (x * x + y * y).sqrt();
1282    (length.is_finite() && length > 0.0).then(|| (x / length, y / length))
1283}
1284
1285/// `constrain_radii` proportionally reduces circular radii to fit a rectangle.
1286///
1287/// Radii are ordered clockwise from the top-left. Negative values become zero.
1288pub fn constrain_radii(r: &Rect, radii: [f32; 4]) -> [f32; 4] {
1289    constrain_radii_elliptical(r, radii.map(|v| [v; 2])).map(|[x, _]| x)
1290}
1291
1292/// `constrain_radii_elliptical` proportionally reduces elliptical radii to fit.
1293///
1294/// Corners are ordered clockwise from the top-left as `[x_radius, y_radius]`.
1295/// Negative components become zero.
1296pub fn constrain_radii_elliptical(r: &Rect, radii: [[f32; 2]; 4]) -> [[f32; 2]; 4] {
1297    let [tl, tr, br, bl] = radii.map(|[x, y]| [x.max(0.0), y.max(0.0)]);
1298    let fit = |side: f32, a: f32, b: f32| if a + b <= side { 1.0 } else { side / (a + b) };
1299    let f = fit(r.width, tl[0], tr[0])
1300        .min(fit(r.width, bl[0], br[0]))
1301        .min(fit(r.height, tl[1], bl[1]))
1302        .min(fit(r.height, tr[1], br[1]));
1303    [tl, tr, br, bl].map(|[x, y]| [x * f, y * f])
1304}
1305
1306/// `Flattener` approximates curves with uniformly parameterized line segments.
1307struct Flattener {
1308    tolerance: f32,
1309    contours: Vec<Contour>,
1310    current: Vec<Point>,
1311    /// Whether a segment verb has landed since the last `move_to`.
1312    has_segments: bool,
1313}
1314
1315impl Flattener {
1316    fn new(tolerance: f32) -> Self {
1317        Self {
1318            tolerance,
1319            contours: Vec::new(),
1320            current: Vec::new(),
1321            has_segments: false,
1322        }
1323    }
1324
1325    fn move_to(&mut self, p: Point) {
1326        self.flush(false);
1327        self.current.push(p);
1328        self.has_segments = false;
1329    }
1330
1331    fn line_to(&mut self, p: Point) {
1332        self.current.push(p);
1333        self.has_segments = true;
1334    }
1335
1336    fn quad_to(&mut self, c: Point, p: Point) {
1337        let Some(&start) = self.current.last() else {
1338            return;
1339        };
1340        self.has_segments = true;
1341        let dev = second_difference(start, c, p);
1342        let n = segment_count((dev / (8.0 * self.tolerance)).sqrt());
1343        for i in 1..=n {
1344            let t = i as f32 / n as f32;
1345            self.current.push(eval_quad(start, c, p, t));
1346        }
1347    }
1348
1349    fn conic_to(&mut self, c: Point, p: Point, w: f32) {
1350        let Some(&start) = self.current.last() else {
1351            return;
1352        };
1353        self.has_segments = true;
1354        let n = segment_count(conic_segment_estimate(start, c, p, w, self.tolerance));
1355        for i in 1..=n {
1356            let t = i as f32 / n as f32;
1357            self.current.push(eval_conic(start, c, p, w, t));
1358        }
1359    }
1360
1361    fn cubic_to(&mut self, c1: Point, c2: Point, p: Point) {
1362        let Some(&start) = self.current.last() else {
1363            return;
1364        };
1365        self.has_segments = true;
1366        let dev = second_difference(start, c1, c2).max(second_difference(c1, c2, p));
1367        let n = segment_count((3.0 * dev / (4.0 * self.tolerance)).sqrt());
1368        for i in 1..=n {
1369            let t = i as f32 / n as f32;
1370            self.current.push(eval_cubic(start, c1, c2, p, t));
1371        }
1372    }
1373
1374    fn close(&mut self) {
1375        // Emit the closing edge back to the contour's start (unless the
1376        // last curve already landed there exactly).
1377        if let (Some(&first), Some(&last)) = (self.current.first(), self.current.last()) {
1378            if self.current.len() >= 2 && (first.x, first.y) != (last.x, last.y) {
1379                self.current.push(first);
1380            }
1381        }
1382        // Closing is itself a drawing command: `move_to(p)` then `close()` is
1383        // an explicit zero-length SUBPATH, which strokes exactly like an
1384        // explicit zero-length segment. Impeller says so directly — its
1385        // `Close()` calls `SegmentEncountered()` — and Skia turns move+close
1386        // into a zero-length line for every non-butt cap.
1387        if !self.current.is_empty() {
1388            self.has_segments = true;
1389        }
1390        self.flush(true);
1391    }
1392
1393    fn finish(mut self) -> Vec<Contour> {
1394        self.flush(false);
1395        self.contours
1396    }
1397
1398    /// `flush` keeps every contour, even lone points.
1399    ///
1400    /// Fills fan nothing from <3 points,
1401    /// but the stroker draws 2-point lines and caps EXPLICIT zero-length
1402    /// subpaths. A move-only contour is kept too, carrying `has_segments:
1403    /// false` so the stroker can tell the two apart.
1404    fn flush(&mut self, closed: bool) {
1405        if !self.current.is_empty() {
1406            self.contours.push(Contour {
1407                points: std::mem::take(&mut self.current),
1408                closed,
1409                has_segments: self.has_segments,
1410            });
1411        }
1412        self.has_segments = false;
1413    }
1414}
1415
1416/// Wang's formula extended to conics — the same estimate Impeller and Skia's
1417/// GPU tessellators use ("Wang's formula for rational quadratics", Skia
1418/// `wangs_formula::conic`), with `precision = 1 / tolerance`.
1419fn conic_segment_estimate(start: Point, control: Point, end: Point, w: f32, tolerance: f32) -> f32 {
1420    let precision = 1.0 / tolerance;
1421    // Recentring on the bounding box improves translation invariance.
1422    let cx = 0.5 * (start.x.min(control.x).min(end.x) + start.x.max(control.x).max(end.x));
1423    let cy = 0.5 * (start.y.min(control.y).min(end.y) + start.y.max(control.y).max(end.y));
1424    let (p0x, p0y) = (start.x - cx, start.y - cy);
1425    let (p1x, p1y) = (control.x - cx, control.y - cy);
1426    let (p2x, p2y) = (end.x - cx, end.y - cy);
1427    let max_len_sq = (p0x * p0x + p0y * p0y)
1428        .max(p1x * p1x + p1y * p1y)
1429        .max(p2x * p2x + p2y * p2y);
1430    let (dpx, dpy) = (p0x - 2.0 * w * p1x + p2x, p0y - 2.0 * w * p1y + p2y);
1431    let dw = (2.0 - 2.0 * w).abs();
1432    let rp_minus_1 = (max_len_sq.sqrt() * precision - 1.0).max(0.0);
1433    let numer = (dpx * dpx + dpy * dpy).sqrt() * precision + rp_minus_1 * dw;
1434    let denom = 4.0 * w.min(1.0);
1435    (numer / denom).sqrt()
1436}
1437
1438fn second_difference(a: Point, b: Point, c: Point) -> f32 {
1439    let dx = a.x - 2.0 * b.x + c.x;
1440    let dy = a.y - 2.0 * b.y + c.y;
1441    (dx * dx + dy * dy).sqrt()
1442}
1443
1444fn segment_count(estimate: f32) -> u32 {
1445    (estimate.ceil() as u32).clamp(1, 64)
1446}
1447
1448fn eval_quad(p0: Point, c: Point, p1: Point, t: f32) -> Point {
1449    let u = 1.0 - t;
1450    Point::new(
1451        u * u * p0.x + 2.0 * u * t * c.x + t * t * p1.x,
1452        u * u * p0.y + 2.0 * u * t * c.y + t * t * p1.y,
1453    )
1454}
1455
1456fn eval_cubic(p0: Point, c1: Point, c2: Point, p1: Point, t: f32) -> Point {
1457    let u = 1.0 - t;
1458    let (uu, tt) = (u * u, t * t);
1459    Point::new(
1460        u * uu * p0.x + 3.0 * uu * t * c1.x + 3.0 * u * tt * c2.x + t * tt * p1.x,
1461        u * uu * p0.y + 3.0 * uu * t * c1.y + 3.0 * u * tt * c2.y + t * tt * p1.y,
1462    )
1463}
1464
1465/// `local_tolerance` returns local curve tolerance for quarter-pixel device error.
1466pub fn local_tolerance(transform: &Matrix) -> f32 {
1467    0.25 / transform.max_scale().max(1e-3)
1468}
1469
1470#[cfg(test)]
1471mod tests {
1472    /// A path knows it is an oval or a rounded rectangle by how it was
1473    /// built, as Skia's does: one added to an empty builder, with nothing
1474    /// after it, simplified as Skia simplifies a rounded rectangle.
1475    #[test]
1476    fn a_path_built_as_an_oval_or_a_rounded_rect_knows_it() {
1477        let built = |build: &dyn Fn(&mut PathBuilder)| {
1478            let mut path = PathBuilder::new();
1479            build(&mut path);
1480            path.build()
1481        };
1482        let r = Rect::new(10.0, 10.0, 40.0, 20.0);
1483
1484        let rounded = built(&|p| {
1485            p.rrect_radii(r, [4.0, 6.0, 0.0, 2.0]);
1486        });
1487        let radii = [[4.0; 2], [6.0; 2], [0.0; 2], [2.0; 2]];
1488        assert_eq!(rounded.as_round_rect(), Some((r, radii)));
1489        assert_eq!(rounded.as_oval(), None);
1490
1491        let circle = built(&|p| {
1492            p.circle((5.0, 5.0), 5.0);
1493        });
1494        assert_eq!(circle.as_oval(), Some(Rect::new(0.0, 0.0, 10.0, 10.0)));
1495        let filled = built(&|p| {
1496            p.rrect_radii_elliptical(r, [[20.0, 10.0]; 4]);
1497        });
1498        assert_eq!(filled.as_oval(), Some(r));
1499        assert_eq!(filled.as_round_rect(), None);
1500
1501        for general in [
1502            built(&|p| {
1503                p.rect(r);
1504            }),
1505            built(&|p| {
1506                p.rrect(r, 0.0);
1507            }),
1508            built(&|p| {
1509                p.rect(r);
1510                p.rrect(r, 4.0);
1511            }),
1512            built(&|p| {
1513                p.circle((5.0, 5.0), 5.0);
1514                p.line_to((20.0, 20.0));
1515            }),
1516        ] {
1517            assert_eq!((general.as_oval(), general.as_round_rect()), (None, None));
1518        }
1519
1520        let after_a_move = built(&|p| {
1521            p.move_to((0.0, 0.0));
1522            p.rrect(r, 4.0);
1523        });
1524        assert!(
1525            after_a_move.as_round_rect().is_some(),
1526            "a move adds no segment"
1527        );
1528    }
1529
1530    fn round_rect_path(r: Rect, radii: [[f32; 2]; 4]) -> Arc<Path> {
1531        let mut path = PathBuilder::new();
1532        path.rrect_radii_elliptical(r, radii);
1533        path.build()
1534    }
1535
1536    const ROUND_RECT: Rect = Rect {
1537        x: 10.0,
1538        y: 20.0,
1539        width: 40.0,
1540        height: 30.0,
1541    };
1542    const RADII: [[f32; 2]; 4] = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]];
1543
1544    /// Skia's `SkPath::offset`: a moved rounded rectangle is still one, so a
1545    /// shadow of it keeps its closed form.
1546    #[test]
1547    fn a_translated_round_rect_or_oval_keeps_its_shape() {
1548        let moved = round_rect_path(ROUND_RECT, RADII).transformed(&Matrix::translation(5.0, -3.0));
1549        assert_eq!(
1550            moved.as_round_rect(),
1551            Some((Rect::new(15.0, 17.0, 40.0, 30.0), RADII))
1552        );
1553        assert_eq!(moved.bounds(), Rect::new(15.0, 17.0, 40.0, 30.0));
1554
1555        let mut circle = PathBuilder::new();
1556        circle.circle((5.0, 5.0), 5.0);
1557        let moved = circle.build().transformed(&Matrix::translation(10.0, 0.0));
1558        assert_eq!(moved.as_oval(), Some(Rect::new(10.0, 0.0, 10.0, 10.0)));
1559    }
1560
1561    /// Under a scale, a mirror or a quarter turn the corners land on other
1562    /// corners, and a quarter turn swaps each corner's radii, as the points
1563    /// Skia maps would trace them.
1564    #[test]
1565    fn a_rect_staying_transform_moves_the_corners_with_their_radii() {
1566        let path = round_rect_path(ROUND_RECT, RADII);
1567        let scaled = path.transformed(&Matrix::scale(2.0, 0.5));
1568        assert_eq!(
1569            scaled.as_round_rect(),
1570            Some((
1571                Rect::new(20.0, 10.0, 80.0, 15.0),
1572                [[2.0, 1.0], [6.0, 2.0], [10.0, 3.0], [14.0, 4.0]]
1573            ))
1574        );
1575        let mirrored = path.transformed(&Matrix::scale(-1.0, 1.0));
1576        assert_eq!(
1577            mirrored.as_round_rect(),
1578            Some((
1579                Rect::new(-50.0, 20.0, 40.0, 30.0),
1580                [RADII[1], RADII[0], RADII[3], RADII[2]]
1581            ))
1582        );
1583        // A clockwise quarter turn takes (x, y) to (-y, x): the top left
1584        // corner goes to the top right.
1585        let turned = path.transformed(&Matrix::from_affine(0.0, 1.0, -1.0, 0.0, 0.0, 0.0));
1586        let swapped = RADII.map(|[x, y]| [y, x]);
1587        assert_eq!(
1588            turned.as_round_rect(),
1589            Some((
1590                Rect::new(-50.0, 10.0, 30.0, 40.0),
1591                [swapped[3], swapped[0], swapped[1], swapped[2]]
1592            ))
1593        );
1594    }
1595
1596    /// Where Skia drops the shape: a turn that is not a quarter, a shear,
1597    /// perspective, a flattening scale, and `addPath`, which `append` is.
1598    #[test]
1599    fn any_other_transform_or_an_append_makes_a_general_path() {
1600        let path = round_rect_path(ROUND_RECT, RADII);
1601        let mut perspective = Matrix::IDENTITY.to_flutter_array();
1602        perspective[3] = 0.001;
1603        for transform in [
1604            Matrix::rotation(0.3),
1605            Matrix::from_affine(1.0, 0.0, 0.5, 1.0, 0.0, 0.0),
1606            Matrix::from_flutter_array(&perspective),
1607            Matrix::scale(0.0, 1.0),
1608        ] {
1609            let moved = path.transformed(&transform);
1610            assert_eq!((moved.as_oval(), moved.as_round_rect()), (None, None));
1611        }
1612        let mut appended = PathBuilder::new();
1613        appended.append(&path, &Matrix::translation(5.0, 0.0));
1614        assert_eq!(appended.build().as_round_rect(), None);
1615    }
1616
1617    /// A transformed path holds the same verbs and weights as the path, its
1618    /// points mapped: what `append` makes of it on an empty builder, without
1619    /// the move `append` adds after a closed contour.
1620    #[test]
1621    fn a_transformed_path_maps_every_point() {
1622        let mut built = PathBuilder::new();
1623        built
1624            .move_to((0.0, 0.0))
1625            .line_to((10.0, 0.0))
1626            .conic_to((10.0, 10.0), (0.0, 10.0), 0.5)
1627            .close();
1628        let path = built.build();
1629        let transform = Matrix::rotation(0.4).then(&Matrix::scale(2.0, 3.0));
1630        let mut appended = PathBuilder::new();
1631        appended.append(&path, &transform);
1632        let appended = appended.build();
1633        let transformed = path.transformed(&transform);
1634        let elements: Vec<PathElement> = transformed.elements().collect();
1635        let appended_elements: Vec<PathElement> = appended.elements().collect();
1636        assert_eq!(elements, appended_elements[..elements.len()]);
1637        assert_eq!(transformed.bounds(), appended.bounds());
1638    }
1639
1640    use super::*;
1641
1642    /// The observable meaning of winding: under the NON-ZERO rule two
1643    /// overlapping contours cancel when their directions oppose and reinforce
1644    /// when they agree. This is the property Chrome exhibits for a
1645    /// `roundRect` given with a negative width, and the reason normalizing
1646    /// the box without carrying the direction is wrong — the second rectangle
1647    /// would add instead of subtract.
1648    #[test]
1649    fn opposed_windings_cancel_under_the_non_zero_rule() {
1650        let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
1651        let radii = [[12.0, 12.0]; 4];
1652        let inside = Point::new(50.0, 50.0);
1653
1654        let mut opposed = PathBuilder::new();
1655        opposed.rrect_radii_elliptical_wound(rect, radii, Winding::Clockwise);
1656        opposed.rrect_radii_elliptical_wound(rect, radii, Winding::CounterClockwise);
1657        assert!(
1658            !opposed.build().contains(inside, FillRule::NonZero),
1659            "opposed windings must cancel"
1660        );
1661
1662        let mut agreeing = PathBuilder::new();
1663        agreeing.rrect_radii_elliptical_wound(rect, radii, Winding::Clockwise);
1664        agreeing.rrect_radii_elliptical_wound(rect, radii, Winding::Clockwise);
1665        assert!(
1666            agreeing.build().contains(inside, FillRule::NonZero),
1667            "agreeing windings must reinforce"
1668        );
1669    }
1670
1671    /// Direction must not move the OUTLINE, only the traversal. A reversed
1672    /// corner whose control points were not swapped with it would bulge the
1673    /// wrong way and show up here.
1674    #[test]
1675    fn winding_reverses_the_walk_without_moving_the_outline() {
1676        let rect = Rect::new(10.0, 20.0, 80.0, 60.0);
1677        let radii = [[8.0, 14.0], [4.0, 4.0], [20.0, 6.0], [0.0, 0.0]];
1678        let wound = |winding| {
1679            let mut path = PathBuilder::new();
1680            path.rrect_radii_elliptical_wound(rect, radii, winding);
1681            path.build()
1682        };
1683        let clockwise = wound(Winding::Clockwise);
1684        let counter = wound(Winding::CounterClockwise);
1685        assert_eq!(clockwise.tight_bounds(), counter.tight_bounds());
1686        // Sample across the shape, including just inside and outside each
1687        // rounded corner.
1688        for point in [
1689            Point::new(50.0, 50.0),
1690            Point::new(14.0, 30.0),
1691            Point::new(86.0, 24.0),
1692            Point::new(74.0, 76.0),
1693            Point::new(12.0, 78.0),
1694            Point::new(5.0, 15.0),
1695            Point::new(95.0, 85.0),
1696        ] {
1697            assert_eq!(
1698                clockwise.contains(point, FillRule::NonZero),
1699                counter.contains(point, FillRule::NonZero),
1700                "the two directions disagree about {point:?}"
1701            );
1702        }
1703    }
1704
1705    /// WHATWG leaves a one-point subpath at the closed contour's origin, so a
1706    /// segment recorded after `closePath` starts from the SEAM.
1707    ///
1708    /// The bug this pins is invisible to any test that paints immediately
1709    /// after the close — the closed shape looks right and the missing
1710    /// diagonal is a segment that was never recorded at all. That is exactly
1711    /// why the conformance fuzzer never caught it.
1712    #[test]
1713    fn a_segment_after_close_resumes_at_the_contour_origin() {
1714        let mut path = PathBuilder::new();
1715        path.move_to((10.0, 10.0));
1716        path.line_to((30.0, 10.0));
1717        path.close();
1718        path.line_to((30.0, 30.0));
1719        let path = path.build();
1720
1721        // The diagonal runs (10,10) → (30,30); its midpoint is (20,20).
1722        let contours = path.flatten(0.05);
1723        let resumed = contours.last().expect("the path continues after the close");
1724        assert_eq!(
1725            resumed.points.first().copied(),
1726            Some(Point::new(10.0, 10.0)),
1727            "the segment after close must start at the contour origin, not its own end"
1728        );
1729        assert!(crate::stroke_contains(
1730            &contours,
1731            &crate::Stroke::new(6.0),
1732            0.05,
1733            Point::new(20.0, 20.0)
1734        ));
1735    }
1736
1737    /// `rect` and `roundRect` resume at `(x, y)` — the bounding box's corner,
1738    /// which is a SEPARATE spec step from the outline they walk.
1739    ///
1740    /// For a rounded rectangle that corner is not on the outline at all: the
1741    /// walk starts at the top-left tangent, `(18, 10)` here. The two points
1742    /// coincide only at radius zero, which is exactly why a rect-only test
1743    /// would miss this.
1744    #[test]
1745    fn a_segment_after_a_shape_helper_resumes_at_the_box_corner() {
1746        let box_corner = Point::new(10.0, 10.0);
1747        for corner in [0.0f32, 8.0] {
1748            let mut path = PathBuilder::new();
1749            if corner == 0.0 {
1750                path.rect(Rect::new(10.0, 10.0, 40.0, 40.0));
1751            } else {
1752                path.rrect_radii_elliptical(Rect::new(10.0, 10.0, 40.0, 40.0), [[corner; 2]; 4]);
1753            }
1754            path.line_to((90.0, 90.0));
1755
1756            let contours = path.build().flatten(0.05);
1757            let resumed = contours.last().expect("the path continues after the shape");
1758            assert_eq!(
1759                resumed.points.first().copied(),
1760                Some(box_corner),
1761                "corner radius {corner}: the trailing segment starts at (x, y)"
1762            );
1763        }
1764
1765        // The same thing said in ink, which is how the divergence was found:
1766        // the diagonal from (10,10) is stroked and the one from the tangent
1767        // (18,10) is not.
1768        let mut path = PathBuilder::new();
1769        path.rrect_radii_elliptical(Rect::new(10.0, 10.0, 40.0, 40.0), [[8.0; 2]; 4]);
1770        path.line_to((90.0, 90.0));
1771        let contours = path.build().flatten(0.05);
1772        let stroke = crate::Stroke::new(4.0);
1773        assert!(
1774            crate::stroke_contains(&contours, &stroke, 0.05, Point::new(50.0, 50.0)),
1775            "the diagonal from (10,10) must be stroked"
1776        );
1777        assert!(
1778            !crate::stroke_contains(&contours, &stroke, 0.05, Point::new(54.0, 50.0)),
1779            "the diagonal from the tangent (18,10) must not be"
1780        );
1781    }
1782
1783    /// `closePath` keeps the contour-origin rule — the shape helpers' `(x, y)`
1784    /// override must not have leaked into it.
1785    #[test]
1786    fn close_still_resumes_at_the_contour_origin() {
1787        let mut path = PathBuilder::new();
1788        path.move_to((10.0, 10.0));
1789        path.line_to((30.0, 10.0));
1790        path.line_to((30.0, 30.0));
1791        path.close();
1792        path.line_to((90.0, 90.0));
1793        let contours = path.build().flatten(0.05);
1794        assert_eq!(
1795            contours
1796                .last()
1797                .and_then(|contour| contour.points.first())
1798                .copied(),
1799            Some(Point::new(10.0, 10.0)),
1800            "close resumes where the contour began, not at any box corner"
1801        );
1802    }
1803
1804    /// A path that never opened a contour still starts where it is told —
1805    /// Skia's implicit `moveTo(0, 0)` is deliberately not copied.
1806    #[test]
1807    fn a_first_segment_with_no_contour_starts_at_its_own_point() {
1808        let mut path = PathBuilder::new();
1809        path.line_to((30.0, 30.0));
1810        assert_eq!(
1811            path.build().bounds(),
1812            Rect::from_ltrb(30.0, 30.0, 30.0, 30.0)
1813        );
1814    }
1815
1816    #[test]
1817    fn append_carries_verbs_through_the_transform() {
1818        let mut source = PathBuilder::new();
1819        source.rect(Rect::new(0.0, 0.0, 10.0, 10.0));
1820        let source = source.build();
1821
1822        let mut target = PathBuilder::new();
1823        target.rect(Rect::new(0.0, 0.0, 4.0, 4.0));
1824        target.append(&source, &Matrix::translation(100.0, 50.0));
1825        let target = target.build();
1826
1827        assert_eq!(target.bounds(), Rect::from_ltrb(0.0, 0.0, 110.0, 60.0));
1828        assert!(target.contains(Point::new(105.0, 55.0), FillRule::NonZero));
1829        assert!(!target.contains(Point::new(5.0, 5.0), FillRule::NonZero));
1830    }
1831
1832    /// The reopen after a closed source is what keeps the next segment
1833    /// connected. Without it the `line_to` below starts a fresh contour at
1834    /// its own endpoint and the edge from the seam disappears.
1835    #[test]
1836    fn appending_a_closed_contour_reopens_at_its_seam() {
1837        let mut source = PathBuilder::new();
1838        source.move_to((10.0, 10.0));
1839        source.line_to((20.0, 10.0));
1840        source.close();
1841        let source = source.build();
1842
1843        let mut target = PathBuilder::new();
1844        target.append(&source, &Matrix::IDENTITY);
1845        target.line_to((10.0, 40.0));
1846        let built = target.build();
1847
1848        // The seam is (10, 10); the new edge runs from there to (10, 40).
1849        assert_eq!(built.bounds(), Rect::from_ltrb(10.0, 10.0, 20.0, 40.0));
1850        assert!(built.contains(Point::new(10.0, 25.0), FillRule::NonZero));
1851    }
1852
1853    /// An appended OPEN contour becomes the receiver's contour, origin
1854    /// included. Keeping the receiver's own origin would send a later
1855    /// `close` + segment back to the wrong seam.
1856    #[test]
1857    fn appending_an_open_contour_hands_over_its_origin() {
1858        let mut source = PathBuilder::new();
1859        source.move_to((50.0, 50.0));
1860        source.line_to((60.0, 50.0));
1861        let source = source.build();
1862
1863        let mut target = PathBuilder::new();
1864        target.move_to((0.0, 0.0));
1865        target.line_to((10.0, 0.0));
1866        target.append(&source, &Matrix::IDENTITY);
1867        target.close();
1868        target.line_to((90.0, 90.0));
1869
1870        let contours = target.build().flatten(0.05);
1871        let resumed = contours.last().expect("the path continues after the close");
1872        assert_eq!(
1873            resumed.points.first().copied(),
1874            Some(Point::new(50.0, 50.0)),
1875            "the resumed segment must start at the APPENDED contour's origin"
1876        );
1877    }
1878
1879    #[test]
1880    fn appending_nothing_leaves_an_open_contour_open() {
1881        let empty = PathBuilder::new().build();
1882        let mut target = PathBuilder::new();
1883        target.move_to((0.0, 0.0));
1884        target.line_to((10.0, 0.0));
1885        target.append(&empty, &Matrix::IDENTITY);
1886        target.line_to((10.0, 10.0));
1887        assert_eq!(
1888            target.build().bounds(),
1889            Rect::from_ltrb(0.0, 0.0, 10.0, 10.0)
1890        );
1891    }
1892
1893    #[test]
1894    fn appending_an_open_contour_leaves_it_open() {
1895        let mut source = PathBuilder::new();
1896        source.move_to((0.0, 0.0));
1897        source.line_to((10.0, 0.0));
1898        let source = source.build();
1899
1900        let mut target = PathBuilder::new();
1901        target.append(&source, &Matrix::IDENTITY);
1902        // Without the contour-open handoff this would restart at the origin
1903        // and the bounds would be unchanged by the new point.
1904        target.line_to((10.0, 10.0));
1905        assert_eq!(
1906            target.build().bounds(),
1907            Rect::from_ltrb(0.0, 0.0, 10.0, 10.0)
1908        );
1909    }
1910
1911    #[test]
1912    fn tight_bounds_use_curve_extrema_not_control_points() {
1913        let mut path = PathBuilder::new();
1914        path.move_to((0.0, 0.0));
1915        path.quad_to((100.0, 100.0), (200.0, 0.0));
1916        let path = path.build();
1917        assert_eq!(path.bounds(), Rect::new(0.0, 0.0, 200.0, 100.0));
1918        assert_eq!(path.tight_bounds(), Rect::new(0.0, 0.0, 200.0, 50.0));
1919    }
1920
1921    #[test]
1922    fn tight_bounds_keep_extrema_below_f32_epsilon() {
1923        let mut path = PathBuilder::new();
1924        path.move_to((0.0, 0.0));
1925        path.quad_to((0.0, 1.0e-8), (0.0, 0.0));
1926        let bounds = path.build().tight_bounds();
1927        assert!((bounds.height - 5.0e-9).abs() < 1.0e-12);
1928    }
1929
1930    #[test]
1931    fn cubic_extrema_preserve_the_small_root() {
1932        let roots = cubic_extrema(0.0, 1.0e-8, -0.5, -0.5);
1933        assert!(roots
1934            .into_iter()
1935            .flatten()
1936            .any(|root| (root - 1.0e-8).abs() < 1.0e-10));
1937    }
1938
1939    #[test]
1940    fn radii_constrain_together() {
1941        let r = Rect::new(0.0, 0.0, 100.0, 40.0);
1942        // tl+bl = 80 > height 40 → everything scales by 0.5.
1943        let out = constrain_radii(&r, [40.0, 10.0, 10.0, 40.0]);
1944        assert_eq!(out, [20.0, 5.0, 5.0, 20.0]);
1945        // Already fitting radii pass through untouched.
1946        assert_eq!(constrain_radii(&r, [8.0, 8.0, 8.0, 8.0]), [8.0; 4]);
1947    }
1948
1949    #[test]
1950    fn per_corner_rrect_stays_in_rect() {
1951        let r = Rect::new(10.0, 10.0, 100.0, 60.0);
1952        let mut b = PathBuilder::new();
1953        b.rrect_radii(r, [30.0, 0.0, 16.0, 8.0]);
1954        assert_eq!(b.build().bounds(), r);
1955    }
1956
1957    #[test]
1958    fn bounds_cover_control_points() {
1959        let mut b = PathBuilder::new();
1960        b.move_to((10.0, 10.0)).quad_to((50.0, -20.0), (90.0, 10.0));
1961        let p = b.build();
1962        assert_eq!(p.bounds(), Rect::from_ltrb(10.0, -20.0, 90.0, 10.0));
1963    }
1964
1965    #[test]
1966    fn circle_flattens_to_radius() {
1967        let mut b = PathBuilder::new();
1968        b.circle((0.0, 0.0), 100.0);
1969        let contours = b.build().flatten(0.1);
1970        assert_eq!(contours.len(), 1);
1971        assert!(contours[0].closed, "circle closes its contour");
1972        for p in &contours[0].points {
1973            let r = (p.x * p.x + p.y * p.y).sqrt();
1974            assert!((r - 100.0).abs() < 0.5, "point off circle: r={r}");
1975        }
1976    }
1977
1978    #[test]
1979    fn finer_tolerance_means_more_segments() {
1980        let path = {
1981            let mut b = PathBuilder::new();
1982            b.circle((0.0, 0.0), 100.0);
1983            b.build()
1984        };
1985        let coarse = path.flatten(2.0)[0].points.len();
1986        let fine = path.flatten(0.05)[0].points.len();
1987        assert!(fine > coarse, "fine {fine} vs coarse {coarse}");
1988    }
1989
1990    #[test]
1991    fn small_contours_survive_for_the_stroker() {
1992        let mut b = PathBuilder::new();
1993        b.move_to((0.0, 0.0)).line_to((10.0, 0.0)); // a stroked line segment
1994        b.move_to((50.0, 50.0)); // a lone point (caps render it)
1995        let contours = b.build().flatten(0.1);
1996        assert_eq!(contours.len(), 2);
1997        assert_eq!(contours[0].points.len(), 2);
1998        assert!(!contours[0].closed);
1999        assert_eq!(contours[1].points.len(), 1);
2000    }
2001
2002    #[test]
2003    fn close_emits_the_closing_edge_and_marks_the_contour() {
2004        let mut b = PathBuilder::new();
2005        b.move_to((0.0, 0.0))
2006            .line_to((10.0, 0.0))
2007            .line_to((10.0, 10.0))
2008            .close();
2009        let contours = b.build().flatten(0.1);
2010        assert!(contours[0].closed);
2011        assert_eq!(contours[0].points.len(), 4, "closing edge in the polyline");
2012        assert_eq!(contours[0].points[3], Point::new(0.0, 0.0));
2013    }
2014
2015    #[test]
2016    fn bounds_keep_a_first_point_at_the_origin() {
2017        let mut b = PathBuilder::new();
2018        b.move_to((0.0, 0.0)).line_to((50.0, 80.0));
2019        assert_eq!(b.build().bounds(), Rect::from_ltrb(0.0, 0.0, 50.0, 80.0));
2020
2021        let mut b = PathBuilder::new();
2022        b.move_to((0.0, 0.0)).line_to((100.0, 0.0)); // zero-height line
2023        assert_eq!(b.build().bounds(), Rect::from_ltrb(0.0, 0.0, 100.0, 0.0));
2024    }
2025
2026    #[test]
2027    fn curve_without_move_starts_contour() {
2028        let mut b = PathBuilder::new();
2029        b.line_to((10.0, 0.0))
2030            .line_to((10.0, 10.0))
2031            .line_to((0.0, 10.0));
2032        let contours = b.build().flatten(0.1);
2033        assert_eq!(contours.len(), 1);
2034        assert_eq!(contours[0].points.len(), 4);
2035    }
2036
2037    /// The circular constructor must be EXACTLY the rx == ry case of the
2038    /// elliptical one — same constraint order, same cubics — so every
2039    /// existing rrect golden also pins the elliptical code path.
2040    #[test]
2041    fn circular_rrect_is_the_equal_axes_elliptical_case() {
2042        let r = Rect::new(10.0, 20.0, 120.0, 80.0);
2043        let radii = [24.0, 8.0, 30.0, 0.0];
2044        let mut circular = PathBuilder::new();
2045        circular.rrect_radii(r, radii);
2046        let mut elliptical = PathBuilder::new();
2047        elliptical.rrect_radii_elliptical(r, radii.map(|v| [v; 2]));
2048        assert_eq!(
2049            circular.build().flatten(0.1)[0].points,
2050            elliptical.build().flatten(0.1)[0].points,
2051        );
2052    }
2053
2054    #[test]
2055    fn elliptical_radii_constrain_per_axis() {
2056        // A 100×40 rect with tall corner ellipses: the HEIGHT edges force
2057        // the scale (20 + 30 > 40 → f = 0.8); x components ride along.
2058        let r = Rect::new(0.0, 0.0, 100.0, 40.0);
2059        let out = constrain_radii_elliptical(
2060            &r,
2061            [[10.0, 20.0], [10.0, 20.0], [10.0, 30.0], [10.0, 30.0]],
2062        );
2063        assert_eq!(out[0], [8.0, 16.0]);
2064        assert_eq!(out[2], [8.0, 24.0]);
2065        // Negative radii clamp to zero before constraining.
2066        let out = constrain_radii_elliptical(&r, [[-5.0, 10.0], [0.0; 2], [0.0; 2], [0.0; 2]]);
2067        assert_eq!(out[0], [0.0, 10.0]);
2068    }
2069
2070    #[test]
2071    fn elliptical_corner_lands_on_axis_extremes() {
2072        // One elliptical corner (rx 40, ry 10): the arc must start 40 in
2073        // from the corner on x and end 10 down on y.
2074        let r = Rect::new(0.0, 0.0, 200.0, 100.0);
2075        let mut b = PathBuilder::new();
2076        b.rrect_radii_elliptical(r, [[0.0; 2], [40.0, 10.0], [0.0; 2], [0.0; 2]]);
2077        let points = &b.build().flatten(0.05)[0].points;
2078        // The top edge stops at x = 160 (200 - rx) and the right edge
2079        // starts at y = 10 (ry) — both points must be on the outline.
2080        assert!(points
2081            .iter()
2082            .any(|p| (p.x - 160.0).abs() < 0.5 && p.y.abs() < 0.5));
2083        assert!(points
2084            .iter()
2085            .any(|p| (p.x - 200.0).abs() < 0.5 && (p.y - 10.0).abs() < 0.5));
2086    }
2087
2088    // ── arcs ────────────────────────────────────────────────────────────────
2089
2090    /// Every point of a swept circle sits on the circle, to well under a
2091    /// tenth of a pixel — the cubic approximation's whole claim.
2092    #[test]
2093    fn swept_arc_stays_on_its_circle() {
2094        let (center, radius) = (Point::new(50.0, 60.0), 40.0);
2095        let mut b = PathBuilder::new();
2096        b.arc(center, radius, 0.0, std::f32::consts::TAU);
2097        for point in &b.build().flatten(0.01)[0].points {
2098            let offset = (point.x - center.x).hypot(point.y - center.y);
2099            assert!(
2100                (offset - radius).abs() < 0.05,
2101                "point {point:?} is {offset} from the centre, not {radius}"
2102            );
2103        }
2104    }
2105
2106    /// A quarter turn ends exactly where trigonometry says it does.
2107    #[test]
2108    fn quarter_arc_ends_where_it_should() {
2109        let mut b = PathBuilder::new();
2110        b.arc((0.0, 0.0), 100.0, 0.0, std::f32::consts::FRAC_PI_2);
2111        let points = &b.build().flatten(0.01)[0].points;
2112        let (first, last) = (points[0], *points.last().unwrap());
2113        assert!(
2114            (first.x - 100.0).abs() < 0.01 && first.y.abs() < 0.01,
2115            "{first:?}"
2116        );
2117        assert!(
2118            last.x.abs() < 0.05 && (last.y - 100.0).abs() < 0.05,
2119            "{last:?}"
2120        );
2121    }
2122
2123    /// An ellipse reaches its own half-extents on each axis.
2124    #[test]
2125    fn ellipse_reaches_both_radii() {
2126        let mut b = PathBuilder::new();
2127        b.ellipse((0.0, 0.0), [80.0, 20.0], 0.0, 0.0, std::f32::consts::TAU);
2128        let points = &b.build().flatten(0.01)[0].points;
2129        let widest = points.iter().fold(0.0f32, |m, p| m.max(p.x.abs()));
2130        let tallest = points.iter().fold(0.0f32, |m, p| m.max(p.y.abs()));
2131        assert!((widest - 80.0).abs() < 0.1, "widest {widest}");
2132        assert!((tallest - 20.0).abs() < 0.1, "tallest {tallest}");
2133    }
2134
2135    /// The rotation turns the ellipse: a 90° turn swaps which axis is long.
2136    #[test]
2137    fn ellipse_rotation_swaps_the_axes() {
2138        let mut b = PathBuilder::new();
2139        b.ellipse(
2140            (0.0, 0.0),
2141            [80.0, 20.0],
2142            std::f32::consts::FRAC_PI_2,
2143            0.0,
2144            std::f32::consts::TAU,
2145        );
2146        let points = &b.build().flatten(0.01)[0].points;
2147        let widest = points.iter().fold(0.0f32, |m, p| m.max(p.x.abs()));
2148        let tallest = points.iter().fold(0.0f32, |m, p| m.max(p.y.abs()));
2149        assert!((widest - 20.0).abs() < 0.1, "widest {widest}");
2150        assert!((tallest - 80.0).abs() < 0.1, "tallest {tallest}");
2151    }
2152
2153    /// A right-angle `arc_to` with radius r touches down r before the corner
2154    /// and leaves r after it, and every point between is r from the centre
2155    /// the two tangents share.
2156    #[test]
2157    fn arc_to_rounds_a_right_angle() {
2158        let radius = 20.0f32;
2159        let mut b = PathBuilder::new();
2160        b.move_to((0.0, 0.0))
2161            .arc_to((100.0, 0.0), (100.0, 100.0), radius);
2162        let points = &b.build().flatten(0.01)[0].points;
2163
2164        let entry = Point::new(100.0 - radius, 0.0);
2165        let exit = Point::new(100.0, radius);
2166        assert!(points
2167            .iter()
2168            .any(|p| (p.x - entry.x).abs() < 0.1 && (p.y - entry.y).abs() < 0.1));
2169        assert!(points
2170            .iter()
2171            .any(|p| (p.x - exit.x).abs() < 0.1 && (p.y - exit.y).abs() < 0.1));
2172
2173        let center = Point::new(100.0 - radius, radius);
2174        for point in points.iter().filter(|p| p.x > entry.x - 0.01) {
2175            let offset = (point.x - center.x).hypot(point.y - center.y);
2176            assert!(
2177                (offset - radius).abs() < 0.1,
2178                "{point:?} is {offset} from the centre"
2179            );
2180        }
2181    }
2182
2183    /// Collinear points and a zero radius both degenerate to a plain line,
2184    /// which is what the Canvas2D algorithm prescribes.
2185    #[test]
2186    fn degenerate_arc_to_falls_back_to_a_line() {
2187        for (corner, next, radius) in [
2188            ((50.0, 0.0), (100.0, 0.0), 20.0), // straight through
2189            ((50.0, 0.0), (50.0, 50.0), 0.0),  // no radius
2190        ] {
2191            let mut b = PathBuilder::new();
2192            b.move_to((0.0, 0.0)).arc_to(corner, next, radius);
2193            let points = &b.build().flatten(0.01)[0].points;
2194            assert_eq!(points.len(), 2, "expected a bare line, got {points:?}");
2195            assert!((points[1].x - corner.0).abs() < 0.01 && (points[1].y - corner.1).abs() < 0.01);
2196        }
2197    }
2198
2199    // ── containment ─────────────────────────────────────────────────────────
2200
2201    #[test]
2202    fn rect_contains_what_it_covers() {
2203        let mut b = PathBuilder::new();
2204        b.rect(Rect::new(10.0, 10.0, 80.0, 60.0));
2205        let path = b.build();
2206        assert!(path.contains(Point::new(50.0, 40.0), FillRule::NonZero));
2207        assert!(!path.contains(Point::new(5.0, 40.0), FillRule::NonZero));
2208        assert!(!path.contains(Point::new(50.0, 80.0), FillRule::NonZero));
2209        // Exactly on the outline counts as inside — on EVERY edge. The far
2210        // two are the ones a half-open bounds check silently loses.
2211        for on_outline in [
2212            Point::new(10.0, 40.0), // left
2213            Point::new(50.0, 10.0), // top
2214            Point::new(90.0, 40.0), // right
2215            Point::new(50.0, 70.0), // bottom
2216            Point::new(90.0, 70.0), // the far corner
2217        ] {
2218            assert!(
2219                path.contains(on_outline, FillRule::NonZero),
2220                "{on_outline:?} is on the outline and must count as inside"
2221            );
2222        }
2223    }
2224
2225    /// Canvas2D caps an arc at one turn. Without the clamp a huge sweep asks
2226    /// for billions of cubic pieces, which is an allocation the process does
2227    /// not survive — so this test is a crash guard, not a geometry check.
2228    #[test]
2229    fn an_enormous_sweep_stays_one_turn() {
2230        let mut b = PathBuilder::new();
2231        b.arc((0.0, 0.0), 50.0, 0.0, 1e20);
2232        let path = b.build();
2233        let contours = path.flatten(0.1);
2234        assert_eq!(contours.len(), 1);
2235        // One turn at this tolerance is a few hundred points, never millions.
2236        assert!(
2237            contours[0].points.len() < 1_000,
2238            "a clamped turn should stay small, got {}",
2239            contours[0].points.len()
2240        );
2241        assert!(contours[0].closed, "a full turn closes its contour");
2242    }
2243
2244    #[test]
2245    fn a_negative_sweep_turns_the_other_way() {
2246        let quarter = std::f32::consts::FRAC_PI_2;
2247        let mut clockwise = PathBuilder::new();
2248        clockwise.arc((0.0, 0.0), 50.0, 0.0, quarter);
2249        let mut anticlockwise = PathBuilder::new();
2250        anticlockwise.arc((0.0, 0.0), 50.0, 0.0, -quarter);
2251
2252        // y-down: a positive sweep from +x heads towards +y, a negative one
2253        // towards -y. Both start at the same point.
2254        let forward = clockwise.build().bounds();
2255        let backward = anticlockwise.build().bounds();
2256        assert!(forward.bottom() > 40.0, "positive sweep reaches +y");
2257        assert!(backward.y < -40.0, "negative sweep reaches -y");
2258    }
2259
2260    /// Containment runs on the CURVE, so it agrees with the true circle at
2261    /// every angle — a flattened test would drift inside the chords.
2262    #[test]
2263    fn circle_containment_is_exact_all_the_way_round() {
2264        let (center, radius) = (Point::new(0.0, 0.0), 100.0f32);
2265        let mut b = PathBuilder::new();
2266        b.circle(center, radius);
2267        let path = b.build();
2268        for step in 0..64 {
2269            let angle = step as f32 / 64.0 * std::f32::consts::TAU;
2270            let (sine, cosine) = angle.sin_cos();
2271            let inside = Point::new(cosine * radius * 0.99, sine * radius * 0.99);
2272            let outside = Point::new(cosine * radius * 1.01, sine * radius * 1.01);
2273            assert!(
2274                path.contains(inside, FillRule::NonZero),
2275                "{inside:?} should be in"
2276            );
2277            assert!(
2278                !path.contains(outside, FillRule::NonZero),
2279                "{outside:?} should be out"
2280            );
2281        }
2282    }
2283
2284    /// The two fill rules disagree exactly where they should: a hole wound
2285    /// the same way as its parent is solid under non-zero, empty under
2286    /// even-odd.
2287    #[test]
2288    fn fill_rules_disagree_about_a_same_wound_hole() {
2289        let mut b = PathBuilder::new();
2290        b.rect(Rect::new(0.0, 0.0, 100.0, 100.0));
2291        b.rect(Rect::new(25.0, 25.0, 50.0, 50.0));
2292        let path = b.build();
2293        let middle = Point::new(50.0, 50.0);
2294        assert!(path.contains(middle, FillRule::NonZero));
2295        assert!(!path.contains(middle, FillRule::EvenOdd));
2296        // Between the rings both rules agree it is filled.
2297        let ring = Point::new(10.0, 50.0);
2298        assert!(path.contains(ring, FillRule::NonZero));
2299        assert!(path.contains(ring, FillRule::EvenOdd));
2300    }
2301
2302    /// An unclosed contour still fills, so it must still contain.
2303    #[test]
2304    fn open_contour_closes_implicitly() {
2305        let mut b = PathBuilder::new();
2306        b.move_to((0.0, 0.0))
2307            .line_to((100.0, 0.0))
2308            .line_to((100.0, 100.0));
2309        let path = b.build();
2310        assert!(path.contains(Point::new(80.0, 40.0), FillRule::NonZero));
2311        assert!(!path.contains(Point::new(20.0, 60.0), FillRule::NonZero));
2312    }
2313
2314    /// Curved segments contribute their real crossings, not a chord's.
2315    #[test]
2316    fn containment_handles_curves_that_double_back() {
2317        let mut b = PathBuilder::new();
2318        b.move_to((0.0, 0.0))
2319            .cubic_to((120.0, 120.0), (-20.0, 120.0), (100.0, 0.0))
2320            .close();
2321        let path = b.build();
2322        assert!(path.contains(Point::new(50.0, 40.0), FillRule::NonZero));
2323        assert!(!path.contains(Point::new(50.0, -10.0), FillRule::NonZero));
2324        assert!(!path.contains(Point::new(-30.0, 40.0), FillRule::NonZero));
2325    }
2326
2327    // ── conic segments ─────────────────────────────────────────────────────
2328
2329    /// A conic quarter with weight cos(45°) IS the circle: every flattened
2330    /// point sits on it exactly, not within the old cubic approximation's
2331    /// 0.027%-of-radius bulge. Ignoring the weight (treating the segment as
2332    /// a plain quad) would miss by ~6% of the radius.
2333    #[test]
2334    fn circle_flattens_onto_the_exact_circle() {
2335        let mut b = PathBuilder::new();
2336        b.circle((10.0, -20.0), 100.0);
2337        let contours = b.build().flatten(0.1);
2338        let points: Vec<Point> = contours.iter().flat_map(|c| c.points.clone()).collect();
2339        assert!(points.len() > 20);
2340        for p in &points {
2341            let distance = (p.x - 10.0).hypot(p.y + 20.0);
2342            assert!(
2343                (distance - 100.0).abs() < 2e-3,
2344                "{p:?} is off the circle by {}",
2345                (distance - 100.0).abs()
2346            );
2347        }
2348    }
2349
2350    /// `ellipse` runs on conics too: sampled points must satisfy the ellipse
2351    /// equation, including through a rotation.
2352    #[test]
2353    fn ellipse_arc_flattens_onto_the_exact_ellipse() {
2354        let mut b = PathBuilder::new();
2355        let rotation = 0.5f32;
2356        b.ellipse((5.0, 7.0), [80.0, 30.0], rotation, 0.3, 4.0);
2357        let contours = b.build().flatten(0.05);
2358        let (sin_r, cos_r) = rotation.sin_cos();
2359        for p in contours.iter().flat_map(|c| &c.points) {
2360            let (dx, dy) = (p.x - 5.0, p.y - 7.0);
2361            // Undo the rotation, then normalize by the radii.
2362            let (ux, uy) = (dx * cos_r + dy * sin_r, -dx * sin_r + dy * cos_r);
2363            let value = (ux / 80.0).powi(2) + (uy / 30.0).powi(2);
2364            assert!((value - 1.0).abs() < 1e-3, "{p:?} deviates: {value}");
2365        }
2366    }
2367
2368    /// The conic's rational midpoint reaches the true circle edge, so the
2369    /// tight bounds of a circle are its exact box — no cubic overshoot, and
2370    /// no undershoot from treating control points as reachable.
2371    #[test]
2372    fn conic_circle_tight_bounds_are_exact() {
2373        let mut b = PathBuilder::new();
2374        b.circle((0.0, 0.0), 50.0);
2375        let tight = b.build().tight_bounds();
2376        for (got, want) in [
2377            (tight.x, -50.0),
2378            (tight.y, -50.0),
2379            (tight.right(), 50.0),
2380            (tight.bottom(), 50.0),
2381        ] {
2382            assert!((got - want).abs() < 1e-3, "bound {got} should be {want}");
2383        }
2384        // The arc helper's extremum lies between piece endpoints: an arc
2385        // through the top must still reach exactly -50 in y.
2386        let mut arc = PathBuilder::new();
2387        arc.arc((0.0, 0.0), 50.0, -3.0, 2.5);
2388        let tight = arc.build().tight_bounds();
2389        assert!((tight.y + 50.0).abs() < 1e-3, "arc top: {}", tight.y);
2390    }
2391
2392    /// Analytic containment solves the conic itself: probes 0.05 units off a
2393    /// 100-unit circle land on the right side at every angle.
2394    #[test]
2395    fn conic_containment_is_exact_on_the_curve() {
2396        let mut b = PathBuilder::new();
2397        b.circle((0.0, 0.0), 100.0);
2398        let path = b.build();
2399        for i in 0..64 {
2400            let angle = i as f32 / 64.0 * std::f32::consts::TAU;
2401            let (s, c) = angle.sin_cos();
2402            let inside = Point::new(c * 99.95, s * 99.95);
2403            let outside = Point::new(c * 100.05, s * 100.05);
2404            assert!(
2405                path.contains(inside, FillRule::NonZero),
2406                "{inside:?} at angle {i} should be inside"
2407            );
2408            assert!(
2409                !path.contains(outside, FillRule::NonZero),
2410                "{outside:?} at angle {i} should be outside"
2411            );
2412        }
2413    }
2414
2415    /// Conic circles wind like any other contour: an opposing inner circle
2416    /// carves a hole under the non-zero rule.
2417    #[test]
2418    fn conic_windings_cancel_under_the_non_zero_rule() {
2419        let mut b = PathBuilder::new();
2420        b.circle((0.0, 0.0), 100.0);
2421        // The same circle traversed the other way: swap the conic sweep
2422        // direction by walking the quarters in reverse.
2423        let w = std::f32::consts::FRAC_1_SQRT_2;
2424        b.move_to((60.0, 0.0))
2425            .conic_to((60.0, -60.0), (0.0, -60.0), w)
2426            .conic_to((-60.0, -60.0), (-60.0, 0.0), w)
2427            .conic_to((-60.0, 60.0), (0.0, 60.0), w)
2428            .conic_to((60.0, 60.0), (60.0, 0.0), w)
2429            .close();
2430        let path = b.build();
2431        assert!(!path.contains(Point::new(0.0, 0.0), FillRule::NonZero));
2432        assert!(path.contains(Point::new(80.0, 0.0), FillRule::NonZero));
2433    }
2434
2435    /// `append` carries conic weights through its transform: a rotated
2436    /// circle is still a circle.
2437    #[test]
2438    fn append_preserves_conic_weights() {
2439        let mut source = PathBuilder::new();
2440        source.circle((0.0, 0.0), 40.0);
2441        let source = source.build();
2442        let mut b = PathBuilder::new();
2443        b.append(&source, &Matrix::rotation(0.7));
2444        for p in b.build().flatten(0.05).iter().flat_map(|c| &c.points) {
2445            let distance = p.x.hypot(p.y);
2446            assert!((distance - 40.0).abs() < 1e-3, "{p:?} off by {distance}");
2447        }
2448    }
2449
2450    /// Degenerate weights lower instead of recording: nonpositive to a line,
2451    /// exactly 1 to a quad, non-finite to the control polygon.
2452    #[test]
2453    fn degenerate_conic_weights_lower_to_simpler_verbs() {
2454        let mut zero = PathBuilder::new();
2455        zero.move_to((0.0, 0.0))
2456            .conic_to((50.0, 50.0), (100.0, 0.0), 0.0);
2457        let contour = &zero.build().flatten(0.1)[0];
2458        assert_eq!(contour.points.len(), 2, "weight 0 must be a straight line");
2459
2460        let mut quad = PathBuilder::new();
2461        quad.move_to((0.0, 0.0))
2462            .conic_to((50.0, 50.0), (100.0, 0.0), 1.0);
2463        let mut plain = PathBuilder::new();
2464        plain
2465            .move_to((0.0, 0.0))
2466            .quad_to((50.0, 50.0), (100.0, 0.0));
2467        assert_eq!(
2468            quad.build().flatten(0.1),
2469            plain.build().flatten(0.1),
2470            "weight 1 must match the plain quadratic"
2471        );
2472
2473        let mut infinite = PathBuilder::new();
2474        infinite
2475            .move_to((0.0, 0.0))
2476            .conic_to((50.0, 50.0), (100.0, 0.0), f32::INFINITY);
2477        let contour = &infinite.build().flatten(0.1)[0];
2478        assert_eq!(
2479            contour.points,
2480            vec![
2481                Point::new(0.0, 0.0),
2482                Point::new(50.0, 50.0),
2483                Point::new(100.0, 0.0)
2484            ],
2485            "an unbounded weight collapses onto the control polygon"
2486        );
2487    }
2488
2489    /// Extremum-finding must survive coordinates far from the origin: the
2490    /// quadratic's coefficients are built from point DIFFERENCES (Skia's
2491    /// `conic_find_extrema` form) in f64, because the absolute-coordinate
2492    /// form cancels catastrophically in f32. Audit repro: this curve near
2493    /// y=442028 has a real interior maximum that the naive form misses.
2494    #[test]
2495    fn conic_extrema_survive_large_coordinates() {
2496        let p0 = Point::new(0.0, 442_027.38);
2497        let c = Point::new(50.0, 442_028.47);
2498        let p2 = Point::new(100.0, 442_027.03);
2499        let w = 20.189_045;
2500        let mut b = PathBuilder::new();
2501        b.move_to(p0).conic_to(c, p2, w).close();
2502        let path = b.build();
2503        let bottom = path.tight_bounds().bottom();
2504        assert!(
2505            (bottom - 442_028.4).abs() < 0.05,
2506            "tight bottom {bottom} should reach the true maximum ~442028.41"
2507        );
2508        assert!(
2509            path.contains(Point::new(49.660_536, 442_028.0), FillRule::NonZero),
2510            "an interior point above the chord must be inside"
2511        );
2512    }
2513
2514    /// Flattening error stays within the requested tolerance for a strongly
2515    /// hyperbolic weight (the superellipse emits weights past 8): the chord
2516    /// midpoints of consecutive flattened points may deviate from the curve
2517    /// by at most the tolerance.
2518    #[test]
2519    fn conic_flattening_respects_tolerance_for_large_weights() {
2520        let (p0, c, p2, w) = (
2521            Point::new(0.0, 100.0),
2522            Point::new(35.0, 100.0),
2523            Point::new(40.0, 90.0),
2524            8.3f32,
2525        );
2526        let tolerance = 0.05f32;
2527        let mut b = PathBuilder::new();
2528        b.move_to(p0).conic_to(c, p2, w);
2529        let contour = &b.build().flatten(tolerance)[0];
2530        // Dense reference polyline on the true curve.
2531        let reference: Vec<Point> = (0..=4096)
2532            .map(|i| eval_conic(p0, c, p2, w, i as f32 / 4096.0))
2533            .collect();
2534        for pair in contour.points.windows(2) {
2535            let mid = Point::new((pair[0].x + pair[1].x) / 2.0, (pair[0].y + pair[1].y) / 2.0);
2536            let distance = reference
2537                .iter()
2538                .map(|r| (r.x - mid.x).hypot(r.y - mid.y))
2539                .fold(f32::MAX, f32::min);
2540            assert!(
2541                distance <= tolerance * 1.1,
2542                "chord midpoint {mid:?} is {distance} off the curve"
2543            );
2544        }
2545    }
2546}
2547
2548#[cfg(test)]
2549mod element_tests {
2550    use super::*;
2551
2552    #[test]
2553    fn elements_rebuild_an_equal_path() {
2554        let mut builder = PathBuilder::new();
2555        builder
2556            .move_to((0.0, 0.0))
2557            .line_to((10.0, 0.0))
2558            .quad_to((10.0, 5.0), (10.0, 10.0))
2559            .conic_to((5.0, 10.0), (0.0, 10.0), 0.7)
2560            .cubic_to((0.0, 7.0), (0.0, 3.0), (0.0, 0.0))
2561            .close();
2562        let path = builder.build();
2563        let mut rebuilt = PathBuilder::new();
2564        for element in path.elements() {
2565            match element {
2566                PathElement::MoveTo(p) => rebuilt.move_to(p),
2567                PathElement::LineTo(p) => rebuilt.line_to(p),
2568                PathElement::QuadTo(c, p) => rebuilt.quad_to(c, p),
2569                PathElement::ConicTo(c, p, w) => rebuilt.conic_to(c, p, w),
2570                PathElement::CubicTo(a, b, p) => rebuilt.cubic_to(a, b, p),
2571                PathElement::Close => rebuilt.close(),
2572            };
2573        }
2574        let rebuilt = rebuilt.build();
2575        assert_eq!(path.elements().count(), 6);
2576        assert_eq!(rebuilt.bounds(), path.bounds());
2577        assert!(path.elements().eq(rebuilt.elements()));
2578    }
2579}