From e265149c5a1cefb638980987e2a8b78eb11cebb3 Mon Sep 17 00:00:00 2001 From: "Thomas Rasch (OpenCode)" Date: Wed, 28 Oct 2026 12:59:32 +0000 Subject: [PATCH] Support extended geometry types in WKB, WKT and TWKB --- CHANGELOG.md | 14 + .../GISTools.docc/GeoJSONAndCoders.md | 26 + .../GISTools/GeoJson/CurveLinearization.swift | 151 +++++ Sources/GISTools/GeoJson/TWKBCoder.swift | 20 +- Sources/GISTools/GeoJson/WKBCoder.swift | 532 ++++++++++++++++-- Sources/GISTools/GeoJson/WKTCoder.swift | 486 +++++++++++++++- Tests/GISToolsTests/GeoJson/TWKBTests.swift | 73 ++- Tests/GISToolsTests/GeoJson/WKBTests.swift | 144 ++++- Tests/GISToolsTests/GeoJson/WKTTests.swift | 132 +++++ 9 files changed, 1481 insertions(+), 97 deletions(-) create mode 100644 Sources/GISTools/GeoJson/CurveLinearization.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a1e99ba..249db271 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -204,6 +204,20 @@ The deprecated aliases from 2.x have been removed. Use the current names: are covered by a new differential test suite; the generator script is development-only and the package keeps no third-party runtime dependency. +- Extended WKB/WKT/TWKB geometry coverage (#404): + - WKB and WKT decode `CircularString`, `CompoundCurve`, `CurvePolygon`, + `MultiCurve` and `MultiSurface`, linearizing arcs into `LineString`, + `Polygon`, `MultiLineString` and `MultiPolygon`. + - `TIN` and `PolyhedralSurface` decode to `MultiPolygon`, with each triangle + or patch represented as a `Polygon`. + - `POINT EMPTY` decodes to an empty `MultiPoint`; WKT `EMPTY` is accepted for + every geometry type and empty geometries encode as `TYPE EMPTY`. + - WKB accepts ISO SQL/MM dimension codes (`+1000` Z, `+2000` M, `+3000` ZM) + in addition to EWKB dimension flags. + - TWKB empty metadata decodes to the matching empty geometry. PostGIS + encodes `TIN` as a `GeometryCollection` in TWKB; curves and + `PolyhedralSurface` are not representable in TWKB. + - API compatibility CI (#380): pull requests now run `swift package diagnose-api-breaking-changes` against their base branch. Accidental public API removals or signature changes fail CI; intentional diff --git a/Sources/GISTools/GISTools.docc/GeoJSONAndCoders.md b/Sources/GISTools/GISTools.docc/GeoJSONAndCoders.md index 18d73073..cfb7b254 100644 --- a/Sources/GISTools/GISTools.docc/GeoJSONAndCoders.md +++ b/Sources/GISTools/GISTools.docc/GeoJSONAndCoders.md @@ -129,6 +129,27 @@ exercise insertion and fetching for every supported geometry type. ring, polygon, multi-point, multi-line string, multi-polygon, geometry collection and triangle geometry types. +Curved geometries are linearized into the existing model types while decoding: + +| Input | Decoded as | +| --- | --- | +| `CircularString` | `LineString` | +| `CompoundCurve` | `LineString` | +| `CurvePolygon` | `Polygon` | +| `MultiCurve` | `MultiLineString` | +| `MultiSurface` | `MultiPolygon` | + +`TIN` and `PolyhedralSurface` decode to a `MultiPolygon`, with every triangle +or patch represented as a `Polygon`. The mapping is lossy: re-encoding writes +the linear type, not the original curve or surface type. + +`POINT EMPTY` decodes to an empty `MultiPoint` because the model has no empty +`Point`. The other empty geometries decode as their empty counterparts, and WKT +writes `TYPE EMPTY` when encoding an empty geometry. + +WKB accepts both EWKB dimension flags and the ISO SQL/MM dimension codes used +by PostGIS (`+1000` for Z, `+2000` for M, `+3000` for ZM). + Every geometry also has convenience initializers for decoding and `asWKB` and `asWKT` accessors. Decoding can reproject on the fly: @@ -159,6 +180,11 @@ let point = try TWKBCoder.decode( sourceProjection: .epsg4326) ``` +TWKB empty metadata decodes to the corresponding empty geometry. PostGIS +encodes `TIN` as a `GeometryCollection` of polygons in TWKB, so it decodes as a +collection rather than a `MultiPolygon`. PostGIS rejects curves and +`PolyhedralSurface` when writing TWKB. + A `Feature` or `FeatureCollection` containing an unlocated feature cannot be encoded to WKB or WKT; encoding returns `nil`. diff --git a/Sources/GISTools/GeoJson/CurveLinearization.swift b/Sources/GISTools/GeoJson/CurveLinearization.swift new file mode 100644 index 00000000..95b6120a --- /dev/null +++ b/Sources/GISTools/GeoJson/CurveLinearization.swift @@ -0,0 +1,151 @@ +import Foundation + +/// Linearizes curved WKB/WKT geometries into the straight geometry types that +/// the GeoJSON model supports. +/// +/// The GeoJSON model has no native curve types, so `CircularString`, +/// `CompoundCurve`, `CurvePolygon`, `MultiCurve` and `MultiSurface` are +/// converted while decoding. Circular arcs are sampled with +/// ``segmentsPerQuadrant`` segments per quarter circle. +enum CurveLinearization { + + /// The number of line segments used for a quarter circle. + static let segmentsPerQuadrant = 32 + + /// Converts the points of a `CircularString` into a linear coordinate list. + /// + /// A `CircularString` stores arcs as consecutive triples: start, a point on + /// the arc, and end. Consecutive arcs share their first and last point. + /// + /// - Parameter coordinates: The control points of the circular string. + /// - Returns: The linearized coordinates. + static func circularString(_ coordinates: [Coordinate3D]) -> [Coordinate3D] { + guard coordinates.count >= 3 else { return coordinates } + + var result: [Coordinate3D] = [coordinates[0]] + var index = 0 + + while index + 2 < coordinates.count { + let arc = arc( + from: coordinates[index], + through: coordinates[index + 1], + to: coordinates[index + 2]) + + result.append(contentsOf: arc.dropFirst()) + index += 2 + } + + // Invalid input with an even number of points: keep the trailing point + // instead of silently dropping it. + if index + 1 < coordinates.count { + result.append(coordinates[index + 1]) + } + + return result + } + + /// Samples the circular arc through three points. + /// + /// - Parameters: + /// - start: The start point. + /// - mid: A point on the arc between `start` and `end`. + /// - end: The end point. + /// - Returns: The sampled arc, including both endpoints. + private static func arc( + from start: Coordinate3D, + through mid: Coordinate3D, + to end: Coordinate3D, + ) -> [Coordinate3D] { + let ax = start.x + let ay = start.y + let bx = mid.x + let by = mid.y + let cx = end.x + let cy = end.y + + let scale = max(1.0, abs(ax), abs(ay), abs(bx), abs(by), abs(cx), abs(cy)) + let tolerance = 1e-9 * scale + + let determinant = 2.0 * ((ax * (by - cy)) + (bx * (cy - ay)) + (cx * (ay - by))) + + guard abs(determinant) > 1e-12 * scale * scale else { + // Collinear or coincident points: no meaningful circle. + return [start, mid, end] + } + + let aSquared = (ax * ax) + (ay * ay) + let bSquared = (bx * bx) + (by * by) + let cSquared = (cx * cx) + (cy * cy) + + let centerX = ((aSquared * (by - cy)) + (bSquared * (cy - ay)) + (cSquared * (ay - by))) / determinant + let centerY = ((aSquared * (cx - bx)) + (bSquared * (ax - cx)) + (cSquared * (bx - ax))) / determinant + + let radius = hypot(ax - centerX, ay - centerY) + guard radius > tolerance else { return [start, mid, end] } + + let startAngle = atan2(ay - centerY, ax - centerX) + let midAngle = atan2(by - centerY, bx - centerX) + let endAngle = atan2(cy - centerY, cx - centerX) + + let isFullCircle = hypot(ax - cx, ay - cy) <= tolerance + let sweep: Double + + if isFullCircle { + // The start and end point are identical, so use the side of the + // centre that the middle point lies on to choose the direction. + let cross = ((bx - centerX) * (ay - centerY)) - ((by - centerY) * (ax - centerX)) + sweep = cross >= 0 ? 2.0 * .pi : -2.0 * .pi + } + else { + let counterClockwiseSweep = normalizedAngle(endAngle - startAngle) + let counterClockwiseMid = normalizedAngle(midAngle - startAngle) + sweep = counterClockwiseMid <= counterClockwiseSweep + ? counterClockwiseSweep + : counterClockwiseSweep - (2.0 * .pi) + } + + let segmentCount = max( + 2, + Int(ceil(abs(sweep) / (.pi / 2.0) * Double(segmentsPerQuadrant)))) + + var result: [Coordinate3D] = [] + result.reserveCapacity(segmentCount + 1) + + for index in 0 ... segmentCount { + let fraction = Double(index) / Double(segmentCount) + let angle = startAngle + (sweep * fraction) + + result.append( + Coordinate3D( + x: centerX + (radius * cos(angle)), + y: centerY + (radius * sin(angle)), + z: interpolate(start.z, end.z, fraction), + m: interpolate(start.m, end.m, fraction), + projection: start.projection)) + } + + // Avoid trigonometric drift at the endpoints. + result[0] = start + result[result.count - 1] = end + + return result + } + + /// Normalizes an angle to `0 ..< 2π`. + private static func normalizedAngle(_ angle: Double) -> Double { + var result = angle.truncatingRemainder(dividingBy: 2.0 * .pi) + if result < 0 { + result += 2.0 * .pi + } + return result + } + + /// Linearly interpolates an optional value. + private static func interpolate(_ start: Double?, _ end: Double?, _ fraction: Double) -> Double? { + if let start, let end { + return start + ((end - start) * fraction) + } + return start ?? end + } + +} diff --git a/Sources/GISTools/GeoJson/TWKBCoder.swift b/Sources/GISTools/GeoJson/TWKBCoder.swift index b2762578..bf3b0396 100644 --- a/Sources/GISTools/GeoJson/TWKBCoder.swift +++ b/Sources/GISTools/GeoJson/TWKBCoder.swift @@ -510,7 +510,25 @@ public enum TWKBCoder { let (geomType, scale) = try decodeHeader(bytes: bytes, offset: &offset) let metadata = try decodeMetadata(bytes: bytes, offset: &offset) - guard !metadata.isEmpty else { throw TWKBError.emptyGeometry } + + if metadata.isEmpty { + switch geomType { + case 1, 4: + return MultiPoint() + case 2: + return LineString() + case 3: + return Polygon() + case 5: + return MultiLineString() + case 6: + return MultiPolygon() + case 7: + return GeometryCollection([]) + default: + throw TWKBError.unexpectedType + } + } let sourceProjection = sourceProjection ?? .epsg4326 diff --git a/Sources/GISTools/GeoJson/WKBCoder.swift b/Sources/GISTools/GeoJson/WKBCoder.swift index 9927f5e9..b0a2c289 100644 --- a/Sources/GISTools/GeoJson/WKBCoder.swift +++ b/Sources/GISTools/GeoJson/WKBCoder.swift @@ -358,6 +358,13 @@ public enum WKBCoder { case multiLineString = 5 case multiPolygon = 6 case geometryCollection = 7 + case circularString = 8 + case compoundCurve = 9 + case curvePolygon = 10 + case multiCurve = 11 + case multiSurface = 12 + case polyhedralSurface = 15 + case tin = 16 case triangle = 17 } @@ -465,93 +472,211 @@ extension WKBCoder { // MARK: - + /// The parsed header of a WKB geometry. + private struct WKBHeader { + + let byteOrder: ByteOrder + let typeCode: WKBTypeCode + let decodeZ: Bool + let decodeM: Bool + let sourceProjection: Projection + + } + private static func decodeGeometry( bytes: [UInt8], offset: inout Int, sourceProjection: Projection?, targetProjection: Projection ) throws -> GeoJsonGeometry { + let header = try decodeHeader( + bytes: bytes, + offset: &offset, + sourceProjection: sourceProjection, + targetProjection: targetProjection) + + switch header.typeCode { + case .point: + return try decodePoint( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder, + sourceProjection: header.sourceProjection, + targetProjection: targetProjection, + decodeZ: header.decodeZ, + decodeM: header.decodeM) + + case .multiPoint: + return try decodeMultiPoint( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder, + sourceProjection: header.sourceProjection, + targetProjection: targetProjection, + decodeZ: header.decodeZ, + decodeM: header.decodeM) + + case .lineString: + return try decodeLineString( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder, + sourceProjection: header.sourceProjection, + targetProjection: targetProjection, + decodeZ: header.decodeZ, + decodeM: header.decodeM) + + case .multiLineString: + return try decodeMultiLineString( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder, + sourceProjection: header.sourceProjection, + targetProjection: targetProjection, + decodeZ: header.decodeZ, + decodeM: header.decodeM) + + case .polygon, .triangle: + return try decodePolygon( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder, + sourceProjection: header.sourceProjection, + targetProjection: targetProjection, + decodeZ: header.decodeZ, + decodeM: header.decodeM) + + case .multiPolygon: + return try decodeMultiPolygon( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder, + sourceProjection: header.sourceProjection, + targetProjection: targetProjection, + decodeZ: header.decodeZ, + decodeM: header.decodeM) + + case .geometryCollection: + return try decodeGeometryCollection( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder, + sourceProjection: header.sourceProjection, + targetProjection: targetProjection) + + case .circularString, .compoundCurve: + let coordinates = try decodeCurveCoordinates( + bytes: bytes, + offset: &offset, + header: header, + targetProjection: targetProjection) + return LineString(coordinates.projected(to: targetProjection)) ?? LineString() + + case .curvePolygon: + let rings = try decodeCurvePolygonRings( + bytes: bytes, + offset: &offset, + header: header, + targetProjection: targetProjection) + return try polygon(from: rings, targetProjection: targetProjection) + + case .multiCurve: + return try decodeMultiCurve( + bytes: bytes, + offset: &offset, + header: header, + targetProjection: targetProjection) + + case .multiSurface: + return try decodeMultiSurface( + bytes: bytes, + offset: &offset, + header: header, + targetProjection: targetProjection) + + case .polyhedralSurface, .tin: + // Surface patches are encoded as Polygons (PolyhedralSurface) or + // Triangles (TIN), which the regular polygon decoder handles. + return try decodeMultiPolygon( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder, + sourceProjection: header.sourceProjection, + targetProjection: targetProjection, + decodeZ: header.decodeZ, + decodeM: header.decodeM) + } + } + + /// Reads a WKB geometry header. + /// + /// Supports both EWKB dimension flags (the high bits) and the ISO + /// SQL/MM dimension offsets used by PostGIS for `TIN`, `PolyhedralSurface` + /// and the curve types (`+1000` for Z, `+2000` for M, `+3000` for ZM). + private static func decodeHeader( + bytes: [UInt8], + offset: inout Int, + sourceProjection: Projection?, + targetProjection: Projection, + ) throws -> WKBHeader { guard let byteOrder = try ByteOrder(rawValue: decodeUInt8(bytes: bytes, offset: &offset, byteOrder: .bigEndian)) else { throw WKBCoderError.dataCorrupted } var typeCodeValue = try decodeUInt32(bytes: bytes, offset: &offset, byteOrder: byteOrder) - var decodeZ = false - var decodeM = false + var decodeZ = typeCodeValue & 0x8000_0000 != 0 + var decodeM = typeCodeValue & 0x4000_0000 != 0 let hasSRID = typeCodeValue & 0x2000_0000 != 0 - if typeCodeValue & 0x8000_0000 != 0 { + typeCodeValue &= 0x0FFF_FFFF + + if typeCodeValue >= 3000 { decodeZ = true + decodeM = true + typeCodeValue -= 3000 } - if typeCodeValue & 0x4000_0000 != 0 { + else if typeCodeValue >= 2000 { decodeM = true + typeCodeValue -= 2000 + } + else if typeCodeValue >= 1000 { + decodeZ = true + typeCodeValue -= 1000 } - typeCodeValue &= 0x0FFF_FFFF guard let typeCode = WKBTypeCode(rawValue: Int(typeCodeValue)) else { throw WKBCoderError.unexpectedType } - let embeddedSRID: Int? - if hasSRID { - embeddedSRID = try Int(decodeUInt32( - bytes: bytes, - offset: &offset, - byteOrder: byteOrder)) - } - else { - embeddedSRID = nil - } + let embeddedSRID: Int? = + if hasSRID { + try Int(decodeUInt32( + bytes: bytes, + offset: &offset, + byteOrder: byteOrder)) + } + else { + nil + } - var sourceProjection = sourceProjection - if sourceProjection == nil, let embeddedSRID { - sourceProjection = Projection(srid: embeddedSRID) + var resolvedSourceProjection = sourceProjection + if resolvedSourceProjection == nil, let embeddedSRID { + resolvedSourceProjection = Projection(srid: embeddedSRID) } - guard let sourceProjection else { throw WKBCoderError.unknownSRID } + guard let resolvedSourceProjection else { throw WKBCoderError.unknownSRID } - if sourceProjection == .noSRID, + if resolvedSourceProjection == .noSRID, targetProjection != .noSRID { throw WKBCoderError.targetProjectionMustBeNoSRID } - switch typeCode { - case .point: - return try decodePoint(bytes: bytes, offset: &offset, byteOrder: byteOrder, sourceProjection: sourceProjection, targetProjection: targetProjection, decodeZ: decodeZ, decodeM: decodeM) - case .multiPoint: - return try decodeMultiPoint(bytes: bytes, offset: &offset, byteOrder: byteOrder, sourceProjection: sourceProjection, targetProjection: targetProjection, decodeZ: decodeZ, decodeM: decodeM) - case .lineString: - return try decodeLineString(bytes: bytes, offset: &offset, byteOrder: byteOrder, sourceProjection: sourceProjection, targetProjection: targetProjection, decodeZ: decodeZ, decodeM: decodeM) - case .multiLineString: - return try decodeMultiLineString(bytes: bytes, offset: &offset, byteOrder: byteOrder, sourceProjection: sourceProjection, targetProjection: targetProjection, decodeZ: decodeZ, decodeM: decodeM) - case .polygon, .triangle: - return try decodePolygon(bytes: bytes, offset: &offset, byteOrder: byteOrder, sourceProjection: sourceProjection, targetProjection: targetProjection, decodeZ: decodeZ, decodeM: decodeM) - case .multiPolygon: - return try decodeMultiPolygon(bytes: bytes, offset: &offset, byteOrder: byteOrder, sourceProjection: sourceProjection, targetProjection: targetProjection, decodeZ: decodeZ, decodeM: decodeM) - case .geometryCollection: - return try decodeGeometryCollection(bytes: bytes, offset: &offset, byteOrder: byteOrder, sourceProjection: sourceProjection, targetProjection: targetProjection) - } - } - - private static func decodeCoordinate( - bytes: [UInt8], - offset: inout Int, - byteOrder: ByteOrder, - sourceProjection: Projection?, - targetProjection: Projection, - decodeZ: Bool, - decodeM: Bool - ) throws -> Coordinate3D { - // Single-coordinate path (Point): project directly. - try decodeRawCoordinate( - bytes: bytes, - offset: &offset, + return WKBHeader( byteOrder: byteOrder, - sourceProjection: sourceProjection, - targetProjection: targetProjection, + typeCode: typeCode, decodeZ: decodeZ, - decodeM: decodeM) - .projected(to: targetProjection) + decodeM: decodeM, + sourceProjection: resolvedSourceProjection) } /// Decodes a coordinate in the source projection, without projecting it: @@ -604,9 +729,59 @@ extension WKBCoder { sourceProjection: Projection?, targetProjection: Projection, decodeZ: Bool, - decodeM: Bool - ) throws -> Point { - try Point(decodeCoordinate(bytes: bytes, offset: &offset, byteOrder: byteOrder, sourceProjection: sourceProjection, targetProjection: targetProjection, decodeZ: decodeZ, decodeM: decodeM)) + decodeM: Bool, + ) throws -> GeoJsonGeometry { + guard let coordinate = try decodeRawPointCoordinate( + bytes: bytes, + offset: &offset, + byteOrder: byteOrder, + sourceProjection: sourceProjection, + decodeZ: decodeZ, + decodeM: decodeM) + else { + // `POINT EMPTY` is encoded with NaN coordinates. The GeoJSON model + // has no empty Point, so use the empty point geometry instead. + return MultiPoint() + } + + return Point(coordinate.projected(to: targetProjection)) + } + + /// Reads a Point coordinate, returning `nil` for an empty Point. + /// + /// All coordinate components are consumed even when the point is empty so + /// that the offset stays correct. + private static func decodeRawPointCoordinate( + bytes: [UInt8], + offset: inout Int, + byteOrder: ByteOrder, + sourceProjection: Projection?, + decodeZ: Bool, + decodeM: Bool, + ) throws -> Coordinate3D? { + guard let sourceProjection else { throw WKBCoderError.unknownSRID } + + let x = try decodeDouble(bytes: bytes, offset: &offset, byteOrder: byteOrder) + let y = try decodeDouble(bytes: bytes, offset: &offset, byteOrder: byteOrder) + + var z: Double? + var m: Double? + if decodeZ { + z = try decodeDouble(bytes: bytes, offset: &offset, byteOrder: byteOrder) + if z?.isFinite == false { + z = nil + } + } + if decodeM { + m = try decodeDouble(bytes: bytes, offset: &offset, byteOrder: byteOrder) + if m?.isFinite == false { + m = nil + } + } + + guard x.isFinite, y.isFinite else { return nil } + + return Coordinate3D(x: x, y: y, z: z, m: m, projection: sourceProjection) } private static func decodeMultiPoint( @@ -754,6 +929,247 @@ extension WKBCoder { return GeometryCollection(geometries) } + // MARK: - Curves and surfaces + + /// Decodes a LineString, CircularString or CompoundCurve into a linear + /// coordinate list in the source projection. + private static func decodeCurveCoordinates( + bytes: [UInt8], + offset: inout Int, + header: WKBHeader, + targetProjection: Projection, + ) throws -> [Coordinate3D] { + switch header.typeCode { + case .lineString: + return try decodeRawCoordinateList( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder, + header: header) + + case .circularString: + let coordinates = try decodeRawCoordinateList( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder, + header: header) + return CurveLinearization.circularString(coordinates) + + case .compoundCurve: + let count = try decodeUInt32( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder) + + var coordinates: [Coordinate3D] = [] + try count.times { + let partHeader = try decodeHeader( + bytes: bytes, + offset: &offset, + sourceProjection: header.sourceProjection, + targetProjection: targetProjection) + let part = try decodeCurveCoordinates( + bytes: bytes, + offset: &offset, + header: partHeader, + targetProjection: targetProjection) + + if coordinates.isEmpty { + coordinates = part + } + else { + // Consecutive curve segments share their first/last point. + coordinates.append(contentsOf: part.dropFirst()) + } + } + + return coordinates + + default: + throw WKBCoderError.invalidGeometry + } + } + + /// Decodes the rings of a CurvePolygon into linear coordinate lists in the + /// source projection. + private static func decodeCurvePolygonRings( + bytes: [UInt8], + offset: inout Int, + header: WKBHeader, + targetProjection: Projection, + ) throws -> [[Coordinate3D]] { + let count = try decodeUInt32( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder) + + var rings: [[Coordinate3D]] = [] + try count.times { + let ringHeader = try decodeHeader( + bytes: bytes, + offset: &offset, + sourceProjection: header.sourceProjection, + targetProjection: targetProjection) + try rings.append( + decodeCurveCoordinates( + bytes: bytes, + offset: &offset, + header: ringHeader, + targetProjection: targetProjection)) + } + + return rings + } + + /// Decodes a MultiCurve into a MultiLineString. + private static func decodeMultiCurve( + bytes: [UInt8], + offset: inout Int, + header: WKBHeader, + targetProjection: Projection, + ) throws -> MultiLineString { + let count = try decodeUInt32( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder) + + var lineStrings: [LineString] = [] + try count.times { + let curveHeader = try decodeHeader( + bytes: bytes, + offset: &offset, + sourceProjection: header.sourceProjection, + targetProjection: targetProjection) + let coordinates = try decodeCurveCoordinates( + bytes: bytes, + offset: &offset, + header: curveHeader, + targetProjection: targetProjection) + .projected(to: targetProjection) + + lineStrings.append(LineString(coordinates) ?? LineString()) + } + + return MultiLineString(lineStrings) ?? MultiLineString() + } + + /// Decodes a MultiSurface into a MultiPolygon. + private static func decodeMultiSurface( + bytes: [UInt8], + offset: inout Int, + header: WKBHeader, + targetProjection: Projection, + ) throws -> MultiPolygon { + let count = try decodeUInt32( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder) + + var polygons: [Polygon] = [] + try count.times { + let surfaceHeader = try decodeHeader( + bytes: bytes, + offset: &offset, + sourceProjection: header.sourceProjection, + targetProjection: targetProjection) + + let rings: [[Coordinate3D]] + switch surfaceHeader.typeCode { + case .polygon: + rings = try decodeRawPolygonRings( + bytes: bytes, + offset: &offset, + header: surfaceHeader) + + case .curvePolygon: + rings = try decodeCurvePolygonRings( + bytes: bytes, + offset: &offset, + header: surfaceHeader, + targetProjection: targetProjection) + + default: + throw WKBCoderError.invalidGeometry + } + + try polygons.append( + polygon(from: rings, targetProjection: targetProjection)) + } + + return MultiPolygon(polygons) ?? MultiPolygon() + } + + /// Reads a raw coordinate list in the source projection. + private static func decodeRawCoordinateList( + bytes: [UInt8], + offset: inout Int, + byteOrder: ByteOrder, + header: WKBHeader, + ) throws -> [Coordinate3D] { + let count = try decodeUInt32( + bytes: bytes, + offset: &offset, + byteOrder: byteOrder) + + var coordinates: [Coordinate3D] = [] + try count.times { + try coordinates.append( + decodeRawCoordinate( + bytes: bytes, + offset: &offset, + byteOrder: byteOrder, + sourceProjection: header.sourceProjection, + targetProjection: header.sourceProjection, + decodeZ: header.decodeZ, + decodeM: header.decodeM)) + } + + return coordinates + } + + /// Reads the raw rings of a Polygon in the source projection. + private static func decodeRawPolygonRings( + bytes: [UInt8], + offset: inout Int, + header: WKBHeader, + ) throws -> [[Coordinate3D]] { + let count = try decodeUInt32( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder) + + var rings: [[Coordinate3D]] = [] + try count.times { + try rings.append( + decodeRawCoordinateList( + bytes: bytes, + offset: &offset, + byteOrder: header.byteOrder, + header: header)) + } + + return rings + } + + /// Projects raw rings and builds a Polygon. + private static func polygon( + from rings: [[Coordinate3D]], + targetProjection: Projection, + ) throws -> Polygon { + guard rings.isNotEmpty else { return Polygon() } + + var result: [Ring] = [] + for coordinates in rings { + guard let ring = Ring(coordinates.projected(to: targetProjection)) else { + throw WKBCoderError.invalidGeometry + } + + result.append(ring) + } + + return Polygon(result) ?? Polygon() + } + // MARK: - private static func decodeUInt8( diff --git a/Sources/GISTools/GeoJson/WKTCoder.swift b/Sources/GISTools/GeoJson/WKTCoder.swift index 38fe8737..25db2a1c 100644 --- a/Sources/GISTools/GeoJson/WKTCoder.swift +++ b/Sources/GISTools/GeoJson/WKTCoder.swift @@ -331,6 +331,13 @@ public enum WKTCoder { case multiPolygon = "multipolygon" case geometryCollection = "geometrycollection" case triangle + case circularString = "circularstring" + case compoundCurve = "compoundcurve" + case curvePolygon = "curvepolygon" + case multiCurve = "multicurve" + case multiSurface = "multisurface" + case polyhedralSurface = "polyhedralsurface" + case tin } @@ -435,11 +442,34 @@ extension WKTCoder { ) throws -> GeoJsonGeometry { var decodeZ = false var decodeM = false + var isEmpty = false - guard let type = scanType(scanner: scanner, decodeZ: &decodeZ, decodeM: &decodeM) else { + guard let type = scanType( + scanner: scanner, + decodeZ: &decodeZ, + decodeM: &decodeM, + isEmpty: &isEmpty) + else { throw WKTCoderError.dataCorrupted } + if isEmpty { + switch type { + case .multiPoint, .point: + return MultiPoint() + case .circularString, .compoundCurve, .linearRing, .lineString: + return LineString() + case .curvePolygon, .polygon, .triangle: + return Polygon() + case .multiCurve, .multiLineString: + return MultiLineString() + case .multiPolygon, .multiSurface, .polyhedralSurface, .tin: + return MultiPolygon() + case .geometryCollection: + return GeometryCollection([]) + } + } + switch type { case .point: guard let coordinates = try scanCoordinates( @@ -550,6 +580,54 @@ extension WKTCoder { return multiPolygon + case .circularString: + let coordinates = try scanCircularStringRaw( + scanner: scanner, + sourceProjection: sourceProjection, + decodeZ: decodeZ, + decodeM: decodeM) + return LineString(coordinates.projected(to: targetProjection)) ?? LineString() + + case .compoundCurve: + let coordinates = try scanCompoundCurveRaw( + scanner: scanner, + sourceProjection: sourceProjection, + decodeZ: decodeZ, + decodeM: decodeM) + return LineString(coordinates.projected(to: targetProjection)) ?? LineString() + + case .curvePolygon: + return try scanCurvePolygon( + scanner: scanner, + sourceProjection: sourceProjection, + targetProjection: targetProjection, + decodeZ: decodeZ, + decodeM: decodeM) + + case .multiCurve: + return try scanMultiCurve( + scanner: scanner, + sourceProjection: sourceProjection, + targetProjection: targetProjection, + decodeZ: decodeZ, + decodeM: decodeM) + + case .multiSurface: + return try scanMultiSurface( + scanner: scanner, + sourceProjection: sourceProjection, + targetProjection: targetProjection, + decodeZ: decodeZ, + decodeM: decodeM) + + case .polyhedralSurface, .tin: + return try scanPolygonSurface( + scanner: scanner, + sourceProjection: sourceProjection, + targetProjection: targetProjection, + decodeZ: decodeZ, + decodeM: decodeM) + case .geometryCollection: var geometries: [GeoJsonGeometry] = [] @@ -594,12 +672,29 @@ extension WKTCoder { decodeZ: Bool, decodeM: Bool ) throws -> Polygon { - var rings: [Ring] = [] - guard scanner.scanString("(") != nil else { throw WKTCoderError.dataCorrupted } + return try decodePolygonBody( + scanner: scanner, + sourceProjection: sourceProjection, + targetProjection: targetProjection, + decodeZ: decodeZ, + decodeM: decodeM) + } + + /// Scans the rings of a polygon after its opening parenthesis has been + /// consumed. + private static func decodePolygonBody( + scanner: Scanner, + sourceProjection: Projection, + targetProjection: Projection, + decodeZ: Bool, + decodeM: Bool, + ) throws -> Polygon { + var rings: [Ring] = [] + while scanner.scanString(")") == nil { guard let coordinates = try scanCoordinates( scanner: scanner, @@ -644,13 +739,20 @@ extension WKTCoder { private static func scanType( scanner: Scanner, decodeZ: inout Bool, - decodeM: inout Bool + decodeM: inout Bool, + isEmpty: inout Bool, ) -> WKTTypeCode? { let boundarySet = CharacterSet(charactersIn: "(") guard let rawType = scanner.scanUpToCharacters(from: boundarySet) else { return nil } var rawTypeLowercased = rawType.lowercased().trimmed() + if rawTypeLowercased.hasSuffix("empty") { + isEmpty = true + rawTypeLowercased.removeLast("empty".count) + rawTypeLowercased = rawTypeLowercased.trimmed() + } + if rawTypeLowercased.hasSuffix("m") { decodeM = true rawTypeLowercased.removeLast() @@ -672,16 +774,31 @@ extension WKTCoder { sourceProjection: Projection, targetProjection: Projection, decodeZ: Bool, - decodeM: Bool + decodeM: Bool, + ) throws -> [Coordinate3D]? { + guard let raw = try scanRawCoordinates( + scanner: scanner, + sourceProjection: sourceProjection, + decodeZ: decodeZ, + decodeM: decodeM) + else { return nil } + + return raw.projected(to: targetProjection).nilIfEmpty + } + + private static func scanRawCoordinates( + scanner: Scanner, + sourceProjection: Projection, + decodeZ: Bool, + decodeM: Bool, ) throws -> [Coordinate3D]? { guard scanner.scanString("(") != nil else { throw WKTCoderError.dataCorrupted } - return try scanCoordinateSequence( + return try scanRawCoordinateSequence( scanner: scanner, sourceProjection: sourceProjection, - targetProjection: targetProjection, decodeZ: decodeZ, decodeM: decodeM) } @@ -691,7 +808,23 @@ extension WKTCoder { sourceProjection: Projection, targetProjection: Projection, decodeZ: Bool, - decodeM: Bool + decodeM: Bool, + ) throws -> [Coordinate3D]? { + guard let raw = try scanRawCoordinateSequence( + scanner: scanner, + sourceProjection: sourceProjection, + decodeZ: decodeZ, + decodeM: decodeM) + else { return nil } + + return raw.projected(to: targetProjection).nilIfEmpty + } + + private static func scanRawCoordinateSequence( + scanner: Scanner, + sourceProjection: Projection, + decodeZ: Bool, + decodeM: Bool, ) throws -> [Coordinate3D]? { var coordinates: [Coordinate3D] = [] var closed = false @@ -754,7 +887,272 @@ extension WKTCoder { throw WKTCoderError.dataCorrupted } - return coordinates.projected(to: targetProjection).nilIfEmpty + return coordinates.nilIfEmpty + } + + // MARK: - Curves and surfaces + + private static func scanCircularStringRaw( + scanner: Scanner, + sourceProjection: Projection, + decodeZ: Bool, + decodeM: Bool, + ) throws -> [Coordinate3D] { + guard let coordinates = try scanRawCoordinates( + scanner: scanner, + sourceProjection: sourceProjection, + decodeZ: decodeZ, + decodeM: decodeM) + else { return [] } + + return CurveLinearization.circularString(coordinates) + } + + private static func scanCompoundCurveRaw( + scanner: Scanner, + sourceProjection: Projection, + decodeZ: Bool, + decodeM: Bool, + ) throws -> [Coordinate3D] { + guard scanner.scanString("(") != nil else { + throw WKTCoderError.dataCorrupted + } + + var coordinates: [Coordinate3D] = [] + + while scanner.scanString(")") == nil { + let part = try scanCurveSegmentRaw( + scanner: scanner, + sourceProjection: sourceProjection, + decodeZ: decodeZ, + decodeM: decodeM) + + if coordinates.isEmpty { + coordinates = part + } + else { + // Consecutive curve segments share their first/last point. + coordinates.append(contentsOf: part.dropFirst()) + } + + _ = scanner.scanString(",") + } + + return coordinates + } + + private static func scanCurveSegmentRaw( + scanner: Scanner, + sourceProjection: Projection, + decodeZ: Bool, + decodeM: Bool, + ) throws -> [Coordinate3D] { + if scanner.scanString("(") != nil { + return try scanRawCoordinateSequence( + scanner: scanner, + sourceProjection: sourceProjection, + decodeZ: decodeZ, + decodeM: decodeM) ?? [] + } + + var segmentZ = false + var segmentM = false + var segmentEmpty = false + + guard let type = scanType( + scanner: scanner, + decodeZ: &segmentZ, + decodeM: &segmentM, + isEmpty: &segmentEmpty) + else { + throw WKTCoderError.dataCorrupted + } + + if segmentEmpty { + return [] + } + + let z = decodeZ || segmentZ + let m = decodeM || segmentM + + switch type { + case .lineString: + return try scanRawCoordinates( + scanner: scanner, + sourceProjection: sourceProjection, + decodeZ: z, + decodeM: m) ?? [] + + case .circularString: + return try scanCircularStringRaw( + scanner: scanner, + sourceProjection: sourceProjection, + decodeZ: z, + decodeM: m) + + case .compoundCurve: + return try scanCompoundCurveRaw( + scanner: scanner, + sourceProjection: sourceProjection, + decodeZ: z, + decodeM: m) + + default: + throw WKTCoderError.invalidGeometry + } + } + + private static func scanCurvePolygon( + scanner: Scanner, + sourceProjection: Projection, + targetProjection: Projection, + decodeZ: Bool, + decodeM: Bool, + ) throws -> Polygon { + guard scanner.scanString("(") != nil else { + throw WKTCoderError.dataCorrupted + } + + var rings: [Ring] = [] + + while scanner.scanString(")") == nil { + let coordinates = try scanCurveSegmentRaw( + scanner: scanner, + sourceProjection: sourceProjection, + decodeZ: decodeZ, + decodeM: decodeM) + + guard let ring = Ring(coordinates.projected(to: targetProjection)) else { + throw WKTCoderError.invalidGeometry + } + + rings.append(ring) + _ = scanner.scanString(",") + } + + return Polygon(rings) ?? Polygon() + } + + private static func scanMultiCurve( + scanner: Scanner, + sourceProjection: Projection, + targetProjection: Projection, + decodeZ: Bool, + decodeM: Bool, + ) throws -> MultiLineString { + guard scanner.scanString("(") != nil else { + throw WKTCoderError.dataCorrupted + } + + var lineStrings: [LineString] = [] + + while scanner.scanString(")") == nil { + let coordinates = try scanCurveSegmentRaw( + scanner: scanner, + sourceProjection: sourceProjection, + decodeZ: decodeZ, + decodeM: decodeM) + + lineStrings.append( + LineString(coordinates.projected(to: targetProjection)) ?? LineString()) + _ = scanner.scanString(",") + } + + return MultiLineString(lineStrings) ?? MultiLineString() + } + + private static func scanMultiSurface( + scanner: Scanner, + sourceProjection: Projection, + targetProjection: Projection, + decodeZ: Bool, + decodeM: Bool, + ) throws -> MultiPolygon { + guard scanner.scanString("(") != nil else { + throw WKTCoderError.dataCorrupted + } + + var polygons: [Polygon] = [] + + while scanner.scanString(")") == nil { + if scanner.scanString("(") != nil { + try polygons.append( + decodePolygonBody( + scanner: scanner, + sourceProjection: sourceProjection, + targetProjection: targetProjection, + decodeZ: decodeZ, + decodeM: decodeM)) + } + else { + var itemZ = false + var itemM = false + var itemEmpty = false + + guard let itemType = scanType( + scanner: scanner, + decodeZ: &itemZ, + decodeM: &itemM, + isEmpty: &itemEmpty) + else { + throw WKTCoderError.dataCorrupted + } + + switch itemType { + case .curvePolygon: + try polygons.append( + scanCurvePolygon( + scanner: scanner, + sourceProjection: sourceProjection, + targetProjection: targetProjection, + decodeZ: decodeZ || itemZ, + decodeM: decodeM || itemM)) + + case .polygon: + try polygons.append( + decodePolygon( + scanner: scanner, + sourceProjection: sourceProjection, + targetProjection: targetProjection, + decodeZ: decodeZ || itemZ, + decodeM: decodeM || itemM)) + + default: + throw WKTCoderError.invalidGeometry + } + } + + _ = scanner.scanString(",") + } + + return MultiPolygon(polygons) ?? MultiPolygon() + } + + private static func scanPolygonSurface( + scanner: Scanner, + sourceProjection: Projection, + targetProjection: Projection, + decodeZ: Bool, + decodeM: Bool, + ) throws -> MultiPolygon { + guard scanner.scanString("(") != nil else { + throw WKTCoderError.dataCorrupted + } + + var polygons: [Polygon] = [] + + while scanner.scanString(")") == nil { + try polygons.append( + decodePolygon( + scanner: scanner, + sourceProjection: sourceProjection, + targetProjection: targetProjection, + decodeZ: decodeZ, + decodeM: decodeM)) + _ = scanner.scanString(",") + } + + return MultiPolygon(polygons) ?? MultiPolygon() } } @@ -768,7 +1166,7 @@ extension WKTCoder { /// - Parameters: /// - geometry: The GeoJSON geometry to encode. /// - targetProjection: The projection to encode into. If `nil`, the geometry's native projection is used. Defaults to `.epsg4326`. - /// - Returns: A WKT string, or `nil` if the geometry is empty. + /// - Returns: A WKT string, or `nil` if the geometry cannot be encoded. public static func encode( geometry: GeoJsonGeometry, targetProjection: Projection? = .epsg4326 @@ -830,7 +1228,12 @@ extension WKTCoder { to result: inout String ) { appendTypeCode(WKTTypeCode.multiPoint.rawValue, for: value.points.first?.coordinate, targetProjection: targetProjection, includeSRID: includeSRID, to: &result) - appendString(string(for: value.coordinates, targetProjection: targetProjection), to: &result) + if value.points.isEmpty { + appendString(" EMPTY", to: &result) + } + else { + appendString(string(for: value.coordinates, targetProjection: targetProjection), to: &result) + } } private static func encode( @@ -840,7 +1243,12 @@ extension WKTCoder { to result: inout String ) { appendTypeCode(WKTTypeCode.lineString.rawValue, for: value.coordinates.first, targetProjection: targetProjection, includeSRID: includeSRID, to: &result) - appendString(string(for: value.coordinates, targetProjection: targetProjection), to: &result) + if value.coordinates.isEmpty { + appendString(" EMPTY", to: &result) + } + else { + appendString(string(for: value.coordinates, targetProjection: targetProjection), to: &result) + } } private static func encode( @@ -850,9 +1258,14 @@ extension WKTCoder { to result: inout String ) { appendTypeCode(WKTTypeCode.multiLineString.rawValue, for: value.lineStrings.first?.coordinates.first, targetProjection: targetProjection, includeSRID: includeSRID, to: &result) - appendString("(", to: &result) - appendString(value.lineStrings.map({ string(for: $0.coordinates, targetProjection: targetProjection) }).joined(separator: ","), to: &result) - appendString(")", to: &result) + if value.lineStrings.isEmpty { + appendString(" EMPTY", to: &result) + } + else { + appendString("(", to: &result) + appendString(value.lineStrings.map({ string(for: $0.coordinates, targetProjection: targetProjection) }).joined(separator: ","), to: &result) + appendString(")", to: &result) + } } private static func encode( @@ -862,7 +1275,12 @@ extension WKTCoder { to result: inout String ) { appendTypeCode(WKTTypeCode.polygon.rawValue, for: value.rings.first?.coordinates.first, targetProjection: targetProjection, includeSRID: includeSRID, to: &result) - appendString(string(for: value, targetProjection: targetProjection), to: &result) + if value.rings.isEmpty { + appendString(" EMPTY", to: &result) + } + else { + appendString(string(for: value, targetProjection: targetProjection), to: &result) + } } private static func encode( @@ -872,9 +1290,14 @@ extension WKTCoder { to result: inout String ) { appendTypeCode(WKTTypeCode.multiPolygon.rawValue, for: value.polygons.first?.rings.first?.coordinates.first, targetProjection: targetProjection, includeSRID: includeSRID, to: &result) - appendString("(", to: &result) - appendString(value.polygons.map({ string(for: $0, targetProjection: targetProjection) }).joined(separator: ","), to: &result) - appendString(")", to: &result) + if value.polygons.isEmpty { + appendString(" EMPTY", to: &result) + } + else { + appendString("(", to: &result) + appendString(value.polygons.map({ string(for: $0, targetProjection: targetProjection) }).joined(separator: ","), to: &result) + appendString(")", to: &result) + } } private static func encode( @@ -884,18 +1307,23 @@ extension WKTCoder { to result: inout String ) { appendTypeCode(WKTTypeCode.geometryCollection.rawValue, for: nil, targetProjection: targetProjection, includeSRID: includeSRID, to: &result) - appendString("(", to: &result) - for (i, geometry) in value.geometries.enumerated() { - encode( - geometry: geometry, - targetProjection: targetProjection, - includeSRID: false, - to: &result) - if i < (value.geometries.count - 1) { - appendString(",", to: &result) + if value.geometries.isEmpty { + appendString(" EMPTY", to: &result) + } + else { + appendString("(", to: &result) + for (i, geometry) in value.geometries.enumerated() { + encode( + geometry: geometry, + targetProjection: targetProjection, + includeSRID: false, + to: &result) + if i < (value.geometries.count - 1) { + appendString(",", to: &result) + } } + appendString(")", to: &result) } - appendString(")", to: &result) } // MARK: - diff --git a/Tests/GISToolsTests/GeoJson/TWKBTests.swift b/Tests/GISToolsTests/GeoJson/TWKBTests.swift index 6b76252e..c2b94c78 100644 --- a/Tests/GISToolsTests/GeoJson/TWKBTests.swift +++ b/Tests/GISToolsTests/GeoJson/TWKBTests.swift @@ -441,14 +441,18 @@ extension TWKBTests { ]) } - /// Empty geometry metadata is reported as an error. + /// Empty geometry metadata decodes as an empty geometry. @Test - func twkbEmptyGeometryFails() { + func twkbEmptyMetadataDecoding() throws { let data = Data([0x02, 0x10]) - #expect(throws: TWKBCoder.TWKBError.self) { - try TWKBCoder.decode(twkb: data, sourceProjection: .epsg4326) - } + let lineString = try #require( + try TWKBCoder.decode( + twkb: data, + sourceProjection: .epsg4326) as? LineString, + ) + + #expect(lineString.coordinates.isEmpty) } /// Negative precision is stored with zigzag encoding in the type byte. @@ -482,4 +486,63 @@ extension TWKBTests { } } + // MARK: - Empty geometries and surfaces + + /// PostGIS: ST_AsTWKB('POINT EMPTY'::geometry) + @Test + func twkbEmptyPointDecoding() throws { + let multiPoint = try #require(try TWKBCoder.decode( + twkb: Data([0xA1, 0x10]), + sourceProjection: .epsg4326) as? MultiPoint) + + #expect(multiPoint.points.isEmpty) + } + + /// PostGIS emits a metadata-only TWKB for empty geometries. + @Test + func twkbEmptyGeometryDecoding() throws { + let cases: [(Data, GeoJsonType)] = [ + (Data([0xA2, 0x10]), .lineString), + (Data([0xA3, 0x10]), .polygon), + (Data([0xA4, 0x10]), .multiPoint), + (Data([0xA5, 0x10]), .multiLineString), + (Data([0xA6, 0x10]), .multiPolygon), + (Data([0xA7, 0x10]), .geometryCollection), + ] + + for (data, expectedType) in cases { + let geometry = try TWKBCoder.decode( + twkb: data, + sourceProjection: .epsg4326) + #expect(geometry.type == expectedType) + #expect(geometry.allCoordinates.isEmpty) + } + } + + /// PostGIS encodes TIN as a TWKB GeometryCollection of Polygons. + @Test + func twkbTinDecoding() throws { + // PostGIS: ST_AsTWKB('TIN(((0 0 0, 1 0 0, 0 1 0, 0 0 0)))'::geometry) + let data = try #require(Data(hex: "A7080101A308010104000000C09A0C0000BF9A0CC09A0C0000BF9A0C00")) + + let collection = try #require(try TWKBCoder.decode( + twkb: data, + sourceProjection: .epsg4326) as? GeometryCollection) + + #expect(collection.geometries.count == 1) + #expect(collection.geometries[0] is Polygon) + } + + /// TWKB has no curve or PolyhedralSurface type codes. + @Test + func twkbUnsupportedTypeFails() { + for typeCode: UInt8 in [0x08, 0x0F, 0x10] { + let data = Data([typeCode, 0x00]) + + #expect(throws: TWKBCoder.TWKBError.self) { + try TWKBCoder.decode(twkb: data, sourceProjection: .epsg4326) + } + } + } + } diff --git a/Tests/GISToolsTests/GeoJson/WKBTests.swift b/Tests/GISToolsTests/GeoJson/WKBTests.swift index 0b841232..a2651eec 100644 --- a/Tests/GISToolsTests/GeoJson/WKBTests.swift +++ b/Tests/GISToolsTests/GeoJson/WKBTests.swift @@ -178,12 +178,17 @@ struct WKBTests { /// SELECT ST_ClipByBox2D(ToPoint('POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))'::geometry), ST_MakeEnvelope(0,0,0.2,0.2)); private let invalidPointData = Data(hex: "0101000000000000000000F87F000000000000F87F")! - /// Validates that decoding an invalid WKB Point (NaN coordinates) throws an error. + /// Validates that a WKB Point with NaN coordinates decodes as an empty + /// MultiPoint, matching `POINT EMPTY`. @Test func invalidPointDecoding() throws { - #expect(throws: WKBCoder.WKBCoderError.self) { - try WKBCoder.decode(wkb: invalidPointData, sourceProjection: .epsg4326) as? Point - } + let multiPoint = try #require( + try WKBCoder.decode( + wkb: invalidPointData, + sourceProjection: .epsg4326) as? MultiPoint, + ) + + #expect(multiPoint.points.isEmpty) } // MARK: - MultiPoint @@ -734,4 +739,135 @@ extension WKBTests { #expect(decoded.coordinates == coordinates) } + // MARK: - Curves and surfaces + + /// PostGIS: ST_AsBinary('CIRCULARSTRING(0 0, 1 1, 2 0)'::geometry) + private static let circularStringData = Data(hex: "01080000000300000000000000000000000000000000000000000000000000F03F000000000000F03F00000000000000400000000000000000")! + + /// PostGIS: ST_AsBinary('COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 2 0), (2 0, 3 1))'::geometry) + private static let compoundCurveData = Data(hex: "01090000000200000001080000000300000000000000000000000000000000000000000000000000F03F000000000000F03F00000000000000400000000000000000010200000002000000000000000000004000000000000000000000000000000840000000000000F03F")! + + /// PostGIS: ST_AsBinary('CURVEPOLYGON(CIRCULARSTRING(0 0, 1 1, 2 0, 1 -1, 0 0))'::geometry) + private static let curvePolygonData = Data(hex: "010A0000000100000001080000000500000000000000000000000000000000000000000000000000F03F000000000000F03F00000000000000400000000000000000000000000000F03F000000000000F0BF00000000000000000000000000000000")! + + /// PostGIS: ST_AsBinary('MULTICURVE(CIRCULARSTRING(0 0, 1 1, 2 0), (2 0, 3 1))'::geometry) + private static let multiCurveData = Data(hex: "010B0000000200000001080000000300000000000000000000000000000000000000000000000000F03F000000000000F03F00000000000000400000000000000000010200000002000000000000000000004000000000000000000000000000000840000000000000F03F")! + + /// PostGIS: ST_AsBinary('MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(0 0, 1 1, 2 0, 1 -1, 0 0)))'::geometry) + private static let multiSurfaceData = Data(hex: "010C00000001000000010A0000000100000001080000000500000000000000000000000000000000000000000000000000F03F000000000000F03F00000000000000400000000000000000000000000000F03F000000000000F0BF00000000000000000000000000000000")! + + /// PostGIS: ST_AsBinary('TIN(((0 0, 1 0, 0 1, 0 0)))'::geometry) + private static let tinData = Data(hex: "0110000000010000000111000000010000000400000000000000000000000000000000000000000000000000F03F00000000000000000000000000000000000000000000F03F00000000000000000000000000000000")! + + /// PostGIS: ST_AsBinary('POLYHEDRALSURFACE(((0 0, 1 0, 0 1, 0 0)))'::geometry) + private static let polyhedralSurfaceData = Data(hex: "010F000000010000000103000000010000000400000000000000000000000000000000000000000000000000F03F00000000000000000000000000000000000000000000F03F00000000000000000000000000000000")! + + /// PostGIS: ST_AsBinary('TIN(((0 0 0, 1 0 0, 0 1 0, 0 0 0)))'::geometry) + private static let tinZData = Data(hex: "01F80300000100000001F90300000100000004000000000000000000000000000000000000000000000000000000000000000000F03F000000000000000000000000000000000000000000000000000000000000F03F0000000000000000000000000000000000000000000000000000000000000000")! + + /// PostGIS: ST_AsBinary('POINT EMPTY'::geometry) + private static let emptyPointData = Data(hex: "0101000000000000000000F87F000000000000F87F")! + + /// PostGIS: ST_AsBinary('POINT Z (1 2 3)'::geometry), ISO type code 1001. + private static let isoPointZData = Data(hex: "01E9030000000000000000F03F00000000000000400000000000000840")! + + /// Validates that a CircularString is linearized into a LineString. + @Test + func circularStringDecoding() throws { + let lineString = try #require(try WKBCoder.decode(wkb: Self.circularStringData, sourceProjection: .epsg4326) as? LineString) + + #expect(lineString.coordinates.count > 3) + #expect(abs(lineString.coordinates[0].longitude - 0.0) < 1e-9) + #expect(abs(lineString.coordinates[0].latitude - 0.0) < 1e-9) + #expect(try abs(#require(lineString.coordinates.last?.longitude) - 2.0) < 1e-9) + #expect(try abs(#require(lineString.coordinates.last?.latitude) - 0.0) < 1e-9) + #expect(lineString.coordinates.contains { coordinate in + abs(coordinate.longitude - 1.0) < 1e-6 && abs(coordinate.latitude - 1.0) < 1e-6 + }) + } + + /// Validates that a CompoundCurve is linearized into a LineString. + @Test + func compoundCurveDecoding() throws { + let lineString = try #require(try WKBCoder.decode(wkb: Self.compoundCurveData, sourceProjection: .epsg4326) as? LineString) + + #expect(try abs(#require(lineString.coordinates.first?.longitude) - 0.0) < 1e-9) + #expect(try abs(#require(lineString.coordinates.last?.longitude) - 3.0) < 1e-9) + #expect(try abs(#require(lineString.coordinates.last?.latitude) - 1.0) < 1e-9) + #expect(lineString.coordinates.contains { coordinate in + abs(coordinate.longitude - 2.0) < 1e-9 && abs(coordinate.latitude - 0.0) < 1e-9 + }) + } + + /// Validates that a CurvePolygon is linearized into a Polygon. + @Test + func curvePolygonDecoding() throws { + let polygon = try #require(try WKBCoder.decode(wkb: Self.curvePolygonData, sourceProjection: .epsg4326) as? Polygon) + + #expect(polygon.coordinates.count == 1) + #expect(polygon.coordinates[0].count > 4) + #expect(polygon.coordinates[0].first == polygon.coordinates[0].last) + } + + /// Validates that a MultiCurve is linearized into a MultiLineString. + @Test + func multiCurveDecoding() throws { + let multiLineString = try #require(try WKBCoder.decode(wkb: Self.multiCurveData, sourceProjection: .epsg4326) as? MultiLineString) + + #expect(multiLineString.coordinates.count == 2) + #expect(multiLineString.coordinates[0].count > 3) + #expect(try abs(#require(multiLineString.coordinates[1].last?.longitude) - 3.0) < 1e-9) + } + + /// Validates that a MultiSurface is linearized into a MultiPolygon. + @Test + func multiSurfaceDecoding() throws { + let multiPolygon = try #require(try WKBCoder.decode(wkb: Self.multiSurfaceData, sourceProjection: .epsg4326) as? MultiPolygon) + + #expect(multiPolygon.polygons.count == 1) + #expect(multiPolygon.polygons[0].coordinates[0].count > 4) + } + + /// Validates that TIN and PolyhedralSurface decode to a MultiPolygon. + @Test + func tinAndPolyhedralSurfaceDecoding() throws { + let tin = try #require(try WKBCoder.decode(wkb: Self.tinData, sourceProjection: .epsg4326) as? MultiPolygon) + #expect(tin.polygons.count == 1) + #expect(tin.polygons[0].coordinates[0].count == 4) + + let polyhedralSurface = try #require(try WKBCoder.decode(wkb: Self.polyhedralSurfaceData, sourceProjection: .epsg4326) as? MultiPolygon) + #expect(polyhedralSurface.polygons.count == 1) + #expect(polyhedralSurface.polygons[0].coordinates[0].count == 4) + } + + /// Validates ISO SQL/MM dimension codes as used by PostGIS for TIN. + @Test + func tinZDecoding() throws { + let tin = try #require(try WKBCoder.decode(wkb: Self.tinZData, sourceProjection: .epsg4326) as? MultiPolygon) + + #expect(tin.polygons.count == 1) + #expect(tin.polygons[0].coordinates[0][0].altitude == 0) + #expect(tin.polygons[0].coordinates[0][1].altitude == 0) + #expect(tin.polygons[0].coordinates[0][2].altitude == 0) + } + + /// Validates ISO SQL/MM dimension codes for a Point. + @Test + func isoPointZDecoding() throws { + let point = try #require(try WKBCoder.decode(wkb: Self.isoPointZData, sourceProjection: .epsg4326) as? Point) + + #expect(point.coordinate.longitude == 1) + #expect(point.coordinate.latitude == 2) + #expect(point.coordinate.altitude == 3) + } + + /// Validates that POINT EMPTY becomes an empty MultiPoint. + @Test + func emptyPointDecoding() throws { + let multiPoint = try #require(try WKBCoder.decode(wkb: Self.emptyPointData, sourceProjection: .epsg4326) as? MultiPoint) + + #expect(multiPoint.points.isEmpty) + #expect(multiPoint.allCoordinates.isEmpty) + } + } diff --git a/Tests/GISToolsTests/GeoJson/WKTTests.swift b/Tests/GISToolsTests/GeoJson/WKTTests.swift index be83c4e5..a74eb6f5 100644 --- a/Tests/GISToolsTests/GeoJson/WKTTests.swift +++ b/Tests/GISToolsTests/GeoJson/WKTTests.swift @@ -681,4 +681,136 @@ extension WKTTests { #expect(wkt == "POINT(1000000.0 2000000.0)") } + // MARK: - Curves and surfaces + + /// Validates that CIRCULARSTRING is linearized into a LineString. + @Test + func wktCircularStringDecoding() throws { + let lineString = try #require(try WKTCoder.decode( + wkt: "CIRCULARSTRING(0 0, 1 1, 2 0)", + sourceProjection: .epsg4326) as? LineString) + + #expect(lineString.coordinates.count > 3) + #expect(lineString.coordinates.first == Coordinate3D(latitude: 0, longitude: 0)) + #expect(lineString.coordinates.last == Coordinate3D(latitude: 0, longitude: 2)) + #expect(lineString.coordinates.contains { coordinate in + abs(coordinate.longitude - 1.0) < 1e-6 && abs(coordinate.latitude - 1.0) < 1e-6 + }) + } + + /// Validates that COMPOUNDCURVE is linearized into a LineString. + @Test + func wktCompoundCurveDecoding() throws { + let lineString = try #require(try WKTCoder.decode( + wkt: "COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 2 0), (2 0, 3 1))", + sourceProjection: .epsg4326) as? LineString) + + #expect(lineString.coordinates.first == Coordinate3D(latitude: 0, longitude: 0)) + #expect(lineString.coordinates.last == Coordinate3D(latitude: 1, longitude: 3)) + #expect(lineString.coordinates.contains { coordinate in + abs(coordinate.longitude - 2.0) < 1e-9 && abs(coordinate.latitude - 0.0) < 1e-9 + }) + } + + /// Validates that CURVEPOLYGON is linearized into a Polygon. + @Test + func wktCurvePolygonDecoding() throws { + let polygon = try #require(try WKTCoder.decode( + wkt: "CURVEPOLYGON(CIRCULARSTRING(0 0, 1 1, 2 0, 1 -1, 0 0))", + sourceProjection: .epsg4326) as? Polygon) + + #expect(polygon.coordinates.count == 1) + #expect(polygon.coordinates[0].count > 4) + #expect(polygon.coordinates[0].first == polygon.coordinates[0].last) + } + + /// Validates that MULTICURVE is linearized into a MultiLineString. + @Test + func wktMultiCurveDecoding() throws { + let multiLineString = try #require(try WKTCoder.decode( + wkt: "MULTICURVE(CIRCULARSTRING(0 0, 1 1, 2 0), (2 0, 3 1))", + sourceProjection: .epsg4326) as? MultiLineString) + + #expect(multiLineString.coordinates.count == 2) + #expect(multiLineString.coordinates[1].last == Coordinate3D(latitude: 1, longitude: 3)) + } + + /// Validates that MULTISURFACE is linearized into a MultiPolygon. + @Test + func wktMultiSurfaceDecoding() throws { + let multiPolygon = try #require(try WKTCoder.decode( + wkt: "MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(0 0, 1 1, 2 0, 1 -1, 0 0)))", + sourceProjection: .epsg4326) as? MultiPolygon) + + #expect(multiPolygon.polygons.count == 1) + #expect(multiPolygon.polygons[0].coordinates[0].count > 4) + } + + /// Validates that TIN and POLYHEDRALSURFACE decode to a MultiPolygon. + @Test + func wktTinAndPolyhedralSurfaceDecoding() throws { + let tin = try #require(try WKTCoder.decode( + wkt: "TIN(((0 0, 1 0, 0 1, 0 0)))", + sourceProjection: .epsg4326) as? MultiPolygon) + #expect(tin.polygons.count == 1) + #expect(tin.polygons[0].coordinates[0].count == 4) + + let polyhedralSurface = try #require(try WKTCoder.decode( + wkt: "POLYHEDRALSURFACE(((0 0, 1 0, 0 1, 0 0)))", + sourceProjection: .epsg4326) as? MultiPolygon) + #expect(polyhedralSurface.polygons.count == 1) + #expect(polyhedralSurface.polygons[0].coordinates[0].count == 4) + } + + /// Validates that POINT EMPTY becomes an empty MultiPoint. + @Test + func wktEmptyPointDecoding() throws { + let multiPoint = try #require(try WKTCoder.decode( + wkt: "POINT EMPTY", + sourceProjection: .epsg4326) as? MultiPoint) + + #expect(multiPoint.points.isEmpty) + } + + /// Validates EMPTY for the other geometry types. + @Test + func wktEmptyGeometryDecoding() throws { + #expect(try WKTCoder.decode(wkt: "LINESTRING EMPTY", sourceProjection: .epsg4326) is LineString) + #expect(try WKTCoder.decode(wkt: "POLYGON EMPTY", sourceProjection: .epsg4326) is Polygon) + #expect(try WKTCoder.decode(wkt: "MULTIPOINT EMPTY", sourceProjection: .epsg4326) is MultiPoint) + #expect(try WKTCoder.decode(wkt: "MULTILINESTRING EMPTY", sourceProjection: .epsg4326) is MultiLineString) + #expect(try WKTCoder.decode(wkt: "MULTIPOLYGON EMPTY", sourceProjection: .epsg4326) is MultiPolygon) + #expect(try WKTCoder.decode(wkt: "GEOMETRYCOLLECTION EMPTY", sourceProjection: .epsg4326) is GeometryCollection) + } + + /// Validates that empty geometries encode with the WKT EMPTY keyword. + @Test + func wktEmptyGeometryEncoding() { + #expect(WKTCoder.encode(geometry: MultiPoint(), targetProjection: nil) == "MULTIPOINT EMPTY") + #expect(WKTCoder.encode(geometry: LineString(), targetProjection: nil) == "LINESTRING EMPTY") + #expect(WKTCoder.encode(geometry: Polygon(), targetProjection: nil) == "POLYGON EMPTY") + #expect(WKTCoder.encode(geometry: MultiLineString(), targetProjection: nil) == "MULTILINESTRING EMPTY") + #expect(WKTCoder.encode(geometry: MultiPolygon(), targetProjection: nil) == "MULTIPOLYGON EMPTY") + #expect(WKTCoder.encode(geometry: GeometryCollection([]), targetProjection: nil) == "GEOMETRYCOLLECTION EMPTY") + } + + /// Validates Z coordinates and dimension suffixes inside curved types. + @Test + func wktCurvedGeometryZDecoding() throws { + let multiSurface = try #require(try WKTCoder.decode( + wkt: "MULTISURFACE Z (CURVEPOLYGON Z (CIRCULARSTRING Z (0 0 1, 1 1 2, 2 0 3, 1 -1 4, 0 0 1)))", + sourceProjection: .epsg4326) as? MultiPolygon) + + let ring = try #require(multiSurface.polygons.first?.coordinates.first) + #expect(ring.first?.altitude == 1) + #expect(ring.contains { $0.altitude == 2 }) + + let compoundCurve = try #require(try WKTCoder.decode( + wkt: "COMPOUNDCURVE Z (CIRCULARSTRING Z (0 0 1, 1 1 2, 2 0 3), (2 0 3, 3 1 4))", + sourceProjection: .epsg4326) as? LineString) + + #expect(compoundCurve.coordinates.first?.altitude == 1) + #expect(compoundCurve.coordinates.last?.altitude == 4) + } + }