diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b20345c..002df449 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,18 @@ All notable changes to this project are documented in this file. ## Unreleased +### Fixed + +- Line clipping across the antimeridian (#408): `LineString.clipped(to:)` and + `MultiLineString.clipped(to:)` no longer drop one half of a segment that + spans more than 180° of longitude. Such a segment is unwrapped across the + antimeridian, so it is longer than one world period and can reach into more + than one copy of the clip box. Clipping now evaluates every world copy that + the unwrapped line overlaps and keeps all resulting pieces, instead of + clipping against a single copy chosen from the line's centre. This fixes + routes and tracks that were truncated to a small stub near ±180°, including + at z0 where the clip box is the whole world. + ## 3.0.0 - 2026-10-30 ### Breaking changes diff --git a/Sources/GISTools/Algorithms/BoundingBoxClip.swift b/Sources/GISTools/Algorithms/BoundingBoxClip.swift index f5ebe090..b1fb982b 100644 --- a/Sources/GISTools/Algorithms/BoundingBoxClip.swift +++ b/Sources/GISTools/Algorithms/BoundingBoxClip.swift @@ -330,45 +330,81 @@ extension BoundingBox { /// Clips a line against a possibly antimeridian-crossing box by splitting /// the box into its non-crossing parts and clipping against each one. + /// + /// The coordinates are unwrapped into a continuous frame first, so a + /// segment that crosses the antimeridian becomes a segment that leaves the + /// world on one side and re-enters on the other. A segment spanning more + /// than half the world is therefore longer than one world period and can + /// reach into more than one copy of the clip box. Every world copy that + /// the unwrapped line touches is clipped and all resulting pieces are + /// kept, so neither half of such a segment is lost. fileprivate func clipLineParts( coordinates: [Coordinate3D], projection: Projection, ) -> [[Coordinate3D]] { let boxes = clipBoxes(projection: projection) - let extent = projection.wraparoundExtent - let period = (extent ?? 0.0) * 2.0 - let unwrapped = extent.map { - AntimeridianCutting.unwrapCoordinates(coordinates, extent: $0) - } ?? coordinates - let lineCenter = unwrapped.reduce(0.0) { $0 + $1.x } / Double(max(unwrapped.count, 1)) + + guard let extent = projection.wraparoundExtent, + extent > 0.0 + else { + return boxes.flatMap { $0.clipLine(coordinates: coordinates) } + } + + let period = extent * 2.0 + let unwrapped = AntimeridianCutting.unwrapCoordinates(coordinates, extent: extent) + + guard let lineMinX = unwrapped.map(\.x).min(), + let lineMaxX = unwrapped.map(\.x).max() + else { return [] } var parts: [[Coordinate3D]] = [] var seen: Set<[Coordinate3D]> = [] for box in boxes { - var candidate = unwrapped - if period > 0.0 { - let boxCenter = (box.southWest.x + box.northEast.x) / 2.0 - let shift = ((boxCenter - lineCenter) / period).rounded() * period - if shift != 0.0 { - candidate = candidate.map { + let boxMinX = box.southWest.x + let boxMaxX = box.northEast.x + + // World copies of the box are the box shifted by whole periods. + // Copy `k` covers `boxMinX + k * period ... boxMaxX + k * period`; + // it overlaps the unwrapped line when + // `k >= (lineMinX - boxMaxX) / period` and + // `k <= (lineMaxX - boxMinX) / period`. Only whole copies count, + // hence the `ceil`/`floor` bounds. + let firstCopyValue = ((lineMinX - boxMaxX) / period).rounded(.up) + let lastCopyValue = ((lineMaxX - boxMinX) / period).rounded(.down) + + guard firstCopyValue.isFinite, + lastCopyValue.isFinite, + firstCopyValue <= lastCopyValue, + firstCopyValue >= Double(Int.min), + lastCopyValue <= Double(Int.max) + else { continue } + + let firstCopy = Int(firstCopyValue) + let lastCopy = Int(lastCopyValue) + + for copyIndex in firstCopy ... lastCopy { + // Clipping against the copy shifted by `shift` is equivalent to + // shifting the line by the same amount in the opposite + // direction, then clipping against the box itself. + let shift = Double(copyIndex) * period + let candidate = shift == 0.0 + ? unwrapped + : unwrapped.map { Coordinate3D( - x: $0.x + shift, + x: $0.x - shift, y: $0.y, z: $0.altitude, m: $0.m, projection: $0.projection) } - } - } - for part in box.clipLine(coordinates: candidate) { - let normalized = extent == nil - ? part - : part.map { $0.normalized() } - guard seen.insert(normalized).inserted else { continue } + for part in box.clipLine(coordinates: candidate) { + let normalized = part.map { $0.normalized() } + guard seen.insert(normalized).inserted else { continue } - parts.append(normalized) + parts.append(normalized) + } } } diff --git a/Tests/GISToolsTests/Algorithms/BoundingBoxClipTests.swift b/Tests/GISToolsTests/Algorithms/BoundingBoxClipTests.swift index ff60ab9b..48439f92 100644 --- a/Tests/GISToolsTests/Algorithms/BoundingBoxClipTests.swift +++ b/Tests/GISToolsTests/Algorithms/BoundingBoxClipTests.swift @@ -511,4 +511,184 @@ struct BoundingBoxClipTests { }) } + // MARK: - Segments spanning more than 180° of longitude + + /// A segment spanning more than 180° of longitude is unwrapped across the + /// antimeridian, so its short way runs through ±180° and it spans more + /// than one world period. A box that covers both sides of the seam must + /// keep both pieces instead of silently dropping one half. + @Test + func segmentSpanningMoreThanHalfTheWorldKeepsBothHalves() throws { + let line = try #require(LineString([ + Coordinate3D(x: -100.0, y: 0.0, projection: .epsg4326), + Coordinate3D(x: 100.0, y: 0.0, projection: .epsg4326), + ])) + let box = BoundingBox( + southWest: Coordinate3D(latitude: -85.0, longitude: -110.0), + northEast: Coordinate3D(latitude: 85.0, longitude: 110.0)) + + let clipped = try #require(line.clipped(to: box)) + #expect(clipped.lineStrings.count == 2) + + let endpoints = clipped.lineStrings.flatMap { lineString in + [lineString.coordinates.first, lineString.coordinates.last] + .compactMap { $0?.longitude } + } + // One piece runs -100 → -110, the other 110 → 100. + #expect(endpoints.contains { abs($0 + 100.0) < 0.000001 }) + #expect(endpoints.contains { abs($0 + 110.0) < 0.000001 }) + #expect(endpoints.contains { abs($0 - 100.0) < 0.000001 }) + #expect(endpoints.contains { abs($0 - 110.0) < 0.000001 }) + + // 10° on each side of the seam. + let expectedLength = Self.equatorLength(from: -100.0, to: -110.0) + + Self.equatorLength(from: 110.0, to: 100.0) + let totalLength = clipped.lineStrings.reduce(0.0) { $0 + $1.length } + #expect(abs(totalLength - expectedLength) < expectedLength * 0.000001) + } + + /// The world box must keep a >180° segment intact (as the two + /// antimeridian pieces), not truncate it to a stub near 180°. + @Test + func segmentSpanningMoreThanHalfTheWorldInsideWorldBoxIsKept() throws { + let line = try #require(LineString([ + Coordinate3D(x: -100.0, y: 0.0, projection: .epsg4326), + Coordinate3D(x: 100.0, y: 0.0, projection: .epsg4326), + ])) + + let clipped = try #require(line.clipped(to: .world)) + #expect(clipped.lineStrings.count == 2) + + let endpoints = clipped.lineStrings.flatMap { lineString in + [lineString.coordinates.first, lineString.coordinates.last] + .compactMap { $0?.longitude } + } + #expect(endpoints.contains { abs($0 + 180.0) < 0.000001 }) + #expect(endpoints.contains { abs($0 - 180.0) < 0.000001 }) + + // The short way through ±180° is 160° of longitude. + let totalLength = clipped.lineStrings.reduce(0.0) { $0 + $1.length } + #expect(abs(totalLength - line.length) < line.length * 0.000001) + } + + /// Boxes ending exactly at 180° or at -180°, and boxes ending just inside + /// either edge, must all keep both halves of a >180° segment. + @Test(arguments: [ + (-180.0, 180.0), + (-180.0, 179.999), + (-179.999, 180.0), + (-180.0, 170.0), + (-170.0, 180.0), + ] as [(Double, Double)]) + func segmentSpanningMoreThanHalfTheWorldAtWorldEdges( + _ west: Double, + _ east: Double, + ) throws { + let line = try #require(LineString([ + Coordinate3D(x: -100.0, y: 0.0, projection: .epsg4326), + Coordinate3D(x: 100.0, y: 0.0, projection: .epsg4326), + ])) + let box = BoundingBox( + southWest: Coordinate3D(latitude: -85.0, longitude: west), + northEast: Coordinate3D(latitude: 85.0, longitude: east)) + + let clipped = try #require(line.clipped(to: box)) + #expect(clipped.lineStrings.count == 2) + + // Both vertices of the original segment must survive on their own side + // of the seam, and every coordinate must stay inside the box. + let coordinates = clipped.allCoordinates + #expect(coordinates.contains { abs($0.longitude + 100.0) < 0.000001 }) + #expect(coordinates.contains { abs($0.longitude - 100.0) < 0.000001 }) + for coordinate in coordinates { + #expect(coordinate.longitude >= west - 0.000001) + #expect(coordinate.longitude <= east + 0.000001) + } + } + + /// A crossing box narrower than the segment trims the parts that leave the + /// box but keeps everything inside it on both sides of the seam. + @Test + func segmentSpanningMoreThanHalfTheWorldIsTrimmedByNarrowBox() throws { + let line = try #require(LineString([ + Coordinate3D(x: -100.0, y: 0.0, projection: .epsg4326), + Coordinate3D(x: 100.0, y: 0.0, projection: .epsg4326), + ])) + let box = BoundingBox( + southWest: Coordinate3D(latitude: -5.0, longitude: 170.0), + northEast: Coordinate3D(latitude: 5.0, longitude: -170.0)) + + let clipped = try #require(line.clipped(to: box)) + #expect(clipped.lineStrings.count == 2) + + for coordinate in clipped.allCoordinates { + #expect(coordinate.longitude >= 170.0 - 0.000001 || coordinate.longitude <= -170.0 + 0.000001) + } + + // 10° on each side of the seam. + let expectedLength = Self.equatorLength(from: 170.0, to: 180.0) + + Self.equatorLength(from: -180.0, to: -170.0) + let totalLength = clipped.lineStrings.reduce(0.0) { $0 + $1.length } + #expect(abs(totalLength - expectedLength) < expectedLength * 0.000001) + } + + /// A >180° segment in EPSG:3857 behaves like the EPSG:4326 case. + @Test + func segmentSpanningMoreThanHalfTheWorld3857IsKept() throws { + let shift = GISTool.originShift + let line = try #require(LineString([ + Coordinate3D(x: -shift / 1.8, y: 0.0, projection: .epsg3857), + Coordinate3D(x: shift / 1.8, y: 0.0, projection: .epsg3857), + ])) + let box = BoundingBox( + southWest: Coordinate3D(x: -shift, y: -shift, projection: .epsg3857), + northEast: Coordinate3D(x: shift, y: shift, projection: .epsg3857)) + + let clipped = try #require(line.clipped(to: box)) + #expect(clipped.lineStrings.count == 2) + + let totalLength = clipped.lineStrings.reduce(0.0) { $0 + $1.length } + #expect(abs(totalLength - line.length) < line.length * 0.000001) + } + + /// A plain antimeridian-crossing line clipped against the world box must + /// keep both sides of the seam. At z0 the clip box is the whole world, so + /// this is the case that used to drop one half of a route. + @Test + func antimeridianCrossingLineInsideWorldBoxIsKept() throws { + let line = try #require(LineString([ + Coordinate3D(x: 179.0, y: 0.0, projection: .epsg4326), + Coordinate3D(x: -179.0, y: 0.0, projection: .epsg4326), + ])) + + let clipped = try #require(line.clipped(to: .world)) + #expect(clipped.lineStrings.count == 2) + + let totalLength = clipped.lineStrings.reduce(0.0) { $0 + $1.length } + #expect(abs(totalLength - line.length) < line.length * 0.000001) + } + + /// The length of an equatorial segment between two longitudes. + private static func equatorLength(from: Double, to: Double) -> Double { + Coordinate3D(latitude: 0.0, longitude: from) + .distance(to: Coordinate3D(latitude: 0.0, longitude: to)) + } + + /// A >180° segment in EPSG:4978 has no wraparound axis, so it is clipped + /// as a plain axis-aligned segment. + @Test + func segmentSpanningMoreThanHalfTheWorld4978IsClippedFlat() throws { + let line = try #require(LineString([ + Coordinate3D(x: -100.0, y: 0.0, z: 0.0, projection: .epsg4978), + Coordinate3D(x: 100.0, y: 0.0, z: 0.0, projection: .epsg4978), + ])) + let box = BoundingBox( + southWest: Coordinate3D(x: -110.0, y: -85.0, z: 0.0, projection: .epsg4978), + northEast: Coordinate3D(x: 110.0, y: 85.0, z: 0.0, projection: .epsg4978)) + + let clipped = try #require(line.clipped(to: box)) + #expect(clipped.lineStrings.count == 1) + #expect(clipped.allCoordinates.count == 2) + } + }