Skip to main content

vello_encoding/
path.rs

1// Copyright 2022 the Vello Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use bytemuck::{Pod, Zeroable};
5use peniko::Fill;
6use peniko::kurbo::{Cap, Join, Shape, Stroke};
7
8use super::Monoid;
9
10/// Data structure encoding stroke or fill style.
11#[derive(Clone, Copy, Debug, Zeroable, Pod, Default, PartialEq)]
12#[repr(C)]
13pub struct Style {
14    /// Encodes the stroke and fill style parameters. This field is split into two 16-bit
15    /// parts:
16    ///
17    /// - `flags: u16` - encodes fill vs stroke, even-odd vs non-zero fill
18    ///   mode for fills and cap and join style for strokes. See the
19    ///   `FLAGS_*` constants below for more information.
20    ///
21    ///   ```text
22    ///   flags: |style|fill|join|start cap|end cap|reserved|
23    ///    bits:  0     1    2-3  4-5       6-7     8-15
24    ///   ```
25    ///
26    /// - `miter_limit: u16` - The miter limit for a stroke, encoded in
27    ///   binary16 (half) floating point representation. This field is
28    ///   only meaningful for the `Join::Miter` join style. It's ignored
29    ///   for other stroke styles and fills.
30    pub flags_and_miter_limit: u32,
31
32    /// Encodes the stroke width. This field is ignored for fills.
33    pub line_width: f32,
34}
35
36impl Style {
37    /// 0 for a fill, 1 for a stroke
38    pub const FLAGS_STYLE_BIT: u32 = 0x8000_0000;
39
40    /// 0 for non-zero, 1 for even-odd
41    pub const FLAGS_FILL_BIT: u32 = 0x4000_0000;
42
43    /// Encodings for join style:
44    ///    - 0b00 -> bevel
45    ///    - 0b01 -> miter
46    ///    - 0b10 -> round
47    pub const FLAGS_JOIN_BITS_BEVEL: u32 = 0;
48    pub const FLAGS_JOIN_BITS_MITER: u32 = 0x1000_0000;
49    pub const FLAGS_JOIN_BITS_ROUND: u32 = 0x2000_0000;
50    pub const FLAGS_JOIN_MASK: u32 = 0x3000_0000;
51
52    /// Encodings for cap style:
53    ///    - 0b00 -> butt
54    ///    - 0b01 -> square
55    ///    - 0b10 -> round
56    pub const FLAGS_CAP_BITS_BUTT: u32 = 0;
57    pub const FLAGS_CAP_BITS_SQUARE: u32 = 0x0100_0000;
58    pub const FLAGS_CAP_BITS_ROUND: u32 = 0x0200_0000;
59
60    pub const FLAGS_START_CAP_BITS_BUTT: u32 = Self::FLAGS_CAP_BITS_BUTT << 2;
61    pub const FLAGS_START_CAP_BITS_SQUARE: u32 = Self::FLAGS_CAP_BITS_SQUARE << 2;
62    pub const FLAGS_START_CAP_BITS_ROUND: u32 = Self::FLAGS_CAP_BITS_ROUND << 2;
63    pub const FLAGS_END_CAP_BITS_BUTT: u32 = Self::FLAGS_CAP_BITS_BUTT;
64    pub const FLAGS_END_CAP_BITS_SQUARE: u32 = Self::FLAGS_CAP_BITS_SQUARE;
65    pub const FLAGS_END_CAP_BITS_ROUND: u32 = Self::FLAGS_CAP_BITS_ROUND;
66
67    pub const FLAGS_START_CAP_MASK: u32 = 0x0C00_0000;
68    pub const FLAGS_END_CAP_MASK: u32 = 0x0300_0000;
69    pub const MITER_LIMIT_MASK: u32 = 0xFFFF;
70
71    pub fn from_fill(fill: Fill) -> Self {
72        let fill_bit = match fill {
73            Fill::NonZero => 0,
74            Fill::EvenOdd => Self::FLAGS_FILL_BIT,
75        };
76        Self {
77            flags_and_miter_limit: fill_bit,
78            line_width: 0.,
79        }
80    }
81
82    /// Creates a style from a stroke.
83    ///
84    /// As it isn't meaningful to encode a zero width stroke, returns None if the width is zero.
85    pub fn from_stroke(stroke: &Stroke) -> Option<Self> {
86        if stroke.width == 0.0 {
87            return None;
88        }
89        let style = Self::FLAGS_STYLE_BIT;
90        let join = match stroke.join {
91            Join::Bevel => Self::FLAGS_JOIN_BITS_BEVEL,
92            Join::Miter => Self::FLAGS_JOIN_BITS_MITER,
93            Join::Round => Self::FLAGS_JOIN_BITS_ROUND,
94        };
95        let start_cap = match stroke.start_cap {
96            Cap::Butt => Self::FLAGS_START_CAP_BITS_BUTT,
97            Cap::Square => Self::FLAGS_START_CAP_BITS_SQUARE,
98            Cap::Round => Self::FLAGS_START_CAP_BITS_ROUND,
99        };
100        let end_cap = match stroke.end_cap {
101            Cap::Butt => Self::FLAGS_END_CAP_BITS_BUTT,
102            Cap::Square => Self::FLAGS_END_CAP_BITS_SQUARE,
103            Cap::Round => Self::FLAGS_END_CAP_BITS_ROUND,
104        };
105        let miter_limit = crate::math::f32_to_f16(stroke.miter_limit as f32) as u32;
106        Some(Self {
107            flags_and_miter_limit: style | join | start_cap | end_cap | miter_limit,
108            line_width: stroke.width as f32,
109        })
110    }
111
112    #[cfg(test)]
113    fn fill(self) -> Option<Fill> {
114        if self.is_fill() {
115            Some(
116                if (self.flags_and_miter_limit & Self::FLAGS_FILL_BIT) == 0 {
117                    Fill::NonZero
118                } else {
119                    Fill::EvenOdd
120                },
121            )
122        } else {
123            None
124        }
125    }
126
127    #[cfg(test)]
128    fn stroke_width(self) -> Option<f64> {
129        if self.is_fill() {
130            return None;
131        }
132        Some(self.line_width.into())
133    }
134
135    #[cfg(test)]
136    fn stroke_join(self) -> Option<Join> {
137        if self.is_fill() {
138            return None;
139        }
140        let join = self.flags_and_miter_limit & Self::FLAGS_JOIN_MASK;
141        Some(match join {
142            Self::FLAGS_JOIN_BITS_BEVEL => Join::Bevel,
143            Self::FLAGS_JOIN_BITS_MITER => Join::Miter,
144            Self::FLAGS_JOIN_BITS_ROUND => Join::Round,
145            _ => unreachable!("unsupported join encoding"),
146        })
147    }
148
149    #[cfg(test)]
150    fn stroke_start_cap(self) -> Option<Cap> {
151        if self.is_fill() {
152            return None;
153        }
154        let cap = self.flags_and_miter_limit & Self::FLAGS_START_CAP_MASK;
155        Some(match cap {
156            Self::FLAGS_START_CAP_BITS_BUTT => Cap::Butt,
157            Self::FLAGS_START_CAP_BITS_SQUARE => Cap::Square,
158            Self::FLAGS_START_CAP_BITS_ROUND => Cap::Round,
159            _ => unreachable!("unsupported start cap encoding"),
160        })
161    }
162
163    #[cfg(test)]
164    fn stroke_end_cap(self) -> Option<Cap> {
165        if self.is_fill() {
166            return None;
167        }
168        let cap = self.flags_and_miter_limit & Self::FLAGS_END_CAP_MASK;
169        Some(match cap {
170            Self::FLAGS_END_CAP_BITS_BUTT => Cap::Butt,
171            Self::FLAGS_END_CAP_BITS_SQUARE => Cap::Square,
172            Self::FLAGS_END_CAP_BITS_ROUND => Cap::Round,
173            _ => unreachable!("unsupported end cap encoding"),
174        })
175    }
176
177    #[cfg(test)]
178    fn stroke_miter_limit(self) -> Option<u16> {
179        if self.is_fill() {
180            return None;
181        }
182        Some((self.flags_and_miter_limit & Self::MITER_LIMIT_MASK) as u16)
183    }
184
185    #[cfg(test)]
186    fn is_fill(self) -> bool {
187        (self.flags_and_miter_limit & Self::FLAGS_STYLE_BIT) == 0
188    }
189}
190
191/// Line segment (after flattening, before tiling).
192#[derive(Clone, Copy, Debug, Zeroable, Pod, Default)]
193#[repr(C)]
194pub struct LineSoup {
195    pub path_ix: u32,
196    pub _padding: u32,
197    pub p0: [f32; 2],
198    pub p1: [f32; 2],
199}
200
201/// Line segment (after flattening, before tiling).
202#[derive(Clone, Copy, Debug, Zeroable, Pod, Default)]
203#[repr(C)]
204pub struct SegmentCount {
205    pub line_ix: u32,
206    // This could more accurately be modeled as:
207    //     segment_within_line: u16,
208    //     segment_within_slice: u16,
209    // However, here we mirror the way it's written in WGSL
210    pub counts: u32,
211}
212
213/// Path segment.
214#[derive(Clone, Copy, Debug, Zeroable, Pod, Default)]
215#[repr(C)]
216pub struct PathSegment {
217    // Points are relative to tile origin
218    pub point0: [f32; 2],
219    pub point1: [f32; 2],
220    pub y_edge: f32,
221    pub _padding: u32,
222}
223
224/// Path segment type.
225///
226/// The values of the segment types are equivalent to the number of associated
227/// points for each segment in the path data stream.
228#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Pod, Zeroable)]
229#[repr(C)]
230pub struct PathSegmentType(pub u8);
231
232impl PathSegmentType {
233    /// Line segment.
234    pub const LINE_TO: Self = Self(0x1);
235
236    /// Quadratic segment.
237    pub const QUAD_TO: Self = Self(0x2);
238
239    /// Cubic segment.
240    pub const CUBIC_TO: Self = Self(0x3);
241}
242
243/// Path tag representation.
244#[derive(Copy, Clone, PartialEq, Eq, Pod, Zeroable)]
245#[repr(C)]
246pub struct PathTag(pub u8);
247
248impl PathTag {
249    /// 32-bit floating point line segment.
250    ///
251    /// This is equivalent to `(PathSegmentType::LINE_TO | PathTag::F32_BIT)`.
252    pub const LINE_TO_F32: Self = Self(0x9);
253
254    /// 32-bit floating point quadratic segment.
255    ///
256    /// This is equivalent to `(PathSegmentType::QUAD_TO | PathTag::F32_BIT)`.
257    pub const QUAD_TO_F32: Self = Self(0xa);
258
259    /// 32-bit floating point cubic segment.
260    ///
261    /// This is equivalent to `(PathSegmentType::CUBIC_TO | PathTag::F32_BIT)`.
262    pub const CUBIC_TO_F32: Self = Self(0xb);
263
264    /// 16-bit integral line segment.
265    pub const LINE_TO_I16: Self = Self(0x1);
266
267    /// 16-bit integral quadratic segment.
268    pub const QUAD_TO_I16: Self = Self(0x2);
269
270    /// 16-bit integral cubic segment.
271    pub const CUBIC_TO_I16: Self = Self(0x3);
272
273    /// Transform marker.
274    pub const TRANSFORM: Self = Self(0x20);
275
276    /// Path marker.
277    pub const PATH: Self = Self(0x10);
278
279    /// Style setting.
280    pub const STYLE: Self = Self(0x40);
281
282    /// Bit that marks a segment that is the end of a subpath.
283    pub const SUBPATH_END_BIT: u8 = 0x4;
284
285    /// Bit for path segments that are represented as f32 values. If unset
286    /// they are represented as i16.
287    const F32_BIT: u8 = 0x8;
288
289    /// Mask for bottom 3 bits that contain the [`PathSegmentType`].
290    const SEGMENT_MASK: u8 = 0x3;
291
292    /// Returns `true` if the tag is a segment.
293    pub fn is_path_segment(self) -> bool {
294        self.path_segment_type().0 != 0
295    }
296
297    /// Returns `true` if this is a 32-bit floating point segment.
298    pub fn is_f32(self) -> bool {
299        self.0 & Self::F32_BIT != 0
300    }
301
302    /// Returns `true` if this segment ends a subpath.
303    pub fn is_subpath_end(self) -> bool {
304        self.0 & Self::SUBPATH_END_BIT != 0
305    }
306
307    /// Sets the subpath end bit.
308    pub fn set_subpath_end(&mut self) {
309        self.0 |= Self::SUBPATH_END_BIT;
310    }
311
312    /// Returns the segment type.
313    pub fn path_segment_type(self) -> PathSegmentType {
314        PathSegmentType(self.0 & Self::SEGMENT_MASK)
315    }
316}
317
318/// Monoid for the path tag stream.
319#[derive(Copy, Clone, Pod, Zeroable, Default, Debug)]
320#[repr(C)]
321pub struct PathMonoid {
322    /// Index into transform stream.
323    pub trans_ix: u32,
324    /// Path segment index.
325    pub pathseg_ix: u32,
326    /// Offset into path segment stream.
327    pub pathseg_offset: u32,
328    /// Index into style stream.
329    pub style_ix: u32,
330    /// Index of containing path.
331    pub path_ix: u32,
332}
333
334impl Monoid for PathMonoid {
335    type SourceValue = u32;
336
337    /// Reduces a packed 32-bit word containing 4 tags.
338    fn new(tag_word: u32) -> Self {
339        let mut c = Self::default();
340        let point_count = tag_word & 0x3030303;
341        c.pathseg_ix = ((point_count * 7) & 0x4040404).count_ones();
342        c.trans_ix = (tag_word & (PathTag::TRANSFORM.0 as u32 * 0x1010101)).count_ones();
343        let n_points = point_count + ((tag_word >> 2) & 0x1010101);
344        let mut a = n_points + (n_points & (((tag_word >> 3) & 0x1010101) * 15));
345        a += a >> 8;
346        a += a >> 16;
347        c.pathseg_offset = a & 0xff;
348        c.path_ix = (tag_word & (PathTag::PATH.0 as u32 * 0x1010101)).count_ones();
349        let style_size = (size_of::<Style>() / size_of::<u32>()) as u32;
350        c.style_ix = (tag_word & (PathTag::STYLE.0 as u32 * 0x1010101)).count_ones() * style_size;
351        c
352    }
353
354    /// Monoid combination.
355    fn combine(&self, other: &Self) -> Self {
356        Self {
357            trans_ix: self.trans_ix + other.trans_ix,
358            pathseg_ix: self.pathseg_ix + other.pathseg_ix,
359            pathseg_offset: self.pathseg_offset + other.pathseg_offset,
360            style_ix: self.style_ix + other.style_ix,
361            path_ix: self.path_ix + other.path_ix,
362        }
363    }
364}
365
366/// Cubic path segment.
367#[derive(Copy, Clone, Pod, Zeroable, Debug, Default)]
368#[repr(C)]
369pub struct Cubic {
370    pub p0: [f32; 2],
371    pub p1: [f32; 2],
372    pub p2: [f32; 2],
373    pub p3: [f32; 2],
374    pub stroke: [f32; 2],
375    pub path_ix: u32,
376    pub flags: u32,
377}
378
379/// Path bounding box.
380#[derive(Copy, Clone, Pod, Zeroable, Default, Debug)]
381#[repr(C)]
382pub struct PathBbox {
383    /// Minimum x value.
384    pub x0: i32,
385    /// Minimum y value.
386    pub y0: i32,
387    /// Maximum x value.
388    pub x1: i32,
389    /// Maximum y value.
390    pub y1: i32,
391    /// Style flags
392    pub draw_flags: u32,
393    /// Index into the transform stream.
394    pub trans_ix: u32,
395}
396
397/// Tiled path object.
398#[derive(Copy, Clone, Pod, Zeroable, Debug, Default)]
399#[repr(C)]
400#[expect(
401    clippy::partial_pub_fields,
402    reason = "Padding is meaningless to manipulate directly"
403)]
404pub struct Path {
405    /// Bounding box in tiles.
406    pub bbox: [u32; 4],
407    /// Offset (in u32s) to tile rectangle.
408    pub tiles: u32,
409    _padding: [u32; 3],
410}
411
412/// Tile object.
413#[derive(Copy, Clone, Pod, Zeroable, Debug, Default)]
414#[repr(C)]
415pub struct Tile {
416    /// Accumulated backdrop at the left edge of the tile.
417    pub backdrop: i32,
418    /// An enum that holds either the count of the number of path
419    /// segments in this tile, or an index to the beginning of an
420    /// allocated slice of `PathSegment` objects. In the latter case,
421    /// the bits are inverted.
422    pub segment_count_or_ix: u32,
423}
424
425/// Encoder for path segments.
426pub struct PathEncoder<'a> {
427    tags: &'a mut Vec<PathTag>,
428    data: &'a mut Vec<u32>,
429    n_segments: &'a mut u32,
430    n_paths: &'a mut u32,
431    first_point: [f32; 2],
432    first_start_tangent_end: [f32; 2],
433    state: PathState,
434    n_encoded_segments: u32,
435    is_fill: bool,
436}
437
438#[derive(PartialEq)]
439enum PathState {
440    Start,
441    MoveTo,
442    NonemptySubpath,
443}
444
445impl<'a> PathEncoder<'a> {
446    /// Creates a new path encoder for the specified path tags and data.
447    ///
448    /// If `is_fill` is true, ensures that all subpaths are closed. Otherwise, the path is treated
449    /// as a stroke and an additional "stroke cap marker" segment is inserted at the end of every
450    /// subpath.
451    ///
452    /// Stroke Encoding
453    /// ---------------
454    /// Every subpath within a stroked path is terminated with a "stroke cap marker" segment. This
455    /// segment tells the GPU stroker whether to draw a cap or a join based on the topology of the
456    /// path:
457    ///
458    /// 1. This marker segment is encoded as a `quad-to` (2 additional points) for an open path and
459    ///    a `line-to` (1 additional point) for a closed path. An open path gets drawn with a start
460    ///    and end cap. A closed path gets drawn with a single join in place of the caps where the
461    ///    subpath's start and end control points meet.
462    ///
463    /// 2. The marker segment tells the GPU flattening stage how to render caps and joins while
464    ///    processing each path segment in parallel. All subpaths end with the marker segment which
465    ///    is the only segment that has the `SUBPATH_END_BIT` set to 1.
466    ///
467    ///    The algorithm is as follows:
468    ///
469    ///    - If a GPU thread is processing a regular segment (i.e. `SUBPATH_END_BIT` is 0), it
470    ///      outputs the offset curves for the segment. If the segment is immediately followed by
471    ///      the marker segment, then the same thread draws an end cap if the subpath is open
472    ///      (i.e. the marker is a quad-to) or a join if the subpath is closed (i.e. the marker is
473    ///      a line-to) using the tangent encoded in the marker segment.
474    ///      If the segment is immediately followed by another regular segment, then the thread
475    ///      draws a join using the start tangent of the neighboring segment.
476    ///
477    ///    - If a GPU thread is processing the marker segment (i.e. `SUBPATH_END_BIT` is 1), then
478    ///      it draws a start cap using the information encoded in the segment IF the subpath is
479    ///      open (i.e. the marker is a quad-to). If the subpath is closed (i.e. the marker is a
480    ///      line-to), the thread draws nothing.
481    pub fn new(
482        tags: &'a mut Vec<PathTag>,
483        data: &'a mut Vec<u32>,
484        n_segments: &'a mut u32,
485        n_paths: &'a mut u32,
486        is_fill: bool,
487    ) -> Self {
488        Self {
489            tags,
490            data,
491            n_segments,
492            n_paths,
493            first_point: [0.0, 0.0],
494            first_start_tangent_end: [0.0, 0.0],
495            state: PathState::Start,
496            n_encoded_segments: 0,
497            is_fill,
498        }
499    }
500
501    /// Encodes a move, starting a new subpath.
502    pub fn move_to(&mut self, x: f32, y: f32) {
503        if self.is_fill {
504            self.close();
505        }
506        let buf = [x, y];
507        let bytes = bytemuck::cast_slice(&buf);
508        if self.state == PathState::MoveTo {
509            let new_len = self.data.len() - 2;
510            self.data.truncate(new_len);
511        } else if self.state == PathState::NonemptySubpath {
512            if !self.is_fill {
513                self.insert_stroke_cap_marker_segment(false);
514            }
515            if let Some(tag) = self.tags.last_mut() {
516                tag.set_subpath_end();
517            }
518        }
519        self.first_point = buf;
520        self.data.extend_from_slice(bytes);
521        self.state = PathState::MoveTo;
522    }
523
524    /// Encodes a line.
525    pub fn line_to(&mut self, x: f32, y: f32) {
526        if self.state == PathState::Start {
527            if self.n_encoded_segments == 0 {
528                // This copies the behavior of kurbo which treats an initial line, quad
529                // or curve as a move.
530                self.move_to(x, y);
531                return;
532            }
533            self.move_to(self.first_point[0], self.first_point[1]);
534        }
535        if self.state == PathState::MoveTo {
536            // Ensure that we don't end up with a zero-length start tangent.
537            let Some((x, y)) = self.start_tangent_for_line((x, y)) else {
538                return;
539            };
540            self.first_start_tangent_end = [x, y];
541        }
542        // Drop the segment if its length is zero
543        if self.is_zero_length_segment((x, y), None, None) {
544            return;
545        }
546        let buf = [x, y];
547        let bytes = bytemuck::cast_slice(&buf);
548        self.data.extend_from_slice(bytes);
549        self.tags.push(PathTag::LINE_TO_F32);
550        self.state = PathState::NonemptySubpath;
551        self.n_encoded_segments += 1;
552    }
553
554    /// Encodes a quadratic bezier.
555    pub fn quad_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32) {
556        if self.state == PathState::Start {
557            if self.n_encoded_segments == 0 {
558                self.move_to(x2, y2);
559                return;
560            }
561            self.move_to(self.first_point[0], self.first_point[1]);
562        }
563        if self.state == PathState::MoveTo {
564            // Ensure that we don't end up with a zero-length start tangent.
565            let Some((x, y)) = self.start_tangent_for_quad((x1, y1), (x2, y2)) else {
566                return;
567            };
568            self.first_start_tangent_end = [x, y];
569        }
570        // Drop the segment if its length is zero
571        if self.is_zero_length_segment((x1, y1), Some((x2, y2)), None) {
572            return;
573        }
574        let buf = [x1, y1, x2, y2];
575        let bytes = bytemuck::cast_slice(&buf);
576        self.data.extend_from_slice(bytes);
577        self.tags.push(PathTag::QUAD_TO_F32);
578        self.state = PathState::NonemptySubpath;
579        self.n_encoded_segments += 1;
580    }
581
582    /// Encodes a cubic bezier.
583    pub fn cubic_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32) {
584        if self.state == PathState::Start {
585            if self.n_encoded_segments == 0 {
586                self.move_to(x3, y3);
587                return;
588            }
589            self.move_to(self.first_point[0], self.first_point[1]);
590        }
591        if self.state == PathState::MoveTo {
592            // Ensure that we don't end up with a zero-length start tangent.
593            let Some((x, y)) = self.start_tangent_for_curve((x1, y1), (x2, y2), (x3, y3)) else {
594                return;
595            };
596            self.first_start_tangent_end = [x, y];
597        }
598        // Drop the segment if its length is zero
599        if self.is_zero_length_segment((x1, y1), Some((x2, y2)), Some((x3, y3))) {
600            return;
601        }
602        let buf = [x1, y1, x2, y2, x3, y3];
603        let bytes = bytemuck::cast_slice(&buf);
604        self.data.extend_from_slice(bytes);
605        self.tags.push(PathTag::CUBIC_TO_F32);
606        self.state = PathState::NonemptySubpath;
607        self.n_encoded_segments += 1;
608    }
609
610    /// Encodes an empty path (as placeholder for begin clip).
611    pub(crate) fn empty_path(&mut self) {
612        let coords = [0.0_f32, 0., 0., 0.];
613        let bytes = bytemuck::cast_slice(&coords);
614        self.data.extend_from_slice(bytes);
615        self.tags.push(PathTag::LINE_TO_F32);
616        self.n_encoded_segments += 1;
617    }
618
619    /// Closes the current subpath.
620    pub fn close(&mut self) {
621        match self.state {
622            PathState::Start => return,
623            PathState::MoveTo => {
624                // If we close a new-opened path, delete it.
625                let new_len = self.data.len() - 2;
626                self.data.truncate(new_len);
627                self.state = PathState::Start;
628                return;
629            }
630            PathState::NonemptySubpath => (),
631        }
632        let len = self.data.len();
633        if len < 2 {
634            if cfg!(debug_assertions) {
635                unreachable!("There is an open path, so there must be data.")
636            }
637            return;
638        }
639        let first_bytes = bytemuck::cast_slice(&self.first_point);
640        if &self.data[len - 2..len] != first_bytes {
641            self.data.extend_from_slice(first_bytes);
642            self.tags.push(PathTag::LINE_TO_F32);
643            self.n_encoded_segments += 1;
644        }
645        if !self.is_fill {
646            self.insert_stroke_cap_marker_segment(true);
647        }
648        if let Some(tag) = self.tags.last_mut() {
649            tag.set_subpath_end();
650        }
651        self.state = PathState::Start;
652    }
653
654    /// Encodes a shape.
655    pub fn shape(&mut self, shape: &impl Shape) {
656        self.path_elements(shape.path_elements(0.1));
657    }
658
659    /// Encodes a path iterator
660    pub fn path_elements(&mut self, path: impl Iterator<Item = peniko::kurbo::PathEl>) {
661        use peniko::kurbo::PathEl;
662        for el in path {
663            match el {
664                PathEl::MoveTo(p0) => self.move_to(p0.x as f32, p0.y as f32),
665                PathEl::LineTo(p0) => self.line_to(p0.x as f32, p0.y as f32),
666                PathEl::QuadTo(p0, p1) => {
667                    self.quad_to(p0.x as f32, p0.y as f32, p1.x as f32, p1.y as f32);
668                }
669                PathEl::CurveTo(p0, p1, p2) => self.cubic_to(
670                    p0.x as f32,
671                    p0.y as f32,
672                    p1.x as f32,
673                    p1.y as f32,
674                    p2.x as f32,
675                    p2.y as f32,
676                ),
677                PathEl::ClosePath => self.close(),
678            }
679        }
680    }
681
682    /// Completes path encoding and returns the actual number of encoded segments.
683    ///
684    /// If `insert_path_marker` is true, encodes the [`PathTag::PATH`] tag to signify
685    /// the end of a complete path object. Setting this to false allows encoding
686    /// multiple paths with differing transforms for a single draw object.
687    pub fn finish(mut self, insert_path_marker: bool) -> u32 {
688        if self.is_fill {
689            self.close();
690        }
691        if self.state == PathState::MoveTo {
692            let new_len = self.data.len() - 2;
693            self.data.truncate(new_len);
694        }
695        if self.n_encoded_segments != 0 {
696            if !self.is_fill && self.state == PathState::NonemptySubpath {
697                self.insert_stroke_cap_marker_segment(false);
698            }
699            if let Some(tag) = self.tags.last_mut() {
700                tag.set_subpath_end();
701            }
702            *self.n_segments += self.n_encoded_segments;
703            if insert_path_marker {
704                self.tags.push(PathTag::PATH);
705                *self.n_paths += 1;
706            }
707        }
708        self.n_encoded_segments
709    }
710
711    fn insert_stroke_cap_marker_segment(&mut self, is_closed: bool) {
712        assert!(!self.is_fill);
713        assert!(self.state == PathState::NonemptySubpath);
714        if is_closed {
715            // We expect that the most recently encoded pair of coordinates in the path data stream
716            // contain the first control point in the path segment (see `PathEncoder::close`).
717            // Hence a line-to encoded here should embed the subpath's start tangent.
718            self.line_to(
719                self.first_start_tangent_end[0],
720                self.first_start_tangent_end[1],
721            );
722        } else {
723            self.quad_to(
724                self.first_point[0],
725                self.first_point[1],
726                self.first_start_tangent_end[0],
727                self.first_start_tangent_end[1],
728            );
729        }
730    }
731
732    fn last_point(&self) -> Option<(f32, f32)> {
733        let len = self.data.len();
734        if len < 2 {
735            return None;
736        }
737        Some((
738            bytemuck::cast(self.data[len - 2]),
739            bytemuck::cast(self.data[len - 1]),
740        ))
741    }
742
743    fn is_zero_length_segment(
744        &self,
745        p1: (f32, f32),
746        p2: Option<(f32, f32)>,
747        p3: Option<(f32, f32)>,
748    ) -> bool {
749        let p0 = self.last_point().unwrap();
750        let p2 = p2.unwrap_or(p1);
751        let p3 = p3.unwrap_or(p1);
752
753        let x_min = p0.0.min(p1.0.min(p2.0.min(p3.0)));
754        let x_max = p0.0.max(p1.0.max(p2.0.max(p3.0)));
755        let y_min = p0.1.min(p1.1.min(p2.1.min(p3.1)));
756        let y_max = p0.1.max(p1.1.max(p2.1.max(p3.1)));
757
758        !(x_max - x_min > EPSILON || y_max - y_min > EPSILON)
759    }
760
761    // Returns the end point of the start tangent of a curve starting at `(x0, y0)`, or `None` if the
762    // curve is degenerate / has zero-length. The inputs are a sequence of control points that
763    // represent a cubic Bezier.
764    //
765    // `self.first_point` is always treated as the first control point of the curve.
766    fn start_tangent_for_curve(
767        &self,
768        p1: (f32, f32),
769        p2: (f32, f32),
770        p3: (f32, f32),
771    ) -> Option<(f32, f32)> {
772        let p0 = (self.first_point[0], self.first_point[1]);
773        let pt = if (p1.0 - p0.0).abs() > EPSILON || (p1.1 - p0.1).abs() > EPSILON {
774            p1
775        } else if (p2.0 - p0.0).abs() > EPSILON || (p2.1 - p0.1).abs() > EPSILON {
776            p2
777        } else if (p3.0 - p0.0).abs() > EPSILON || (p3.1 - p0.1).abs() > EPSILON {
778            p3
779        } else {
780            return None;
781        };
782        Some(pt)
783    }
784
785    /// Similar to [`Self::start_tangent_for_curve`] but for a line.
786    fn start_tangent_for_line(&self, p1: (f32, f32)) -> Option<(f32, f32)> {
787        let p0 = (self.first_point[0], self.first_point[1]);
788        let pt = if (p1.0 - p0.0).abs() > EPSILON || (p1.1 - p0.1).abs() > EPSILON {
789            (
790                p0.0 + 1. / 3. * (p1.0 - p0.0),
791                p0.1 + 1. / 3. * (p1.1 - p0.1),
792            )
793        } else {
794            return None;
795        };
796        Some(pt)
797    }
798
799    // Similar to `start_tangent_for_curve` but for a quadratic Bézier.
800    fn start_tangent_for_quad(&self, p1: (f32, f32), p2: (f32, f32)) -> Option<(f32, f32)> {
801        let p0 = (self.first_point[0], self.first_point[1]);
802        let pt = if (p1.0 - p0.0).abs() > EPSILON || (p1.1 - p0.1).abs() > EPSILON {
803            (
804                p1.0 + 1. / 3. * (p0.0 - p1.0),
805                p1.1 + 1. / 3. * (p0.1 - p1.1),
806            )
807        } else if (p2.0 - p0.0).abs() > EPSILON || (p2.1 - p0.1).abs() > EPSILON {
808            (
809                p1.0 + 1. / 3. * (p2.0 - p1.0),
810                p1.1 + 1. / 3. * (p2.1 - p1.1),
811            )
812        } else {
813            return None;
814        };
815        Some(pt)
816    }
817}
818
819impl skrifa::outline::OutlinePen for PathEncoder<'_> {
820    fn move_to(&mut self, x: f32, y: f32) {
821        self.move_to(x, y);
822    }
823
824    fn line_to(&mut self, x: f32, y: f32) {
825        self.line_to(x, y);
826    }
827
828    fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
829        self.quad_to(cx0, cy0, x, y);
830    }
831
832    fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
833        self.cubic_to(cx0, cy0, cx1, cy1, x, y);
834    }
835
836    fn close(&mut self) {
837        self.close();
838    }
839}
840
841const EPSILON: f32 = 1e-12;
842
843#[cfg(test)]
844mod tests {
845    use super::*;
846
847    #[test]
848    fn test_fill_style() {
849        assert_eq!(Some(Fill::NonZero), Style::from_fill(Fill::NonZero).fill());
850        assert_eq!(Some(Fill::EvenOdd), Style::from_fill(Fill::EvenOdd).fill());
851        assert_eq!(None, Style::from_stroke(&Stroke::default()).unwrap().fill());
852    }
853
854    #[test]
855    fn test_stroke_style() {
856        assert_eq!(None, Style::from_fill(Fill::NonZero).stroke_width());
857        assert_eq!(None, Style::from_fill(Fill::EvenOdd).stroke_width());
858        let caps = [Cap::Butt, Cap::Square, Cap::Round];
859        let joins = [Join::Bevel, Join::Miter, Join::Round];
860        for start in caps {
861            for end in caps {
862                for join in joins {
863                    let stroke = Stroke::new(1.0)
864                        .with_start_cap(start)
865                        .with_end_cap(end)
866                        .with_join(join)
867                        .with_miter_limit(0.);
868                    let encoded = Style::from_stroke(&stroke).unwrap();
869                    assert_eq!(Some(stroke.width), encoded.stroke_width());
870                    assert_eq!(Some(stroke.join), encoded.stroke_join());
871                    assert_eq!(Some(stroke.start_cap), encoded.stroke_start_cap());
872                    assert_eq!(Some(stroke.end_cap), encoded.stroke_end_cap());
873                    assert_eq!(Some(0), encoded.stroke_miter_limit());
874                }
875            }
876        }
877    }
878}