Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,22 @@ All notable changes to this project are documented in this file.
routes and tracks that were truncated to a small stub near ±180°, including
at z0 where the clip box is the whole world.

- Polygon clipping to a pole-reaching bounding box (#409): `Polygon.clipped(to:)`
no longer crashes when the box's latitude reaches ±90°. Such a box projects
to infinity in the EPSG:3857 working frame used by the overlay, which made
the overlay grid's cell size NaN and trapped on an `Int` conversion. The
overlay now replaces non-finite coordinates with the Web Mercator limit
before any geometry or grid math runs, so a polygon inside the box comes
back unchanged. Finite coordinates are left untouched, so geometry above the
Mercator limit keeps its exact values in operations that do not involve a
pole-reaching box. This also fixes the same trap in `union`, `intersection`,
`difference` and `symmetricDifference`, which share the overlay.

Both overlay grids (the uniform cell index and the prepared-ring scanline
index) additionally refuse to build from non-finite bounds and clamp their
indices as `Double` before converting to `Int`, so a non-finite input can no
longer trap regardless of where it comes from.

## 3.0.0 - 2026-10-30

### Breaking changes
Expand Down
147 changes: 138 additions & 9 deletions Sources/GISTools/Algorithms/Overlay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,22 @@ enum Overlay {
let maxX = boxes.reduce(first.maxX) { max($0, $1.box.maxX) }
let maxY = boxes.reduce(first.maxY) { max($0, $1.box.maxY) }

// A non-finite bound cannot be turned into a grid: the cell
// size would become NaN and the index conversions below would
// trap. Index every polygon in a single cell instead, so
// containment tests stay correct without a grid.
guard minX.isFinite, minY.isFinite, maxX.isFinite, maxY.isFinite else {
self.originX = 0.0
self.originY = 0.0
self.cellWidth = 1.0
self.cellHeight = 1.0
self.columns = 1
self.rows = 1
self.cells = [boxes.map(\.index)]
self.large = []
return
}

let side = max(8, min(64, Int(sqrt(Double(max(polygons.count, 1))))))
let columns = side
let rows = side
Expand Down Expand Up @@ -222,10 +238,14 @@ enum Overlay {
}

func cellIndex(for point: Coordinate3D) -> Int? {
guard columns > 0, rows > 0 else { return nil }

let column = min(max(Int(floor((point.x - originX) / cellWidth)), 0), columns - 1)
let row = min(max(Int(floor((point.y - originY) / cellHeight)), 0), rows - 1)
guard columns > 0, rows > 0,
let column = Self.clampedIndex(
(point.x - originX) / cellWidth,
count: columns),
let row = Self.clampedIndex(
(point.y - originY) / cellHeight,
count: rows)
else { return nil }

return row * columns + column
}
Expand All @@ -236,7 +256,7 @@ enum Overlay {
cellSize: Double,
count: Int
) -> Int {
min(max(Int((value - origin) / cellSize), 0), count - 1)
clampedIndex((value - origin) / cellSize, count: count) ?? 0
}

private static func row(
Expand All @@ -245,7 +265,22 @@ enum Overlay {
cellSize: Double,
count: Int
) -> Int {
min(max(Int((value - origin) / cellSize), 0), count - 1)
clampedIndex((value - origin) / cellSize, count: count) ?? 0
}

/// Clamps a grid index into `0 ..< count`, returning `nil` when the
/// value is not finite.
///
/// The value is clamped as a `Double` *before* the `Int` conversion:
/// converting a huge but finite value (or NaN/infinity) to `Int`
/// traps.
private static func clampedIndex(
_ value: Double,
count: Int,
) -> Int? {
guard count > 0, value.isFinite else { return nil }

return Int(min(max(value, 0.0), Double(count - 1)))
}

}
Expand All @@ -265,6 +300,11 @@ enum Overlay {
/// ``PolygonIndex`` over the normalized polygons is passed to
/// `boundaryTest`, so the test always sees the same frame as the edges.
///
/// A latitude of ±90° projects to infinity in EPSG:3857, so a legal
/// geographic bounding box can arrive here with non-finite coordinates.
/// Those are replaced with the projection's valid extent before any
/// geometry or grid math runs; finite coordinates are left untouched.
///
/// - Parameters:
/// - polygons: The input polygons.
/// - boundaryTest: Returns `true` when an edge is part of the result boundary.
Expand All @@ -275,6 +315,8 @@ enum Overlay {
) -> MultiPolygon? {
guard polygons.isNotEmpty else { return nil }

let polygons = sanitizedForOverlay(polygons)

let frame = antimeridianFrame(for: polygons)
let normalized = frame.polygons

Expand Down Expand Up @@ -399,6 +441,63 @@ private struct IndexedEdge: BoundingBoxRepresentable {

extension Overlay {

// MARK: - Non-finite input sanitization

/// Replaces non-finite coordinates with the EPSG:3857 valid extent.
///
/// The overlay works in EPSG:3857, where a latitude of ±90° projects to
/// infinity (or a very large finite value). A legal geographic bounding
/// box can therefore reach the overlay with non-finite coordinates, which
/// would poison the geometry math and the integer grid. Clamping those
/// values to ±``GISTool/originShift`` keeps the overlay well-defined.
///
/// Only non-finite values are touched: finite coordinates are returned
/// unchanged, so geometry above the Mercator limit keeps its exact values
/// in operations that do not involve a pole-reaching box.
///
/// - Parameter polygons: The polygons in EPSG:3857.
/// - Returns: The polygons with all coordinates finite.
static func sanitizedForOverlay(_ polygons: [Polygon]) -> [Polygon] {
var changed = false

let result = polygons.map { polygon in
var polygonChanged = false

let rings = polygon.coordinates.map { ring in
ring.map { coordinate -> Coordinate3D in
guard !coordinate.x.isFinite || !coordinate.y.isFinite else {
return coordinate
}

polygonChanged = true
return Coordinate3D(
x: clampedToMercatorLimit(coordinate.x),
y: clampedToMercatorLimit(coordinate.y),
z: coordinate.altitude,
m: coordinate.m,
projection: coordinate.projection)
}
}

guard polygonChanged else { return polygon }

changed = true
return Polygon(unchecked: rings, calculateBoundingBox: false)
}

return changed ? result : polygons
}

/// Maps a non-finite value onto the Web Mercator limit, preserving sign.
///
/// - Parameter value: The coordinate component.
/// - Returns: `value` when finite, otherwise ±``GISTool/originShift``.
fileprivate static func clampedToMercatorLimit(_ value: Double) -> Double {
guard !value.isFinite else { return value }

return value > 0.0 ? GISTool.originShift : -GISTool.originShift
}

// MARK: - Antimeridian normalization

/// Returns a frame in which no ring crosses the wraparound axis.
Expand Down Expand Up @@ -979,6 +1078,18 @@ private struct OverlayPreparedRing: Sendable {
return
}

// A non-finite bound cannot be turned into a scanline index: the row
// scale would become NaN and the `Int` conversions below would trap.
// Fall back to no rows, which makes `contains` return `false`.
guard minY.isFinite, maxY.isFinite else {
self.minY = 0.0
self.maxY = 0.0
self.rowScale = 0.0
self.rowCount = 0
self.rows = []
return
}

let rowCount = max(8, min(256, edgeCount / 4))
let span = maxY - minY
let rowScale = Double(rowCount) / span
Expand All @@ -989,8 +1100,8 @@ private struct OverlayPreparedRing: Sendable {
let b = coordinates[(index + 1) % edgeCount]
let low = min(a.y, b.y)
let high = max(a.y, b.y)
let startRow = min(max(Int((low - minY) * rowScale), 0), rowCount - 1)
let endRow = min(max(Int((high - minY) * rowScale), 0), rowCount - 1)
let startRow = Self.rowIndex(low, minY: minY, rowScale: rowScale, rowCount: rowCount)
let endRow = Self.rowIndex(high, minY: minY, rowScale: rowScale, rowCount: rowCount)

for row in startRow ... endRow {
rows[row].append(index)
Expand All @@ -1004,14 +1115,32 @@ private struct OverlayPreparedRing: Sendable {
self.rows = rows
}

/// Clamps a y value into `0 ..< rowCount`.
///
/// The value is clamped as a `Double` *before* the `Int` conversion:
/// converting a huge but finite value (or NaN/infinity) to `Int` traps.
private static func rowIndex(
_ y: Double,
minY: Double,
rowScale: Double,
rowCount: Int,
) -> Int {
guard rowCount > 0 else { return 0 }

let value = (y - minY) * rowScale
guard value.isFinite else { return 0 }

return Int(min(max(value, 0.0), Double(rowCount - 1)))
}

func contains(_ point: Coordinate3D) -> Bool {
guard edgeCount >= 3,
rowCount > 0,
point.y >= minY,
point.y <= maxY
else { return false }

let row = min(max(Int((point.y - minY) * rowScale), 0), rowCount - 1)
let row = Self.rowIndex(point.y, minY: minY, rowScale: rowScale, rowCount: rowCount)
var inside = false

for index in rows[row] {
Expand Down
64 changes: 64 additions & 0 deletions Tests/GISToolsTests/Algorithms/BoundingBoxClipTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,70 @@ struct BoundingBoxClipTests {
})
}

// MARK: - Clip boxes reaching the poles

/// Clipping a polygon to a box whose latitude reaches ±90° must not trap.
///
/// A latitude of ±90° projects to infinity in EPSG:3857, which used to
/// make the overlay grid's cell size NaN and trap on the `Int` conversion.
@Test
func polygonInsidePoleReachingBoxIsKept() throws {
let box = BoundingBox(
southWest: Coordinate3D(latitude: -90.0, longitude: -180.0),
northEast: Coordinate3D(latitude: 90.0, longitude: 180.0))
let polygon = try #require(Polygon([[
Coordinate3D(x: -45.0, y: 60.0, projection: .epsg4326),
Coordinate3D(x: 45.0, y: 60.0, projection: .epsg4326),
Coordinate3D(x: 45.0, y: -60.0, projection: .epsg4326),
Coordinate3D(x: -45.0, y: -60.0, projection: .epsg4326),
Coordinate3D(x: -45.0, y: 60.0, projection: .epsg4326),
]]))

let clipped = try #require(polygon.clipped(to: box))
#expect(clipped.polygons.count == 1)
#expect(abs(clipped.area - polygon.area) < polygon.area * 0.000001)
}

/// A box reaching the south pole only must also keep a contained polygon.
@Test
func polygonInsideSouthPoleBoxIsKept() throws {
let box = BoundingBox(
southWest: Coordinate3D(latitude: -90.0, longitude: -180.0),
northEast: Coordinate3D(latitude: 0.0, longitude: 180.0))
let polygon = try #require(Polygon([[
Coordinate3D(x: -45.0, y: -60.0, projection: .epsg4326),
Coordinate3D(x: 45.0, y: -60.0, projection: .epsg4326),
Coordinate3D(x: 45.0, y: -20.0, projection: .epsg4326),
Coordinate3D(x: -45.0, y: -20.0, projection: .epsg4326),
Coordinate3D(x: -45.0, y: -60.0, projection: .epsg4326),
]]))

let clipped = try #require(polygon.clipped(to: box))
#expect(clipped.polygons.count == 1)
#expect(abs(clipped.area - polygon.area) < polygon.area * 0.000001)
}

/// A pole-reaching box must not trap in EPSG:4978 either, where the box is
/// projected before clipping.
@Test
func polygonInsidePoleReachingBox4978IsKept() throws {
let polygon4326 = try #require(Polygon([[
Coordinate3D(x: -45.0, y: 60.0, projection: .epsg4326),
Coordinate3D(x: 45.0, y: 60.0, projection: .epsg4326),
Coordinate3D(x: 45.0, y: -60.0, projection: .epsg4326),
Coordinate3D(x: -45.0, y: -60.0, projection: .epsg4326),
Coordinate3D(x: -45.0, y: 60.0, projection: .epsg4326),
]]))
let polygon = polygon4326.projected(to: .epsg4978)
let box = BoundingBox(
southWest: Coordinate3D(latitude: -90.0, longitude: -180.0),
northEast: Coordinate3D(latitude: 90.0, longitude: 180.0))

let clipped = try #require(polygon.clipped(to: box))
#expect(clipped.polygons.isNotEmpty)
#expect(clipped.projection == .epsg4978)
}

// MARK: - Segments spanning more than 180° of longitude

/// A segment spanning more than 180° of longitude is unwrapped across the
Expand Down
64 changes: 64 additions & 0 deletions Tests/GISToolsTests/Algorithms/OverlayTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,68 @@ struct OverlayTests {
#expect(result.isValid)
}

// MARK: - Non-finite input

/// The overlay grid must never trap on a non-finite bound.
///
/// A latitude of −90° projects to `-infinity` in EPSG:3857, which used to
/// make the grid's cell size NaN and trap on the `Int` conversion. The
/// index is built directly here so the guard is exercised without running
/// the full overlay on a pathological polygon.
@Test
func polygonIndexWithInfiniteBoundsDoesNotTrap() {
let infinite = Polygon(unchecked: [[
Coordinate3D(x: 0.0, y: 0.0, projection: .noSRID),
Coordinate3D(x: 10.0, y: 0.0, projection: .noSRID),
Coordinate3D(x: 10.0, y: .infinity, projection: .noSRID),
Coordinate3D(x: 0.0, y: .infinity, projection: .noSRID),
Coordinate3D(x: 0.0, y: 0.0, projection: .noSRID),
]])
let index = Overlay.PolygonIndex([infinite])

// Must return without trapping.
_ = index.contains(Coordinate3D(x: 5.0, y: 5.0, projection: .noSRID))
_ = index.contains(Coordinate3D(x: 5.0, y: .infinity, projection: .noSRID))
_ = index.contains(Coordinate3D(x: .nan, y: .nan, projection: .noSRID))
}

/// The overlay grid must never trap on a NaN bound either.
@Test
func polygonIndexWithNaNBoundsDoesNotTrap() {
let nan = Polygon(unchecked: [[
Coordinate3D(x: 0.0, y: 0.0, projection: .noSRID),
Coordinate3D(x: 10.0, y: 0.0, projection: .noSRID),
Coordinate3D(x: 10.0, y: .nan, projection: .noSRID),
Coordinate3D(x: 0.0, y: .nan, projection: .noSRID),
Coordinate3D(x: 0.0, y: 0.0, projection: .noSRID),
]])
let index = Overlay.PolygonIndex([nan])

_ = index.contains(Coordinate3D(x: 5.0, y: 5.0, projection: .noSRID))
_ = index.contains(Coordinate3D(x: .nan, y: .nan, projection: .noSRID))
}

/// A non-finite coordinate in an overlay input is replaced with the Web
/// Mercator limit, so the overlay math never sees infinities or NaN.
@Test
func overlaySanitizesNonFiniteCoordinates() {
let finite = square(0.0, 10.0)
let infinite = Polygon(unchecked: [[
Coordinate3D(x: 0.0, y: 0.0, projection: .noSRID),
Coordinate3D(x: 10.0, y: 0.0, projection: .noSRID),
Coordinate3D(x: 10.0, y: .infinity, projection: .noSRID),
Coordinate3D(x: 0.0, y: .infinity, projection: .noSRID),
Coordinate3D(x: 0.0, y: 0.0, projection: .noSRID),
]])

let sanitized = Overlay.sanitizedForOverlay([finite, infinite])
#expect(sanitized.count == 2)
// The finite polygon is returned unchanged.
#expect(sanitized[0].coordinates == finite.coordinates)
// The infinite coordinate is clamped to the Mercator limit.
// swiftformat:disable:next preferKeyPath
#expect(sanitized[1].allCoordinates.allSatisfy({ $0.y.isFinite }))
#expect(sanitized[1].allCoordinates.contains { abs($0.y - GISTool.originShift) < 0.000001 })
}

}
Loading