Skip to content

Commit 184ea04

Browse files
authored
Fix MLT polygon winding artifacts in maplibre-gl-js (#54)
1 parent 6e08f61 commit 184ea04

4 files changed

Lines changed: 159 additions & 12 deletions

File tree

‎Dependencies/maplibre-tile-spec‎

Submodule maplibre-tile-spec updated 153 files

‎Sources/CMLT/Bridge.cpp‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,31 @@ uint8_t* mlt_encoder_finish(
788788
// filters compare those strings. Do NOT re-enable this setting without
789789
// first verifying round-trip decoding against the maplibre-gl-js WASM
790790
// decoder across a representative set of tiles.
791-
auto result = state->encoder.encode(state->layers, mlt::EncoderConfig::with([](auto& c) { c.useFsst = false; }));
791+
//
792+
// Morton/Hilbert dictionary vertex encoding is also disabled. With real
793+
// PostGIS-sourced tiles (many features per layer, mixed geometries,
794+
// vertices spanning the buffer zone with negative coordinates), the
795+
// C++ MLT encoder's space-filling-curve dictionary path produces tiles
796+
// whose decoded ring0 starts at a dictionary-sorted anchor rather than
797+
// the encoded first vertex and whose winding is flipped. This breaks
798+
// maplibre-gl-js's `classifyRings` (it keys exterior-vs-hole off the
799+
// first ring's signed area) and produces triangular fill artifacts on
800+
// polygons-with-holes. Plain (zigzag-delta) vertex encoding preserves
801+
// vertex order and winding at the cost of slightly larger tiles.
802+
//
803+
// Disabling `enableMortonEncoding` alone is NOT sufficient: the Hilbert
804+
// path is gated only by `validCoordinateRange`, not by config. To force
805+
// the plain path, `geometryEncodingOption` is set to a non-AUTO value so
806+
// `encodeGeometryColumn` takes the early-return plain branch when morton
807+
// is disabled (see geometry.hpp:
808+
// `if (integerEncodingOption != AUTO && !enableMortonEncoding)`).
809+
// Do NOT re-enable without a fix for the upstream encoder:
810+
// https://github.com/maplibre/maplibre-tile-spec
811+
auto result = state->encoder.encode(state->layers, mlt::EncoderConfig::with([](auto& c) {
812+
c.useFsst = false;
813+
c.enableMortonEncoding = false;
814+
c.geometryEncodingOption = mlt::IntegerEncodingOption::PLAIN;
815+
}));
792816
auto* buffer = static_cast<uint8_t*>(std::malloc(result.size()));
793817
std::memcpy(buffer, result.data(), result.size());
794818
*outLength = result.size();

‎Sources/MVTTools/Coders/MLT/MLTEncoder.swift‎

Lines changed: 50 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -141,14 +141,35 @@ enum MLTEncoder {
141141
// the decoder. Storing it would inflate every ring size by 1 and
142142
// shift all subsequent cumulative ring offsets, corrupting polygon
143143
// geometry for consumers like maplibre-gl-js.
144-
let collectRing: ([Coordinate3D]) -> Void = { ring in
145-
var coords = ring
146-
if coords.count > 1, coords.first == coords.last {
147-
coords.removeLast()
144+
145+
// Tile-space signed area (maplibre's calculateSignedArea formula,
146+
// y grows downward). Negative area = exterior for mvt-style rings.
147+
func tileArea(_ ring: [(Int, Int)]) -> Double {
148+
var sum = 0.0
149+
let n = ring.count
150+
for i in 0 ..< n {
151+
let (x1, y1) = ring[i]
152+
let (x2, y2) = ring[(i + 1) % n]
153+
sum += Double(x2 - x1) * Double(y1 + y2)
148154
}
149-
let projected = coords.map(projectionFunction)
150-
partSizes.append(UInt32(projected.count))
151-
projectedCoords.append(contentsOf: projected)
155+
return sum
156+
}
157+
158+
// Normalize one polygon's winding in TILE SPACE so that the
159+
// exterior (first) ring has negative area and all holes have
160+
// positive area. maplibre's classifyRings operates on the
161+
// flattened, tile-space ring list, so winding must be consistent
162+
// there (not only in the source projection).
163+
func normalizePolygonTilespace(_ rings: [[(Int, Int)]]) -> [[(Int, Int)]] {
164+
guard var first = rings.first else { return rings }
165+
if tileArea(first) > 0 { first.reverse() }
166+
var result = [first]
167+
for hole in rings.dropFirst() {
168+
var h = hole
169+
if tileArea(h) < 0 { h.reverse() }
170+
result.append(h)
171+
}
172+
return result
152173
}
153174

154175
switch feature.geometry.type {
@@ -158,13 +179,32 @@ enum MLTEncoder {
158179

159180
case .polygon:
160181
let poly = feature.geometry as! Polygon
161-
for ring in poly.rings { collectRing(ring.coordinates) }
182+
var rings = poly.rings.map { ring in
183+
var coords = ring.coordinates
184+
if coords.count > 1, coords.first == coords.last { coords.removeLast() }
185+
return coords.map(projectionFunction)
186+
}
187+
rings = normalizePolygonTilespace(rings)
188+
polygonRingCounts.append(UInt32(rings.count))
189+
for ring in rings {
190+
partSizes.append(UInt32(ring.count))
191+
projectedCoords.append(contentsOf: ring)
192+
}
162193

163194
case .multiPolygon:
164195
let mpoly = feature.geometry as! MultiPolygon
165196
for poly in mpoly.coordinates {
166-
polygonRingCounts.append(UInt32(poly.count))
167-
for ring in poly { collectRing(ring) }
197+
var rings = poly.map { (ringCoords: [Coordinate3D]) -> [(Int, Int)] in
198+
var coords = ringCoords
199+
if coords.count > 1, coords.first == coords.last { coords.removeLast() }
200+
return coords.map(projectionFunction)
201+
}
202+
rings = normalizePolygonTilespace(rings)
203+
polygonRingCounts.append(UInt32(rings.count))
204+
for ring in rings {
205+
partSizes.append(UInt32(ring.count))
206+
projectedCoords.append(contentsOf: ring)
207+
}
168208
}
169209

170210
default:

‎Tests/MVTToolsTests/MLT/MLTRoundtripGeometryTests.swift‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,89 @@ struct MLTRoundtripGeometryTests {
164164
#expect(feat.geometry is MultiPoint)
165165
}
166166

167+
// Regression: a MultiPolygon with a single polygon containing many rings
168+
// and vertices that fall OUTSIDE the tile extent (negative coords, as
169+
// happens with buffered PostGIS tiles). The C++ MLT encoder must preserve
170+
// the ring→vertex mapping so that decoding returns each ring's original
171+
// vertices in order. This validates the workaround that disables the
172+
// Morton/Hilbert dictionary vertex encoding in Bridge.cpp.
173+
@Test
174+
func multiPolygonManyRingsWithNegativeCoordsRoundtrip() throws {
175+
// One polygon with 67 rings; ring0 has 5 vertices starting at (-405, 2730).
176+
// Holes use smaller rings. Coordinates deliberately include negative
177+
// values (buffer zone) to exercise the space-filling-curve path.
178+
var rings: [[Coordinate3D]] = []
179+
// Ring 0 (exterior): a large rectangle spanning the buffer + tile.
180+
// Winding is chosen so that `normalizePolygonTilespace` does NOT reverse
181+
// it (negative tile-space area), so expectedRing0 == ring0.
182+
let ring0 = [
183+
Coordinate3D(x: -405.0, y: -400.0, projection: .noSRID),
184+
Coordinate3D(x: 4502.0, y: -400.0, projection: .noSRID),
185+
Coordinate3D(x: 4502.0, y: 2730.0, projection: .noSRID),
186+
Coordinate3D(x: -405.0, y: 2730.0, projection: .noSRID),
187+
Coordinate3D(x: -405.0, y: -400.0, projection: .noSRID),
188+
]
189+
rings.append(ring0)
190+
// 66 holes, each a small triangle in-tile to vary winding/offsets.
191+
for i in 0 ..< 66 {
192+
let base = Double(i * 60) + 10
193+
rings.append([
194+
Coordinate3D(x: base, y: base, projection: .noSRID),
195+
Coordinate3D(x: base + 50, y: base, projection: .noSRID),
196+
Coordinate3D(x: base + 25, y: base + 50, projection: .noSRID),
197+
Coordinate3D(x: base, y: base, projection: .noSRID),
198+
])
199+
}
200+
let poly = try #require(Polygon(rings))
201+
let mpoly = try #require(MultiPolygon([poly]))
202+
// Add MANY features with VARIED geometries in the same layer, so the
203+
// Morton/Hilbert dictionary is built across heterogeneous vertices
204+
// (this mirrors real tiles like `oceans` where features have different
205+
// ring counts/sizes and is what triggers the reorder bug).
206+
var features: [Feature] = []
207+
features.append(Feature(mpoly, id: .int(0)))
208+
// Add small varied polygons with different vertex ranges.
209+
for i in 1 ..< 25 {
210+
let off = Double(i) * 100.0
211+
let small = try #require(Polygon([[
212+
Coordinate3D(x: off, y: off, projection: .noSRID),
213+
Coordinate3D(x: off + 200, y: off, projection: .noSRID),
214+
Coordinate3D(x: off + 100, y: off + 200, projection: .noSRID),
215+
Coordinate3D(x: off, y: off, projection: .noSRID),
216+
]]))
217+
features.append(Feature(try #require(MultiPolygon([small])), id: .int(i)))
218+
}
219+
220+
guard let data = MLTEncoder.encode(
221+
layers: ["test": VectorTile.LayerContainer(features: features, boundingBox: nil)],
222+
x: 0, y: 0, z: 0, projection: .noSRID)
223+
else { return }
224+
let decoded = try MLTDecoder.decode(from: data, x: 0, y: 0, z: 0, projection: .noSRID)
225+
let layer = try #require(decoded["test"])
226+
#expect(layer.features.count == 25, "all 25 features decoded")
227+
// Find the feature whose ring0 has 67 rings (the big mpoly). Its ring0
228+
// must come back with its original first vertex.
229+
let big = try #require(layer.features.first(where: {
230+
($0.geometry as? MultiPolygon)?.coordinates.first?.count == 67
231+
}))
232+
let result = try #require(big.geometry as? MultiPolygon)
233+
#expect(result.coordinates.count == 1, "one polygon")
234+
#expect(result.coordinates[0].count == 67, "67 rings")
235+
// Ring 0 must come back with its original first vertex (allowing Int rounding).
236+
// normalizePolygonTilespace keeps ring0 as-is because its tile-space area
237+
// is negative (exterior), so expected == original.
238+
let expectedRing0 = ring0
239+
let decodedRing0 = result.coordinates[0][0]
240+
#expect(decodedRing0.count == expectedRing0.count)
241+
#expect(abs(decodedRing0[0].x - expectedRing0[0].x) < 1.0, "ring0 first x preserved (got \(decodedRing0[0].x), want \(expectedRing0[0].x))")
242+
#expect(abs(decodedRing0[0].y - expectedRing0[0].y) < 1.0, "ring0 first y preserved (got \(decodedRing0[0].y), want \(expectedRing0[0].y))")
243+
// Diagnostic: dump decoded ring0 vs expected to spot any misalignment.
244+
if abs(decodedRing0[0].y - expectedRing0[0].y) >= 1.0 {
245+
print("Expected ring0: \(expectedRing0.map { "(\($0.x),\($0.y))" })")
246+
print("Decoded ring0: \(decodedRing0.map { "(\($0.x),\($0.y))" })")
247+
}
248+
}
249+
167250
@Test
168251
func altitudeIsDropped() throws {
169252
let coord = Coordinate3D(latitude: 10.0, longitude: 20.0, altitude: 500.0, m: 123.0)

0 commit comments

Comments
 (0)