use crate::geometry::mercator::TileCoord;
use geo::{BooleanOps, Coord, LineString, MultiPolygon, Polygon};
const BUFFER: f64 = 4.0 / 256.0;
const CLIP_PAD: f64 = 1.0e6;
#[derive(Debug, Clone, Copy)]
enum Axis {
X,
Y,
}
impl Axis {
#[inline]
const fn get(self, p: &[f64; 2]) -> f64 {
match self {
Axis::X => p[0],
Axis::Y => p[1],
}
}
}
#[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);
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
}
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()
}
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);
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
}
#[derive(Debug, Clone)]
pub struct ClippedPolygon {
pub exterior: Vec<[f64; 2]>,
pub interiors: Vec<Vec<[f64; 2]>>,
}
#[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
}
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)
}
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(),
}
}
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,
})
}
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
}
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())
}
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
}
#[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() {
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() {
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());
}
#[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]
}
}