cranpose-ui-graphics 0.15.0

Geometry, units, paths and render data for Cranpose UI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Paths an app builds from lines and curves, and the styles a draw scope
//! fills or strokes them with: Compose's `Path`, `DrawStyle` and
//! `PathEffect.dashPathEffect`.
//!
//! Curves are flattened as they are added, within the tolerance vector icons
//! use, so a path holds polylines only. A fill rasterizes them as
//! [`crate::VectorPath`] does; a stroke draws each flattened edge as a
//! [`crate::DrawPrimitive::Line`] on the GPU.

use crate::{
    LineGeometry, PathFillRule, Point, Rect, Stroke, StrokeCap, StrokeJoin, VectorPath,
    vector_path::{flatten_cubic_into, quad_as_cubic},
};

/// One contour of a [`Path`]: its flattened points and whether it closes
/// back to its first.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PathContour {
    /// Flattened points of the contour, in the path's coordinates.
    pub points: Vec<Point>,
    /// Whether the contour closes back to its first point.
    pub closed: bool,
}

impl PathContour {
    /// Points a contour holds before it first grows: room for a chart's
    /// few dozen points in a few growths instead of one per doubling from
    /// one.
    const INITIAL_POINTS: usize = 16;

    /// A contour at `point`, in the room a dropped path left on this thread
    /// when there is some.
    fn starting_at(point: Point) -> Self {
        let mut points =
            crate::thread_state::with(|state| state.path_buffers.borrow_mut().points());
        points.push(point);
        Self {
            points,
            closed: false,
        }
    }
}

/// The point lists and contour lists dropped paths left on a thread, which
/// the next paths built there take: a path an app builds in each draw, as
/// Compose apps do, then allocates nothing once its lists reached its size.
pub(crate) struct PathBuffers {
    points: Vec<Vec<Point>>,
    /// The room of the kept point lists, in points.
    kept_points: usize,
    contours: Vec<Vec<PathContour>>,
}

impl PathBuffers {
    /// The most contour lists a thread keeps.
    const KEPT: usize = 32;
    /// The most room, in points, the kept point lists hold together: 32 KB,
    /// small enough for an ESP32 build.
    const POINT_BUDGET: usize = 4096;

    pub(crate) const fn new() -> Self {
        Self {
            points: Vec::new(),
            kept_points: 0,
            contours: Vec::new(),
        }
    }

    fn points(&mut self) -> Vec<Point> {
        match self.points.pop() {
            Some(points) => {
                self.kept_points -= points.capacity();
                points
            }
            None => Vec::with_capacity(PathContour::INITIAL_POINTS),
        }
    }

    fn contours(&mut self) -> Vec<PathContour> {
        self.contours.pop().unwrap_or_default()
    }

    /// Keeps the point lists of `contours`, which it leaves empty.
    fn keep_points(&mut self, contours: &mut Vec<PathContour>) {
        for PathContour { mut points, .. } in contours.drain(..) {
            let room = points.capacity();
            if self.kept_points + room <= Self::POINT_BUDGET {
                points.clear();
                self.kept_points += room;
                self.points.push(points);
            }
        }
    }

    /// Keeps the point lists of `contours` and the list itself.
    fn keep(&mut self, mut contours: Vec<PathContour>) {
        self.keep_points(&mut contours);
        if self.contours.len() < Self::KEPT {
            self.contours.push(contours);
        }
    }
}

/// A path built from lines and curves: Compose's `Path`.
///
/// Example: a sparkline, stroked by [`crate::DrawScope::draw_path`]:
///
/// ```
/// use cranpose_ui_graphics::{Path, Point};
///
/// let mut path = Path::new();
/// path.move_to(Point::new(0.0, 10.0));
/// path.line_to(Point::new(10.0, 4.0));
/// path.quadratic_to(Point::new(15.0, 0.0), Point::new(20.0, 6.0));
/// assert_eq!(path.contours().len(), 1);
/// ```
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Path {
    contours: Vec<PathContour>,
    pen: Point,
}

impl Path {
    /// An empty path.
    pub fn new() -> Self {
        Self::default()
    }

    /// Starts a new contour at `point`.
    pub fn move_to(&mut self, point: Point) {
        self.push_contour(point);
        self.pen = point;
    }

    fn push_contour(&mut self, start: Point) {
        if self.contours.capacity() == 0 {
            self.contours =
                crate::thread_state::with(|state| state.path_buffers.borrow_mut().contours());
        }
        self.contours.push(PathContour::starting_at(start));
    }

    /// Adds a straight edge from the pen to `point`.
    #[inline]
    pub fn line_to(&mut self, point: Point) {
        match self.contours.last_mut() {
            Some(contour) if !contour.closed => contour.points.push(point),
            _ => self.open_contour().push(point),
        }
        self.pen = point;
    }

    /// Adds the quadratic curve from the pen through `control` to `end`:
    /// Compose's `quadraticTo`.
    pub fn quadratic_to(&mut self, control: Point, end: Point) {
        let (first, second) = quad_as_cubic(self.pen, control, end);
        self.cubic_to(first, second, end);
    }

    /// Adds the cubic curve from the pen through `first` and `second` to
    /// `end`: Compose's `cubicTo`.
    pub fn cubic_to(&mut self, first: Point, second: Point, end: Point) {
        let start = self.pen;
        flatten_cubic_into(self.open_contour(), start, first, second, end);
        self.pen = end;
    }

    /// Closes the current contour back to its first point; the next edge
    /// starts a new contour there.
    pub fn close(&mut self) {
        if let Some(contour) = self.contours.last_mut().filter(|contour| !contour.closed) {
            contour.closed = true;
            if let Some(&first) = contour.points.first() {
                self.pen = first;
            }
        }
    }

    /// Removes every contour.
    pub fn reset(&mut self) {
        if !self.contours.is_empty() {
            crate::thread_state::with(|state| {
                state
                    .path_buffers
                    .borrow_mut()
                    .keep_points(&mut self.contours);
            });
        }
        self.pen = Point::ZERO;
    }

    /// The contours, each flattened to points.
    pub fn contours(&self) -> &[PathContour] {
        &self.contours
    }

    /// Whether the path has no edge.
    pub fn is_empty(&self) -> bool {
        !self
            .contours
            .iter()
            .any(|contour| contour.points.len() >= 2)
    }

    /// The box of every point, or an empty rect at the origin for an
    /// empty path.
    pub fn bounds(&self) -> Rect {
        let mut points = self.contours.iter().flat_map(|contour| &contour.points);
        let Some(&first) = points.next() else {
            return Rect::EMPTY;
        };
        let (min, max) = points.fold((first, first), |(min, max), point| {
            (
                Point::new(min.x.min(point.x), min.y.min(point.y)),
                Point::new(max.x.max(point.x), max.y.max(point.y)),
            )
        });
        Rect {
            x: min.x,
            y: min.y,
            width: max.x - min.x,
            height: max.y - min.y,
        }
    }

    /// The path as a fill: every contour closed, under `fill_rule`.
    pub fn to_vector_path(&self, fill_rule: PathFillRule) -> VectorPath {
        VectorPath::from_subpaths(
            self.contours
                .iter()
                .filter(|contour| contour.points.len() >= 2)
                .map(|contour| contour.points.clone())
                .collect(),
            fill_rule,
        )
    }

    /// The contour an edge extends: the last one when it is still open,
    /// otherwise a new one starting at the pen.
    fn open_contour(&mut self) -> &mut Vec<Point> {
        if self.contours.last().is_none_or(|contour| contour.closed) {
            self.push_contour(self.pen);
        }
        let last = self.contours.len() - 1;
        &mut self.contours[last].points
    }
}

impl Drop for Path {
    fn drop(&mut self) {
        if self.contours.capacity() == 0 {
            return;
        }
        let contours = std::mem::take(&mut self.contours);
        crate::thread_state::with(|state| state.path_buffers.borrow_mut().keep(contours));
    }
}

/// Dashes along a stroke: on for the first interval, off for the second,
/// and so on, starting `phase` into the pattern. Compose's
/// `PathEffect.dashPathEffect(intervals, phase)`. Up to
/// [`DashPathEffect::MAX_INTERVALS`] intervals; a pattern with an odd
/// count or a non-positive sum draws the stroke whole, as Skia does.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DashPathEffect {
    intervals: [f32; DashPathEffect::MAX_INTERVALS],
    count: usize,
    phase: f32,
}

impl DashPathEffect {
    /// The most intervals a pattern holds.
    pub const MAX_INTERVALS: usize = 8;

    /// A dash pattern of `intervals`, the extras past
    /// [`Self::MAX_INTERVALS`] dropped, starting `phase` into it.
    pub fn new(intervals: &[f32], phase: f32) -> Self {
        let mut stored = [0.0; Self::MAX_INTERVALS];
        let count = intervals.len().min(Self::MAX_INTERVALS);
        stored[..count].copy_from_slice(&intervals[..count]);
        Self {
            intervals: stored,
            count,
            phase,
        }
    }

    /// The intervals, on then off in turn.
    pub fn intervals(&self) -> &[f32] {
        &self.intervals[..self.count]
    }

    fn period(&self) -> Option<f32> {
        let period: f32 = self
            .intervals()
            .iter()
            .map(|interval| interval.max(0.0))
            .sum();
        (self.count >= 2 && self.count.is_multiple_of(2) && period > 0.0 && period.is_finite())
            .then_some(period)
    }

    /// Hands `dash` each dash of the polyline through `points` in turn, as
    /// a polyline of its own; the whole polyline when the pattern draws it
    /// whole.
    pub fn for_each_dash(&self, points: &[Point], mut dash: impl FnMut(&[Point])) {
        let Some(period) = self.period() else {
            dash(points);
            return;
        };
        let interval = |index: usize| self.intervals[index].max(0.0);
        let mut current: Vec<Point> = Vec::new();
        // Where in the pattern the walk is, and which interval it is in.
        let mut into = self.phase.rem_euclid(period);
        let mut index = 0;
        while into >= interval(index) {
            into -= interval(index);
            index = (index + 1) % self.count;
        }
        for pair in points.windows(2) {
            let (start, end) = (pair[0], pair[1]);
            let length = ((end.x - start.x).powi(2) + (end.y - start.y).powi(2)).sqrt();
            let at = |distance: f32| {
                let t = if length > 0.0 { distance / length } else { 0.0 };
                Point::new(
                    start.x + (end.x - start.x) * t,
                    start.y + (end.y - start.y) * t,
                )
            };
            let mut walked = 0.0;
            while walked < length {
                let on = index.is_multiple_of(2);
                let step = (interval(index) - into).min(length - walked);
                if on {
                    if current.is_empty() {
                        current.push(at(walked));
                    }
                    current.push(at(walked + step));
                }
                walked += step;
                into += step;
                if into >= interval(index) {
                    into = 0.0;
                    if on && current.len() >= 2 {
                        dash(&current);
                    }
                    current.clear();
                    index = (index + 1) % self.count;
                }
            }
        }
        if current.len() >= 2 {
            dash(&current);
        }
    }
}

/// How [`crate::DrawScope::draw_path`] paints a path: Compose's `Fill` and
/// `Stroke` draw styles, the stroke dashed when it carries a path effect.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DrawStyle {
    /// Fills the path's contours, each closed, under the non-zero rule.
    Fill,
    /// Strokes the path's edges with the stroke's width, cap and join.
    Stroke(Stroke),
    /// Strokes the dashes the effect cuts the path's edges into, each dash
    /// capped by the stroke's cap.
    DashedStroke(Stroke, DashPathEffect),
}

/// Hands `line` the segments a stroke draws for the polyline through
/// `points`, closed back to its first point when `closed`. An open
/// polyline's two ends take the stroke's cap; every corner takes the cap
/// closest to the stroke's join, round for round and bevel joins, square
/// for a miter, which is exact at a right angle. A segment whose two ends
/// want the same cap draws with it; one whose ends differ draws butt ends,
/// grown by half the width at a square end, and a dot of the stroke at a
/// round one.
pub fn for_each_stroke_line(
    points: &[Point],
    closed: bool,
    stroke: Stroke,
    mut line: impl FnMut(LineGeometry),
) {
    let corner = match stroke.join {
        StrokeJoin::Miter => StrokeCap::Square,
        StrokeJoin::Round | StrokeJoin::Bevel => StrokeCap::Round,
    };
    let closing = closed
        .then(|| points.first().zip(points.last()))
        .flatten()
        .filter(|(first, last)| first != last)
        .map(|(&first, &last)| (last, first));
    let mut edges = points
        .windows(2)
        .map(|pair| (pair[0], pair[1]))
        .chain(closing)
        .filter(|(start, end)| start != end)
        .peekable();
    let mut first = true;
    while let Some((start, end)) = edges.next() {
        let start_cap = if closed || !first { corner } else { stroke.cap };
        first = false;
        let end_cap = if closed || edges.peek().is_some() {
            corner
        } else {
            stroke.cap
        };
        let with_cap = |cap| Stroke { cap, ..stroke };
        if start_cap == end_cap {
            line(LineGeometry::new(start, end, with_cap(start_cap)));
            continue;
        }
        let half_width = stroke.half_width();
        let length = ((end.x - start.x).powi(2) + (end.y - start.y).powi(2)).sqrt();
        let grow = |cap: StrokeCap| {
            if cap == StrokeCap::Square {
                half_width / length
            } else {
                0.0
            }
        };
        let (back, ahead) = (grow(start_cap), grow(end_cap));
        let (dx, dy) = (end.x - start.x, end.y - start.y);
        line(LineGeometry::new(
            Point::new(start.x - dx * back, start.y - dy * back),
            Point::new(end.x + dx * ahead, end.y + dy * ahead),
            with_cap(StrokeCap::Butt),
        ));
        for (point, cap) in [(start, start_cap), (end, end_cap)] {
            if cap == StrokeCap::Round {
                line(LineGeometry::new(point, point, with_cap(StrokeCap::Round)));
            }
        }
    }
}

#[cfg(test)]
#[path = "tests/path_tests.rs"]
mod tests;