Skip to main content

rgpui/
path_builder.rs

1//! 路径构建器:矢量路径构建与「单调二次曲线轮廓」产出(环绕数路径渲染,D3)。
2//!
3//! 与旧实现的差异:不再用 lyon 镶嵌成三角形,而是把轮廓转成闭合的单调二次
4//! 曲线链,交由 `path_winding` 分桶、GPU 逐像素计算环绕数填充。描边与虚线
5//! 用 tiny-skia-path 展开成闭合轮廓后再走同一条填充管线。
6
7use 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
21/// PathBuilder 的样式。
22pub enum PathStyle {
23    /// 描边样式。
24    Stroke(StrokeOptions),
25    /// 填充样式。
26    Fill(FillOptions),
27}
28
29/// 描边参数。
30#[derive(Clone, Copy, Debug, PartialEq)]
31pub struct StrokeOptions {
32    /// 描边宽度。
33    pub line_width: f32,
34    /// 开放子路径与虚线端点的形状。
35    pub line_cap: LineCap,
36    /// 拐角形状。
37    pub line_join: LineJoin,
38    /// 斜接长度超过线宽的多少倍后改为斜切。
39    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    /// 设置描边宽度(与旧版 lyon 同名 builder 方法对齐,调用点无须改动)。
55    pub fn with_line_width(mut self, line_width: f32) -> Self {
56        self.line_width = line_width;
57        self
58    }
59
60    /// 设置端点形状。
61    pub fn with_line_cap(mut self, line_cap: LineCap) -> Self {
62        self.line_cap = line_cap;
63        self
64    }
65
66    /// 设置拐角形状。
67    pub fn with_line_join(mut self, line_join: LineJoin) -> Self {
68        self.line_join = line_join;
69        self
70    }
71
72    /// 设置斜接上限。
73    pub fn with_miter_limit(mut self, miter_limit: f32) -> Self {
74        self.miter_limit = miter_limit;
75        self
76    }
77}
78
79/// 填充参数。
80#[derive(Clone, Copy, Debug, PartialEq)]
81pub struct FillOptions {
82    /// 重叠轮廓合成填充区域的规则。
83    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    /// 设置填充规则。
96    pub fn with_fill_rule(mut self, fill_rule: FillRule) -> Self {
97        self.fill_rule = fill_rule;
98        self
99    }
100}
101
102/// [`Path`] 构建器。
103pub struct PathBuilder {
104    raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>,
105    transform: Option<lyon_path::math::Transform>,
106    /// PathBuilder 的 PathStyle。
107    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    /// 创建新的 [`PathBuilder`] 以构建描边路径。
166    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    /// 创建新的 [`PathBuilder`] 以构建填充路径。
177    pub fn fill() -> Self {
178        Self::default()
179    }
180
181    /// 设置 [`PathBuilder`] 的样式。
182    pub fn with_style(self, style: PathStyle) -> Self {
183        Self { style, ..self }
184    }
185
186    /// 设置 [`PathBuilder`] 的虚线数组。填充样式忽略虚线。
187    ///
188    /// [MDN](https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Attribute/stroke-dasharray)
189    pub fn dash_array(mut self, dash_array: &[Pixels]) -> Self {
190        // 如果提供奇数个值,则重复该值列表以产生偶数个值。
191        // 因此,5,3,2 等效于 5,3,2,5,3,2。
192        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    /// 将当前点移动到给定点。
205    #[inline]
206    pub fn move_to(&mut self, to: Point<Pixels>) {
207        self.raw.move_to(to.into());
208    }
209
210    /// 从当前点到给定点绘制直线。
211    #[inline]
212    pub fn line_to(&mut self, to: Point<Pixels>) {
213        self.raw.line_to(to.into());
214    }
215
216    /// 从当前点到给定点绘制曲线,使用给定的控制点。
217    #[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    /// 向 [`Path`] 添加三次贝塞尔曲线,给定其两个控制点和终点。
223    #[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    /// 添加椭圆弧。
235    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    /// 等效于相对坐标中的 `arc_to`。
252    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    /// 添加多边形。
269    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    /// 关闭当前子路径。
278    #[inline]
279    pub fn close(&mut self) {
280        self.raw.close();
281    }
282
283    /// 对路径应用变换。
284    #[inline]
285    pub fn transform(&mut self, transform: Transform) {
286        self.transform = Some(transform);
287    }
288
289    /// 对路径应用平移。
290    #[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    /// 对路径应用缩放。
300    #[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    /// 对路径应用旋转。
310    ///
311    /// `angle` 是以度为单位的值,范围为 0.0 到 360.0。
312    #[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    /// 构建为 [`Path`]。
323    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    /// 待填充的闭合轮廓曲线与填充规则。
329    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    /// 描边:用 tiny-skia 把路径展开成闭合轮廓(虚线先切再描),再转成单调曲线。
346    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                        // 非法虚线数组按无虚线描边(与 SVG 一致)。
360                        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    /// 把 lyon 路径转成填充轮廓(每个子路径闭合)。
407    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/// 一条填充路径:闭合的单调曲线轮廓(逻辑像素)。由 [`PathBuilder`] 构建。
426#[derive(Clone, Debug)]
427pub struct Path {
428    /// 闭合轮廓的单调曲线(逻辑像素)。
429    curves: Arc<[PathCurve]>,
430    /// 是否按奇偶规则填充。
431    even_odd: bool,
432}
433
434impl Path {
435    /// 由曲线与填充规则构建路径。
436    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    /// 是否按奇偶规则填充。
444    pub(crate) fn even_odd(&self) -> bool {
445        self.even_odd
446    }
447
448    /// 按给定显示比例把曲线分桶成设备像素瓦片,供绘制使用。
449    pub(crate) fn bin(&self, scale: f32) -> PathTiles {
450        crate::path_winding::bin(&self.curves, self.even_odd, scale)
451    }
452}
453
454/// [`PathBuilder`] 收集的路径轮廓:闭合的单调曲线链。
455#[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    /// 这些点全部有限时才能继续加入线段。
465    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    /// 关闭当前轮廓并在给定点开新轮廓。
473    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        /// 最大误差(逻辑像素)。
499        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    /// 用直线闭合当前轮廓回到起点。
519    pub(crate) fn close(&mut self) {
520        let start = self.start;
521        self.line_to(start);
522    }
523
524    /// 取曲线,所有轮廓均已闭合;含非有限坐标时整条路径失败。
525    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    /// 一条直线:二次项精确为零。
547    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    /// 在极值点拆分二次曲线,产出 xy 单调的曲线段。
560    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        // 不用 `split_range`:它会把舍入推出端点包围盒的控制点原样保留,
567        // 这里把控制点钳回端点盒。
568        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            // 水平曲线保留:向上的射线要与它交叉。
575            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
585/// 端点统一成「自上而下」方向,返回 (p0, p1, 符号)。
586fn 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
594/// 描边在逻辑像素中展开。tiny-skia 把偏移曲线保持在
595/// `0.25 / STROKE_RESOLUTION_SCALE` 精度内(2x 下为四分之一设备像素),并按
596/// `0.5 / STROKE_RESOLUTION_SCALE` 精度展平曲线以测量虚线。圆头/圆角忽略该
597/// 常量:其弧线按 0.25 逻辑像素近似。
598const STROKE_RESOLUTION_SCALE: f32 = 2.0;
599
600/// 空几何返回 [`None`]。
601fn 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}