linesweeper 0.3.0

Robust sweep-line algorithm and two-dimensional boolean ops
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
445
446
447
448
449
//! An algorithm for laying out curves in a given order.
//!
//! Our boolean ops algorithms work by first deciding horizontal orderings for curves
//! (with some guarantees about being approximately correct)
//! and then laying out the curves in a way that has the horizontal orders we decided
//! on. For this second step, which is the task of this module, we really
//! guarantee correctness: the curves that we output really have the specified
//! orders.

use std::collections::BinaryHeap;

use kurbo::{BezPath, CubicBez};

use crate::{
    curve::{
        transverse::{transversal_after, transversal_before},
        y_subsegment, EstParab, Order,
    },
    num::CheapOrderedFloat,
    order::ComparisonCache,
    topology::{HalfOutputSegVec, OutputSegIdx, OutputSegVec, ScanLineOrder},
    SegIdx, Segment, Segments,
};

// TODO: maybe a Context type to keep the parameters in check?
#[allow(clippy::too_many_arguments)]
fn ordered_curves_all_close(
    segs: &Segments,
    order: &[SegIdx],
    output_order: &[OutputSegIdx],
    out: &mut OutputSegVec<PositionedOutputSeg>,
    mut y0: f64,
    y1: f64,
    endpoints: &HalfOutputSegVec<kurbo::Point>,
    accuracy: f64,
) {
    if order.iter().all(|&s| segs[s].is_line()) {
        // If everything is a line, since our endpoints are already in the right order
        // the segments between them are also guaranteed to be in the right order.
        return;
    }

    if order.len() == 2 {
        let s0 = order[0];
        let s1 = order[1];
        let o0 = output_order[0];
        let o1 = output_order[1];

        let p0 = bez_end(&out[o0].path);
        let p1 = bez_end(&out[o1].path);
        let q0 = endpoints[o0.second_half()];
        let q1 = endpoints[o1.second_half()];

        if p0.y == y0 && p1.y == y0 {
            let c0 = next_subsegment(&segs[s0], &out[o0].path, y1, q0);
            let c1 = next_subsegment(&segs[s1], &out[o1].path, y1, q1);

            if transversal_after(c0, c1, y1) {
                return;
            }
        }

        if q0.y == y1 && q1.y == y1 {
            let c0 = next_subsegment(&segs[s0], &out[o0].path, y1, q0);
            let c1 = next_subsegment(&segs[s1], &out[o1].path, y1, q1);

            if transversal_before(c0, c1, y0) {
                return;
            }
        }
    }

    // Ensure everything in `out` goes up to `y0`. Anything that doesn't go up to `y0` is
    // an output where we can just copy from the input.
    for (&seg_idx, &out_idx) in order.iter().zip(output_order) {
        let out = &mut out[out_idx];
        if bez_end_y(&out.path) < y0 {
            out.copied_idx = Some(out.path.elements().len() - 1);
            let endpoint = endpoints[out_idx.second_half()];
            if segs[seg_idx].is_line() {
                out.path.line_to(endpoint)
            } else {
                let c = next_subsegment(&segs[seg_idx], &out.path, y0, endpoint);
                out.path.curve_to(c.p1, c.p2, c.p3);
            }
        }
    }

    let mut approxes = Vec::new();

    // The recentering helps, but there are still some issues with approximation when almost horizontal
    while y0 < y1 {
        let next_y0 = approximate(y0, y1, order, segs, accuracy, &mut approxes);

        let y_mid = (y0 + next_y0) / 2.0;

        let mut x_mid_max_so_far = f64::NEG_INFINITY;
        let mut x1_max_so_far = f64::NEG_INFINITY;
        for (quad, out_idx) in approxes.iter().zip(output_order) {
            // These would be the control points, but since `approximate` recenters the y interval,
            // they're different...
            // let x_mid = quad.c0 + y_mid * quad.c1 + y0 * next_y0 * quad.c2;
            // let x1 = quad.c0 + quad.c1 * next_y0 + quad.c2 * next_y0 * next_y0;
            let x_mid = quad.c0 + (y0 - y_mid) * (next_y0 - y_mid) * quad.c2;
            let x1 = quad.c0
                + quad.c1 * (next_y0 - y_mid)
                + quad.c2 * (next_y0 - y_mid) * (next_y0 - y_mid);

            x_mid_max_so_far = x_mid_max_so_far.max(x_mid);
            x1_max_so_far = x1_max_so_far.max(x1);

            out[*out_idx]
                .path
                .quad_to((x_mid_max_so_far, y_mid), (x1_max_so_far, next_y0));
        }
        approxes.clear();

        y0 = next_y0;
    }
}

fn horizontal_error_weight(c: CubicBez) -> f64 {
    let tangents = [c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2];
    let mut weight = 0.0f64;

    fn different_signs(x: f64, y: f64) -> bool {
        (x > 0.0 && y < 0.0) || (x < 0.0) && (y > 0.0)
    }

    if different_signs(tangents[0].x, tangents[1].x)
        || different_signs(tangents[1].x, tangents[2].x)
    {
        return 1.0;
    }

    for v in tangents {
        let denom = v.hypot2().sqrt();
        if denom != 0.0 {
            let w = v.y.abs() / denom;
            weight = weight.max(w);
        }
    }
    weight
}

// Pushes approximating parabolas into `out`, and returns the final y position.
fn approximate(
    y0: f64,
    mut y1: f64,
    order: &[SegIdx],
    segs: &Segments,
    accuracy: f64,
    out: &mut Vec<EstParab>,
) -> f64 {
    let orig_len = out.len();

    'retry: loop {
        let y_mid = (y0 + y1) / 2.0;
        for seg_idx in order {
            let cubic = segs[*seg_idx].to_kurbo_cubic();
            let mut cubic = y_subsegment(cubic, y0, y1);
            cubic.p0.y -= y_mid;
            cubic.p1.y -= y_mid;
            cubic.p2.y -= y_mid;
            cubic.p3.y -= y_mid;
            let approx = EstParab::from_cubic(cubic);

            let factor = horizontal_error_weight(cubic);

            let too_short = y1 <= y0 + accuracy;
            let accurate = approx.dmax.max(-approx.dmin) * factor < accuracy;
            if !too_short && !accurate {
                // TODO: can we be smarter about this?
                y1 = (y0 + y1) / 2.0;
                out.truncate(orig_len);
                continue 'retry;
            }

            out.push(approx);
        }

        return y1;
    }
}

#[derive(Debug, PartialEq, Eq)]
struct HeapEntry {
    y: CheapOrderedFloat,
    idx: OutputSegIdx,
}

impl Ord for HeapEntry {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        other.y.cmp(&self.y).then(self.idx.cmp(&other.idx))
    }
}

impl PartialOrd for HeapEntry {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

fn bez_end(path: &BezPath) -> kurbo::Point {
    match path.elements().last().unwrap() {
        kurbo::PathEl::MoveTo(p)
        | kurbo::PathEl::LineTo(p)
        | kurbo::PathEl::QuadTo(_, p)
        | kurbo::PathEl::CurveTo(_, _, p) => *p,
        kurbo::PathEl::ClosePath => unreachable!(),
    }
}

fn bez_end_y(path: &BezPath) -> f64 {
    bez_end(path).y
}

fn next_subsegment(seg: &Segment, out: &BezPath, y1: f64, endpoint: kurbo::Point) -> CubicBez {
    let p0 = bez_end(out);
    let mut c = y_subsegment(seg.to_kurbo_cubic(), p0.y, y1);
    c.p0 = p0;
    if endpoint.y == y1 {
        c.p3 = endpoint;
    }
    c
}

/// A positioned output segment, possibly perturbed from the original.
///
/// We perturb output segments in order to strictly enforce ordering.
/// A single segment might be expanded into a longer path.
#[derive(Default)]
pub struct PositionedOutputSeg {
    /// The path, which is guaranteed to start and end at the same points as the
    /// output segment did.
    pub path: BezPath,
    /// Sometimes (often, even) a large part of the output segment didn't need
    /// to be perturbed. Our sweep-line invariants guarantee that unperturbed
    /// part can only be a single contiguous interval: this stores the index
    /// of the unperturbed part within `path.segments()`.
    pub copied_idx: Option<usize>,
}

/// Compute positions for all of the output segments.
///
/// The orders between the output segments is specified by `order`. The endpoints
/// should have been already computed (in a way that satisfies the order), and
/// are provided in `endpoints`. For each output segment, we return a Bézier
/// path.
pub(crate) fn compute_positions(
    segs: &Segments,
    orig_seg_map: &OutputSegVec<SegIdx>,
    cmp: &mut ComparisonCache,
    endpoints: &HalfOutputSegVec<kurbo::Point>,
    scan_order: &ScanLineOrder,
    accuracy: f64,
) -> OutputSegVec<PositionedOutputSeg> {
    let mut out = OutputSegVec::<PositionedOutputSeg>::with_size(orig_seg_map.len());
    // We try to build `out` lazily, by avoiding copying input segments to outputs segments
    // until they're needed (by copying in one go, we avoid excess subdivisions). That means
    // we need to separately keep track of how far down we've looked at each output. If
    // we weren't lazy, that would just be the last `y` coordinate in `out`.
    let mut last_y = OutputSegVec::<f64>::with_size(orig_seg_map.len());
    let mut queue = BinaryHeap::<HeapEntry>::new();
    for idx in out.indices() {
        let p = endpoints[idx.first_half()];
        let q = endpoints[idx.second_half()];
        if p.y == q.y {
            out[idx].path.move_to(p);
            out[idx].path.line_to(q);
            out[idx].copied_idx = Some(0);
            continue;
        }
        out[idx].path.move_to(p);
        queue.push(HeapEntry { y: p.y.into(), idx });
    }

    while let Some(entry) = queue.pop() {
        // Maybe this entry was already handled by one of its neighbors, in which case we skip it.
        let y0 = entry.y.into_inner();
        if last_y[entry.idx] > y0 {
            continue;
        }

        let mut y1 = endpoints[entry.idx.second_half()].y;
        let mut west_scan = vec![entry.idx];
        let mut cur = entry.idx;
        while let Some(nbr) = scan_order.west_neighbor_after(cur, y0) {
            let order = cmp.compare_segments(segs, orig_seg_map[nbr], orig_seg_map[cur]);
            let (_, cmp_end_y, cmp_order) = order.iter().find(|(_, end_y, _)| *end_y > y0).unwrap();

            if cmp_order == Order::Left {
                let next_close_y = scan_order
                    .close_west_neighbor_height_after(cur, y0, orig_seg_map, segs, cmp)
                    .unwrap_or(f64::INFINITY);
                y1 = y1.min(next_close_y.max(cmp_end_y));
                break;
            } else {
                y1 = y1.min(cmp_end_y).min(endpoints[nbr.second_half()].y);
                west_scan.push(nbr);
            }
            cur = nbr;
        }

        let mut east_scan = vec![];
        let mut cur = entry.idx;
        while let Some(nbr) = scan_order.east_neighbor_after(cur, y0) {
            let order = cmp.compare_segments(segs, orig_seg_map[cur], orig_seg_map[nbr]);
            let (_, cmp_end_y, cmp_order) = order.iter().find(|(_, end_y, _)| *end_y > y0).unwrap();

            if cmp_order == Order::Left {
                let next_close_y = scan_order
                    .close_east_neighbor_height_after(cur, y0, orig_seg_map, segs, cmp)
                    .unwrap_or(f64::INFINITY);
                y1 = y1.min(next_close_y.max(cmp_end_y));
                break;
            } else {
                y1 = y1.min(cmp_end_y).min(endpoints[nbr.second_half()].y);
                east_scan.push(nbr);
            }
            cur = nbr;
        }

        let mut neighbors = west_scan;
        neighbors.reverse();
        neighbors.extend(east_scan);
        if neighbors.len() == 1 {
            let idx = entry.idx;
            // We're far from everything, so we can just copy the input bezier to the output.
            // We only actually do this eagerly for horizontal segments: for other segments
            // we'll hold off on the copying because it might allow us to avoid further
            // subdivision.
            if y0 == y1 {
                out[idx].copied_idx = Some(out[idx].path.elements().len() - 1);
                out[idx].path.line_to(endpoints[idx.second_half()]);
            }
        } else {
            let orig_neighbors = neighbors
                .iter()
                .map(|idx| orig_seg_map[*idx])
                .collect::<Vec<_>>();

            ordered_curves_all_close(
                segs,
                &orig_neighbors,
                &neighbors,
                &mut out,
                y0,
                y1,
                endpoints,
                accuracy,
            );
        }
        for idx in neighbors {
            let y_end = endpoints[idx.second_half()].y;
            if y1 < y_end {
                queue.push(HeapEntry { y: y1.into(), idx });
            }
            last_y[idx] = y1;
        }
    }

    for out_idx in out.indices() {
        let out = &mut out[out_idx];
        let endpoint = endpoints[out_idx.second_half()];
        if bez_end_y(&out.path) < endpoint.y {
            let seg_idx = orig_seg_map[out_idx];
            out.copied_idx = Some(out.path.elements().len() - 1);
            if segs[seg_idx].is_line() {
                out.path.line_to(endpoint)
            } else {
                let c = next_subsegment(&segs[seg_idx], &out.path, endpoint.y, endpoint);
                out.path.curve_to(c.p1, c.p2, c.p3);
            }
        } else {
            // The quadratic approximations don't respect the fixed endpoints, so tidy them
            // up. Since both the quadratic approximations and the endpoints satisfy
            // the ordering, this doesn't mess up the ordering.
            match out.path.elements_mut().last_mut().unwrap() {
                kurbo::PathEl::MoveTo(p)
                | kurbo::PathEl::LineTo(p)
                | kurbo::PathEl::QuadTo(_, p)
                | kurbo::PathEl::CurveTo(_, _, p) => {
                    *p = endpoints[out_idx.second_half()];
                }
                kurbo::PathEl::ClosePath => unreachable!(),
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use kurbo::{BezPath, CubicBez, Line, PathSeg};

    use crate::Segments;

    use super::horizontal_error_weight;

    #[test]
    fn error_weight() {
        // Vertical lines have a weight of 1.
        let c: CubicBez = PathSeg::from(Line::new((0.0, 0.0), (0.0, 1.0))).to_cubic();
        assert_eq!(horizontal_error_weight(c), 1.0);

        // Horizontal lines have a weight of 0.
        let c: CubicBez = PathSeg::from(Line::new((1.0, 0.0), (0.0, 0.0))).to_cubic();
        assert_eq!(horizontal_error_weight(c), 0.0);

        let c: CubicBez = PathSeg::from(Line::new((0.0, 0.0), (1.0, 0.0))).to_cubic();
        assert_eq!(horizontal_error_weight(c), 0.0);

        // S-shaped curves have a weight of 1
        let c = CubicBez::new((0.0, 0.0), (1.0, 0.0), (-1.0, 1.0), (0.0, 1.0));
        assert_eq!(horizontal_error_weight(c), 1.0);

        // Diagonal lines have a weight of about 1/sqrt(2).
        let c: CubicBez = PathSeg::from(Line::new((0.0, 0.0), (1.0, 1.0))).to_cubic();
        assert_eq!(horizontal_error_weight(c), 1.0 / 2.0f64.sqrt());
    }

    // Here's an example of lines where we used to have a bad
    // approximation. Check that they only require a single
    // approximation step.
    #[test]
    fn linear_approx() {
        let mut p0 = BezPath::new();
        p0.move_to((-212.00062561035156, 90.03582000732422));
        p0.line_to((211.99937438964844, 90.03646087646484));
        p0.close_path();

        let mut p1 = BezPath::new();
        p1.move_to((211.99964904785153, -90.0358200073242));
        p1.line_to((211.99937438964844, 90.03646087646484));
        p1.close_path();

        let mut segs = Segments::default();
        segs.add_bez_path(&p0).unwrap();
        segs.add_bez_path(&p1).unwrap();
        let s0 = segs.indices().next().unwrap();
        let s1 = segs.indices().nth(2).unwrap();

        let mut out = Vec::new();
        let y1 = 90.03646087646484;
        let next_y0 = super::approximate(90.03645987646233, y1, &[s0, s1], &segs, 2.5e-7, &mut out);
        assert_eq!(next_y0, y1);
    }
}