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 thiserror::Error;
16
17use crate::geometry::{Point, Rect};
18
19/// Maximum recursion depth for adaptive curve flattening.
20const MAX_FLATTEN_DEPTH: u32 = 12;
21/// Curve flattening tolerance in path units.
22const FLATTEN_TOLERANCE: f32 = 0.05;
23/// Arc sampling: maximum angle step per segment.
24const ARC_MAX_ANGLE_STEP: f32 = std::f32::consts::PI / 16.0;
25/// Anti-aliasing sub-scanlines per pixel row.
26const SUBSAMPLES: usize = 4;
27
28/// Errors produced while parsing SVG path data.
29#[derive(Debug, Clone, PartialEq, Eq, Error)]
30pub enum SvgPathError {
31    #[error("unexpected byte {byte:?} at offset {offset}")]
32    UnexpectedByte { byte: char, offset: usize },
33    #[error("expected a number at offset {offset}")]
34    ExpectedNumber { offset: usize },
35    #[error("expected an arc flag (0 or 1) at offset {offset}")]
36    ExpectedFlag { offset: usize },
37    #[error("path data must start with a moveto (M/m) command")]
38    MissingMoveTo,
39}
40
41/// Fill rule for [`VectorPath`] rasterization.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43pub enum PathFillRule {
44    /// Fill where the winding number is non-zero (SVG default).
45    #[default]
46    NonZero,
47    /// Fill where a ray crosses an odd number of edges.
48    EvenOdd,
49}
50
51/// A parsed SVG path: subpaths flattened to polylines, ready to fill.
52#[derive(Debug, Clone)]
53pub struct VectorPath {
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    pub(crate) 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        let mut edges = self.scanline_edges(origin, scale);
163        if edges.is_empty() {
164            return mask;
165        }
166        edges.sort_by(|a, b| a.top.y.total_cmp(&b.top.y));
167        let mut scanner = EdgeScanner::new(&edges);
168        let mut row_coverage = vec![0.0f32; width];
169        let subsample_weight = 1.0 / SUBSAMPLES as f32;
170        for (row, mask_row) in mask.chunks_exact_mut(width).enumerate() {
171            row_coverage.fill(0.0);
172            let mut row_touched = false;
173            for sub in 0..SUBSAMPLES {
174                let sample_y = row as f32 + (sub as f32 + 0.5) * subsample_weight;
175                let crossings = scanner.crossings_at(sample_y);
176                row_touched |= self.fill_rule.for_each_span(crossings, |x0, x1| {
177                    accumulate_span(&mut row_coverage, x0, x1, subsample_weight, width)
178                });
179            }
180            if row_touched {
181                add_row_coverage(mask_row, &row_coverage);
182            }
183        }
184        mask
185    }
186
187    /// The path's non-horizontal edges in pixel space, each from its top
188    /// to its bottom, with the direction it ran in.
189    fn scanline_edges(&self, origin: Point, scale: f32) -> Vec<Edge> {
190        let map = |p: &Point| Point::new((p.x - origin.x) * scale, (p.y - origin.y) * scale);
191        let closed = self.subpaths.iter().filter(|subpath| subpath.len() >= 3);
192        closed
193            .flat_map(|subpath| {
194                let next = subpath.iter().skip(1).chain(subpath.first());
195                subpath.iter().zip(next).filter_map(move |(a, b)| {
196                    let (a, b) = (map(a), map(b));
197                    match a.y.total_cmp(&b.y) {
198                        std::cmp::Ordering::Less => Some(Edge {
199                            top: a,
200                            bottom: b,
201                            winding: 1,
202                        }),
203                        std::cmp::Ordering::Greater => Some(Edge {
204                            top: b,
205                            bottom: a,
206                            winding: -1,
207                        }),
208                        std::cmp::Ordering::Equal => None,
209                    }
210                })
211            })
212            .collect()
213    }
214}
215
216/// One edge of a path in pixel space, from its top to its bottom, and the
217/// winding direction it ran in.
218struct Edge {
219    top: Point,
220    bottom: Point,
221    winding: i32,
222}
223
224/// Walks sample lines down a path's edges sorted by their tops, keeping the
225/// edges the current line may cross: lines only descend, so an edge enters
226/// once and leaves once.
227struct EdgeScanner<'a> {
228    edges: &'a [Edge],
229    next: usize,
230    /// The edges the current line crosses, each with where it crosses.
231    active: Vec<(f32, &'a Edge)>,
232    crossings: Vec<(f32, i32)>,
233}
234
235impl<'a> EdgeScanner<'a> {
236    fn new(edges: &'a [Edge]) -> Self {
237        Self {
238            edges,
239            next: 0,
240            active: Vec::new(),
241            crossings: Vec::new(),
242        }
243    }
244
245    /// Where the edges cross the line at `sample_y`, left to right, each
246    /// with its winding direction.
247    fn crossings_at(&mut self, sample_y: f32) -> &[(f32, i32)] {
248        while let Some(edge) = self
249            .edges
250            .get(self.next)
251            .filter(|edge| edge.top.y <= sample_y)
252        {
253            self.active.push((0.0, edge));
254            self.next += 1;
255        }
256        self.active.retain(|(_, edge)| sample_y < edge.bottom.y);
257        for (x, edge) in &mut self.active {
258            let t = (sample_y - edge.top.y) / (edge.bottom.y - edge.top.y);
259            *x = edge.top.x + t * (edge.bottom.x - edge.top.x);
260        }
261        // Each crossing is computed once, then sorted: the order barely
262        // changes from one sample line to the next, which the sort finds in
263        // one pass. Crossings at the same x bound an empty span either way.
264        self.active
265            .sort_unstable_by(|(a, _), (b, _)| a.total_cmp(b));
266        self.crossings.clear();
267        self.crossings
268            .extend(self.active.iter().map(|(x, edge)| (*x, edge.winding)));
269        &self.crossings
270    }
271}
272
273impl PathFillRule {
274    /// Hands `span` each run of a sample line that lies inside the fill,
275    /// from `crossings` sorted left to right; whether any span touched a
276    /// pixel.
277    fn for_each_span(
278        self,
279        crossings: &[(f32, i32)],
280        mut span: impl FnMut(f32, f32) -> bool,
281    ) -> bool {
282        if crossings.len() < 2 {
283            return false;
284        }
285        let inside = |winding: i32| match self {
286            Self::NonZero => winding != 0,
287            Self::EvenOdd => winding % 2 != 0,
288        };
289        let mut touched = false;
290        let mut winding = 0i32;
291        let mut span_start = 0.0f32;
292        for &(x, direction) in crossings {
293            let was_inside = inside(winding);
294            winding += match self {
295                Self::NonZero => direction,
296                Self::EvenOdd => 1,
297            };
298            match (was_inside, inside(winding)) {
299                (false, true) => span_start = x,
300                (true, false) => touched |= span(span_start, x),
301                _ => {}
302            }
303        }
304        touched
305    }
306}
307
308/// Adds a row's summed coverage onto its row of the 8-bit mask.
309fn add_row_coverage(mask_row: &mut [u8], row_coverage: &[f32]) {
310    for (dst, coverage) in mask_row.iter_mut().zip(row_coverage) {
311        let existing = *dst as f32 / 255.0;
312        let combined = (existing + coverage).min(1.0);
313        *dst = (combined * 255.0 + 0.5) as u8;
314    }
315}
316
317/// Adds one horizontal span `[x0, x1)` of one sub-scanline into the row
318/// coverage accumulator, handling fractional span ends. Returns whether any
319/// pixel was touched.
320fn accumulate_span(row_coverage: &mut [f32], x0: f32, x1: f32, weight: f32, width: usize) -> bool {
321    let x0 = x0.max(0.0);
322    let x1 = x1.min(width as f32);
323    if x1 <= x0 {
324        return false;
325    }
326
327    // Pixels the span covers whole take the weight as it is; only the
328    // pixels holding its ends take a fraction.
329    let first = x0.floor() as usize;
330    let last = (x1.ceil() as usize).min(width);
331    let partial = |pixel: usize| {
332        let pixel_start = pixel as f32;
333        (x1.min(pixel_start + 1.0) - x0.max(pixel_start)).max(0.0) * weight
334    };
335    let Some(span) = row_coverage.get_mut(first..last) else {
336        return false;
337    };
338    match span {
339        [] => {}
340        [only] => *only += partial(first),
341        [head, interior @ .., tail] => {
342            *head += partial(first);
343            for coverage in interior {
344                *coverage += weight;
345            }
346            *tail += partial(last - 1);
347        }
348    }
349    true
350}
351
352struct PathLexer<'a> {
353    bytes: &'a [u8],
354    pos: usize,
355}
356
357impl<'a> PathLexer<'a> {
358    fn new(d: &'a str) -> Self {
359        Self {
360            bytes: d.as_bytes(),
361            pos: 0,
362        }
363    }
364
365    fn skip_separators(&mut self) {
366        while self.pos < self.bytes.len() {
367            match self.bytes[self.pos] {
368                b' ' | b'\t' | b'\r' | b'\n' | b',' => self.pos += 1,
369                _ => break,
370            }
371        }
372    }
373
374    fn peek(&mut self) -> Option<u8> {
375        self.skip_separators();
376        self.bytes.get(self.pos).copied()
377    }
378
379    fn at_number(&mut self) -> bool {
380        matches!(self.peek(), Some(b'0'..=b'9' | b'.' | b'-' | b'+'))
381    }
382
383    fn next_command(&mut self) -> Option<u8> {
384        let byte = self.peek()?;
385        if byte.is_ascii_alphabetic() {
386            self.pos += 1;
387            Some(byte)
388        } else {
389            None
390        }
391    }
392
393    fn next_number(&mut self) -> Result<f32, SvgPathError> {
394        self.skip_separators();
395        let start = self.pos;
396        let bytes = self.bytes;
397        let mut pos = self.pos;
398
399        if pos < bytes.len() && (bytes[pos] == b'+' || bytes[pos] == b'-') {
400            pos += 1;
401        }
402        let int_digits = Self::eat_digits(bytes, &mut pos);
403        let mut frac_digits = 0;
404        if pos < bytes.len() && bytes[pos] == b'.' {
405            pos += 1;
406            frac_digits = Self::eat_digits(bytes, &mut pos);
407        }
408        if int_digits == 0 && frac_digits == 0 {
409            return Err(SvgPathError::ExpectedNumber { offset: start });
410        }
411        if pos < bytes.len() && (bytes[pos] == b'e' || bytes[pos] == b'E') {
412            let mut exp_pos = pos + 1;
413            if exp_pos < bytes.len() && (bytes[exp_pos] == b'+' || bytes[exp_pos] == b'-') {
414                exp_pos += 1;
415            }
416            if Self::eat_digits(bytes, &mut exp_pos) > 0 {
417                pos = exp_pos;
418            }
419        }
420
421        let text = std::str::from_utf8(&bytes[start..pos])
422            .map_err(|_| SvgPathError::ExpectedNumber { offset: start })?;
423        let value = text
424            .parse::<f32>()
425            .map_err(|_| SvgPathError::ExpectedNumber { offset: start })?;
426        self.pos = pos;
427        Ok(value)
428    }
429
430    fn eat_digits(bytes: &[u8], pos: &mut usize) -> usize {
431        let start = *pos;
432        while *pos < bytes.len() && bytes[*pos].is_ascii_digit() {
433            *pos += 1;
434        }
435        *pos - start
436    }
437
438    fn next_flag(&mut self) -> Result<bool, SvgPathError> {
439        self.skip_separators();
440        match self.bytes.get(self.pos) {
441            Some(b'0') => {
442                self.pos += 1;
443                Ok(false)
444            }
445            Some(b'1') => {
446                self.pos += 1;
447                Ok(true)
448            }
449            _ => Err(SvgPathError::ExpectedFlag { offset: self.pos }),
450        }
451    }
452
453    fn at_end(&mut self) -> bool {
454        self.peek().is_none()
455    }
456}
457
458struct PathBuilder {
459    subpaths: Vec<Vec<Point>>,
460    current: Vec<Point>,
461    position: Point,
462    subpath_start: Point,
463    last_cubic_control: Option<Point>,
464    last_quad_control: Option<Point>,
465}
466
467impl PathBuilder {
468    fn new() -> Self {
469        Self {
470            subpaths: Vec::new(),
471            current: Vec::new(),
472            position: Point::ZERO,
473            subpath_start: Point::ZERO,
474            last_cubic_control: None,
475            last_quad_control: None,
476        }
477    }
478
479    fn flush_subpath(&mut self) {
480        if self.current.len() >= 2 {
481            self.subpaths.push(std::mem::take(&mut self.current));
482        } else {
483            self.current.clear();
484        }
485    }
486
487    fn move_to(&mut self, point: Point) {
488        self.flush_subpath();
489        self.position = point;
490        self.subpath_start = point;
491        self.current.push(point);
492    }
493
494    fn line_to(&mut self, point: Point) {
495        self.begin_segment();
496        self.current.push(point);
497        self.position = point;
498    }
499
500    /// Starts the current polyline at the pen if nothing has, and returns
501    /// where the next segment starts.
502    fn begin_segment(&mut self) -> Point {
503        if self.current.is_empty() {
504            self.current.push(self.position);
505        }
506        self.position
507    }
508
509    fn close(&mut self) {
510        self.position = self.subpath_start;
511        self.flush_subpath();
512        self.current.push(self.subpath_start);
513    }
514
515    fn finish(mut self) -> Vec<Vec<Point>> {
516        self.flush_subpath();
517        self.subpaths
518    }
519}
520
521fn parse_path_data(d: &str) -> Result<Vec<Vec<Point>>, SvgPathError> {
522    let mut lexer = PathLexer::new(d);
523    let mut builder = PathBuilder::new();
524    let mut command: Option<u8> = None;
525    let mut seen_moveto = false;
526
527    loop {
528        if lexer.at_end() {
529            break;
530        }
531
532        if let Some(next) = lexer.next_command() {
533            command = Some(next);
534        } else if command.is_none() || !lexer.at_number() {
535            let offset = lexer.pos;
536            let byte = lexer.bytes.get(offset).copied().unwrap_or(b'?') as char;
537            return Err(SvgPathError::UnexpectedByte { byte, offset });
538        }
539
540        let Some(cmd) = command else {
541            return Err(SvgPathError::MissingMoveTo);
542        };
543        if !seen_moveto && !matches!(cmd, b'M' | b'm') {
544            return Err(SvgPathError::MissingMoveTo);
545        }
546        let relative = cmd.is_ascii_lowercase();
547        let pos = builder.position;
548        let rel = |value: Point| {
549            if relative {
550                Point::new(pos.x + value.x, pos.y + value.y)
551            } else {
552                value
553            }
554        };
555
556        match cmd.to_ascii_uppercase() {
557            b'M' => {
558                let point = rel(read_point(&mut lexer)?);
559                builder.move_to(point);
560                seen_moveto = true;
561                builder.last_cubic_control = None;
562                builder.last_quad_control = None;
563                command = Some(if relative { b'l' } else { b'L' });
564            }
565            b'L' => {
566                let point = rel(read_point(&mut lexer)?);
567                builder.line_to(point);
568                builder.last_cubic_control = None;
569                builder.last_quad_control = None;
570            }
571            b'H' => {
572                let x = lexer.next_number()?;
573                let x = if relative { pos.x + x } else { x };
574                builder.line_to(Point::new(x, pos.y));
575                builder.last_cubic_control = None;
576                builder.last_quad_control = None;
577            }
578            b'V' => {
579                let y = lexer.next_number()?;
580                let y = if relative { pos.y + y } else { y };
581                builder.line_to(Point::new(pos.x, y));
582                builder.last_cubic_control = None;
583                builder.last_quad_control = None;
584            }
585            b'C' => {
586                let c1 = rel(read_point(&mut lexer)?);
587                let c2 = rel(read_point(&mut lexer)?);
588                let end = rel(read_point(&mut lexer)?);
589                emit_cubic(&mut builder, c1, c2, end);
590            }
591            b'S' => {
592                let c1 = match builder.last_cubic_control {
593                    Some(control) => reflect(pos, control),
594                    None => pos,
595                };
596                let c2 = rel(read_point(&mut lexer)?);
597                let end = rel(read_point(&mut lexer)?);
598                emit_cubic(&mut builder, c1, c2, end);
599            }
600            b'Q' => {
601                let control = rel(read_point(&mut lexer)?);
602                let end = rel(read_point(&mut lexer)?);
603                emit_quad(&mut builder, control, end);
604            }
605            b'T' => {
606                let control = match builder.last_quad_control {
607                    Some(control) => reflect(pos, control),
608                    None => pos,
609                };
610                let end = rel(read_point(&mut lexer)?);
611                emit_quad(&mut builder, control, end);
612            }
613            b'A' => {
614                let rx = lexer.next_number()?;
615                let ry = lexer.next_number()?;
616                let x_rotation_deg = lexer.next_number()?;
617                let large_arc = lexer.next_flag()?;
618                let sweep = lexer.next_flag()?;
619                let end = rel(read_point(&mut lexer)?);
620                emit_arc(&mut builder, rx, ry, x_rotation_deg, large_arc, sweep, end);
621                builder.last_cubic_control = None;
622                builder.last_quad_control = None;
623            }
624            b'Z' => {
625                builder.close();
626                builder.last_cubic_control = None;
627                builder.last_quad_control = None;
628                command = None;
629            }
630            other => {
631                return Err(SvgPathError::UnexpectedByte {
632                    byte: other as char,
633                    offset: lexer.pos.saturating_sub(1),
634                });
635            }
636        }
637    }
638
639    if !seen_moveto {
640        return Err(SvgPathError::MissingMoveTo);
641    }
642    Ok(builder.finish())
643}
644
645fn read_point(lexer: &mut PathLexer<'_>) -> Result<Point, SvgPathError> {
646    let x = lexer.next_number()?;
647    let y = lexer.next_number()?;
648    Ok(Point::new(x, y))
649}
650
651fn reflect(origin: Point, point: Point) -> Point {
652    Point::new(2.0 * origin.x - point.x, 2.0 * origin.y - point.y)
653}
654
655fn emit_cubic(builder: &mut PathBuilder, c1: Point, c2: Point, end: Point) {
656    let start = builder.begin_segment();
657    flatten_cubic_into(&mut builder.current, start, c1, c2, end);
658    builder.position = end;
659    builder.last_cubic_control = Some(c2);
660    builder.last_quad_control = None;
661}
662
663fn emit_quad(builder: &mut PathBuilder, control: Point, end: Point) {
664    let start = builder.begin_segment();
665    let (c1, c2) = quad_as_cubic(start, control, end);
666    flatten_cubic_into(&mut builder.current, start, c1, c2, end);
667    builder.position = end;
668    builder.last_quad_control = Some(control);
669    builder.last_cubic_control = None;
670}
671
672/// The cubic controls that trace the quadratic curve from `start` through
673/// `control` to `end`.
674pub(crate) fn quad_as_cubic(start: Point, control: Point, end: Point) -> (Point, Point) {
675    (
676        Point::new(
677            start.x + 2.0 / 3.0 * (control.x - start.x),
678            start.y + 2.0 / 3.0 * (control.y - start.y),
679        ),
680        Point::new(
681            end.x + 2.0 / 3.0 * (control.x - end.x),
682            end.y + 2.0 / 3.0 * (control.y - end.y),
683        ),
684    )
685}
686
687/// Appends the cubic from `p0` to `p3` to `points` as a polyline within
688/// [`FLATTEN_TOLERANCE`] of the curve, `p0` left out: the caller's polyline
689/// already ends there.
690pub(crate) fn flatten_cubic_into(
691    points: &mut Vec<Point>,
692    p0: Point,
693    p1: Point,
694    p2: Point,
695    p3: Point,
696) {
697    flatten_cubic(points, p0, p1, p2, p3, 0);
698}
699
700fn flatten_cubic(points: &mut Vec<Point>, p0: Point, p1: Point, p2: Point, p3: Point, depth: u32) {
701    if depth >= MAX_FLATTEN_DEPTH || cubic_is_flat(p0, p1, p2, p3) {
702        points.push(p3);
703        return;
704    }
705
706    let mid = |a: Point, b: Point| Point::new((a.x + b.x) * 0.5, (a.y + b.y) * 0.5);
707    let p01 = mid(p0, p1);
708    let p12 = mid(p1, p2);
709    let p23 = mid(p2, p3);
710    let p012 = mid(p01, p12);
711    let p123 = mid(p12, p23);
712    let p0123 = mid(p012, p123);
713
714    flatten_cubic(points, p0, p01, p012, p0123, depth + 1);
715    flatten_cubic(points, p0123, p123, p23, p3, depth + 1);
716}
717
718/// Flatness test: both control points close enough to the chord.
719fn cubic_is_flat(p0: Point, p1: Point, p2: Point, p3: Point) -> bool {
720    let d1 = point_to_chord_distance_squared(p1, p0, p3);
721    let d2 = point_to_chord_distance_squared(p2, p0, p3);
722    let tolerance = FLATTEN_TOLERANCE * FLATTEN_TOLERANCE;
723    d1 <= tolerance && d2 <= tolerance
724}
725
726fn point_to_chord_distance_squared(point: Point, a: Point, b: Point) -> f32 {
727    let ab = Point::new(b.x - a.x, b.y - a.y);
728    let ap = Point::new(point.x - a.x, point.y - a.y);
729    let ab_len_sq = ab.x * ab.x + ab.y * ab.y;
730    if ab_len_sq <= f32::EPSILON {
731        return ap.x * ap.x + ap.y * ap.y;
732    }
733    let cross = ab.x * ap.y - ab.y * ap.x;
734    cross * cross / ab_len_sq
735}
736
737/// Converts an SVG endpoint-parameterized arc to line segments
738/// (W3C SVG 2 appendix B.2.4).
739fn emit_arc(
740    builder: &mut PathBuilder,
741    rx: f32,
742    ry: f32,
743    x_rotation_deg: f32,
744    large_arc: bool,
745    sweep: bool,
746    end: Point,
747) {
748    let start = builder.position;
749    if (start.x - end.x).abs() <= f32::EPSILON && (start.y - end.y).abs() <= f32::EPSILON {
750        return;
751    }
752    let mut rx = rx.abs();
753    let mut ry = ry.abs();
754    if rx <= f32::EPSILON || ry <= f32::EPSILON {
755        builder.line_to(end);
756        return;
757    }
758
759    let phi = x_rotation_deg.to_radians();
760    let (sin_phi, cos_phi) = phi.sin_cos();
761
762    let dx2 = (start.x - end.x) * 0.5;
763    let dy2 = (start.y - end.y) * 0.5;
764    let x1p = cos_phi * dx2 + sin_phi * dy2;
765    let y1p = -sin_phi * dx2 + cos_phi * dy2;
766
767    let lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
768    if lambda > 1.0 {
769        let scale = lambda.sqrt();
770        rx *= scale;
771        ry *= scale;
772    }
773
774    let rx_sq = rx * rx;
775    let ry_sq = ry * ry;
776    let numerator = (rx_sq * ry_sq - rx_sq * y1p * y1p - ry_sq * x1p * x1p).max(0.0);
777    let denominator = rx_sq * y1p * y1p + ry_sq * x1p * x1p;
778    let mut coefficient = if denominator <= f32::EPSILON {
779        0.0
780    } else {
781        (numerator / denominator).sqrt()
782    };
783    if large_arc == sweep {
784        coefficient = -coefficient;
785    }
786    let cxp = coefficient * rx * y1p / ry;
787    let cyp = -coefficient * ry * x1p / rx;
788
789    let cx = cos_phi * cxp - sin_phi * cyp + (start.x + end.x) * 0.5;
790    let cy = sin_phi * cxp + cos_phi * cyp + (start.y + end.y) * 0.5;
791
792    let angle_of = |x: f32, y: f32| y.atan2(x);
793    let theta1 = angle_of((x1p - cxp) / rx, (y1p - cyp) / ry);
794    let theta2 = angle_of((-x1p - cxp) / rx, (-y1p - cyp) / ry);
795    let two_pi = std::f32::consts::TAU;
796    let mut delta = theta2 - theta1;
797    if sweep {
798        if delta < 0.0 {
799            delta += two_pi;
800        }
801    } else if delta > 0.0 {
802        delta -= two_pi;
803    }
804
805    let segments = ((delta.abs() / ARC_MAX_ANGLE_STEP).ceil() as usize).max(2);
806    for i in 1..=segments {
807        let theta = theta1 + delta * (i as f32 / segments as f32);
808        let (sin_theta, cos_theta) = theta.sin_cos();
809        let x = cos_phi * rx * cos_theta - sin_phi * ry * sin_theta + cx;
810        let y = sin_phi * rx * cos_theta + cos_phi * ry * sin_theta + cy;
811        builder.line_to(Point::new(x, y));
812    }
813    builder.line_to(end);
814    builder.position = end;
815}
816
817#[cfg(test)]
818#[path = "tests/vector_path_tests.rs"]
819mod tests;