drawland-core 0.5.0

Maps drawn for pen plotters: OSM features to a layered SVG. No I/O.
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
//! The orthographic projection: the Earth as a globe seen from far away
//! (`+proj=ortho +lat_0={lat} +lon_0={lng}`), on the sphere of web
//! Mercator's radius. proj4rs has no `ortho`, so it is here.
//!
//! Half the globe is out of sight. Geometry is cut at the horizon in lon/lat
//! before it is projected ([`Ortho::visible`]): on the unit sphere turned so
//! the view's centre is its top, the hidden half is `z < 0`; a line is cut
//! where it crosses the horizon, an area's ring is cut there too and closed
//! along the horizon, so the sea of the globe's rim ends on the rim. Long
//! edges (a world tile's) are first split to a degree, so they bend round
//! the globe as the ground does.

use geo::{Coord, Geometry, LineString, MultiLineString, MultiPolygon, Polygon};

pub const RADIUS: f64 = 6_378_137.0;

/// Points on the horizon this far inside it (on the unit sphere), so they
/// project in sight.
const EPS: f64 = 1e-7;

/// The longest edge, in degrees, left straight.
const STEP: f64 = 1.0;

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Ortho {
    lon0: f64,
    sin0: f64,
    cos0: f64,
}

/// A point on the unit sphere turned to the view: `x` east and `y` north at
/// the centre, `z` toward the eye.
type V3 = (f64, f64, f64);

impl Ortho {
    /// The view from above `(lon0, lat0)`.
    pub fn new(lon0: f64, lat0: f64) -> Ortho {
        let (sin0, cos0) = lat0.to_radians().sin_cos();
        Ortho { lon0, sin0, cos0 }
    }

    /// An `ortho` PROJ string (its `{lat}` / `{lng}` already written in):
    /// its centre, `lat_0` and `lon_0`, 0 where left out. `None` for any
    /// other projection.
    pub fn parse(definition: &str) -> Option<Ortho> {
        let words: Vec<&str> = definition.split_whitespace().collect();
        if !words.contains(&"+proj=ortho") {
            return None;
        }
        let value = |key: &str| words.iter().find_map(|w| w.strip_prefix(key)).and_then(|v| v.parse::<f64>().ok()).unwrap_or(0.0);
        Some(Ortho::new(value("+lon_0="), value("+lat_0=")))
    }

    fn turn(&self, lon: f64, lat: f64) -> V3 {
        let (sp, cp) = lat.to_radians().sin_cos();
        let (sl, cl) = (lon - self.lon0).to_radians().sin_cos();
        (cp * sl, self.cos0 * sp - self.sin0 * cp * cl, self.sin0 * sp + self.cos0 * cp * cl)
    }

    fn back(&self, (x, y, z): V3) -> (f64, f64) {
        let lat = (y * self.cos0 + z * self.sin0).clamp(-1.0, 1.0).asin();
        let lon = x.atan2(z * self.cos0 - y * self.sin0);
        (wrap(self.lon0 + lon.to_degrees()), lat.to_degrees())
    }

    /// Projected metres; NaN on the far side.
    pub fn forward(&self, lon: f64, lat: f64) -> (f64, f64) {
        let (x, y, z) = self.turn(lon, lat);
        if z < -EPS {
            return (f64::NAN, f64::NAN);
        }
        (RADIUS * x, RADIUS * y)
    }

    /// `(lon, lat)` under projected metres; `None` off the globe.
    pub fn inverse(&self, x: f64, y: f64) -> Option<(f64, f64)> {
        let (x, y) = (x / RADIUS, y / RADIUS);
        let r2 = x * x + y * y;
        if r2 > 1.0 + 1e-12 {
            return None;
        }
        Some(self.back((x, y, (1.0 - r2).max(0.0).sqrt())))
    }

    /// The ground within `radius` degrees of the centre that a globe shows,
    /// as a lon/lat box: past a pole, every longitude to that pole.
    pub fn ground(&self, radius: f64) -> geo::Polygon<f64> {
        let r = radius.clamp(0.0, 90.0);
        let lat0 = self.sin0.atan2(self.cos0).to_degrees();
        let (mut south, mut north) = (lat0 - r, lat0 + r);
        let (mut west, mut east) = (-180.0, 180.0);
        if north >= 90.0 {
            north = 90.0;
        } else if south <= -90.0 {
            south = -90.0;
        } else {
            let s = r.to_radians().sin() / lat0.to_radians().cos();
            if s < 1.0 {
                let d = s.asin().to_degrees();
                if self.lon0 - d >= -180.0 && self.lon0 + d <= 180.0 {
                    (west, east) = (self.lon0 - d, self.lon0 + d);
                }
            }
        }
        geo::Polygon::new(LineString::from(vec![(west, south), (east, south), (east, north), (west, north), (west, south)]), vec![])
    }

    /// Degrees from the centre to `(lon, lat)`.
    pub fn distance(&self, lon: f64, lat: f64) -> f64 {
        self.turn(lon, lat).2.clamp(-1.0, 1.0).acos().to_degrees()
    }

    /// The geometry's part in sight, in lon/lat.
    pub fn visible(&self, g: &Geometry<f64>) -> Geometry<f64> {
        match g {
            Geometry::Point(p) => {
                // Out of sight, a point is left where it projects to nothing.
                Geometry::Point(*p)
            }
            Geometry::MultiPoint(m) => Geometry::MultiPoint(m.iter().filter(|p| self.turn(p.x(), p.y()).2 >= -EPS).copied().collect()),
            Geometry::Line(l) => self.visible(&Geometry::LineString(LineString::new(vec![l.start, l.end]))),
            Geometry::LineString(l) => Geometry::MultiLineString(MultiLineString::new(self.lines(l))),
            Geometry::MultiLineString(m) => Geometry::MultiLineString(MultiLineString::new(m.iter().flat_map(|l| self.lines(l)).collect())),
            Geometry::Polygon(p) => Geometry::MultiPolygon(MultiPolygon::new(self.polygons(p))),
            Geometry::MultiPolygon(m) => Geometry::MultiPolygon(MultiPolygon::new(m.iter().flat_map(|p| self.polygons(p)).collect())),
            Geometry::Rect(r) => self.visible(&Geometry::Polygon(r.to_polygon())),
            Geometry::Triangle(t) => self.visible(&Geometry::Polygon(t.to_polygon())),
            Geometry::GeometryCollection(c) => Geometry::GeometryCollection(c.iter().map(|g| self.visible(g)).collect()),
        }
    }

    /// A line's points on the sphere, its long edges split.
    fn dense(&self, l: &LineString<f64>) -> Vec<V3> {
        self.dense_lonlat(l).into_iter().map(|(p, _)| p).collect()
    }

    /// [`Ortho::dense`], each point with its lon/lat as the line has it
    /// (−180° and 180° apart).
    fn dense_lonlat(&self, l: &LineString<f64>) -> Vec<(V3, (f64, f64))> {
        // 180° is −180°, to the bit: two tiles' areas meeting along the
        // antimeridian then meet point for point once projected, and their
        // union leaves no seam for a shore to draw.
        let turn = |x: f64, y: f64| self.turn(if x >= 180.0 { x - 360.0 } else { x }, y);
        // Tiles end a hair short of ±180° (179.9999°, or leaning a tenth of
        // a degree off it): on the antimeridian they are taken to be, or a
        // world's sea keeps a sliver of no sea down it, which a shore draws
        // as a seam.
        let snap = |c: Coord<f64>| {
            if (c.x.abs() - 180.0).abs() < SEAM {
                Coord { x: 180.0f64.copysign(c.x), y: c.y }
            } else {
                c
            }
        };
        // Where the ring meets the antimeridian: a stretch along it is split
        // at every one of them, so a sea that goes down 180° in one place and
        // up −180° in another, through other tiles' points, runs both ways
        // through the same points, and the two ways cancel to the bit.
        let mut seam: Vec<f64> = l.0.iter().map(|&c| snap(c)).filter(|c| c.x.abs() == 180.0).map(|c| c.y).collect();
        seam.sort_by(f64::total_cmp);
        seam.dedup();
        let mut out = Vec::with_capacity(l.0.len());
        for (i, &c) in l.0.iter().enumerate() {
            let c = snap(c);
            if i > 0 {
                let a = snap(l.0[i - 1]);
                // The same point twice (−180° and 180°, or a pole) is no edge.
                let (pa, pc) = (turn(a.x, a.y), turn(c.x, c.y));
                let same = (pa.0 - pc.0).abs() + (pa.1 - pc.1).abs() + (pa.2 - pc.2).abs() < 1e-12;
                if same {
                } else if a.x == c.x || a.y == c.y {
                    // Along a meridian or a parallel (a tile's edge): split
                    // on whole degrees, so two areas sharing the edge share
                    // its points too.
                    let (from, to) = if a.x == c.x { (a.y, c.y) } else { (a.x, c.x) };
                    let (lo, hi) = (from.min(to), from.max(to));
                    let mut cuts: Vec<f64> = ((lo / STEP).floor() as i64 + 1..=(hi / STEP).ceil() as i64 - 1).map(|k| k as f64 * STEP).filter(|v| *v > lo && *v < hi).collect();
                    if a.x == c.x && a.x.abs() == 180.0 {
                        cuts.extend(seam.iter().copied().filter(|v| *v > lo && *v < hi));
                        cuts.sort_by(f64::total_cmp);
                        cuts.dedup();
                    }
                    if to < from {
                        cuts.reverse();
                    }
                    for v in cuts {
                        let (x, y) = if a.x == c.x { (a.x, v) } else { (v, a.y) };
                        out.push((turn(x, y), (x, y)));
                    }
                } else {
                    let n = ((c.x - a.x).abs().max((c.y - a.y).abs()) / STEP).ceil() as usize;
                    for k in 1..n {
                        let t = k as f64 / n as f64;
                        let (x, y) = (a.x + (c.x - a.x) * t, a.y + (c.y - a.y) * t);
                        out.push((turn(x, y), (x, y)));
                    }
                }
            }
            out.push((turn(c.x, c.y), (c.x, c.y)));
        }
        out
    }

    /// A line's runs in sight.
    fn lines(&self, l: &LineString<f64>) -> Vec<LineString<f64>> {
        let pts = self.dense(l);
        let mut runs = Vec::new();
        let mut run: Vec<Coord<f64>> = Vec::new();
        for (i, &p) in pts.iter().enumerate() {
            let seen = p.2 >= EPS;
            if i > 0 {
                let q = pts[i - 1];
                if (q.2 >= EPS) != seen {
                    run.push(self.coord(cross(q, p)));
                    if !seen {
                        runs.push(LineString::new(std::mem::take(&mut run)));
                    }
                }
            }
            if seen {
                run.push(self.coord(p));
            }
        }
        if run.len() >= 2 {
            runs.push(LineString::new(run));
        }
        runs.retain(|r| r.0.len() >= 2);
        runs
    }

    fn coord(&self, p: V3) -> Coord<f64> {
        let (x, y) = self.back(p);
        Coord { x, y }
    }

    /// A ring's parts in sight, each closed along the horizon where it was
    /// cut, as rings on the sphere. `ccw`: the ring turns counter-clockwise
    /// (an outside), else clockwise (a hole).
    ///
    /// Weiler–Atherton against the horizon: the ring's runs in sight, each
    /// from where it comes into sight to where it leaves; from where a run
    /// leaves, the horizon the ring's way round (the area in sight is the
    /// ring's inside on the disc, whose rim, as part of its edge, turns the
    /// ring's way) to where the next run comes back, and so on until the
    /// first is reached again. A ring that leaves and comes back at the same
    /// point (an area as wide as the world, down one side of the
    /// antimeridian and up the other) is closed by the whole rim.
    fn rings(&self, l: &LineString<f64>, ccw: bool) -> Vec<Vec<V3>> {
        let (mut pts, mut lonlat): (Vec<V3>, Vec<(f64, f64)>) = self.dense_lonlat(l).into_iter().unzip();
        if pts.len() > 1 && pts.first() == pts.last() {
            pts.pop();
            lonlat.pop();
        }
        let n = pts.len();
        if n < 3 {
            return Vec::new();
        }
        let seen = |p: &V3| p.2 >= EPS;
        if pts.iter().all(seen) {
            let ring = unspiked(pts);
            return if ring.len() >= 3 { vec![ring] } else { Vec::new() };
        }
        if !pts.iter().any(seen) {
            // Out of sight all round: the whole disc when the ring holds the
            // view's centre, else nothing.
            return if self.holds_centre(l) { vec![rim(ccw)] } else { Vec::new() };
        }
        // The runs in sight: (where it comes back, the points, where it
        // leaves), and the indices of the hidden points either side.
        let start = (0..n).find(|&i| !seen(&pts[i])).unwrap();
        let mut runs: Vec<(V3, Vec<V3>, V3)> = Vec::new();
        let mut hidden: Vec<(usize, usize)> = Vec::new(); // (last hidden before, first hidden after)
        let mut current: Option<(V3, Vec<V3>, usize)> = None;
        for k in 1..=n {
            let (qi, pi) = ((start + k - 1) % n, (start + k) % n);
            let (q, p) = (pts[qi], pts[pi]);
            match (seen(&q), seen(&p)) {
                (false, true) => current = Some((cross(q, p), vec![inward(p)], qi)),
                (true, true) => {
                    if let Some((_, run, _)) = current.as_mut() {
                        run.push(inward(p));
                    }
                }
                (true, false) => {
                    if let Some((entry, run, before)) = current.take() {
                        runs.push((entry, run, cross(q, p)));
                        hidden.push((before, pi));
                    }
                }
                (false, false) => {}
            }
        }
        // Whether the ring, out of sight from where run `a` leaves to where
        // run `b` comes back, goes round an area (as a world's sea goes down
        // the antimeridian at 180° and up it at −180°), not back along its
        // own way (a tile's edge, a spike): only then is a way back at the
        // very point it left the whole rim round.
        let encloses = |a: usize, b: usize| {
            let (from, to) = (hidden[a].1, hidden[b].0);
            let len = (to + n - from) % n + 1;
            // In lon/lat as the ring has it: a world's sea goes down at 180°
            // and up at −180°, one line on the sphere but a band apart here.
            let ll: Vec<(f64, f64)> = (0..len).map(|k| lonlat[(from + k) % n]).collect();
            let twice: f64 = (0..ll.len()).map(|i| {
                let (p, q) = (ll[i], ll[(i + 1) % ll.len()]);
                p.0 * q.1 - q.0 * p.1
            }).sum();
            twice.abs() / 2.0 > 1.0 // square degrees
        };
        let angle = |p: &V3| p.1.atan2(p.0);
        // How far round the rim, the ring's way, from where run `i` leaves
        // to where run `j` comes back: [0, 2π]; at the same point, all the
        // way round if the ring went round an area out of sight, else none.
        let along = |i: usize, j: usize| {
            let (a, b) = (&runs[i].2, &runs[j].0);
            let d = if ccw { angle(b) - angle(a) } else { angle(a) - angle(b) };
            let d = d.rem_euclid(std::f64::consts::TAU);
            if d < 1e-9 || std::f64::consts::TAU - d < 1e-9 {
                if encloses(i, j) { std::f64::consts::TAU } else { 0.0 }
            } else {
                d
            }
        };
        let mut used = vec![false; runs.len()];
        let mut out = Vec::new();
        for first in 0..runs.len() {
            if used[first] {
                continue;
            }
            let mut ring: Vec<V3> = Vec::new();
            let mut i = first;
            for _ in 0..=runs.len() {
                used[i] = true;
                let (entry, run, exit) = &runs[i];
                ring.push(*entry);
                ring.extend(run.iter().copied());
                ring.push(*exit);
                // The run whose way back is met first round the rim.
                let next = (0..runs.len()).min_by(|&a, &b| along(i, a).total_cmp(&along(i, b))).unwrap();
                ring.extend(horizon(*exit, along(i, next) * if ccw { 1.0 } else { -1.0 }));
                if next == first {
                    break;
                }
                if used[next] {
                    break;
                }
                i = next;
            }
            let ring = unspiked(ring);
            if ring.len() >= 3 {
                out.push(ring);
            }
        }
        out
    }

    /// Whether the ring, in lon/lat, holds the view's centre.
    fn holds_centre(&self, l: &LineString<f64>) -> bool {
        let lat0 = self.sin0.atan2(self.cos0).to_degrees();
        let (x, y) = (self.lon0, lat0);
        let mut inside = false;
        for w in l.0.windows(2) {
            let (a, b) = (w[0], w[1]);
            if (a.y > y) != (b.y > y) && x < a.x + (y - a.y) / (b.y - a.y) * (b.x - a.x) {
                inside = !inside;
            }
        }
        inside
    }

    fn to_ring(&self, pts: Vec<V3>) -> LineString<f64> {
        let mut ring: Vec<Coord<f64>> = pts.into_iter().map(|p| self.coord(p)).collect();
        ring.push(ring[0]);
        LineString::new(ring)
    }

    /// A polygon's parts in sight: each outside cut, with the holes cut and
    /// given to the part they lie in.
    fn polygons(&self, p: &Polygon<f64>) -> Vec<Polygon<f64>> {
        // Turned by role, whatever way the data drew them: the outside
        // counter-clockwise, the holes clockwise.
        let turned = |l: &LineString<f64>, ccw: bool| {
            if (signed_area(l) > 0.0) == ccw {
                l.clone()
            } else {
                LineString::new(l.0.iter().rev().copied().collect())
            }
        };
        let outsides = self.rings(&turned(p.exterior(), true), true);
        if outsides.is_empty() {
            return Vec::new();
        }
        // An outside that passes along itself (the world's sea down 180°
        // and, far round its ring, up −180°: one line once on the sphere) is
        // no polygon; resolved, it is the ones it bounds, with any holes it
        // closes off.
        // Only a polygon that reaches the antimeridian can, and only when an
        // outside of it is no polygon: the rest are taken as they are (a tile
        // that ends on 180° keeps its points, which its neighbour shares).
        let on_seam = p.exterior().0.iter().any(|c| c.x.abs() > 180.0 - SEAM)
            && outsides.iter().any(|o| {
                let flat = LineString::new(o.iter().chain(o.first()).map(|p| Coord { x: p.0, y: p.1 }).collect::<Vec<_>>());
                !geo::Validation::is_valid(&Polygon::new(flat, vec![]))
            });
        let (outsides, mut made): (Vec<Vec<V3>>, Vec<Vec<Vec<V3>>>) =
            if on_seam { resolved(outsides) } else { outsides.into_iter().map(|o| (o, Vec::new())).collect() }.into_iter().unzip();
        let holes: Vec<Vec<V3>> = p.interiors().iter().flat_map(|h| self.rings(&turned(h, false), false)).collect();
        // On the disc (x, y) a hole is in the outside that holds a point of it.
        let flat = |r: &[V3]| LineString::new(r.iter().map(|p| Coord { x: p.0, y: p.1 }).collect::<Vec<_>>());
        let shapes: Vec<Polygon<f64>> = outsides.iter().map(|o| Polygon::new(flat(o), vec![])).collect();
        let mut given: Vec<Vec<Vec<V3>>> = std::mem::take(&mut made);
        for h in holes {
            let mid = h.iter().fold((0.0, 0.0), |a, p| (a.0 + p.0, a.1 + p.1));
            let at = geo::Point::new(mid.0 / h.len() as f64, mid.1 / h.len() as f64);
            let k = shapes.iter().position(|s| geo::Contains::contains(s, &at)).unwrap_or(0);
            given[k].push(h);
        }
        outsides
            .into_iter()
            .zip(given)
            .map(|(o, hs)| Polygon::new(self.to_ring(o), hs.into_iter().map(|h| self.to_ring(h)).collect()))
            .collect()
    }
}

/// An area on the unit disc too thin to be anything but a sliver.
const SLIVER: f64 = 1e-7;

/// The outsides on the visible disc of a polygon that reaches the
/// antimeridian, as the polygons they bound together (non-zero): each with
/// the holes it closes off. The world's sea goes down 180° in one outside
/// and up −180° in another (the horizon cuts its ring apart), one line on
/// the sphere run both ways: taken together the two ways cancel and the sea
/// on either side is one, with no line between them for a shore to draw.
fn resolved(outsides: Vec<Vec<V3>>) -> Vec<(Vec<V3>, Vec<Vec<V3>>)> {
    use i_overlay::core::fill_rule::FillRule;
    use i_overlay::float::simplify::SimplifyShape;
    let paths: Vec<Vec<[f64; 2]>> = outsides.iter().filter(|r| r.len() >= 3).map(|r| r.iter().map(|p| [p.0, p.1]).collect()).collect();
    // Back on the near side of the sphere.
    let lift = |r: &Vec<[f64; 2]>| -> Vec<V3> { r.iter().map(|&[x, y]| (x, y, (1.0 - x * x - y * y).max(0.0).sqrt())).collect() };
    // Slivers the two ways along the line may leave between them go: a
    // shore would draw each as a stitch.
    let area = |r: &Vec<[f64; 2]>| (0..r.len()).map(|i| { let (a, b) = (r[i], r[(i + 1) % r.len()]); a[0] * b[1] - b[0] * a[1] }).sum::<f64>().abs() / 2.0;
    paths
        .simplify_shape(FillRule::NonZero)
        .iter()
        .filter_map(|shape| {
            let (outer, holes) = shape.split_first()?;
            (outer.len() >= 3 && area(outer) > SLIVER).then(|| (lift(outer), holes.iter().filter(|h| h.len() >= 3 && area(h) > SLIVER).map(lift).collect()))
        })
        .collect()
}

/// A ring with its ways out and back along itself taken out: a world's sea
/// goes down the antimeridian at 180° and up it at −180°, one line on the
/// sphere, which a shore would draw as a seam across the sea.
fn unspiked(pts: Vec<V3>) -> Vec<V3> {
    let close = |a: &V3, b: &V3| (a.0 - b.0).abs() + (a.1 - b.1).abs() + (a.2 - b.2).abs() < 1e-9;
    let mut out: Vec<V3> = Vec::with_capacity(pts.len());
    for p in pts {
        if out.last().is_some_and(|l| close(l, &p)) {
            continue;
        }
        if out.len() >= 2 && close(&out[out.len() - 2], &p) {
            out.pop();
            continue;
        }
        out.push(p);
    }
    // Round the ring's start: out and back over its first point.
    loop {
        let n = out.len();
        if n >= 2 && close(&out[0], &out[n - 1]) {
            out.pop();
        } else if n >= 3 && close(&out[1], &out[n - 1]) {
            out.remove(0);
            out.pop();
        } else {
            break;
        }
    }
    out
}

/// How near ±180° a longitude is taken to be on it, degrees (≈ 11 km at
/// the equator): a globe's tiles are shallow, their edges along the
/// antimeridian drawn to about that (down to Antarctica one leans 0.09°
/// off it), and a globe's pixel spans more.
const SEAM: f64 = 0.1;

/// How far out from the centre a cut ring's points may lie, on the disc: a
/// chord of the rim a degree long comes this far in at its middle. A shore
/// nearer the rim than that would cross the rim's chords, and a ring that
/// crosses itself is no area to a union.
const RIM_IN: f64 = 0.999_961_923_064_171; // cos 0.5°

/// A point in sight, moved in to [`RIM_IN`] when it lies nearer the rim
/// (at most 240 m on the ground).
fn inward(p: V3) -> V3 {
    let r = p.0.hypot(p.1);
    if r <= RIM_IN * (1.0 - EPS * EPS).sqrt() {
        return p;
    }
    let k = RIM_IN * (1.0 - EPS * EPS).sqrt() / r;
    let (x, y) = (p.0 * k, p.1 * k);
    (x, y, (1.0 - x * x - y * y).max(0.0).sqrt())
}

/// The whole rim, a point a degree, counter-clockwise or not.
fn rim(ccw: bool) -> Vec<V3> {
    let r = (1.0 - EPS * EPS).sqrt();
    (0..360)
        .map(|k| {
            let t = (k as f64).to_radians() * if ccw { 1.0 } else { -1.0 };
            (r * t.cos(), r * t.sin(), EPS)
        })
        .collect()
}

/// `lon` in −180..180.
fn wrap(lon: f64) -> f64 {
    let l = (lon + 180.0).rem_euclid(360.0) - 180.0;
    if l == -180.0 && lon > 0.0 { 180.0 } else { l }
}

/// Where the edge from `a` to `b` meets the horizon (a hair inside it).
fn cross(a: V3, b: V3) -> V3 {
    let t = ((EPS - a.2) / (b.2 - a.2)).clamp(0.0, 1.0);
    let p = (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t, EPS);
    let r = (p.0 * p.0 + p.1 * p.1).sqrt().max(1e-12);
    let k = (1.0 - EPS * EPS).sqrt() / r;
    (p.0 * k, p.1 * k, EPS)
}

/// Twice a ring's signed area in lon/lat: positive counter-clockwise.
fn signed_area(l: &LineString<f64>) -> f64 {
    l.0.windows(2).map(|w| w[0].x * w[1].y - w[1].x * w[0].y).sum()
}

/// The horizon from `a`, `sweep` radians round (counter-clockwise when
/// positive), to just before the end: a point a degree.
fn horizon(a: V3, sweep: f64) -> Vec<V3> {
    let ta = a.1.atan2(a.0);
    let n = (sweep.abs().to_degrees() / STEP).ceil() as usize;
    let r = (1.0 - EPS * EPS).sqrt();
    (1..n)
        .map(|k| {
            let t = ta + sweep * k as f64 / n as f64;
            (r * t.cos(), r * t.sin(), EPS)
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use geo::Area;

    #[test]
    fn the_centre_is_the_origin_and_the_far_side_is_hidden() {
        let o = Ortho::new(12.0, 42.0);
        let (x, y) = o.forward(12.0, 42.0);
        assert!(x.abs() < 1e-6 && y.abs() < 1e-6);
        let (x, y) = o.forward(12.0 + 180.0, -42.0);
        assert!(x.is_nan() && y.is_nan(), "the antipode");
        let (x, y) = o.forward(13.0, 42.0);
        assert!(x > 80_000.0 && y.abs() < 2_000.0, "east is right: {x} {y}");
        let (lon, lat) = o.inverse(o.forward(40.0, 10.0).0, o.forward(40.0, 10.0).1).unwrap();
        assert!((lon - 40.0).abs() < 1e-9 && (lat - 10.0).abs() < 1e-9);
        assert_eq!(o.inverse(RADIUS * 1.01, 0.0), None);
    }

    #[test]
    fn parsed_from_a_proj_string() {
        let o = Ortho::parse("+proj=ortho +lat_0=42.5 +lon_0=-10").unwrap();
        assert_eq!(o, Ortho::new(-10.0, 42.5));
        assert_eq!(Ortho::parse("+proj=laea +lat_0=1"), None);
    }

    #[test]
    fn a_line_over_the_horizon_is_cut_there() {
        // Along the equator from the centre round to the far side.
        let o = Ortho::new(0.0, 0.0);
        let l = LineString::from(vec![(0.0, 0.0), (170.0, 0.0)]);
        let Geometry::MultiLineString(m) = o.visible(&Geometry::LineString(l)) else { panic!() };
        assert_eq!(m.0.len(), 1);
        let end = m.0[0].0.last().unwrap();
        assert!((end.x - 90.0).abs() < 0.01, "{end:?}");
    }

    #[test]
    fn an_area_over_the_horizon_is_closed_along_it() {
        // A band from 60° west to 150° east, seen from 0°: cut at 90° east,
        // its edge there the horizon.
        let o = Ortho::new(0.0, 0.0);
        let band = Polygon::new(LineString::from(vec![(-60.0, -30.0), (150.0, -30.0), (150.0, 30.0), (-60.0, 30.0), (-60.0, -30.0)]), vec![]);
        let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(band)) else { panic!() };
        assert_eq!(m.0.len(), 1);
        let xs: Vec<f64> = m.0[0].exterior().0.iter().map(|c| c.x).collect();
        let east = xs.iter().cloned().fold(f64::MIN, f64::max);
        assert!((east - 90.0).abs() < 0.01, "{east}");
        // Projected, it is the band from −60° to the rim: a real area.
        let projected = m.0[0].exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>();
        assert!(projected.iter().all(|p| p.0.is_finite()));
        let area = Polygon::new(LineString::from(projected), vec![]).unsigned_area();
        assert!(area > 1e13, "{area}");
        // Wholly hidden, nothing.
        let far = Polygon::new(LineString::from(vec![(120.0, -10.0), (150.0, -10.0), (150.0, 10.0), (120.0, 10.0), (120.0, -10.0)]), vec![]);
        let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(far)) else { panic!() };
        assert!(m.0.is_empty());
    }

    #[test]
    fn a_ring_either_way_round_closes_on_the_same_side() {
        // A sea from 60° west to 150° east and 80° south to 10° north, seen
        // from 0°, 0°: cut at the rim on the east. Drawn clockwise or
        // counter-clockwise, its part in sight is the same.
        let o = Ortho::new(0.0, 0.0);
        let ring = vec![(-60.0, -80.0), (150.0, -80.0), (150.0, 10.0), (-60.0, 10.0), (-60.0, -80.0)];
        let area = |pts: Vec<(f64, f64)>| {
            let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(Polygon::new(LineString::from(pts), vec![]))) else { panic!() };
            m.0.iter().map(|p| Polygon::new(LineString::from(p.exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]).unsigned_area()).sum::<f64>()
        };
        let (ccw, cw) = (area(ring.clone()), area(ring.into_iter().rev().collect()));
        assert!(ccw > 1e13 && (ccw - cw).abs() < ccw * 1e-6, "{ccw} {cw}");
        // Less than the half disc south of the equator plus a strip: not the
        // whole disc, as an arc the long way round would make it.
        assert!(ccw < 0.75 * std::f64::consts::PI * RADIUS * RADIUS, "{ccw}");
    }

    #[test]
    fn an_area_as_wide_as_the_world_fills_the_disc() {
        // A world tile's sea, −180° to 180°: it leaves sight down the
        // antimeridian and comes back up it. Either way round, the disc.
        let o = Ortho::new(-40.0, 30.0);
        let disc = std::f64::consts::PI * RADIUS * RADIUS;
        let world = vec![(-180.0, -85.0), (180.0, -85.0), (180.0, 85.0), (-180.0, 85.0), (-180.0, -85.0)];
        for ring in [world.clone(), world.into_iter().rev().collect()] {
            let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(Polygon::new(LineString::from(ring), vec![]))) else { panic!() };
            let a: f64 = m.0.iter().map(|p| Polygon::new(LineString::from(p.exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]).unsigned_area()).sum();
            assert!((a / disc - 1.0).abs() < 1e-3, "{}", a / disc);
        }
    }

    #[test]
    fn a_far_area_reaching_into_sight_twice_is_two_pieces() {
        // Seen from 0°, 0°, the horizon is the 90th meridian. A sea beyond
        // it, with two fingers reaching west to 80°: in sight, the fingers
        // alone, not the rim joined round the far side of the disc.
        let o = Ortho::new(0.0, 0.0);
        let sea = vec![
            (95.0, -40.0), (140.0, -40.0), (140.0, 40.0), (95.0, 40.0), (95.0, 30.0), (80.0, 30.0), (80.0, 20.0), (95.0, 20.0),
            (95.0, -20.0), (80.0, -20.0), (80.0, -30.0), (95.0, -30.0), (95.0, -40.0),
        ];
        let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(Polygon::new(LineString::from(sea), vec![]))) else { panic!() };
        assert_eq!(m.0.len(), 2);
        let disc = std::f64::consts::PI * RADIUS * RADIUS;
        let a: f64 = m.0.iter().map(|p| Polygon::new(LineString::from(p.exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]).unsigned_area()).sum();
        assert!(a > 0.0 && a < 0.02 * disc, "{}", a / disc);
    }

    #[test]
    fn a_world_sea_keeps_its_land_from_the_equator() {
        // The world's sea, a hole for a land in the middle of the view: seen
        // from the equator (both poles on the rim) and from 10° north alike.
        let world = LineString::from(vec![(-180.0, -85.05), (180.0, -85.05), (180.0, 85.05), (-180.0, 85.05), (-180.0, -85.05)]);
        let land = LineString::from(vec![(0.0, -30.0), (0.0, 30.0), (40.0, 30.0), (40.0, -30.0), (0.0, -30.0)]);
        let sea = Polygon::new(world, vec![land]);
        for lat in [10.0, 5.0, 0.0, -5.0, -10.0] {
            let o = Ortho::new(20.0, lat);
            let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(sea.clone())) else { panic!() };
            let flat = |l: &LineString<f64>| Polygon::new(LineString::from(l.0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]).unsigned_area();
            let holes: usize = m.0.iter().map(|p| p.interiors().len()).sum();
            let disc = std::f64::consts::PI * RADIUS * RADIUS;
            let outs: Vec<f64> = m.0.iter().map(|p| flat(p.exterior()) / disc).collect();
            eprintln!("lat {lat}: outsides {outs:?}, holes {holes}");
            // The land is a hole in the piece that holds the view's centre.
            let centre = m.0.iter().find(|p| geo::Contains::contains(&Polygon::new(LineString::from(p.exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]), &geo::Point::new(1.0, 1.0)));
            assert!(centre.is_some_and(|p| p.interiors().len() == 1), "lat {lat}");
        }
    }

    #[test]
    fn a_ring_back_along_its_own_way_is_no_area() {
        // A tile's edge along 85° north, out and back: no area. Seen from
        // near the equator it leaves sight and comes back at one point, as
        // a world's sea does; it is not closed by the whole rim, which made
        // the sea cover every land.
        let mut pts: Vec<(f64, f64)> = (0..=360).map(|i| (-180.0 + i as f64, 85.0)).collect();
        pts.extend((0..=360).rev().map(|i| (-180.0 + i as f64, 85.0)));
        for lat in [0.0, 3.0, 5.0, 10.0] {
            let o = Ortho::new(20.0, lat);
            let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(Polygon::new(LineString::from(pts.clone()), vec![]))) else { panic!() };
            let a: f64 = m.0.iter().map(|p| Polygon::new(LineString::from(p.exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]).unsigned_area()).sum();
            assert!(a < 1.0, "lat {lat}: {a}");
        }
    }

    #[test]
    fn a_world_sea_has_no_seam_down_the_antimeridian() {
        // Seen from the Pacific, the world's sea goes down 180° and up −180°
        // in sight: one line, out and back, taken out.
        let o = Ortho::new(-170.0, 10.0);
        // As tiles have it: a hair short of ±180°.
        let e = 179.999_899_790_331_74;
        let world = Polygon::new(LineString::from(vec![(-e, -85.0), (e, -85.0), (e, 85.0), (-e, 85.0), (-e, -85.0)]), vec![]);
        let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(world)) else { panic!() };
        let near_seam = m.0.iter().flat_map(|p| p.exterior().0.iter()).filter(|c| (c.x.abs() - 180.0).abs() < 1e-3 && c.y.abs() < 60.0).count();
        assert_eq!(near_seam, 0, "no points down the antimeridian");
        let disc = std::f64::consts::PI * RADIUS * RADIUS;
        let a: f64 = m.0.iter().map(|p| Polygon::new(LineString::from(p.exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]).unsigned_area()).sum();
        assert!((a / disc - 1.0).abs() < 0.02, "still the disc: {}", a / disc);
    }

    #[test]
    fn two_tiles_meeting_at_the_antimeridian_join_without_a_seam() {
        // A sea in two tiles, east and west of 180°: once cut and projected
        // they share their edge point for point, and their union is one.
        use geo::{BooleanOps, MapCoords};
        let o = Ortho::new(-178.3, 4.0);
        let square = |x0: f64, x1: f64| Polygon::new(LineString::from(vec![(x0, -10.5), (x1, -10.5), (x1, 10.5), (x0, 10.5), (x0, -10.5)]), vec![]);
        let flat = |p: Polygon<f64>| {
            let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(p)) else { panic!() };
            m.map_coords(|c| {
                let (x, y) = o.forward(c.x, c.y);
                Coord { x, y }
            })
        };
        let joined = flat(square(169.5, 180.0)).union(&flat(square(-180.0, -170.5)));
        assert_eq!(joined.0.len(), 1);
        assert!(joined.0[0].interiors().is_empty());
    }

    #[test]
    fn a_hidden_ring_round_the_centre_is_the_disc() {
        // All of it beyond the horizon, but round the view's centre: a sea
        // whose shore is a far ring holds the whole near side.
        let o = Ortho::new(0.0, 89.0);
        let ring = LineString::from(vec![(-180.0, -10.0), (180.0, -10.0), (180.0, 89.5), (-180.0, 89.5), (-180.0, -10.0)]);
        assert!(o.holds_centre(&ring));
    }

    #[test]
    fn a_shore_along_the_rim_still_makes_an_area() {
        // Seen from 0°, 0°, the horizon is the 90th meridian. A sea from
        // beyond it whose shore comes into sight and runs a hair inside the
        // rim (89.995°, a metre of disc) for five degrees: the rim's chords,
        // a degree each, sag further in than that, so the cut must keep its
        // shore off them, or it crosses itself and a union drops it.
        let o = Ortho::new(0.0, 0.0);
        let mut ring = vec![(95.0, -3.0)];
        ring.extend((0..=10).map(|k| (89.995, -2.5 + k as f64 * 0.5)));
        ring.extend([(95.0, 3.0), (95.0, -3.0)]);
        let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(Polygon::new(LineString::from(ring), vec![]))) else { panic!() };
        let pr = |l: &LineString<f64>| LineString::from(l.0.iter().map(|c| { let (x, y) = o.forward(c.x, c.y); (x, -y) }).collect::<Vec<_>>());
        let cut = geo::MultiPolygon::new(m.0.iter().map(|p| Polygon::new(pr(p.exterior()), vec![])).collect());
        use geo::Validation;
        assert!(cut.is_valid(), "the cut crosses itself");
        let united = crate::geom::union_multi([&cut]);
        assert!(cut.unsigned_area() > 0.0);
        assert!((united.unsigned_area() / cut.unsigned_area() - 1.0).abs() < 1e-3, "{} {}", united.unsigned_area(), cut.unsigned_area());
    }

    #[test]
    fn a_ring_that_starts_out_of_sight_still_closes() {
        let o = Ortho::new(0.0, 0.0);
        let band = Polygon::new(LineString::from(vec![(150.0, -30.0), (150.0, 30.0), (-60.0, 30.0), (-60.0, -30.0), (150.0, -30.0)]), vec![]);
        let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(band)) else { panic!() };
        assert_eq!(m.0.len(), 1);
        assert!(m.0[0].exterior().0.iter().all(|c| c.x.is_finite() && c.y.is_finite()));
        let projected = m.0[0].exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>();
        assert!(Polygon::new(LineString::from(projected), vec![]).unsigned_area() > 1e13);
    }
}