cranpose-ui-graphics 0.30.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
441
442
443
444
// The outline of what a stroke's lines cover, as closed contours that all
// turn one way: a non-zero fill of them covers each point once, so a
// translucent stroke drawn as that fill shows no darker overlap where its
// lines meet.

use std::f32::consts::{PI, TAU};

use crate::{
    PathContour, Point, Stroke, StrokeCap, StrokeJoin, vector_path::FLATTEN_TOLERANCE,
    whole::to_i32,
};

// The most points a disc at a round end takes. Discs take an even count, so
// no edge of one stands upright, which a fill's slices cannot follow.
const MAX_DISC_POINTS: usize = 64;

// Default miter limit (matches Compose / Skia): miter ratio <= 4.0, so
// 1 + dot >= 2 / 4^2 = 0.125.
const MIN_MITER_DENOM: f32 = 2.0 / 16.0;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ContourClosure {
    Open,
    Closed,
}

#[derive(Debug, Default)]
pub(crate) struct StrokeOutline {
    // The contours, the first `used` of them this outline's: the rest keep
    // their room for the next.
    contours: Vec<PathContour>,
    used: usize,
    // Reused scratch buffers for building one joined stroked contour.
    pos_side: Vec<Point>,
    neg_side: Vec<Point>,
}

impl StrokeOutline {
    pub(crate) const fn new() -> Self {
        Self {
            contours: Vec::new(),
            used: 0,
            pos_side: Vec::new(),
            neg_side: Vec::new(),
        }
    }

    pub(crate) fn clear(&mut self) {
        self.used = 0;
    }

    pub(crate) fn contours(&self) -> &[PathContour] {
        &self.contours[..self.used]
    }

    // Builds only the two offset sides for a single open non-round-capped
    // contour, returning `Some((pos, neg))` when the polyline has segments so
    // `PathSlicer::slice_monotone_sides` can slice them without copying into a
    // closed contour. Falls back to `None` for degenerate dot contours.
    pub(crate) fn build_open_sides(
        &mut self,
        points: &[Point],
        stroke: Stroke,
    ) -> Option<(&[Point], &[Point])> {
        let half = stroke.half_width();
        if half <= 0.0 || !half.is_finite() {
            return None;
        }
        let (_, last_seg) = self.trace_sides(points, ContourClosure::Open, stroke, half)?;
        let end = cap_offset(last_seg.end, last_seg.tangent, 1.0, stroke.cap, half);
        self.pos_side.push(offset(end, last_seg.across));
        self.neg_side.push(end - last_seg.across);
        Some((&self.pos_side, &self.neg_side))
    }

    // Materializes the sides built by `build_open_sides` into a closed contour
    // when monotone side slicing rejects them (e.g. a sharp spike that turns
    // back in x).
    pub(crate) fn materialize_open_sides(&mut self) {
        let pos_len = self.pos_side.len();
        let neg_len = self.neg_side.len();
        let contour = next_contour_in(&mut self.contours, &mut self.used);
        contour.reserve(pos_len + neg_len);
        contour.extend_from_slice(&self.pos_side);
        contour.extend(self.neg_side.iter().copied().rev());
    }

    // Builds joined closed fill contours for an open or closed polyline using
    // exact stroke joins and caps so every opacity shares one stroke geometry
    // and `PathSlicer` slices polylines directly into GPU trapezoids.
    pub(crate) fn add_contour(
        &mut self,
        points: &[Point],
        closure: ContourClosure,
        stroke: Stroke,
    ) {
        let half = stroke.half_width();
        if half <= 0.0 || !half.is_finite() {
            return;
        }
        let is_closed = closure == ContourClosure::Closed;
        let Some((first_seg, last_seg)) = self.trace_sides(points, closure, stroke, half) else {
            if let Some(&first) = points.first()
                && first.x.is_finite()
                && first.y.is_finite()
                && points.iter().all(|pt| pt.x.is_finite() && pt.y.is_finite())
            {
                self.add_dot(first, stroke.cap, half);
            }
            return;
        };
        if is_closed {
            push_join(
                &mut self.pos_side,
                &mut self.neg_side,
                last_seg,
                first_seg,
                stroke.join,
                half,
            );
            let outer = next_contour_in(&mut self.contours, &mut self.used);
            outer.extend_from_slice(&self.pos_side);
            let inner = next_contour_in(&mut self.contours, &mut self.used);
            inner.extend(self.neg_side.iter().copied().rev());
        } else {
            self.finish_open_polyline(first_seg, last_seg, stroke.cap, half);
        }
    }

    fn trace_sides(
        &mut self,
        points: &[Point],
        closure: ContourClosure,
        stroke: Stroke,
        half: f32,
    ) -> Option<(Segment, Segment)> {
        let is_closed = closure == ContourClosure::Closed;
        let mut iter = points.iter().copied();
        let first = iter.next()?;
        if !(first.x.is_finite() && first.y.is_finite()) {
            return None;
        }

        let mut prev_seg: Option<Segment> = None;
        let mut first_seg: Option<Segment> = None;
        let mut prev_pt = first;
        self.pos_side.clear();
        self.neg_side.clear();
        self.pos_side.reserve(points.len());
        self.neg_side.reserve(points.len());

        let mut push_segment = |seg: Segment| {
            match prev_seg {
                None => {
                    first_seg = Some(seg);
                    if !is_closed {
                        let start = cap_offset(seg.start, seg.tangent, -1.0, stroke.cap, half);
                        self.pos_side.push(offset(start, seg.across));
                        self.neg_side.push(start - seg.across);
                    }
                }
                Some(prev) => {
                    push_join(
                        &mut self.pos_side,
                        &mut self.neg_side,
                        prev,
                        seg,
                        stroke.join,
                        half,
                    );
                }
            }
            prev_seg = Some(seg);
        };

        for pt in iter {
            if !(pt.x.is_finite() && pt.y.is_finite()) {
                return None;
            }
            if pt == prev_pt {
                continue;
            }
            if let Some(seg) = Segment::new(prev_pt, pt, half) {
                prev_pt = pt;
                push_segment(seg);
            }
        }
        if is_closed
            && prev_pt != first
            && let Some(seg) = Segment::new(prev_pt, first, half)
        {
            push_segment(seg);
        }
        first_seg.zip(prev_seg)
    }

    fn finish_open_polyline(
        &mut self,
        first_seg: Segment,
        last: Segment,
        cap: StrokeCap,
        half: f32,
    ) {
        let end = cap_offset(last.end, last.tangent, 1.0, cap, half);
        self.pos_side.push(offset(end, last.across));
        self.neg_side.push(end - last.across);

        let pos_len = self.pos_side.len();
        let neg_len = self.neg_side.len();
        let contour = next_contour_in(&mut self.contours, &mut self.used);
        contour.reserve(pos_len + neg_len + 8);
        contour.extend_from_slice(&self.pos_side);
        if cap == StrokeCap::Round {
            push_arc(contour, last.end, last.across, neg(last.across), half, -1.0);
        }
        contour.extend(self.neg_side.iter().copied().rev());
        if cap == StrokeCap::Round {
            push_arc(
                contour,
                first_seg.start,
                neg(first_seg.across),
                first_seg.across,
                half,
                -1.0,
            );
        }
    }

    // Paints a degenerate zero-length contour when the stroke cap has area.
    fn add_dot(&mut self, center: Point, cap: StrokeCap, half: f32) {
        match cap {
            StrokeCap::Butt => {}
            StrokeCap::Square => {
                next_contour_in(&mut self.contours, &mut self.used).extend([
                    Point::new(center.x - half, center.y + half),
                    Point::new(center.x + half, center.y + half),
                    Point::new(center.x + half, center.y - half),
                    Point::new(center.x - half, center.y - half),
                ]);
            }
            StrokeCap::Round => {
                let count = disc_points(half);
                let (sin, cos) = (TAU / count as f32).sin_cos();
                let (mut x, mut y) = (half, 0.0_f32);
                let points = next_contour_in(&mut self.contours, &mut self.used);
                for _ in 0..count {
                    points.push(Point::new(center.x + x, center.y + y));
                    (x, y) = (x * cos + y * sin, y * cos - x * sin);
                }
            }
        }
    }
}

fn next_contour_in<'a>(contours: &'a mut Vec<PathContour>, used: &mut usize) -> &'a mut Vec<Point> {
    if *used == contours.len() {
        contours.push(PathContour {
            points: Vec::new(),
            closed: true,
        });
    }
    *used += 1;
    let points = &mut contours[*used - 1].points;
    points.clear();
    points
}

#[derive(Clone, Copy)]
struct Segment {
    start: Point,
    end: Point,
    tangent: Point,
    across: Point,
    length: f32,
}

impl Segment {
    #[inline]
    fn new(start: Point, end: Point, half: f32) -> Option<Self> {
        let delta = end - start;
        let length = delta.distance();
        if length <= 0.0 || !length.is_finite() {
            return None;
        }
        let inv_length = 1.0 / length;
        let tangent = Point::new(delta.x * inv_length, delta.y * inv_length);
        let across = Point::new(-tangent.y * half, tangent.x * half);
        Some(Self {
            start,
            end,
            tangent,
            across,
            length,
        })
    }
}

fn cap_offset(point: Point, tangent: Point, dir: f32, cap: StrokeCap, half: f32) -> Point {
    if cap == StrokeCap::Square {
        Point::new(
            point.x + tangent.x * dir * half,
            point.y + tangent.y * dir * half,
        )
    } else {
        point
    }
}

fn offset(a: Point, b: Point) -> Point {
    Point::new(a.x + b.x, a.y + b.y)
}

fn neg(a: Point) -> Point {
    Point::new(-a.x, -a.y)
}

fn push_join(
    pos_side: &mut Vec<Point>,
    neg_side: &mut Vec<Point>,
    prev: Segment,
    next: Segment,
    join: StrokeJoin,
    half: f32,
) {
    let pivot = next.start;
    let dot = prev.tangent.x * next.tangent.x + prev.tangent.y * next.tangent.y;
    let cross = prev.tangent.x * next.tangent.y - prev.tangent.y * next.tangent.x;
    if cross.abs() <= 1.0e-6 && dot > 0.0 {
        pos_side.push(offset(pivot, next.across));
        neg_side.push(pivot - next.across);
        return;
    }

    let denom = 1.0 + dot;
    let inv_denom = (denom > 1.0e-5).then(|| 1.0 / denom);
    let miter = inv_denom.map(|inv| {
        Point::new(
            (prev.across.x + next.across.x) * inv,
            (prev.across.y + next.across.y) * inv,
        )
    });
    let inner_fits =
        inv_denom.is_some_and(|inv| half * cross.abs() * inv <= prev.length.min(next.length));
    if join == StrokeJoin::Miter
        && denom >= MIN_MITER_DENOM
        && inner_fits
        && let Some(m) = miter
    {
        pos_side.push(offset(pivot, m));
        neg_side.push(pivot - m);
        return;
    }

    // `cross < 0`: pos_side (+across) is outer, neg_side (-across) is inner.
    // `cross > 0`: neg_side (-across) is outer, pos_side (+across) is inner.
    let (outer, inner, outer_a0, outer_a1, outer_m, arc_dir) = if cross < 0.0 {
        (
            pos_side,
            neg_side,
            prev.across,
            next.across,
            miter,
            -1.0_f32,
        )
    } else {
        (
            neg_side,
            pos_side,
            neg(prev.across),
            neg(next.across),
            miter.map(neg),
            1.0_f32,
        )
    };

    if join == StrokeJoin::Miter
        && denom >= MIN_MITER_DENOM
        && let Some(m) = outer_m
    {
        outer.push(offset(pivot, m));
    } else {
        outer.push(offset(pivot, outer_a0));
        if join == StrokeJoin::Round {
            push_arc(outer, pivot, outer_a0, outer_a1, half, arc_dir);
        }
        outer.push(offset(pivot, outer_a1));
    }

    // On the inner side, use the exact miter intersection when it stays
    // within both adjacent segments; otherwise bevel across the corner.
    if inner_fits && let Some(m) = outer_m {
        inner.push(pivot - m);
    } else {
        inner.push(pivot - outer_a0);
        inner.push(pivot - outer_a1);
    }
}

// Appends strictly interior points along the circular arc of `radius` around
// `center` from offset `from` to `to`, sweeping by `arc_dir` (+1 clockwise in
// y-down, -1 counter-clockwise).
fn push_arc(
    out: &mut Vec<Point>,
    center: Point,
    from: Point,
    to: Point,
    radius: f32,
    arc_dir: f32,
) {
    let start_angle = from.y.atan2(from.x);
    let end_angle = to.y.atan2(to.x);
    let mut sweep = (end_angle - start_angle) * arc_dir;
    while sweep <= 0.0 {
        sweep += TAU;
    }
    if sweep > TAU - 1.0e-4 {
        return;
    }
    let full = disc_points(radius) as f32;
    let steps = usize::try_from(to_i32(((sweep / TAU) * full).ceil()))
        .map_or(1, |count| count.clamp(1, MAX_DISC_POINTS));
    if steps <= 1 {
        return;
    }
    let step = (sweep / steps as f32) * arc_dir;
    let (sin, cos) = step.sin_cos();
    let (mut x, mut y) = (from.x, from.y);
    for _ in 1..steps {
        (x, y) = (x * cos - y * sin, x * sin + y * cos);
        out.push(Point::new(center.x + x, center.y + y));
    }
}

// The even count of points that keeps a disc of `radius` within the
// flattening tolerance of its circle.
fn disc_points(radius: f32) -> usize {
    let cos = 1.0 - FLATTEN_TOLERANCE / radius;
    let needed = if cos > -1.0 {
        to_i32((PI / cos.acos()).ceil())
    } else {
        0
    };
    (usize::try_from(needed).map_or(4, |count| count.clamp(4, MAX_DISC_POINTS)) + 1) & !1
}