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