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