valo_geometry/path_operation.rs
1//! Boolean operations on paths: Skia's `Op`, which dart:ui's `Path.combine`
2//! calls under both Skia and Impeller, through `valo-pathops`' port of it.
3//!
4//! A [`Path`] goes to the port as Skia's builder would store the same
5//! commands, and the port's answer comes back verb for verb, so a combined
6//! path is the one Flutter gets for the same input.
7
8use std::sync::Arc;
9
10use valo_pathops::{SkPath, SkPathBuilder, SkPathFillType, SkPathOp, SkPathVerb, SkPoint};
11
12use crate::{FillRule, Path, PathBuilder, PathElement, Point};
13
14/// `PathOperationError` is the failure of [`Path::combine`]: Skia's `Op`
15/// returned no path for these inputs.
16///
17/// Skia gives up when it cannot resolve the curves' intersections or windings
18/// consistently, which happens for some near-coincident or degenerate
19/// geometry; no partial result is given. dart:ui's `Path.combine` throws in
20/// that case.
21pub use valo_pathops::PathOpsError as PathOperationError;
22
23/// `PathOperation` is how [`Path::combine`] joins the areas of two paths:
24/// Skia's `SkPathOp`, dart:ui's `PathOperation`.
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
26pub enum PathOperation {
27 /// `Difference` is the first path's area outside the second.
28 Difference,
29 /// `Intersect` is the area inside both paths.
30 Intersect,
31 /// `Union` is the area inside either path.
32 Union,
33 /// `Xor` is the area inside exactly one of the paths.
34 Xor,
35 /// `ReverseDifference` is the second path's area outside the first.
36 ReverseDifference,
37}
38
39impl Path {
40 /// `combine` is the area that `operation` makes of this path, filled with
41 /// `fill_rule`, and `other`, filled with `other_fill_rule`, as an outline
42 /// to fill with [`FillRule::EvenOdd`]: Skia's `Op`, which dart:ui's
43 /// `Path.combine` runs.
44 ///
45 /// Skia finds where the two paths' curves cross, in doubles and without
46 /// flattening them, and writes the pieces that bound the result as closed
47 /// contours of lines, quadratics, conics and cubics. The result is the one
48 /// Skia gives, point for point; it is a general path
49 /// ([`Self::as_oval`] and [`Self::as_round_rect`] are `None`), and empty
50 /// when the area is. Use it where an area must be cut from another, such
51 /// as a text field's outline around its label or a bottom bar's notch
52 /// around a button; for drawing alone, a clip or a second fill is cheaper.
53 ///
54 /// It fails where Skia's `Op` fails: see [`PathOperationError`].
55 pub fn combine(
56 &self,
57 fill_rule: FillRule,
58 operation: PathOperation,
59 other: &Path,
60 other_fill_rule: FillRule,
61 ) -> Result<Arc<Path>, PathOperationError> {
62 let result = valo_pathops::op(
63 &to_skia_path(self, fill_rule),
64 &to_skia_path(other, other_fill_rule),
65 to_skia_op(operation),
66 )?;
67 Ok(from_skia_path(&result))
68 }
69}
70
71fn to_skia_op(operation: PathOperation) -> SkPathOp {
72 match operation {
73 PathOperation::Difference => SkPathOp::Difference,
74 PathOperation::Intersect => SkPathOp::Intersect,
75 PathOperation::Union => SkPathOp::Union,
76 PathOperation::Xor => SkPathOp::Xor,
77 PathOperation::ReverseDifference => SkPathOp::ReverseDifference,
78 }
79}
80
81/// `to_skia_path` replays `path` into Skia's builder, which stores it as
82/// Skia would have stored the same commands: the two differ only where a
83/// valo path holds a move right after a move, which Skia's builder merges.
84fn to_skia_path(path: &Path, fill_rule: FillRule) -> SkPath {
85 let mut builder = SkPathBuilder::with_fill_type(match fill_rule {
86 FillRule::NonZero => SkPathFillType::Winding,
87 FillRule::EvenOdd => SkPathFillType::EvenOdd,
88 });
89 for element in path.elements() {
90 match element {
91 PathElement::MoveTo(p) => builder.move_to(to_skia_point(p)),
92 PathElement::LineTo(p) => builder.line_to(to_skia_point(p)),
93 PathElement::QuadTo(c, p) => builder.quad_to(to_skia_point(c), to_skia_point(p)),
94 PathElement::ConicTo(c, p, weight) => {
95 builder.conic_to(to_skia_point(c), to_skia_point(p), weight)
96 }
97 PathElement::CubicTo(c1, c2, p) => {
98 builder.cubic_to(to_skia_point(c1), to_skia_point(c2), to_skia_point(p))
99 }
100 PathElement::Close => builder.close(),
101 };
102 }
103 builder.detach()
104}
105
106/// `from_skia_path` is Skia's result as a valo path, verb for verb. Every
107/// contour Skia writes starts with a move and every conic weight it writes is
108/// positive and not 1, so the builder stores the verbs as given.
109fn from_skia_path(path: &SkPath) -> Arc<Path> {
110 let mut builder = PathBuilder::new();
111 let mut points = path.points().iter().map(|p| Point::new(p.x, p.y));
112 let mut weights = path.conic_weights().iter();
113 let mut next_point = || {
114 points
115 .next()
116 .expect("Skia's path has a point per verb point")
117 };
118 for verb in path.verbs() {
119 match verb {
120 SkPathVerb::Move => builder.move_to(next_point()),
121 SkPathVerb::Line => builder.line_to(next_point()),
122 SkPathVerb::Quad => {
123 let control = next_point();
124 builder.quad_to(control, next_point())
125 }
126 SkPathVerb::Conic => {
127 let control = next_point();
128 let weight = *weights.next().expect("Skia's path has a weight per conic");
129 builder.conic_to(control, next_point(), weight)
130 }
131 SkPathVerb::Cubic => {
132 let control1 = next_point();
133 let control2 = next_point();
134 builder.cubic_to(control1, control2, next_point())
135 }
136 SkPathVerb::Close => builder.close(),
137 };
138 }
139 builder.build()
140}
141
142fn to_skia_point(point: Point) -> SkPoint {
143 SkPoint {
144 x: point.x,
145 y: point.y,
146 }
147}