Repository navigation
Expand file tree
/
Copy pathmultipoly.go
More file actions
327 lines (269 loc) · 9.13 KB
/
Copy pathmultipoly.go
File metadata and controls
327 lines (269 loc) · 9.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/*
* Copyright 2026 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package h3
import (
"cmp"
"slices"
)
// Counter-clockwise orderings of a cell's directed edges into its linked loop.
// idxHex is for hexagons (six edges); idxPent is for pentagons (five edges).
var (
idxHex = [numCellEdges]int{0, 4, 3, 5, 1, 2}
idxPent = [numCellEdges - 1]int{0, 1, 3, 2, 4}
)
// arc is one directed edge of a cell during multipolygon assembly. Arcs form
// doubly-linked loops (counter-clockwise) and a union-find forest whose roots
// identify connected components (each component becomes one polygon). Links are
// indices into the arc slice rather than pointers, so the whole graph lives in
// one allocation and survives the slice growing.
type arc struct {
parent int
prev int
next int
id DirectedEdge
rank int
removed bool
visited bool
}
// arcRoot returns the index of the representative arc of idx's connected
// component, compressing the path along the way.
func arcRoot(arcs []arc, idx int) int {
for arcs[idx].parent != idx {
arcs[idx].parent = arcs[arcs[idx].parent].parent
idx = arcs[idx].parent
}
return idx
}
// arcUnion merges the connected components of two arcs, attaching the lower-rank
// root under the higher-rank one.
func arcUnion(arcs []arc, first, second int) {
first = arcRoot(arcs, first)
second = arcRoot(arcs, second)
if arcs[first].rank < arcs[second].rank {
first, second = second, first
}
if first != second {
arcs[first].rank += arcs[second].rank
arcs[second].parent = first
}
}
// validateCellSet checks that the cells are all valid, share one resolution, and
// contain no duplicates, matching the H3 C library's contract.
func validateCellSet(cells []Cell) error {
res := cells[0].Resolution()
for _, cell := range cells {
if !cell.IsValid() {
return ErrCellInvalid
}
if cell.Resolution() != res {
return ErrResolutionMismatch
}
}
if len(cells) >= 2 {
sorted := slices.Clone(cells)
slices.Sort(sorted)
for i := 1; i < len(sorted); i++ {
if sorted[i] == sorted[i-1] {
return ErrDuplicateInput
}
}
}
return nil
}
// buildArcs creates the arcs for every cell, linking each cell's edges into a
// counter-clockwise loop and indexing them by edge id for reverse lookup. Every
// arc in a cell starts in the cell's own connected component. All arcs share one
// backing slice; links are indices into it, and the returned table maps each
// edge id to its arc index.
func buildArcs(cells []Cell) ([]arc, flatTable[DirectedEdge, int]) {
arcs := make([]arc, 0, len(cells)*numCellEdges)
index := newFlatTable[DirectedEdge, int](len(cells) * numCellEdges)
for _, cell := range cells {
var edgeBuf [numCellEdges]DirectedEdge
edges := cell.appendDirectedEdges(edgeBuf[:0])
count := len(edges)
base := len(arcs)
for i := 0; i < count; i++ {
// Every arc in the cell starts rooted at the cell's first arc.
arcs = append(arcs, arc{id: edges[i], rank: 1, parent: base})
}
order := idxHex[:]
if count == numCellEdges-1 {
order = idxPent[:]
}
for i := 0; i < count; i++ {
cur := order[i]
prev := order[(i-1+count)%count]
next := order[(i+1)%count]
arcs[base+cur].prev = base + prev
arcs[base+cur].next = base + next
}
for i := 0; i < count; i++ {
index.insert(arcs[base+i].id, base+i)
}
}
return arcs, index
}
// cancelArcPairs removes each pair of opposite edges shared by two adjacent
// cells, stitching the linked loops back together and merging the two arcs'
// connected components. What remains are the outline loops of the cell set.
func cancelArcPairs(arcs []arc, index *flatTable[DirectedEdge, int]) {
for current := range arcs {
if arcs[current].removed {
continue
}
// arcs[current].id is a valid edge, so reversing it cannot fail.
reversed, _ := arcs[current].id.Reverse()
opposite, ok := index.lookup(reversed)
if !ok {
continue
}
arcs[current].removed = true
arcs[opposite].removed = true
arcs[arcs[current].next].prev = arcs[opposite].prev
arcs[arcs[current].prev].next = arcs[opposite].next
arcs[arcs[opposite].next].prev = arcs[current].prev
arcs[arcs[opposite].prev].next = arcs[current].next
arcUnion(arcs, current, opposite)
}
}
// outlineLoop holds one assembled boundary loop with the connected component it
// belongs to and its area, used to order loops within and across polygons.
type outlineLoop struct {
loop GeoLoop
root DirectedEdge
area float64
}
// buildOutlineLoops walks the remaining arcs into boundary loops, recording each
// loop's connected component and enclosed area. Loops are sorted by component,
// then by area so that each polygon's loops are contiguous with its outer loop
// (smallest enclosed area) first.
func buildOutlineLoops(arcs []arc) []outlineLoop {
for i := range arcs {
arcs[i].visited = false
}
var loops []outlineLoop
for start := range arcs {
if arcs[start].visited || arcs[start].removed {
continue
}
// Count the loop's arcs first so the vertex slice is allocated once.
// Each arc contributes its start vertex, plus a crossing vertex where a
// Class III edge meets an icosahedron face edge.
arcCount := 0
for current := start; ; current = arcs[current].next {
arcCount++
if arcs[current].next == start {
break
}
}
vertsPerArc := 1
if isResClassIII(arcs[start].id.Resolution()) {
vertsPerArc = numEdgeCells
}
verts := make(CellBoundary, 0, arcCount*vertsPerArc)
for current := start; ; current = arcs[current].next {
// arcs[current].id is valid, so its boundary cannot fail. The edge's
// end vertex is the next arc's start vertex, so it is dropped.
verts, _ = arcs[current].id.appendBoundary(verts)
verts = verts[:len(verts)-1]
arcs[current].visited = true
if arcs[current].next == start {
break
}
}
loops = append(loops, outlineLoop{
root: arcs[arcRoot(arcs, start)].id,
loop: GeoLoop(verts),
area: verts.areaRads2(),
})
}
slices.SortStableFunc(loops, func(first, second outlineLoop) int {
if first.root != second.root {
return cmp.Compare(first.root, second.root)
}
return cmp.Compare(first.area, second.area)
})
return loops
}
// assembleMultiPolygon groups contiguous same-component loops into polygons
// (outer loop first, the rest holes) and orders the polygons by decreasing outer
// loop area.
func assembleMultiPolygon(loops []outlineLoop) []GeoPolygon {
type sortablePoly struct {
poly GeoPolygon
outerArea float64
}
var polys []sortablePoly
for i := 0; i < len(loops); {
j := i
for j < len(loops) && loops[j].root == loops[i].root {
j++
}
poly := GeoPolygon{GeoLoop: loops[i].loop}
for k := i + 1; k < j; k++ {
poly.Holes = append(poly.Holes, loops[k].loop)
}
polys = append(polys, sortablePoly{poly: poly, outerArea: loops[i].area})
i = j
}
slices.SortStableFunc(polys, func(first, second sortablePoly) int {
return cmp.Compare(second.outerArea, first.outerArea)
})
out := make([]GeoPolygon, len(polys))
for i := range polys {
out[i] = polys[i].poly
}
return out
}
// globeMultiPolygon returns the eight-triangle representation of the entire
// globe, used when the cell set covers the whole sphere and leaves no outline.
func globeMultiPolygon() []GeoPolygon {
verts := [8][3]LatLng{
{{Lat: halfPiDeg, Lng: 0}, {Lat: 0, Lng: 0}, {Lat: 0, Lng: halfPiDeg}},
{{Lat: halfPiDeg, Lng: 0}, {Lat: 0, Lng: halfPiDeg}, {Lat: 0, Lng: piDeg}},
{{Lat: halfPiDeg, Lng: 0}, {Lat: 0, Lng: piDeg}, {Lat: 0, Lng: -halfPiDeg}},
{{Lat: halfPiDeg, Lng: 0}, {Lat: 0, Lng: -halfPiDeg}, {Lat: 0, Lng: 0}},
{{Lat: -halfPiDeg, Lng: 0}, {Lat: 0, Lng: 0}, {Lat: 0, Lng: -halfPiDeg}},
{{Lat: -halfPiDeg, Lng: 0}, {Lat: 0, Lng: -halfPiDeg}, {Lat: 0, Lng: -piDeg}},
{{Lat: -halfPiDeg, Lng: 0}, {Lat: 0, Lng: -piDeg}, {Lat: 0, Lng: halfPiDeg}},
{{Lat: -halfPiDeg, Lng: 0}, {Lat: 0, Lng: halfPiDeg}, {Lat: 0, Lng: 0}},
}
out := make([]GeoPolygon, len(verts))
for i := range verts {
out[i] = GeoPolygon{GeoLoop: GeoLoop{verts[i][0], verts[i][1], verts[i][2]}}
}
return out
}
// CellsToMultiPolygon outlines a set of cells as GeoPolygons: each polygon has
// one counter-clockwise outer loop followed by any clockwise holes, and polygons
// are ordered by decreasing outer loop area. The cells must all be valid, share
// one resolution, and contain no duplicates.
func CellsToMultiPolygon(cells []Cell) ([]GeoPolygon, error) {
if len(cells) == 0 {
return nil, nil
}
if err := validateCellSet(cells); err != nil {
return nil, err
}
arcs, index := buildArcs(cells)
cancelArcPairs(arcs, &index)
loops := buildOutlineLoops(arcs)
if len(loops) == 0 {
return globeMultiPolygon(), nil
}
return assembleMultiPolygon(loops), nil
}