Skip to main content

cranpose_ui_graphics/
vector_path.rs

1//! SVG path-data (`d` attribute) parsing and CPU fill rasterization.
2//!
3//! [`VectorPath`] parses the SVG path mini-language
4//! (`M/m L/l H/h V/v C/c S/s Q/q T/t A/a Z/z`) into subpaths flattened to
5//! polylines: curves are subdivided adaptively, arcs are converted via the
6//! W3C endpoint-to-center parameterization and sampled. Fills are rendered
7//! with an anti-aliased scanline rasterizer into a coverage mask, which the
8//! draw pipeline turns into an [`crate::ImageBitmap`] primitive — so every
9//! render backend gets vector shapes without new renderer primitives.
10//!
11//! Parse once (`VectorPath::parse`), draw per frame
12//! (`DrawScope::draw_vector_path`); the one-shot
13//! `DrawScope::draw_svg_path(d, brush)` convenience re-parses each call.
14
15use crate::geometry::{Point, Rect};
16use thiserror::Error;
17
18/// Maximum recursion depth for adaptive curve flattening.
19const MAX_FLATTEN_DEPTH: u32 = 12;
20/// Curve flattening tolerance in path units.
21const FLATTEN_TOLERANCE: f32 = 0.05;
22/// Arc sampling: maximum angle step per segment.
23const ARC_MAX_ANGLE_STEP: f32 = std::f32::consts::PI / 16.0;
24/// Anti-aliasing sub-scanlines per pixel row.
25const SUBSAMPLES: usize = 4;
26
27/// Errors produced while parsing SVG path data.
28#[derive(Debug, Clone, PartialEq, Eq, Error)]
29pub enum SvgPathError {
30    #[error("unexpected byte {byte:?} at offset {offset}")]
31    UnexpectedByte { byte: char, offset: usize },
32    #[error("expected a number at offset {offset}")]
33    ExpectedNumber { offset: usize },
34    #[error("expected an arc flag (0 or 1) at offset {offset}")]
35    ExpectedFlag { offset: usize },
36    #[error("path data must start with a moveto (M/m) command")]
37    MissingMoveTo,
38}
39
40/// Fill rule for [`VectorPath`] rasterization.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub enum PathFillRule {
43    /// Fill where the winding number is non-zero (SVG default).
44    #[default]
45    NonZero,
46    /// Fill where a ray crosses an odd number of edges.
47    EvenOdd,
48}
49
50/// A parsed SVG path: subpaths flattened to polylines, ready to fill.
51#[derive(Debug, Clone)]
52pub struct VectorPath {
53    /// Flattened subpaths. Fill treats every subpath as closed.
54    subpaths: Vec<Vec<Point>>,
55    fill_rule: PathFillRule,
56    bounds: Rect,
57}
58
59impl VectorPath {
60    /// Parses SVG path data (the `d` attribute syntax).
61    pub fn parse(d: &str) -> Result<Self, SvgPathError> {
62        let subpaths = parse_path_data(d)?;
63        Ok(Self::from_subpaths(subpaths, PathFillRule::NonZero))
64    }
65
66    /// Parses SVG path data with an explicit fill rule.
67    pub fn parse_with_fill_rule(d: &str, fill_rule: PathFillRule) -> Result<Self, SvgPathError> {
68        let subpaths = parse_path_data(d)?;
69        Ok(Self::from_subpaths(subpaths, fill_rule))
70    }
71
72    fn from_subpaths(subpaths: Vec<Vec<Point>>, fill_rule: PathFillRule) -> Self {
73        let mut min = Point::new(f32::INFINITY, f32::INFINITY);
74        let mut max = Point::new(f32::NEG_INFINITY, f32::NEG_INFINITY);
75        for point in subpaths.iter().flatten() {
76            min.x = min.x.min(point.x);
77            min.y = min.y.min(point.y);
78            max.x = max.x.max(point.x);
79            max.y = max.y.max(point.y);
80        }
81        let bounds = if min.x.is_finite() {
82            Rect {
83                x: min.x,
84                y: min.y,
85                width: (max.x - min.x).max(0.0),
86                height: (max.y - min.y).max(0.0),
87            }
88        } else {
89            Rect {
90                x: 0.0,
91                y: 0.0,
92                width: 0.0,
93                height: 0.0,
94            }
95        };
96        Self {
97            subpaths,
98            fill_rule,
99            bounds,
100        }
101    }
102
103    /// Returns a copy using the given fill rule.
104    pub fn with_fill_rule(mut self, fill_rule: PathFillRule) -> Self {
105        self.fill_rule = fill_rule;
106        self
107    }
108
109    /// Returns a uniformly scaled copy (icon path data drawn at a target
110    /// size: `parse(d)?.scaled(size / view_box)`).
111    pub fn scaled(&self, factor: f32) -> Self {
112        let subpaths = self
113            .subpaths
114            .iter()
115            .map(|subpath| {
116                subpath
117                    .iter()
118                    .map(|point| Point::new(point.x * factor, point.y * factor))
119                    .collect()
120            })
121            .collect();
122        Self::from_subpaths(subpaths, self.fill_rule)
123    }
124
125    /// The fill rule used by [`coverage_mask`](Self::coverage_mask).
126    pub fn fill_rule(&self) -> PathFillRule {
127        self.fill_rule
128    }
129
130    /// Tight bounding box of the flattened path, in path units.
131    pub fn bounds(&self) -> Rect {
132        self.bounds
133    }
134
135    /// Whether the path contains no fillable geometry.
136    pub fn is_empty(&self) -> bool {
137        !self.subpaths.iter().any(|subpath| subpath.len() >= 3)
138    }
139
140    /// Flattened subpaths (each is filled as a closed polygon).
141    pub fn subpaths(&self) -> &[Vec<Point>] {
142        &self.subpaths
143    }
144
145    /// Rasterizes the fill into an anti-aliased 8-bit coverage mask of
146    /// `width x height` pixels. A path point `p` maps to the pixel-space
147    /// position `(p - origin) * scale`.
148    pub fn coverage_mask(&self, width: usize, height: usize, origin: Point, scale: f32) -> Vec<u8> {
149        let mut mask = vec![0u8; width * height];
150        if width == 0 || height == 0 || scale <= 0.0 {
151            return mask;
152        }
153
154        // Collect pixel-space edges from all subpaths (implicitly closed).
155        struct Edge {
156            top: Point,
157            bottom: Point,
158            /// +1 when the original edge points downward (top -> bottom),
159            /// -1 when it points upward.
160            winding: i32,
161        }
162        let mut edges = Vec::new();
163        for subpath in &self.subpaths {
164            if subpath.len() < 3 {
165                continue;
166            }
167            let map = |p: &Point| Point::new((p.x - origin.x) * scale, (p.y - origin.y) * scale);
168            for i in 0..subpath.len() {
169                let a = map(&subpath[i]);
170                let b = map(&subpath[(i + 1) % subpath.len()]);
171                if a.y == b.y {
172                    continue;
173                }
174                if a.y < b.y {
175                    edges.push(Edge {
176                        top: a,
177                        bottom: b,
178                        winding: 1,
179                    });
180                } else {
181                    edges.push(Edge {
182                        top: b,
183                        bottom: a,
184                        winding: -1,
185                    });
186                }
187            }
188        }
189        if edges.is_empty() {
190            return mask;
191        }
192
193        let mut crossings: Vec<(f32, i32)> = Vec::new();
194        let mut row_coverage = vec![0.0f32; width];
195        let subsample_weight = 1.0 / SUBSAMPLES as f32;
196
197        for row in 0..height {
198            row_coverage.fill(0.0);
199            let mut row_touched = false;
200
201            for sub in 0..SUBSAMPLES {
202                let sample_y = row as f32 + (sub as f32 + 0.5) * subsample_weight;
203
204                crossings.clear();
205                for edge in &edges {
206                    if edge.top.y <= sample_y && sample_y < edge.bottom.y {
207                        let t = (sample_y - edge.top.y) / (edge.bottom.y - edge.top.y);
208                        let x = edge.top.x + t * (edge.bottom.x - edge.top.x);
209                        crossings.push((x, edge.winding));
210                    }
211                }
212                if crossings.len() < 2 {
213                    continue;
214                }
215                crossings.sort_by(|a, b| a.0.total_cmp(&b.0));
216
217                // Walk crossings, accumulating spans per fill rule.
218                let mut winding = 0i32;
219                let mut span_start = 0.0f32;
220                for &(x, direction) in crossings.iter() {
221                    let was_inside = match self.fill_rule {
222                        PathFillRule::NonZero => winding != 0,
223                        PathFillRule::EvenOdd => winding % 2 != 0,
224                    };
225                    winding += match self.fill_rule {
226                        PathFillRule::NonZero => direction,
227                        PathFillRule::EvenOdd => 1,
228                    };
229                    let is_inside = match self.fill_rule {
230                        PathFillRule::NonZero => winding != 0,
231                        PathFillRule::EvenOdd => winding % 2 != 0,
232                    };
233                    if !was_inside && is_inside {
234                        span_start = x;
235                    } else if was_inside && !is_inside {
236                        row_touched |= accumulate_span(
237                            &mut row_coverage,
238                            span_start,
239                            x,
240                            subsample_weight,
241                            width,
242                        );
243                    }
244                }
245            }
246
247            if row_touched {
248                let mask_row = &mut mask[row * width..(row + 1) * width];
249                for (dst, coverage) in mask_row.iter_mut().zip(row_coverage.iter()) {
250                    let existing = *dst as f32 / 255.0;
251                    let combined = (existing + coverage).min(1.0);
252                    *dst = (combined * 255.0 + 0.5) as u8;
253                }
254            }
255        }
256
257        mask
258    }
259}
260
261/// Adds one horizontal span `[x0, x1)` of one sub-scanline into the row
262/// coverage accumulator, handling fractional span ends. Returns whether any
263/// pixel was touched.
264fn accumulate_span(row_coverage: &mut [f32], x0: f32, x1: f32, weight: f32, width: usize) -> bool {
265    let x0 = x0.max(0.0);
266    let x1 = x1.min(width as f32);
267    if x1 <= x0 {
268        return false;
269    }
270
271    let first = x0.floor() as usize;
272    let last = (x1.ceil() as usize).min(width);
273    for (pixel, coverage) in row_coverage.iter_mut().enumerate().take(last).skip(first) {
274        let pixel_start = pixel as f32;
275        let pixel_end = pixel_start + 1.0;
276        let covered = (x1.min(pixel_end) - x0.max(pixel_start)).max(0.0);
277        *coverage += covered * weight;
278    }
279    true
280}
281
282// ============================================================================
283// Path data parsing
284// ============================================================================
285
286struct PathLexer<'a> {
287    bytes: &'a [u8],
288    pos: usize,
289}
290
291impl<'a> PathLexer<'a> {
292    fn new(d: &'a str) -> Self {
293        Self {
294            bytes: d.as_bytes(),
295            pos: 0,
296        }
297    }
298
299    fn skip_separators(&mut self) {
300        while self.pos < self.bytes.len() {
301            match self.bytes[self.pos] {
302                b' ' | b'\t' | b'\r' | b'\n' | b',' => self.pos += 1,
303                _ => break,
304            }
305        }
306    }
307
308    fn peek(&mut self) -> Option<u8> {
309        self.skip_separators();
310        self.bytes.get(self.pos).copied()
311    }
312
313    /// Whether the next token can start a number.
314    fn at_number(&mut self) -> bool {
315        matches!(self.peek(), Some(b'0'..=b'9' | b'.' | b'-' | b'+'))
316    }
317
318    fn next_command(&mut self) -> Option<u8> {
319        let byte = self.peek()?;
320        if byte.is_ascii_alphabetic() {
321            self.pos += 1;
322            Some(byte)
323        } else {
324            None
325        }
326    }
327
328    /// Parses one SVG number: `[+-]? (digits [. digits?]? | . digits) exponent?`.
329    /// A second `.` terminates the number, so `1.5.5` lexes as `1.5`, `.5`.
330    fn next_number(&mut self) -> Result<f32, SvgPathError> {
331        self.skip_separators();
332        let start = self.pos;
333        let bytes = self.bytes;
334        let mut pos = self.pos;
335
336        if pos < bytes.len() && (bytes[pos] == b'+' || bytes[pos] == b'-') {
337            pos += 1;
338        }
339        let int_digits = Self::eat_digits(bytes, &mut pos);
340        let mut frac_digits = 0;
341        if pos < bytes.len() && bytes[pos] == b'.' {
342            pos += 1;
343            frac_digits = Self::eat_digits(bytes, &mut pos);
344        }
345        if int_digits == 0 && frac_digits == 0 {
346            return Err(SvgPathError::ExpectedNumber { offset: start });
347        }
348        if pos < bytes.len() && (bytes[pos] == b'e' || bytes[pos] == b'E') {
349            let mut exp_pos = pos + 1;
350            if exp_pos < bytes.len() && (bytes[exp_pos] == b'+' || bytes[exp_pos] == b'-') {
351                exp_pos += 1;
352            }
353            if Self::eat_digits(bytes, &mut exp_pos) > 0 {
354                pos = exp_pos;
355            }
356        }
357
358        let text = std::str::from_utf8(&bytes[start..pos])
359            .map_err(|_| SvgPathError::ExpectedNumber { offset: start })?;
360        let value = text
361            .parse::<f32>()
362            .map_err(|_| SvgPathError::ExpectedNumber { offset: start })?;
363        self.pos = pos;
364        Ok(value)
365    }
366
367    fn eat_digits(bytes: &[u8], pos: &mut usize) -> usize {
368        let start = *pos;
369        while *pos < bytes.len() && bytes[*pos].is_ascii_digit() {
370            *pos += 1;
371        }
372        *pos - start
373    }
374
375    /// Arc flags are single characters and may be packed (`110 10` etc).
376    fn next_flag(&mut self) -> Result<bool, SvgPathError> {
377        self.skip_separators();
378        match self.bytes.get(self.pos) {
379            Some(b'0') => {
380                self.pos += 1;
381                Ok(false)
382            }
383            Some(b'1') => {
384                self.pos += 1;
385                Ok(true)
386            }
387            _ => Err(SvgPathError::ExpectedFlag { offset: self.pos }),
388        }
389    }
390
391    fn at_end(&mut self) -> bool {
392        self.peek().is_none()
393    }
394}
395
396struct PathBuilder {
397    subpaths: Vec<Vec<Point>>,
398    current: Vec<Point>,
399    position: Point,
400    subpath_start: Point,
401    /// Reflection anchors for smooth curves (S/T).
402    last_cubic_control: Option<Point>,
403    last_quad_control: Option<Point>,
404}
405
406impl PathBuilder {
407    fn new() -> Self {
408        Self {
409            subpaths: Vec::new(),
410            current: Vec::new(),
411            position: Point::ZERO,
412            subpath_start: Point::ZERO,
413            last_cubic_control: None,
414            last_quad_control: None,
415        }
416    }
417
418    fn flush_subpath(&mut self) {
419        if self.current.len() >= 2 {
420            self.subpaths.push(std::mem::take(&mut self.current));
421        } else {
422            self.current.clear();
423        }
424    }
425
426    fn move_to(&mut self, point: Point) {
427        self.flush_subpath();
428        self.position = point;
429        self.subpath_start = point;
430        self.current.push(point);
431    }
432
433    fn line_to(&mut self, point: Point) {
434        if self.current.is_empty() {
435            self.current.push(self.position);
436        }
437        self.current.push(point);
438        self.position = point;
439    }
440
441    fn close(&mut self) {
442        self.position = self.subpath_start;
443        self.flush_subpath();
444        // Commands after Z continue from the subpath start.
445        self.current.push(self.subpath_start);
446    }
447
448    fn finish(mut self) -> Vec<Vec<Point>> {
449        self.flush_subpath();
450        self.subpaths
451    }
452}
453
454fn parse_path_data(d: &str) -> Result<Vec<Vec<Point>>, SvgPathError> {
455    let mut lexer = PathLexer::new(d);
456    let mut builder = PathBuilder::new();
457    let mut command: Option<u8> = None;
458    let mut seen_moveto = false;
459
460    loop {
461        if lexer.at_end() {
462            break;
463        }
464
465        if let Some(next) = lexer.next_command() {
466            command = Some(next);
467        } else if command.is_none() || !lexer.at_number() {
468            let offset = lexer.pos;
469            let byte = lexer.bytes.get(offset).copied().unwrap_or(b'?') as char;
470            return Err(SvgPathError::UnexpectedByte { byte, offset });
471        }
472
473        let Some(cmd) = command else {
474            return Err(SvgPathError::MissingMoveTo);
475        };
476        if !seen_moveto && !matches!(cmd, b'M' | b'm') {
477            return Err(SvgPathError::MissingMoveTo);
478        }
479        let relative = cmd.is_ascii_lowercase();
480        let pos = builder.position;
481        let rel = |value: Point| {
482            if relative {
483                Point::new(pos.x + value.x, pos.y + value.y)
484            } else {
485                value
486            }
487        };
488
489        match cmd.to_ascii_uppercase() {
490            b'M' => {
491                let point = rel(read_point(&mut lexer)?);
492                builder.move_to(point);
493                seen_moveto = true;
494                builder.last_cubic_control = None;
495                builder.last_quad_control = None;
496                // Extra coordinate pairs are implicit linetos.
497                command = Some(if relative { b'l' } else { b'L' });
498            }
499            b'L' => {
500                let point = rel(read_point(&mut lexer)?);
501                builder.line_to(point);
502                builder.last_cubic_control = None;
503                builder.last_quad_control = None;
504            }
505            b'H' => {
506                let x = lexer.next_number()?;
507                let x = if relative { pos.x + x } else { x };
508                builder.line_to(Point::new(x, pos.y));
509                builder.last_cubic_control = None;
510                builder.last_quad_control = None;
511            }
512            b'V' => {
513                let y = lexer.next_number()?;
514                let y = if relative { pos.y + y } else { y };
515                builder.line_to(Point::new(pos.x, y));
516                builder.last_cubic_control = None;
517                builder.last_quad_control = None;
518            }
519            b'C' => {
520                let c1 = rel(read_point(&mut lexer)?);
521                let c2 = rel(read_point(&mut lexer)?);
522                let end = rel(read_point(&mut lexer)?);
523                emit_cubic(&mut builder, c1, c2, end);
524            }
525            b'S' => {
526                let c1 = match builder.last_cubic_control {
527                    Some(control) => reflect(pos, control),
528                    None => pos,
529                };
530                let c2 = rel(read_point(&mut lexer)?);
531                let end = rel(read_point(&mut lexer)?);
532                emit_cubic(&mut builder, c1, c2, end);
533            }
534            b'Q' => {
535                let control = rel(read_point(&mut lexer)?);
536                let end = rel(read_point(&mut lexer)?);
537                emit_quad(&mut builder, control, end);
538            }
539            b'T' => {
540                let control = match builder.last_quad_control {
541                    Some(control) => reflect(pos, control),
542                    None => pos,
543                };
544                let end = rel(read_point(&mut lexer)?);
545                emit_quad(&mut builder, control, end);
546            }
547            b'A' => {
548                let rx = lexer.next_number()?;
549                let ry = lexer.next_number()?;
550                let x_rotation_deg = lexer.next_number()?;
551                let large_arc = lexer.next_flag()?;
552                let sweep = lexer.next_flag()?;
553                let end = rel(read_point(&mut lexer)?);
554                emit_arc(&mut builder, rx, ry, x_rotation_deg, large_arc, sweep, end);
555                builder.last_cubic_control = None;
556                builder.last_quad_control = None;
557            }
558            b'Z' => {
559                builder.close();
560                builder.last_cubic_control = None;
561                builder.last_quad_control = None;
562                // Z takes no arguments; require an explicit next command.
563                command = None;
564            }
565            other => {
566                return Err(SvgPathError::UnexpectedByte {
567                    byte: other as char,
568                    offset: lexer.pos.saturating_sub(1),
569                });
570            }
571        }
572    }
573
574    if !seen_moveto {
575        return Err(SvgPathError::MissingMoveTo);
576    }
577    Ok(builder.finish())
578}
579
580fn read_point(lexer: &mut PathLexer<'_>) -> Result<Point, SvgPathError> {
581    let x = lexer.next_number()?;
582    let y = lexer.next_number()?;
583    Ok(Point::new(x, y))
584}
585
586fn reflect(origin: Point, point: Point) -> Point {
587    Point::new(2.0 * origin.x - point.x, 2.0 * origin.y - point.y)
588}
589
590fn emit_cubic(builder: &mut PathBuilder, c1: Point, c2: Point, end: Point) {
591    let start = builder.position;
592    flatten_cubic(builder, start, c1, c2, end, 0);
593    builder.position = end;
594    builder.last_cubic_control = Some(c2);
595    builder.last_quad_control = None;
596}
597
598fn emit_quad(builder: &mut PathBuilder, control: Point, end: Point) {
599    // Elevate the quadratic to a cubic and reuse the cubic flattener.
600    let start = builder.position;
601    let c1 = Point::new(
602        start.x + 2.0 / 3.0 * (control.x - start.x),
603        start.y + 2.0 / 3.0 * (control.y - start.y),
604    );
605    let c2 = Point::new(
606        end.x + 2.0 / 3.0 * (control.x - end.x),
607        end.y + 2.0 / 3.0 * (control.y - end.y),
608    );
609    flatten_cubic(builder, start, c1, c2, end, 0);
610    builder.position = end;
611    builder.last_quad_control = Some(control);
612    builder.last_cubic_control = None;
613}
614
615fn flatten_cubic(
616    builder: &mut PathBuilder,
617    p0: Point,
618    p1: Point,
619    p2: Point,
620    p3: Point,
621    depth: u32,
622) {
623    if depth >= MAX_FLATTEN_DEPTH || cubic_is_flat(p0, p1, p2, p3) {
624        builder.line_to(p3);
625        return;
626    }
627
628    let mid = |a: Point, b: Point| Point::new((a.x + b.x) * 0.5, (a.y + b.y) * 0.5);
629    let p01 = mid(p0, p1);
630    let p12 = mid(p1, p2);
631    let p23 = mid(p2, p3);
632    let p012 = mid(p01, p12);
633    let p123 = mid(p12, p23);
634    let p0123 = mid(p012, p123);
635
636    flatten_cubic(builder, p0, p01, p012, p0123, depth + 1);
637    flatten_cubic(builder, p0123, p123, p23, p3, depth + 1);
638}
639
640/// Flatness test: both control points close enough to the chord.
641fn cubic_is_flat(p0: Point, p1: Point, p2: Point, p3: Point) -> bool {
642    let d1 = point_to_chord_distance_squared(p1, p0, p3);
643    let d2 = point_to_chord_distance_squared(p2, p0, p3);
644    let tolerance = FLATTEN_TOLERANCE * FLATTEN_TOLERANCE;
645    d1 <= tolerance && d2 <= tolerance
646}
647
648fn point_to_chord_distance_squared(point: Point, a: Point, b: Point) -> f32 {
649    let ab = Point::new(b.x - a.x, b.y - a.y);
650    let ap = Point::new(point.x - a.x, point.y - a.y);
651    let ab_len_sq = ab.x * ab.x + ab.y * ab.y;
652    if ab_len_sq <= f32::EPSILON {
653        return ap.x * ap.x + ap.y * ap.y;
654    }
655    let cross = ab.x * ap.y - ab.y * ap.x;
656    cross * cross / ab_len_sq
657}
658
659/// Converts an SVG endpoint-parameterized arc to line segments
660/// (W3C SVG 2 appendix B.2.4).
661fn emit_arc(
662    builder: &mut PathBuilder,
663    rx: f32,
664    ry: f32,
665    x_rotation_deg: f32,
666    large_arc: bool,
667    sweep: bool,
668    end: Point,
669) {
670    let start = builder.position;
671    if (start.x - end.x).abs() <= f32::EPSILON && (start.y - end.y).abs() <= f32::EPSILON {
672        return;
673    }
674    let mut rx = rx.abs();
675    let mut ry = ry.abs();
676    if rx <= f32::EPSILON || ry <= f32::EPSILON {
677        builder.line_to(end);
678        return;
679    }
680
681    let phi = x_rotation_deg.to_radians();
682    let (sin_phi, cos_phi) = phi.sin_cos();
683
684    // Step 1: half the vector between endpoints, in the rotated frame.
685    let dx2 = (start.x - end.x) * 0.5;
686    let dy2 = (start.y - end.y) * 0.5;
687    let x1p = cos_phi * dx2 + sin_phi * dy2;
688    let y1p = -sin_phi * dx2 + cos_phi * dy2;
689
690    // Correct out-of-range radii.
691    let lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
692    if lambda > 1.0 {
693        let scale = lambda.sqrt();
694        rx *= scale;
695        ry *= scale;
696    }
697
698    // Step 2: center in the rotated frame.
699    let rx_sq = rx * rx;
700    let ry_sq = ry * ry;
701    let numerator = (rx_sq * ry_sq - rx_sq * y1p * y1p - ry_sq * x1p * x1p).max(0.0);
702    let denominator = rx_sq * y1p * y1p + ry_sq * x1p * x1p;
703    let mut coefficient = if denominator <= f32::EPSILON {
704        0.0
705    } else {
706        (numerator / denominator).sqrt()
707    };
708    if large_arc == sweep {
709        coefficient = -coefficient;
710    }
711    let cxp = coefficient * rx * y1p / ry;
712    let cyp = -coefficient * ry * x1p / rx;
713
714    // Step 3: center in the original frame.
715    let cx = cos_phi * cxp - sin_phi * cyp + (start.x + end.x) * 0.5;
716    let cy = sin_phi * cxp + cos_phi * cyp + (start.y + end.y) * 0.5;
717
718    // Step 4: start angle and sweep extent.
719    let angle_of = |x: f32, y: f32| y.atan2(x);
720    let theta1 = angle_of((x1p - cxp) / rx, (y1p - cyp) / ry);
721    let theta2 = angle_of((-x1p - cxp) / rx, (-y1p - cyp) / ry);
722    let two_pi = std::f32::consts::TAU;
723    let mut delta = theta2 - theta1;
724    if sweep {
725        if delta < 0.0 {
726            delta += two_pi;
727        }
728    } else if delta > 0.0 {
729        delta -= two_pi;
730    }
731
732    let segments = ((delta.abs() / ARC_MAX_ANGLE_STEP).ceil() as usize).max(2);
733    for i in 1..=segments {
734        let theta = theta1 + delta * (i as f32 / segments as f32);
735        let (sin_theta, cos_theta) = theta.sin_cos();
736        let x = cos_phi * rx * cos_theta - sin_phi * ry * sin_theta + cx;
737        let y = sin_phi * rx * cos_theta + cos_phi * ry * sin_theta + cy;
738        builder.line_to(Point::new(x, y));
739    }
740    // Land exactly on the endpoint despite floating-point sampling error.
741    builder.line_to(end);
742    builder.position = end;
743}
744
745#[cfg(test)]
746mod tests {
747    use super::*;
748
749    fn mask_at(mask: &[u8], width: usize, x: usize, y: usize) -> u8 {
750        mask[y * width + x]
751    }
752
753    // ── parser ──────────────────────────────────────────────────────────
754
755    #[test]
756    fn parses_absolute_triangle() {
757        let path = VectorPath::parse("M 0 0 L 10 0 L 10 10 Z").expect("valid path");
758        assert_eq!(path.subpaths().len(), 1);
759        assert_eq!(
760            path.subpaths()[0],
761            vec![
762                Point::new(0.0, 0.0),
763                Point::new(10.0, 0.0),
764                Point::new(10.0, 10.0)
765            ]
766        );
767        let bounds = path.bounds();
768        assert_eq!((bounds.x, bounds.y), (0.0, 0.0));
769        assert_eq!((bounds.width, bounds.height), (10.0, 10.0));
770    }
771
772    #[test]
773    fn parses_relative_commands_and_h_v() {
774        let path = VectorPath::parse("m 5 5 l 10 0 v 10 h -10 z").expect("valid path");
775        assert_eq!(
776            path.subpaths()[0],
777            vec![
778                Point::new(5.0, 5.0),
779                Point::new(15.0, 5.0),
780                Point::new(15.0, 15.0),
781                Point::new(5.0, 15.0)
782            ]
783        );
784    }
785
786    #[test]
787    fn parses_packed_numbers_and_negative_shorthand() {
788        // "10-5" is two numbers; ".5.5" is (0.5, 0.5).
789        let path = VectorPath::parse("M10-5L.5.5Z").expect("valid path");
790        assert_eq!(
791            path.subpaths()[0],
792            vec![Point::new(10.0, -5.0), Point::new(0.5, 0.5)]
793        );
794    }
795
796    #[test]
797    fn implicit_lineto_after_moveto() {
798        let path = VectorPath::parse("M 0 0 10 0 10 10").expect("valid path");
799        assert_eq!(path.subpaths()[0].len(), 3);
800        assert_eq!(path.subpaths()[0][2], Point::new(10.0, 10.0));
801    }
802
803    #[test]
804    fn cubic_flattening_hits_endpoints() {
805        let path = VectorPath::parse("M 0 0 C 0 10 10 10 10 0").expect("valid path");
806        let points = &path.subpaths()[0];
807        assert_eq!(points[0], Point::new(0.0, 0.0));
808        assert_eq!(*points.last().unwrap(), Point::new(10.0, 0.0));
809        assert!(points.len() > 4, "curve must be subdivided");
810        // The curve midpoint of this symmetric cubic is (5, 7.5).
811        let mid = points
812            .iter()
813            .min_by(|a, b| (a.x - 5.0).abs().total_cmp(&(b.x - 5.0).abs()))
814            .unwrap();
815        assert!(
816            (mid.y - 7.5).abs() < 0.2,
817            "flattened curve must pass near the true midpoint, got {mid:?}"
818        );
819    }
820
821    #[test]
822    fn smooth_cubic_reflects_control_point() {
823        // S after C reflects the previous control point; the joined curves
824        // are C1-continuous, so the polyline has no kink at the join (5,5).
825        let path = VectorPath::parse("M 0 0 C 0 5 2 5 5 5 S 10 5 10 10").expect("valid path");
826        let points = &path.subpaths()[0];
827        assert_eq!(*points.last().unwrap(), Point::new(10.0, 10.0));
828        assert!(points
829            .iter()
830            .any(|p| (p.x - 5.0).abs() < 0.1 && (p.y - 5.0).abs() < 0.1));
831    }
832
833    #[test]
834    fn quadratic_and_smooth_quadratic() {
835        let path = VectorPath::parse("M 0 0 Q 5 10 10 0 T 20 0").expect("valid path");
836        let points = &path.subpaths()[0];
837        assert_eq!(*points.last().unwrap(), Point::new(20.0, 0.0));
838        // Quadratic apex at t=0.5 is (5, 5).
839        assert!(points
840            .iter()
841            .any(|p| (p.x - 5.0).abs() < 0.3 && (p.y - 5.0).abs() < 0.3));
842        // T mirrors the control: the second hump dips to (15, -5).
843        assert!(points
844            .iter()
845            .any(|p| (p.x - 15.0).abs() < 0.3 && (p.y + 5.0).abs() < 0.3));
846    }
847
848    #[test]
849    fn arc_travels_through_expected_quadrant() {
850        // Half circle of radius 5 from (0,0) to (10,0), sweeping below.
851        let path = VectorPath::parse("M 0 0 A 5 5 0 0 1 10 0").expect("valid path");
852        let points = &path.subpaths()[0];
853        assert_eq!(*points.last().unwrap(), Point::new(10.0, 0.0));
854        let lowest = points.iter().fold(0.0f32, |acc, p| acc.min(p.y));
855        assert!(
856            (lowest + 5.0).abs() < 0.1,
857            "sweep=1 arc must pass through (5,-5), lowest y = {lowest}"
858        );
859
860        let path = VectorPath::parse("M 0 0 A 5 5 0 0 0 10 0").expect("valid path");
861        let highest = path.subpaths()[0]
862            .iter()
863            .fold(0.0f32, |acc, p| acc.max(p.y));
864        assert!(
865            (highest - 5.0).abs() < 0.1,
866            "sweep=0 arc must pass through (5,5), highest y = {highest}"
867        );
868    }
869
870    #[test]
871    fn arc_flags_may_be_packed() {
872        let spaced = VectorPath::parse("M 0 0 A 5 5 0 0 1 10 0").expect("valid path");
873        let packed = VectorPath::parse("M0 0A5 5 0 0110 0").expect("valid path");
874        assert_eq!(
875            spaced.subpaths()[0].len(),
876            packed.subpaths()[0].len(),
877            "packed arc flags must parse identically"
878        );
879    }
880
881    #[test]
882    fn multiple_subpaths() {
883        let path =
884            VectorPath::parse("M 0 0 h 4 v 4 h -4 Z M 10 10 h 4 v 4 h -4 Z").expect("valid path");
885        assert_eq!(path.subpaths().len(), 2);
886    }
887
888    #[test]
889    fn rejects_garbage() {
890        assert!(VectorPath::parse("this is not a path").is_err());
891        assert!(
892            VectorPath::parse("L 10 10").is_err(),
893            "must start with moveto"
894        );
895        assert!(VectorPath::parse("M 10").is_err(), "missing y coordinate");
896        assert!(
897            VectorPath::parse("M 0 0 A 5 5 0 2 1 10 0").is_err(),
898            "bad flag"
899        );
900        assert_eq!(
901            VectorPath::parse("").unwrap_err(),
902            SvgPathError::MissingMoveTo
903        );
904    }
905
906    // ── rasterizer ──────────────────────────────────────────────────────
907
908    #[test]
909    fn fills_axis_aligned_rectangle() {
910        let path = VectorPath::parse("M 2 2 H 8 V 8 H 2 Z").expect("valid path");
911        let mask = path.coverage_mask(10, 10, Point::ZERO, 1.0);
912
913        assert_eq!(mask_at(&mask, 10, 5, 5), 255, "interior must be opaque");
914        assert_eq!(mask_at(&mask, 10, 4, 2), 255, "top edge row is inside");
915        assert_eq!(mask_at(&mask, 10, 0, 0), 0, "outside must stay empty");
916        assert_eq!(mask_at(&mask, 10, 9, 9), 0, "outside must stay empty");
917    }
918
919    #[test]
920    fn triangle_edge_is_antialiased() {
921        let path = VectorPath::parse("M 0 0 L 8 0 L 0 8 Z").expect("valid path");
922        let mask = path.coverage_mask(8, 8, Point::ZERO, 1.0);
923
924        assert_eq!(mask_at(&mask, 8, 1, 1), 255, "deep interior is opaque");
925        assert_eq!(mask_at(&mask, 8, 7, 7), 0, "far corner is empty");
926        // Pixels straddling the diagonal must have partial coverage.
927        let diagonal = mask_at(&mask, 8, 4, 3);
928        assert!(
929            diagonal > 30 && diagonal < 225,
930            "diagonal pixel should be partially covered, got {diagonal}"
931        );
932    }
933
934    #[test]
935    fn even_odd_ring_has_a_hole() {
936        // Outer square with an inner square drawn in the SAME winding
937        // direction: even-odd punches the hole, non-zero fills it solid.
938        let d = "M 0 0 H 12 V 12 H 0 Z M 4 4 H 8 V 8 H 4 Z";
939        let even_odd =
940            VectorPath::parse_with_fill_rule(d, PathFillRule::EvenOdd).expect("valid path");
941        let non_zero = VectorPath::parse(d).expect("valid path");
942
943        let even_odd_mask = even_odd.coverage_mask(12, 12, Point::ZERO, 1.0);
944        let non_zero_mask = non_zero.coverage_mask(12, 12, Point::ZERO, 1.0);
945
946        assert_eq!(mask_at(&even_odd_mask, 12, 6, 6), 0, "even-odd hole");
947        assert_eq!(mask_at(&even_odd_mask, 12, 2, 6), 255, "even-odd ring");
948        assert_eq!(mask_at(&non_zero_mask, 12, 6, 6), 255, "non-zero solid");
949    }
950
951    #[test]
952    fn non_zero_ring_with_reversed_inner_winding_has_a_hole() {
953        // Inner square wound the opposite way: non-zero also punches it.
954        let d = "M 0 0 H 12 V 12 H 0 Z M 4 4 V 8 H 8 V 4 Z";
955        let path = VectorPath::parse(d).expect("valid path");
956        let mask = path.coverage_mask(12, 12, Point::ZERO, 1.0);
957        assert_eq!(mask_at(&mask, 12, 6, 6), 0, "reversed winding hole");
958        assert_eq!(mask_at(&mask, 12, 2, 6), 255, "ring stays filled");
959    }
960
961    #[test]
962    fn circle_from_arcs_fills_center_and_respects_radius() {
963        // Full circle of radius 8 centered at (8, 8) from two arcs.
964        let path =
965            VectorPath::parse("M 0 8 A 8 8 0 1 1 16 8 A 8 8 0 1 1 0 8 Z").expect("valid path");
966        let mask = path.coverage_mask(16, 16, Point::ZERO, 1.0);
967
968        assert_eq!(mask_at(&mask, 16, 8, 8), 255, "circle center is opaque");
969        assert_eq!(mask_at(&mask, 16, 0, 0), 0, "circle corner is empty");
970        assert_eq!(mask_at(&mask, 16, 15, 0), 0, "circle corner is empty");
971        // Roughly correct area: sum of coverage ~ pi * r^2.
972        let area: f32 = mask.iter().map(|&value| value as f32 / 255.0).sum();
973        let expected = std::f32::consts::PI * 8.0 * 8.0;
974        assert!(
975            (area - expected).abs() / expected < 0.05,
976            "filled area {area} should be close to {expected}"
977        );
978    }
979
980    #[test]
981    fn scale_and_origin_map_path_units_to_pixels() {
982        let path = VectorPath::parse("M 10 10 H 14 V 14 H 10 Z").expect("valid path");
983        // Rasterize the 4x4 square at 2x with the mask origin at (10, 10).
984        let mask = path.coverage_mask(8, 8, Point::new(10.0, 10.0), 2.0);
985        assert_eq!(mask_at(&mask, 8, 4, 4), 255, "scaled interior");
986        let full: usize = mask.iter().filter(|&&value| value == 255).count();
987        assert_eq!(full, 64, "the 8x8 pixel mask must be fully covered");
988    }
989
990    #[test]
991    fn empty_and_degenerate_paths_produce_empty_masks() {
992        let path = VectorPath::parse("M 5 5 L 6 6").expect("valid path");
993        assert!(path.is_empty());
994        let mask = path.coverage_mask(8, 8, Point::ZERO, 1.0);
995        assert!(mask.iter().all(|&value| value == 0));
996    }
997}