Skip to main content

strata_gpu_path/
path.rs

1//! SVG path construction, verb sequence, and stroke/fill styling.
2
3use crate::curve::{CubicBezier, Point2D, QuadraticBezier, Rect2D};
4
5#[derive(Debug, Clone, Copy, PartialEq)]
6pub enum PathVerb {
7    MoveTo(Point2D),
8    LineTo(Point2D),
9    QuadTo(Point2D, Point2D),
10    CubicTo(Point2D, Point2D, Point2D),
11    Close,
12}
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum FillRule {
16    NonZero,
17    EvenOdd,
18}
19
20#[derive(Debug, Clone, Copy, PartialEq)]
21pub struct StrokeStyle {
22    pub width: f32,
23    pub miter_limit: f32,
24}
25
26impl Default for StrokeStyle {
27    fn default() -> Self {
28        Self {
29            width: 1.0,
30            miter_limit: 4.0,
31        }
32    }
33}
34
35/// A 2D vector path composed of a sequence of path verbs.
36#[derive(Debug, Clone, Default, PartialEq)]
37pub struct Path {
38    pub verbs: Vec<PathVerb>,
39    pub fill_rule: Option<FillRule>,
40    pub stroke: Option<StrokeStyle>,
41}
42
43impl Path {
44    pub fn new() -> Self {
45        Self::default()
46    }
47
48    pub fn with_fill(mut self, rule: FillRule) -> Self {
49        self.fill_rule = Some(rule);
50        self
51    }
52
53    pub fn with_stroke(mut self, stroke: StrokeStyle) -> Self {
54        self.stroke = Some(stroke);
55        self
56    }
57
58    /// Decomposes all path verbs into a flat sequence of Quadratic Bézier curves.
59    pub fn to_quadratics(&self, tolerance: f32) -> Vec<QuadraticBezier> {
60        let mut quadratics = Vec::new();
61        let mut current_pt = Point2D::new(0.0, 0.0);
62        let mut start_subpath = Point2D::new(0.0, 0.0);
63
64        for verb in &self.verbs {
65            match *verb {
66                PathVerb::MoveTo(pt) => {
67                    current_pt = pt;
68                    start_subpath = pt;
69                }
70                PathVerb::LineTo(pt) => {
71                    // Represent line segment as degenerate quadratic with control point at midpoint
72                    let mid = current_pt.lerp(pt, 0.5);
73                    quadratics.push(QuadraticBezier::new(current_pt, mid, pt));
74                    current_pt = pt;
75                }
76                PathVerb::QuadTo(p1, p2) => {
77                    quadratics.push(QuadraticBezier::new(current_pt, p1, p2));
78                    current_pt = p2;
79                }
80                PathVerb::CubicTo(p1, p2, p3) => {
81                    let cubic = CubicBezier::new(current_pt, p1, p2, p3);
82                    quadratics.extend(cubic.to_quadratics(tolerance));
83                    current_pt = p3;
84                }
85                PathVerb::Close => {
86                    if current_pt != start_subpath {
87                        let mid = current_pt.lerp(start_subpath, 0.5);
88                        quadratics.push(QuadraticBezier::new(current_pt, mid, start_subpath));
89                        current_pt = start_subpath;
90                    }
91                }
92            }
93        }
94
95        quadratics
96    }
97
98    /// Computes the bounding box for the entire path.
99    pub fn bounding_box(&self) -> Option<Rect2D> {
100        let quads = self.to_quadratics(0.1);
101        if quads.is_empty() {
102            return None;
103        }
104
105        let mut min_x = f32::INFINITY;
106        let mut min_y = f32::INFINITY;
107        let mut max_x = f32::NEG_INFINITY;
108        let mut max_y = f32::NEG_INFINITY;
109
110        for q in quads {
111            let bb = q.bounding_box();
112            min_x = min_x.min(bb.min_x);
113            min_y = min_y.min(bb.min_y);
114            max_x = max_x.max(bb.max_x);
115            max_y = max_y.max(bb.max_y);
116        }
117
118        Some(Rect2D::new(min_x, min_y, max_x, max_y))
119    }
120}
121
122/// Fluent builder for constructing vector paths, including SVG path string parsing.
123pub struct PathBuilder {
124    path: Path,
125}
126
127impl Default for PathBuilder {
128    fn default() -> Self {
129        Self::new()
130    }
131}
132
133impl PathBuilder {
134    pub fn new() -> Self {
135        Self { path: Path::new() }
136    }
137
138    pub fn move_to(mut self, x: f32, y: f32) -> Self {
139        self.path.verbs.push(PathVerb::MoveTo(Point2D::new(x, y)));
140        self
141    }
142
143    pub fn line_to(mut self, x: f32, y: f32) -> Self {
144        self.path.verbs.push(PathVerb::LineTo(Point2D::new(x, y)));
145        self
146    }
147
148    pub fn quad_to(mut self, cx: f32, cy: f32, x: f32, y: f32) -> Self {
149        self.path
150            .verbs
151            .push(PathVerb::QuadTo(Point2D::new(cx, cy), Point2D::new(x, y)));
152        self
153    }
154
155    pub fn cubic_to(mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32) -> Self {
156        self.path.verbs.push(PathVerb::CubicTo(
157            Point2D::new(c1x, c1y),
158            Point2D::new(c2x, c2y),
159            Point2D::new(x, y),
160        ));
161        self
162    }
163
164    pub fn close(mut self) -> Self {
165        self.path.verbs.push(PathVerb::Close);
166        self
167    }
168
169    pub fn fill(mut self, rule: FillRule) -> Self {
170        self.path.fill_rule = Some(rule);
171        self
172    }
173
174    pub fn stroke(mut self, style: StrokeStyle) -> Self {
175        self.path.stroke = Some(style);
176        self
177    }
178
179    pub fn build(self) -> Path {
180        self.path
181    }
182
183    /// Parses an SVG path data string (e.g. "M 10 20 L 50 60 Q 80 90 100 120 Z").
184    pub fn from_svg(svg_data: &str) -> Path {
185        let mut builder = PathBuilder::new();
186        let tokens: Vec<&str> = svg_data.split_whitespace().collect();
187        let mut idx = 0;
188
189        while idx < tokens.len() {
190            let cmd = tokens[idx];
191            idx += 1;
192
193            match cmd {
194                "M" | "m" if idx + 1 < tokens.len() => {
195                    let x: f32 = tokens[idx].parse().unwrap_or(0.0);
196                    let y: f32 = tokens[idx + 1].parse().unwrap_or(0.0);
197                    idx += 2;
198                    builder = builder.move_to(x, y);
199                }
200                "L" | "l" if idx + 1 < tokens.len() => {
201                    let x: f32 = tokens[idx].parse().unwrap_or(0.0);
202                    let y: f32 = tokens[idx + 1].parse().unwrap_or(0.0);
203                    idx += 2;
204                    builder = builder.line_to(x, y);
205                }
206                "Q" | "q" if idx + 3 < tokens.len() => {
207                    let cx: f32 = tokens[idx].parse().unwrap_or(0.0);
208                    let cy: f32 = tokens[idx + 1].parse().unwrap_or(0.0);
209                    let x: f32 = tokens[idx + 2].parse().unwrap_or(0.0);
210                    let y: f32 = tokens[idx + 3].parse().unwrap_or(0.0);
211                    idx += 4;
212                    builder = builder.quad_to(cx, cy, x, y);
213                }
214                "C" | "c" if idx + 5 < tokens.len() => {
215                    let c1x: f32 = tokens[idx].parse().unwrap_or(0.0);
216                    let c1y: f32 = tokens[idx + 1].parse().unwrap_or(0.0);
217                    let c2x: f32 = tokens[idx + 2].parse().unwrap_or(0.0);
218                    let c2y: f32 = tokens[idx + 3].parse().unwrap_or(0.0);
219                    let x: f32 = tokens[idx + 4].parse().unwrap_or(0.0);
220                    let y: f32 = tokens[idx + 5].parse().unwrap_or(0.0);
221                    idx += 6;
222                    builder = builder.cubic_to(c1x, c1y, c2x, c2y, x, y);
223                }
224                "Z" | "z" => {
225                    builder = builder.close();
226                }
227                _ => {}
228            }
229        }
230
231        builder.build()
232    }
233}