geolith 0.1.2

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
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
//! Stripe-based tile clipping for efficient geometry partitioning.
//!
//! Two-pass vertical→horizontal clipping against tile+buffer rectangles.
//! Polygons use `geo::BooleanOps::intersection` (Vatti, topology-correct) so
//! concave inputs never produce self-intersecting "bowtie" output — the bug
//! pattern that rendered as triangular spike artifacts in earlier builds.
//! Linestrings still use Cohen-Sutherland segment clipping (no bowtie risk).
//!
//! Coordinates are in **tile coordinate space** (0.0 .. 2^z) where integer
//! boundaries align with tile edges.

use crate::geometry::mercator::TileCoord;
use geo::{BooleanOps, Coord, LineString, MultiPolygon, Polygon};

/// Buffer fraction (in tile units) added around each tile for label/line overflow.
/// 4 pixels at 256px tile = 4/256 ≈ 0.015625 tile units.
const BUFFER: f64 = 4.0 / 256.0;

/// Orthogonal padding for clip-rectangle construction. Must comfortably
/// exceed the max tile-space coordinate (2^15 = 32 768 at z=15) but stay
/// below 1e9 — `geo::BooleanOps` via `i-overlay` silently returns empty
/// `MultiPolygon` when coordinate magnitudes approach 1e9 due to numeric
/// precision limits in its fixed-point intersection solver.
const CLIP_PAD: f64 = 1.0e6;

/// Clipping axis.
#[derive(Debug, Clone, Copy)]
enum Axis {
    X,
    Y,
}

impl Axis {
    /// Extract the relevant coordinate from a point.
    #[inline]
    const fn get(self, p: &[f64; 2]) -> f64 {
        match self {
            Axis::X => p[0],
            Axis::Y => p[1],
        }
    }
}

/// Clip a geometry to all tiles it intersects at the given zoom level.
///
/// Input coordinates are in tile coordinate space (0.0 .. 2^z).
/// Returns a list of `(TileCoord, clipped_coords)` pairs where the clipped
/// coords are still in tile coordinate space (to be converted to tile-local later).
///
/// For polygons, a single input ring may produce multiple output pieces on the
/// same tile when the polygon is concave and splits across tile edges — each
/// piece is emitted as its own entry.
///
/// `geom_type`: 1=point, 2=linestring, 3=polygon (matches MVT `GeomType`).
#[must_use]
pub fn stripe_clip(coords: &[[f64; 2]], z: u8, geom_type: u8) -> Vec<(TileCoord, Vec<[f64; 2]>)> {
    if coords.is_empty() {
        return Vec::new();
    }

    let n = 1u32 << z;
    let nf = n as f64;

    if geom_type == 1 {
        return clip_points(coords, z, n);
    }

    let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
    for p in coords {
        min_x = min_x.min(p[0]);
        min_y = min_y.min(p[1]);
        max_x = max_x.max(p[0]);
        max_y = max_y.max(p[1]);
    }

    let x_start = ((min_x - BUFFER).floor() as i64).max(0) as u32;
    let x_end = ((max_x + BUFFER).ceil() as i64).min(nf as i64) as u32;
    let x_end = x_end.min(n - 1);

    // `x_start` is only floored at 0, so a geometry that lies entirely past the
    // right edge of the grid leaves `x_start > x_end`: saturate, never underflow.
    let mut results: Vec<(TileCoord, Vec<[f64; 2]>)> =
        Vec::with_capacity(x_end.saturating_sub(x_start) as usize + 1);

    for stripe_x in x_start..=x_end {
        let left = stripe_x as f64 - BUFFER;
        let right = (stripe_x + 1) as f64 + BUFFER;

        let x_pieces: Vec<Vec<[f64; 2]>> = if geom_type == 3 {
            clip_polygon_to_band(coords, Axis::X, left, right)
        } else {
            let line = clip_linestring_to_band(coords, Axis::X, left, right);
            if line.is_empty() {
                Vec::new()
            } else {
                vec![line]
            }
        };

        for x_piece in &x_pieces {
            if x_piece.is_empty() {
                continue;
            }

            let (mut piece_min_y, mut piece_max_y) = (f64::MAX, f64::MIN);
            for p in x_piece {
                piece_min_y = piece_min_y.min(p[1]);
                piece_max_y = piece_max_y.max(p[1]);
            }

            let y_start = ((piece_min_y - BUFFER).floor() as i64).max(0) as u32;
            let y_end = ((piece_max_y + BUFFER).ceil() as i64).min(nf as i64) as u32;
            let y_end = y_end.min(n - 1);

            for stripe_y in y_start..=y_end {
                let top = stripe_y as f64 - BUFFER;
                let bottom = (stripe_y + 1) as f64 + BUFFER;

                let y_pieces: Vec<Vec<[f64; 2]>> = if geom_type == 3 {
                    clip_polygon_to_band(x_piece, Axis::Y, top, bottom)
                } else {
                    let line = clip_linestring_to_band(x_piece, Axis::Y, top, bottom);
                    if line.is_empty() {
                        Vec::new()
                    } else {
                        vec![line]
                    }
                };

                for y_piece in y_pieces {
                    if !y_piece.is_empty() {
                        results.push((TileCoord::new(z, stripe_x, stripe_y), y_piece));
                    }
                }
            }
        }
    }

    results
}

/// Assign points to their containing tiles.
fn clip_points(coords: &[[f64; 2]], z: u8, n: u32) -> Vec<(TileCoord, Vec<[f64; 2]>)> {
    let max = n - 1;
    coords
        .iter()
        .map(|p| {
            let tx = (p[0].floor() as u32).min(max);
            let ty = (p[1].floor() as u32).min(max);
            (TileCoord::new(z, tx, ty), vec![*p])
        })
        .collect()
}

/// Clip a polygon ring to a band [`min_val`, `max_val`] along the given axis.
///
/// Uses `geo::BooleanOps::intersection` (Vatti-class algorithm via `i-overlay`)
/// which is topology-correct for concave inputs — it can split one input ring
/// into multiple disjoint output rings rather than producing a self-intersecting
/// bowtie (the failure mode of Sutherland-Hodgman on concave inputs).
///
/// Returns zero or more clipped ring vertex lists. Each returned ring is
/// explicitly closed (first == last) and has at least 4 points.
fn clip_polygon_to_band(
    ring: &[[f64; 2]],
    axis: Axis,
    min_val: f64,
    max_val: f64,
) -> Vec<Vec<[f64; 2]>> {
    if ring.len() < 4 {
        return Vec::new();
    }

    let (mut axis_min, mut axis_max) = (f64::MAX, f64::MIN);
    for p in ring {
        let v = axis.get(p);
        axis_min = axis_min.min(v);
        axis_max = axis_max.max(v);
    }
    if axis_max <= min_val || axis_min >= max_val {
        return Vec::new();
    }
    if axis_min >= min_val && axis_max <= max_val {
        return vec![ring.to_vec()];
    }

    let mut coords: Vec<Coord<f64>> = ring.iter().map(|&[x, y]| Coord { x, y }).collect();
    if coords.first() != coords.last()
        && let Some(first) = coords.first().copied()
    {
        coords.push(first);
    }
    let subject = Polygon::new(LineString::new(coords), Vec::new());

    let clip = band_polygon(axis, min_val, max_val);

    // `geo`'s boolean ops panic on some pathological invalid inputs (self-
    // touching rings, figure-8 source data). Catch and skip — a planet-scale
    // build can't abort on a single bad feature.
    let result: MultiPolygon<f64> = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(
        || subject.intersection(&clip),
    )) {
        Ok(mp) => mp,
        Err(_) => return Vec::new(),
    };

    let mut out: Vec<Vec<[f64; 2]>> = Vec::with_capacity(result.0.len());
    for poly in result {
        let mut exterior: Vec<[f64; 2]> = poly.exterior().0.iter().map(|c| [c.x, c.y]).collect();
        if exterior.len() >= 2
            && exterior.first() != exterior.last()
            && let Some(first) = exterior.first().copied()
        {
            exterior.push(first);
        }
        if exterior.len() >= 4 {
            out.push(exterior);
        }
    }
    out
}

/// A polygon clipped to a single tile, in tile coordinate space.
///
/// Holes are preserved as `interiors`. Keeping the exterior/interior split
/// explicit (rather than clipping each ring independently) is what prevents a
/// hole from being emitted as a standalone fill — the MVT-nonzero "phantom
/// landmass" bug. Rings are explicitly closed (first == last).
#[derive(Debug, Clone)]
pub struct ClippedPolygon {
    /// Exterior ring (closed).
    pub exterior: Vec<[f64; 2]>,
    /// Interior rings / holes (each closed).
    pub interiors: Vec<Vec<[f64; 2]>>,
}

/// Clip a whole polygon (exterior + holes) to every tile it intersects.
///
/// Unlike [`stripe_clip`], which clips one ring at a time, this clips the
/// polygon **as a unit** through `geo::BooleanOps::intersection`, so holes are
/// correctly subtracted from their exterior in each output tile. Per-tile
/// results carry the exterior/interior structure (see [`ClippedPolygon`]),
/// which the encoder needs to emit spec-correct MVT winding. Input and output
/// coordinates are in tile coordinate space (0.0 .. 2^z).
#[must_use]
pub fn stripe_clip_polygon(
    exterior: &[[f64; 2]],
    interiors: &[Vec<[f64; 2]>],
    z: u8,
) -> Vec<(TileCoord, ClippedPolygon)> {
    if exterior.len() < 4 {
        return Vec::new();
    }

    let n = 1u32 << z;
    let nf = n as f64;

    let (mut min_x, mut max_x) = (f64::MAX, f64::MIN);
    for p in exterior {
        min_x = min_x.min(p[0]);
        max_x = max_x.max(p[0]);
    }

    let subject = build_polygon(exterior, interiors);

    let x_start = ((min_x - BUFFER).floor() as i64).max(0) as u32;
    let x_end = (((max_x + BUFFER).ceil() as i64).min(nf as i64) as u32).min(n - 1);

    let mut results: Vec<(TileCoord, ClippedPolygon)> = Vec::new();

    for stripe_x in x_start..=x_end {
        let left = stripe_x as f64 - BUFFER;
        let right = (stripe_x + 1) as f64 + BUFFER;

        for x_piece in clip_polygon_with_holes_to_band(&subject, Axis::X, left, right) {
            let (mut piece_min_y, mut piece_max_y) = (f64::MAX, f64::MIN);
            for c in x_piece.exterior() {
                piece_min_y = piece_min_y.min(c.y);
                piece_max_y = piece_max_y.max(c.y);
            }

            let y_start = ((piece_min_y - BUFFER).floor() as i64).max(0) as u32;
            let y_end = (((piece_max_y + BUFFER).ceil() as i64).min(nf as i64) as u32).min(n - 1);

            for stripe_y in y_start..=y_end {
                let top = stripe_y as f64 - BUFFER;
                let bottom = (stripe_y + 1) as f64 + BUFFER;

                for y_piece in clip_polygon_with_holes_to_band(&x_piece, Axis::Y, top, bottom) {
                    if let Some(cp) = polygon_to_clipped(&y_piece) {
                        results.push((TileCoord::new(z, stripe_x, stripe_y), cp));
                    }
                }
            }
        }
    }

    results
}

/// Build a `geo::Polygon` from tile-space exterior + interior ring vertex lists.
fn build_polygon(exterior: &[[f64; 2]], interiors: &[Vec<[f64; 2]>]) -> Polygon<f64> {
    let ext = LineString::new(exterior.iter().map(|&[x, y]| Coord { x, y }).collect());
    let holes: Vec<LineString<f64>> = interiors
        .iter()
        .map(|ring| LineString::new(ring.iter().map(|&[x, y]| Coord { x, y }).collect()))
        .collect();
    Polygon::new(ext, holes)
}

/// Intersect a polygon (with holes) against a band, returning output polygons.
///
/// `geo`'s boolean ops can panic on pathological invalid inputs; catch and skip
/// — a planet-scale build cannot abort on a single bad feature.
fn clip_polygon_with_holes_to_band(
    poly: &Polygon<f64>,
    axis: Axis,
    min_val: f64,
    max_val: f64,
) -> Vec<Polygon<f64>> {
    let (mut axis_min, mut axis_max) = (f64::MAX, f64::MIN);
    for c in poly.exterior() {
        let v = axis.get(&[c.x, c.y]);
        axis_min = axis_min.min(v);
        axis_max = axis_max.max(v);
    }
    if axis_max <= min_val || axis_min >= max_val {
        return Vec::new();
    }
    if axis_min >= min_val && axis_max <= max_val {
        return vec![poly.clone()];
    }

    let clip = band_polygon(axis, min_val, max_val);
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| poly.intersection(&clip))) {
        Ok(mp) => mp.0,
        Err(_) => Vec::new(),
    }
}

/// Convert a clipped `geo::Polygon` to a [`ClippedPolygon`] with closed rings.
fn polygon_to_clipped(poly: &Polygon<f64>) -> Option<ClippedPolygon> {
    let exterior = closed_ring(poly.exterior());
    if exterior.len() < 4 {
        return None;
    }
    let interiors: Vec<Vec<[f64; 2]>> = poly
        .interiors()
        .iter()
        .map(closed_ring)
        .filter(|r| r.len() >= 4)
        .collect();
    Some(ClippedPolygon {
        exterior,
        interiors,
    })
}

/// Collect a `LineString` into a closed `[f64; 2]` ring (first == last).
fn closed_ring(ls: &LineString<f64>) -> Vec<[f64; 2]> {
    let mut ring: Vec<[f64; 2]> = ls.0.iter().map(|c| [c.x, c.y]).collect();
    if ring.len() >= 2
        && ring.first() != ring.last()
        && let Some(first) = ring.first().copied()
    {
        ring.push(first);
    }
    ring
}

/// Construct a clip rectangle spanning the full orthogonal extent.
fn band_polygon(axis: Axis, min_val: f64, max_val: f64) -> Polygon<f64> {
    let coords = match axis {
        Axis::X => vec![
            Coord {
                x: min_val,
                y: -CLIP_PAD,
            },
            Coord {
                x: max_val,
                y: -CLIP_PAD,
            },
            Coord {
                x: max_val,
                y: CLIP_PAD,
            },
            Coord {
                x: min_val,
                y: CLIP_PAD,
            },
            Coord {
                x: min_val,
                y: -CLIP_PAD,
            },
        ],
        Axis::Y => vec![
            Coord {
                x: -CLIP_PAD,
                y: min_val,
            },
            Coord {
                x: CLIP_PAD,
                y: min_val,
            },
            Coord {
                x: CLIP_PAD,
                y: max_val,
            },
            Coord {
                x: -CLIP_PAD,
                y: max_val,
            },
            Coord {
                x: -CLIP_PAD,
                y: min_val,
            },
        ],
    };
    Polygon::new(LineString::new(coords), Vec::new())
}

/// Clip a linestring to a band [`min_val`, `max_val`] along the given axis.
///
/// Uses Cohen-Sutherland style clipping for each segment.
/// Returns the clipped segments concatenated (may produce disconnected points
/// but that's acceptable for our tile-feature pipeline).
fn clip_linestring_to_band(
    coords: &[[f64; 2]],
    axis: Axis,
    min_val: f64,
    max_val: f64,
) -> Vec<[f64; 2]> {
    if coords.len() < 2 {
        return Vec::new();
    }

    let mut output = Vec::new();
    let mut prev_added = false;

    for i in 0..coords.len() - 1 {
        let a = coords[i];
        let b = coords[i + 1];

        let a_val = axis.get(&a);
        let b_val = axis.get(&b);

        if (a_val < min_val && b_val < min_val) || (a_val > max_val && b_val > max_val) {
            prev_added = false;
            continue;
        }

        let mut p0 = a;
        let mut p1 = b;
        let mut v0 = a_val;
        let mut v1 = b_val;

        if v0 < min_val {
            p0 = intersect_edge(p0, p1, axis, min_val);
            v0 = min_val;
        } else if v1 < min_val {
            p1 = intersect_edge(p0, p1, axis, min_val);
            v1 = min_val;
        }

        if v0 > max_val {
            p0 = intersect_edge(p0, p1, axis, max_val);
        } else if v1 > max_val {
            p1 = intersect_edge(p0, p1, axis, max_val);
        }

        let _ = (v0, v1);

        if !prev_added {
            output.push(p0);
        }
        output.push(p1);
        prev_added = true;
    }

    output
}

/// Compute the intersection of a line segment with an axis-aligned boundary.
#[inline]
fn intersect_edge(a: [f64; 2], b: [f64; 2], axis: Axis, boundary: f64) -> [f64; 2] {
    let (a_val, b_val) = (axis.get(&a), axis.get(&b));
    let diff = b_val - a_val;
    if diff.abs() < 1e-12 {
        return a;
    }
    let t = (boundary - a_val) / diff;
    match axis {
        Axis::X => [boundary, a[1] + t * (b[1] - a[1])],
        Axis::Y => [a[0] + t * (b[0] - a[0]), boundary],
    }
}

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

    #[test]
    fn point_assignment_zoom_1() {
        let coords = [[1.5, 0.5]];
        let result = stripe_clip(&coords, 1, 1);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].0, TileCoord::new(1, 1, 0));
    }

    #[test]
    fn polygon_single_tile() {
        let polygon = [[0.2, 0.2], [0.8, 0.2], [0.8, 0.8], [0.2, 0.8], [0.2, 0.2]];
        let result = stripe_clip(&polygon, 1, 3);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].0, TileCoord::new(1, 0, 0));
        assert!(result[0].1.len() >= 4);
    }

    #[test]
    fn polygon_spans_two_tiles_horizontally() {
        let polygon = [[0.5, 0.2], [1.5, 0.2], [1.5, 0.8], [0.5, 0.8], [0.5, 0.2]];
        let result = stripe_clip(&polygon, 1, 3);
        assert!(
            result.len() >= 2,
            "Expected >= 2 tiles, got {}",
            result.len()
        );
        let tile_xs: Vec<u32> = result.iter().map(|(t, _)| t.x).collect();
        assert!(tile_xs.contains(&0), "Should have tile x=0");
        assert!(tile_xs.contains(&1), "Should have tile x=1");
    }

    #[test]
    fn linestring_clipped_to_band() {
        let line = [[0.0, 0.5], [3.0, 0.5]];
        let result = clip_linestring_to_band(&line, Axis::X, 1.0, 2.0);
        assert_eq!(result.len(), 2);
        assert!((result[0][0] - 1.0).abs() < 1e-10);
        assert!((result[1][0] - 2.0).abs() < 1e-10);
    }

    #[test]
    fn polygon_clipped_to_band_stays_inside() {
        let square = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0], [0.0, 0.0]];
        let result = clip_polygon_to_band(&square, Axis::X, 0.5, 1.5);
        assert_eq!(result.len(), 1, "Unit square should yield one clip piece");
        for p in &result[0] {
            assert!(
                p[0] >= 0.5 - 1e-9 && p[0] <= 1.5 + 1e-9,
                "x={} escapes",
                p[0]
            );
        }
        assert_eq!(result[0].first(), result[0].last(), "must be closed");
    }

    #[test]
    fn empty_geometry_returns_empty() {
        let result = stripe_clip(&[], 1, 3);
        assert!(result.is_empty());
    }

    #[test]
    fn polygon_with_hole_keeps_hole_as_interior() {
        // A z1 square covering the whole world with a hole fully inside tile
        // (0,0). That tile's clipped piece must keep the hole as an INTERIOR
        // ring (subtracted), never drop it (which would fill the hole region).
        let exterior = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0], [0.0, 0.0]];
        let hole = vec![[0.3, 0.3], [0.6, 0.3], [0.6, 0.6], [0.3, 0.6], [0.3, 0.3]];
        let result = stripe_clip_polygon(&exterior, &[hole], 1);
        let tile00 = result
            .iter()
            .find(|(t, _)| t.x == 0 && t.y == 0)
            .expect("tile (0,0) must be produced");
        let interior_pts: usize = tile00.1.interiors.iter().map(|r| r.len()).sum();
        assert!(
            interior_pts > 0,
            "fully-contained hole must survive as an interior ring"
        );
    }

    #[test]
    fn polygon_hole_outside_exterior_does_not_leak() {
        // Exterior on the left half, hole entirely in the right half (where the
        // exterior is absent). Clipping as a unit means the right tile gets NO
        // geometry — the hole never becomes a standalone fill there.
        let exterior = [[0.0, 0.0], [0.9, 0.0], [0.9, 2.0], [0.0, 2.0], [0.0, 0.0]];
        let hole = vec![[1.2, 0.8], [1.6, 0.8], [1.6, 1.2], [1.2, 1.2], [1.2, 0.8]];
        let result = stripe_clip_polygon(&exterior, &[hole], 1);
        for (tile, cp) in &result {
            assert!(
                tile.x == 0,
                "no geometry should land in the right tile (x=1); got exterior {:?}",
                cp.exterior
            );
        }
    }

    #[test]
    fn linestring_outside_tile_returns_empty() {
        let line = [[0.2, 0.2], [0.8, 0.3]];
        let result = stripe_clip(&line, 1, 2);
        for (tile, _) in &result {
            assert_eq!(tile.x, 0);
            assert_eq!(tile.y, 0);
        }
    }

    #[test]
    fn c_shape_concave_clipped_produces_valid_rings_no_bowtie() {
        let c_shape = [
            [0.0, 0.0],
            [1.0, 0.0],
            [1.0, 0.3],
            [0.4, 0.3],
            [0.4, 0.7],
            [1.0, 0.7],
            [1.0, 1.0],
            [0.0, 1.0],
            [0.0, 0.0],
        ];
        let result = clip_polygon_to_band(&c_shape, Axis::X, 0.2, 0.8);
        assert!(!result.is_empty(), "should produce at least one piece");
        for ring in &result {
            assert!(ring.len() >= 4);
            assert_eq!(ring.first(), ring.last(), "ring must be closed");
            assert!(
                !has_self_intersection(ring),
                "no bowtie allowed: {:?}",
                ring
            );
        }
    }

    #[test]
    fn u_shape_split_by_band_produces_multiple_rings() {
        let u_shape = [
            [0.0, 0.0],
            [1.0, 0.0],
            [1.0, 1.0],
            [0.7, 1.0],
            [0.7, 0.3],
            [0.3, 0.3],
            [0.3, 1.0],
            [0.0, 1.0],
            [0.0, 0.0],
        ];
        let result = clip_polygon_to_band(&u_shape, Axis::Y, 0.4, 1.1);
        assert_eq!(
            result.len(),
            2,
            "U-shape clipped through opening should produce 2 legs, got {}",
            result.len()
        );
        for ring in &result {
            assert!(!has_self_intersection(ring));
        }
    }

    #[test]
    fn fully_inside_band_passes_through() {
        let square = [[0.2, 0.2], [0.3, 0.2], [0.3, 0.3], [0.2, 0.3], [0.2, 0.2]];
        let result = clip_polygon_to_band(&square, Axis::X, 0.0, 1.0);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0], square);
    }

    #[test]
    fn fully_outside_band_returns_empty() {
        let square = [[0.8, 0.2], [0.9, 0.2], [0.9, 0.3], [0.8, 0.3], [0.8, 0.2]];
        let result = clip_polygon_to_band(&square, Axis::X, 0.0, 0.5);
        assert!(result.is_empty());
    }

    #[test]
    fn degenerate_polygon_returns_empty() {
        let triangle_with_two_points = [[0.0, 0.0], [1.0, 0.0], [0.0, 0.0]];
        let result = clip_polygon_to_band(&triangle_with_two_points, Axis::X, 0.0, 1.0);
        assert!(result.is_empty());
    }

    /// Regression guard for the `CLIP_PAD = 1e6` invariant. `geo::BooleanOps`
    /// silently returns an empty `MultiPolygon` when coordinate magnitudes
    /// approach 1e9 — we verified during development that 1e6 produces correct
    /// results at the maximum tile-coordinate magnitude we ever see (2^15 at z=15).
    /// If anyone bumps `CLIP_PAD` above ~1e8 in the future, this test fails.
    #[test]
    fn max_zoom_tile_coords_clip_correctly() {
        let z = 15_u8;
        let n = (1u32 << z) as f64;
        let tile_x = 16384.0;
        let tile_y = 16384.0;
        let ring = [
            [tile_x - 0.5, tile_y - 0.5],
            [tile_x + 1.5, tile_y - 0.5],
            [tile_x + 1.5, tile_y + 1.5],
            [tile_x - 0.5, tile_y + 1.5],
            [tile_x - 0.5, tile_y - 0.5],
        ];
        let result = stripe_clip(&ring, z, 3);
        assert!(
            !result.is_empty(),
            "z={z}: max-zoom polygon should clip to tiles; got {} results (n={n})",
            result.len()
        );
    }

    fn has_self_intersection(ring: &[[f64; 2]]) -> bool {
        let n = ring.len();
        if n < 5 {
            return false;
        }
        let open_n = n - 1;
        for i in 0..open_n {
            for j in i + 2..open_n {
                if i == 0 && j == open_n - 1 {
                    continue;
                }
                if segments_cross(ring[i], ring[i + 1], ring[j], ring[(j + 1) % open_n.max(1)]) {
                    return true;
                }
            }
        }
        false
    }

    fn segments_cross(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool {
        let d1 = cross(sub(a, c), sub(d, c));
        let d2 = cross(sub(b, c), sub(d, c));
        let d3 = cross(sub(c, a), sub(b, a));
        let d4 = cross(sub(d, a), sub(b, a));
        (d1 * d2 < 0.0) && (d3 * d4 < 0.0)
    }
    fn sub(a: [f64; 2], b: [f64; 2]) -> [f64; 2] {
        [a[0] - b[0], a[1] - b[1]]
    }
    fn cross(a: [f64; 2], b: [f64; 2]) -> f64 {
        a[0] * b[1] - a[1] * b[0]
    }
}