1use anyhow::{Error, bail};
2use etagere::euclid::{Point2D, Vector2D};
3use lyon_path::geom::{Angle, CubicBezierSegment, QuadraticBezierSegment};
4use lyon_path::math::{Vector, vector};
5use lyon_path::traits::SvgPathBuilder;
6use lyon_path::{ArcFlags, Event, Polygon};
7
8pub use lyon_path::math::Transform;
9pub use lyon_path::{FillRule, LineCap, LineJoin};
10
11use crate::{PathCurve, PathTiles, Pixels, Point, point, px};
12use std::sync::Arc;
13
14pub enum PathStyle {
16 Stroke(StrokeOptions),
18 Fill(FillOptions),
20}
21
22#[derive(Clone, Copy, Debug, PartialEq)]
24pub struct StrokeOptions {
25 pub line_width: f32,
27 pub line_cap: LineCap,
29 pub line_join: LineJoin,
31 pub miter_limit: f32,
34}
35
36impl Default for StrokeOptions {
37 fn default() -> Self {
38 Self {
39 line_width: 1.0,
40 line_cap: LineCap::Butt,
41 line_join: LineJoin::Miter,
42 miter_limit: 4.0,
43 }
44 }
45}
46
47#[derive(Clone, Copy, Debug, PartialEq)]
49pub struct FillOptions {
50 pub fill_rule: FillRule,
52}
53
54impl Default for FillOptions {
55 fn default() -> Self {
56 Self {
57 fill_rule: FillRule::EvenOdd,
58 }
59 }
60}
61
62pub struct PathBuilder {
64 raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>,
65 transform: Option<lyon_path::math::Transform>,
66 pub style: PathStyle,
68 dash_array: Option<Vec<Pixels>>,
69}
70
71impl From<lyon_path::Builder> for PathBuilder {
72 fn from(builder: lyon_path::Builder) -> Self {
73 Self {
74 raw: builder.with_svg(),
75 ..Default::default()
76 }
77 }
78}
79
80impl From<lyon_path::builder::WithSvg<lyon_path::BuilderImpl>> for PathBuilder {
81 fn from(raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>) -> Self {
82 Self {
83 raw,
84 ..Default::default()
85 }
86 }
87}
88
89impl From<lyon_path::math::Point> for Point<Pixels> {
90 fn from(p: lyon_path::math::Point) -> Self {
91 point(px(p.x), px(p.y))
92 }
93}
94
95impl From<Point<Pixels>> for lyon_path::math::Point {
96 fn from(p: Point<Pixels>) -> Self {
97 lyon_path::math::point(p.x.0, p.y.0)
98 }
99}
100
101impl From<Point<Pixels>> for Vector {
102 fn from(p: Point<Pixels>) -> Self {
103 vector(p.x.0, p.y.0)
104 }
105}
106
107impl From<Point<Pixels>> for Point2D<f32, Pixels> {
108 fn from(p: Point<Pixels>) -> Self {
109 Point2D::new(p.x.0, p.y.0)
110 }
111}
112
113impl Default for PathBuilder {
114 fn default() -> Self {
115 Self {
116 raw: lyon_path::Path::builder().with_svg(),
117 style: PathStyle::Fill(FillOptions::default()),
118 transform: None,
119 dash_array: None,
120 }
121 }
122}
123
124impl PathBuilder {
125 pub fn stroke(width: Pixels) -> Self {
127 Self {
128 style: PathStyle::Stroke(StrokeOptions {
129 line_width: width.0,
130 ..Default::default()
131 }),
132 ..Self::default()
133 }
134 }
135
136 pub fn fill() -> Self {
138 Self::default()
139 }
140
141 pub fn with_style(self, style: PathStyle) -> Self {
143 Self { style, ..self }
144 }
145
146 pub fn dash_array(mut self, dash_array: &[Pixels]) -> Self {
150 let array = if dash_array.len() % 2 == 1 {
153 let mut new_dash_array = dash_array.to_vec();
154 new_dash_array.extend_from_slice(dash_array);
155 new_dash_array
156 } else {
157 dash_array.to_vec()
158 };
159
160 self.dash_array = Some(array);
161 self
162 }
163
164 #[inline]
166 pub fn move_to(&mut self, to: Point<Pixels>) {
167 self.raw.move_to(to.into());
168 }
169
170 #[inline]
172 pub fn line_to(&mut self, to: Point<Pixels>) {
173 self.raw.line_to(to.into());
174 }
175
176 #[inline]
178 pub fn curve_to(&mut self, to: Point<Pixels>, ctrl: Point<Pixels>) {
179 self.raw.quadratic_bezier_to(ctrl.into(), to.into());
180 }
181
182 #[inline]
185 pub fn cubic_bezier_to(
186 &mut self,
187 to: Point<Pixels>,
188 control_a: Point<Pixels>,
189 control_b: Point<Pixels>,
190 ) {
191 self.raw
192 .cubic_bezier_to(control_a.into(), control_b.into(), to.into());
193 }
194
195 pub fn arc_to(
197 &mut self,
198 radii: Point<Pixels>,
199 x_rotation: Pixels,
200 large_arc: bool,
201 sweep: bool,
202 to: Point<Pixels>,
203 ) {
204 self.raw.arc_to(
205 radii.into(),
206 Angle::degrees(x_rotation.into()),
207 ArcFlags { large_arc, sweep },
208 to.into(),
209 );
210 }
211
212 pub fn relative_arc_to(
214 &mut self,
215 radii: Point<Pixels>,
216 x_rotation: Pixels,
217 large_arc: bool,
218 sweep: bool,
219 to: Point<Pixels>,
220 ) {
221 self.raw.relative_arc_to(
222 radii.into(),
223 Angle::degrees(x_rotation.into()),
224 ArcFlags { large_arc, sweep },
225 to.into(),
226 );
227 }
228
229 pub fn add_polygon(&mut self, points: &[Point<Pixels>], closed: bool) {
231 let points = points.iter().copied().map(|p| p.into()).collect::<Vec<_>>();
232 self.raw.add_polygon(Polygon {
233 points: points.as_ref(),
234 closed,
235 });
236 }
237
238 #[inline]
240 pub fn close(&mut self) {
241 self.raw.close();
242 }
243
244 #[inline]
246 pub fn transform(&mut self, transform: Transform) {
247 self.transform = Some(transform);
248 }
249
250 #[inline]
252 pub fn translate(&mut self, to: Point<Pixels>) {
253 if let Some(transform) = self.transform {
254 self.transform = Some(transform.then_translate(Vector2D::new(to.x.0, to.y.0)));
255 } else {
256 self.transform = Some(Transform::translation(to.x.0, to.y.0))
257 }
258 }
259
260 #[inline]
262 pub fn scale(&mut self, scale: f32) {
263 if let Some(transform) = self.transform {
264 self.transform = Some(transform.then_scale(scale, scale));
265 } else {
266 self.transform = Some(Transform::scale(scale, scale));
267 }
268 }
269
270 #[inline]
274 pub fn rotate(&mut self, angle: f32) {
275 let radians = angle.to_radians();
276 if let Some(transform) = self.transform {
277 self.transform = Some(transform.then_rotate(Angle::radians(radians)));
278 } else {
279 self.transform = Some(Transform::rotation(Angle::radians(radians)));
280 }
281 }
282
283 pub fn build(self) -> Result<Path, Error> {
285 let (curves, fill_rule) = self.outline()?;
286 Ok(Path::from_curves(curves, fill_rule))
287 }
288
289 pub(crate) fn outline(self) -> Result<(Vec<PathCurve>, FillRule), Error> {
291 let path = if let Some(transform) = self.transform {
292 self.raw.build().transformed(&transform)
293 } else {
294 self.raw.build()
295 };
296
297 Ok(match self.style {
298 PathStyle::Stroke(options) => (
299 Self::stroke_outline(&path, &options, self.dash_array.as_deref())?,
300 FillRule::NonZero,
301 ),
302 PathStyle::Fill(options) => (Self::fill_outline(&path)?, options.fill_rule),
303 })
304 }
305
306 fn stroke_outline(
307 path: &lyon_path::Path,
308 options: &StrokeOptions,
309 dash_array: Option<&[Pixels]>,
310 ) -> Result<Vec<PathCurve>, Error> {
311 let outline = skia_path(path)
312 .map(|skia_path| match dash_array {
313 Some(dash_array) => {
314 let array = dash_array.iter().map(|length| length.0).collect();
315 match tiny_skia_path::StrokeDash::new(array, 0.0) {
316 Some(dash) => skia_path
317 .dash(&dash, STROKE_RESOLUTION_SCALE)
318 .unwrap_or(skia_path),
319 None => skia_path,
321 }
322 }
323 None => skia_path,
324 })
325 .and_then(|skia_path| {
326 skia_path.stroke(
327 &tiny_skia_path::Stroke {
328 width: options.line_width,
329 miter_limit: options.miter_limit,
330 line_cap: match options.line_cap {
331 LineCap::Butt => tiny_skia_path::LineCap::Butt,
332 LineCap::Square => tiny_skia_path::LineCap::Square,
333 LineCap::Round => tiny_skia_path::LineCap::Round,
334 },
335 line_join: match options.line_join {
336 LineJoin::Miter => tiny_skia_path::LineJoin::Miter,
337 LineJoin::MiterClip => tiny_skia_path::LineJoin::MiterClip,
338 LineJoin::Round => tiny_skia_path::LineJoin::Round,
339 LineJoin::Bevel => tiny_skia_path::LineJoin::Bevel,
340 },
341 dash: None,
342 },
343 STROKE_RESOLUTION_SCALE,
344 )
345 });
346 let Some(outline) = outline else {
347 return Ok(Vec::new());
348 };
349
350 let mut output = Outline::default();
351 let at = |p: tiny_skia_path::Point| point(p.x, p.y);
352 for segment in outline.segments() {
353 match segment {
354 tiny_skia_path::PathSegment::MoveTo(p) => output.move_to(at(p)),
355 tiny_skia_path::PathSegment::LineTo(p) => output.line_to(at(p)),
356 tiny_skia_path::PathSegment::QuadTo(ctrl, p) => output.curve_to(at(p), at(ctrl)),
357 tiny_skia_path::PathSegment::CubicTo(ctrl1, ctrl2, p) => {
358 output.cubic_to(at(p), at(ctrl1), at(ctrl2))
359 }
360 tiny_skia_path::PathSegment::Close => output.close(),
361 }
362 }
363 output.into_curves()
364 }
365
366 fn fill_outline(path: &lyon_path::Path) -> Result<Vec<PathCurve>, Error> {
368 let mut output = Outline::default();
369 let at = |p: lyon_path::math::Point| point(p.x, p.y);
370 for event in path.iter() {
371 match event {
372 Event::Begin { at: p } => output.move_to(at(p)),
373 Event::Line { to, .. } => output.line_to(at(to)),
374 Event::Quadratic { ctrl, to, .. } => output.curve_to(at(to), at(ctrl)),
375 Event::Cubic {
376 ctrl1, ctrl2, to, ..
377 } => output.cubic_to(at(to), at(ctrl1), at(ctrl2)),
378 Event::End { .. } => output.close(),
379 }
380 }
381 output.into_curves()
382 }
383}
384
385#[derive(Clone, Debug)]
387pub struct Path {
388 curves: Arc<[PathCurve]>,
390 even_odd: bool,
391}
392
393impl Path {
394 pub(crate) fn from_curves(curves: Vec<PathCurve>, fill_rule: FillRule) -> Self {
395 Self {
396 curves: curves.into(),
397 even_odd: matches!(fill_rule, FillRule::EvenOdd),
398 }
399 }
400
401 pub(crate) fn even_odd(&self) -> bool {
402 self.even_odd
403 }
404
405 pub(crate) fn bin(&self, scale: f32) -> PathTiles {
408 crate::path_winding::bin(&self.curves, self.even_odd, scale)
409 }
410
411 pub(crate) fn transformed(&self, matrix: crate::TransformationMatrix, scale: f32) -> Self {
416 let map = |p: Point<f32>| {
417 let moved = matrix.apply(point(Pixels(p.x * scale), Pixels(p.y * scale)));
418 point(moved.x.0 / scale, moved.y.0 / scale)
419 };
420 let mut curves = Vec::with_capacity(self.curves.len());
421 for curve in self.curves.iter() {
422 let (from, to) = if curve.sign < 0.0 {
423 (curve.p1, curve.p0)
424 } else {
425 (curve.p0, curve.p1)
426 };
427 if curve.a == point(0.0, 0.0) {
428 let (from, to) = (map(from), map(to));
429 if from != to {
430 curves.push(PathCurve::line(from, to));
431 }
432 } else {
433 let ctrl = point(curve.p0.x + curve.b.x / 2.0, curve.p0.y + curve.b.y / 2.0);
434 PathCurve::push_monotone(&mut curves, map(from), map(ctrl), map(to));
435 }
436 }
437 Self {
438 curves: curves.into(),
439 even_odd: self.even_odd,
440 }
441 }
442}
443
444#[derive(Default)]
446pub(crate) struct Outline {
447 curves: Vec<PathCurve>,
448 start: Point<f32>,
449 current: Point<f32>,
450 non_finite: bool,
451}
452
453impl Outline {
454 fn accepts(&mut self, points: &[Point<f32>]) -> bool {
456 self.non_finite |= !points
457 .iter()
458 .all(|point| point.x.is_finite() && point.y.is_finite());
459 !self.non_finite
460 }
461
462 pub(crate) fn move_to(&mut self, to: Point<f32>) {
464 if !self.accepts(&[to]) {
465 return;
466 }
467 self.close();
468 self.start = to;
469 self.current = to;
470 }
471
472 pub(crate) fn line_to(&mut self, to: Point<f32>) {
473 if self.accepts(&[to]) && to != self.current {
474 self.curves.push(PathCurve::line(self.current, to));
475 self.current = to;
476 }
477 }
478
479 pub(crate) fn curve_to(&mut self, to: Point<f32>, ctrl: Point<f32>) {
480 if !self.accepts(&[to, ctrl]) || (to == self.current && ctrl == self.current) {
481 return;
482 }
483 PathCurve::push_monotone(&mut self.curves, self.current, ctrl, to);
484 self.current = to;
485 }
486
487 pub(crate) fn cubic_to(&mut self, to: Point<f32>, ctrl1: Point<f32>, ctrl2: Point<f32>) {
488 const TOLERANCE: f32 = 0.25;
490 if !self.accepts(&[to, ctrl1, ctrl2]) {
491 return;
492 }
493 let lyon_point = |p: Point<f32>| lyon_path::math::point(p.x, p.y);
494 let cubic = CubicBezierSegment {
495 from: lyon_point(self.current),
496 ctrl1: lyon_point(ctrl1),
497 ctrl2: lyon_point(ctrl2),
498 to: lyon_point(to),
499 };
500 cubic.for_each_quadratic_bezier(TOLERANCE, &mut |quadratic| {
501 self.curve_to(
502 point(quadratic.to.x, quadratic.to.y),
503 point(quadratic.ctrl.x, quadratic.ctrl.y),
504 );
505 });
506 }
507
508 pub(crate) fn close(&mut self) {
510 let start = self.start;
511 self.line_to(start);
512 }
513
514 pub(crate) fn into_curves(mut self) -> Result<Vec<PathCurve>, Error> {
516 if self.non_finite {
517 bail!("path has a non-finite point");
518 }
519 self.close();
520 Ok(self.curves)
521 }
522}
523
524impl PathCurve {
525 fn new(p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>, sign: f32) -> Self {
526 Self {
527 p0,
528 p1,
529 a: point(p0.x - 2.0 * ctrl.x + p1.x, p0.y - 2.0 * ctrl.y + p1.y),
530 b: point(2.0 * (ctrl.x - p0.x), 2.0 * (ctrl.y - p0.y)),
531 sign,
532 pad: 0,
533 }
534 }
535
536 fn line(from: Point<f32>, to: Point<f32>) -> Self {
538 let (p0, p1, sign) = downward(from, to);
539 Self {
540 p0,
541 p1,
542 a: point(0.0, 0.0),
543 b: point(p1.x - p0.x, p1.y - p0.y),
544 sign,
545 pad: 0,
546 }
547 }
548
549 fn push_monotone(curves: &mut Vec<Self>, p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>) {
551 let curve = QuadraticBezierSegment {
552 from: lyon_path::math::point(p0.x, p0.y),
553 ctrl: lyon_path::math::point(ctrl.x, ctrl.y),
554 to: lyon_path::math::point(p1.x, p1.y),
555 };
556 curve.for_each_monotonic(&mut |monotone| {
559 let from = point(monotone.from.x, monotone.from.y);
560 let to = point(monotone.to.x, monotone.to.y);
561 if from == to {
562 return;
563 }
564 let (p0, p1, sign) = downward(from, to);
566 let ctrl = point(
567 monotone.ctrl.x.clamp(p0.x.min(p1.x), p0.x.max(p1.x)),
568 monotone.ctrl.y.clamp(p0.y, p1.y),
569 );
570 curves.push(Self::new(p0, ctrl, p1, sign));
571 });
572 }
573}
574
575fn downward(from: Point<f32>, to: Point<f32>) -> (Point<f32>, Point<f32>, f32) {
576 if from.y > to.y {
577 (to, from, -1.0)
578 } else {
579 (from, to, 1.0)
580 }
581}
582
583const STROKE_RESOLUTION_SCALE: f32 = 2.0;
589
590fn skia_path(path: &lyon_path::Path) -> Option<tiny_skia_path::Path> {
592 let mut builder = tiny_skia_path::PathBuilder::new();
593 for event in path.iter() {
594 match event {
595 Event::Begin { at } => builder.move_to(at.x, at.y),
596 Event::Line { to, .. } => builder.line_to(to.x, to.y),
597 Event::Quadratic { ctrl, to, .. } => builder.quad_to(ctrl.x, ctrl.y, to.x, to.y),
598 Event::Cubic {
599 ctrl1, ctrl2, to, ..
600 } => builder.cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y),
601 Event::End { close, .. } => {
602 if close {
603 builder.close();
604 }
605 }
606 }
607 }
608 builder.finish()
609}