/
GeometryFixer.java
433 lines (389 loc) · 14.3 KB
/
GeometryFixer.java
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/*
* Copyright (c) 2021 Martin Davis.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
*
* http://www.eclipse.org/org/documents/edl-v10.php.
*/
package org.locationtech.jts.geom.util;
import java.util.ArrayList;
import java.util.List;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.CoordinateArrays;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.MultiLineString;
import org.locationtech.jts.geom.MultiPoint;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.geom.prep.PreparedGeometry;
import org.locationtech.jts.geom.prep.PreparedGeometryFactory;
import org.locationtech.jts.operation.buffer.BufferOp;
import org.locationtech.jts.operation.overlayng.OverlayNG;
import org.locationtech.jts.operation.overlayng.OverlayNGRobust;
/**
* Fixes a geometry to be a valid geometry, while preserving as much as
* possible of the shape and location of the input.
* Validity is determined according to {@link Geometry#isValid()}.
* <p>
* Input geometries are always processed, so even valid inputs may
* have some minor alterations. The output is always a new geometry object.
*
* <h2>Semantic Rules</h2>
* <ol>
* <li>Vertices with non-finite X or Y ordinates are removed
* (as per {@link Coordinate#isValid()}.</li>
* <li>Repeated points are reduced to a single point</li>
* <li>Empty atomic geometries are valid and are returned unchanged</li>
* <li>Empty elements are removed from collections</li>
* <li><code>Point</code>: keep valid coordinate, or EMPTY</li>
* <li><code>LineString</code>: coordinates are fixed</li>
* <li><code>LinearRing</code>: coordinates are fixed. Keep valid ring, or else convert into <code>LineString</code></li>
* <li><code>Polygon</code>: transform into a valid polygon,
* preserving as much of the extent and vertices as possible.
* <ul>
* <li>Rings are fixed to ensure they are valid</li>
* <li>Holes intersecting the shell are subtracted from the shell</li>
* <li>Holes outside the shell are converted into polygons</li>
* </ul></li>
* <li><code>MultiPolygon</code>: each polygon is fixed,
* then result made non-overlapping (via union)</li>
* <li><code>GeometryCollection</code>: each element is fixed</li>
* <li>Collapsed lines and polygons are handled as follows,
* depending on the <code>keepCollapsed</code> setting:
* <ul>
* <li><code>false</code>: (default) collapses are converted to empty geometries
* (and removed if they are elements of collections)</li>
* <li><code>true</code>: collapses are converted to a valid geometry of lower dimension</li>
* </ul>
* </li>
* </ol>
*
* @author Martin Davis
*
* @see Geometry#isValid()
*/
public class GeometryFixer {
private static final boolean DEFAULT_KEEP_MULTI = true;
/**
* Fixes a geometry to be valid.
*
* @param geom the geometry to be fixed
* @return the valid fixed geometry
*/
public static Geometry fix(Geometry geom) {
return fix(geom, DEFAULT_KEEP_MULTI);
}
/**
* Fixes a geometry to be valid, allowing to set a flag controlling how
* single item results from fixed {@code MULTI} geometries should be
* returned.
*
* @param geom the geometry to be fixed
* @param isKeepMulti a flag indicating if {@code MULTI} geometries should not be converted to single instance types
* if they consist of only one item.
* @return the valid fixed geometry
*/
public static Geometry fix(Geometry geom, boolean isKeepMulti) {
GeometryFixer fix = new GeometryFixer(geom);
fix.setKeepMulti(isKeepMulti);
return fix.getResult();
}
private Geometry geom;
private GeometryFactory factory;
private boolean isKeepCollapsed = false;
private boolean isKeepMulti = DEFAULT_KEEP_MULTI;
/**
* Creates a new instance to fix a given geometry.
*
* @param geom the geometry to be fixed
*/
public GeometryFixer(Geometry geom) {
this.geom = geom;
this.factory = geom.getFactory();
}
/**
* Sets whether collapsed geometries are converted to empty,
* (which will be removed from collections),
* or to a valid geometry of lower dimension.
* The default is to convert collapses to empty geometries.
*
* @param isKeepCollapsed whether collapses should be converted to a lower dimension geometry
*/
public void setKeepCollapsed(boolean isKeepCollapsed) {
this.isKeepCollapsed = isKeepCollapsed;
}
/**
* Sets whether fixed {@code MULTI} geometries that consist of
* only one item should still be returned as {@code MULTI} geometries.
*
* The default is to keep {@code MULTI} geometries.
*
* @param isKeepMulti flag whether to keep {@code MULTI} geometries.
*/
public void setKeepMulti(boolean isKeepMulti) {
this.isKeepMulti = isKeepMulti;
}
/**
* Gets the fixed geometry.
*
* @return the fixed geometry
*/
public Geometry getResult() {
/*
* Truly empty geometries are simply copied.
* Geometry collections with elements are evaluated on a per-element basis.
*/
if (geom.getNumGeometries() == 0) {
return geom.copy();
}
if (geom instanceof Point) return fixPoint((Point) geom);
// LinearRing must come before LineString
if (geom instanceof LinearRing) return fixLinearRing((LinearRing) geom);
if (geom instanceof LineString) return fixLineString((LineString) geom);
if (geom instanceof Polygon) return fixPolygon((Polygon) geom);
if (geom instanceof MultiPoint) return fixMultiPoint((MultiPoint) geom);
if (geom instanceof MultiLineString) return fixMultiLineString((MultiLineString) geom);
if (geom instanceof MultiPolygon) return fixMultiPolygon((MultiPolygon) geom);
if (geom instanceof GeometryCollection) return fixCollection((GeometryCollection) geom);
throw new UnsupportedOperationException(geom.getClass().getName());
}
private Point fixPoint(Point geom) {
Geometry pt = fixPointElement(geom);
if (pt == null)
return factory.createPoint();
return (Point) pt;
}
private Point fixPointElement(Point geom) {
if (geom.isEmpty() || ! isValidPoint(geom)) {
return null;
}
return (Point) geom.copy();
}
private static boolean isValidPoint(Point pt) {
Coordinate p = pt.getCoordinate();
return p.isValid();
}
private Geometry fixMultiPoint(MultiPoint geom) {
List<Point> pts = new ArrayList<Point>();
for (int i = 0; i < geom.getNumGeometries(); i++) {
Point pt = (Point) geom.getGeometryN(i);
if (pt.isEmpty()) continue;
Point fixPt = fixPointElement(pt);
if (fixPt != null) {
pts.add(fixPt);
}
}
if (!this.isKeepMulti && pts.size() == 1)
return pts.get(0);
return factory.createMultiPoint(GeometryFactory.toPointArray(pts));
}
private Geometry fixLinearRing(LinearRing geom) {
Geometry fix = fixLinearRingElement(geom);
if (fix == null)
return factory.createLinearRing();
return fix;
}
private Geometry fixLinearRingElement(LinearRing geom) {
if (geom.isEmpty()) return null;
Coordinate[] pts = geom.getCoordinates();
Coordinate[] ptsFix = fixCoordinates(pts);
if (this.isKeepCollapsed) {
if (ptsFix.length == 1) {
return factory.createPoint(ptsFix[0]);
}
if (ptsFix.length > 1 && ptsFix.length <= 3) {
return factory.createLineString(ptsFix);
}
}
//--- too short to be a valid ring
if (ptsFix.length <= 3) {
return null;
}
LinearRing ring = factory.createLinearRing(ptsFix);
//--- convert invalid ring to LineString
if (! ring.isValid()) {
return factory.createLineString(ptsFix);
}
return ring;
}
private Geometry fixLineString(LineString geom) {
Geometry fix = fixLineStringElement(geom);
if (fix == null)
return factory.createLineString();
return fix;
}
private Geometry fixLineStringElement(LineString geom) {
if (geom.isEmpty()) return null;
Coordinate[] pts = geom.getCoordinates();
Coordinate[] ptsFix = fixCoordinates(pts);
if (this.isKeepCollapsed && ptsFix.length == 1) {
return factory.createPoint(ptsFix[0]);
}
if (ptsFix.length <= 1) {
return null;
}
return factory.createLineString(ptsFix);
}
/**
* Returns a clean copy of the input coordinate array.
*
* @param pts coordinates to clean
* @return an array of clean coordinates
*/
private static Coordinate[] fixCoordinates(Coordinate[] pts) {
Coordinate[] ptsClean = CoordinateArrays.removeRepeatedOrInvalidPoints(pts);
return CoordinateArrays.copyDeep(ptsClean);
}
private Geometry fixMultiLineString(MultiLineString geom) {
List<Geometry> fixed = new ArrayList<Geometry>();
boolean isMixed = false;
for (int i = 0; i < geom.getNumGeometries(); i++) {
LineString line = (LineString) geom.getGeometryN(i);
if (line.isEmpty()) continue;
Geometry fix = fixLineStringElement(line);
if (fix == null) continue;
if (! (fix instanceof LineString)) {
isMixed = true;
}
fixed.add(fix);
}
if (fixed.size() == 1) {
if (!this.isKeepMulti || !(fixed.get(0) instanceof LineString))
return fixed.get(0);
}
if (isMixed) {
return factory.createGeometryCollection(GeometryFactory.toGeometryArray(fixed));
}
return factory.createMultiLineString(GeometryFactory.toLineStringArray(fixed));
}
private Geometry fixPolygon(Polygon geom) {
Geometry fix = fixPolygonElement(geom);
if (fix == null)
return factory.createPolygon();
return fix;
}
private Geometry fixPolygonElement(Polygon geom) {
LinearRing shell = geom.getExteriorRing();
Geometry fixShell = fixRing(shell);
if (fixShell.isEmpty()) {
if (this.isKeepCollapsed) {
return fixLineString(shell);
}
//--- if not allowing collapses then return empty polygon
return null;
}
//--- if no holes then done
if (geom.getNumInteriorRing() == 0) {
return fixShell;
}
//--- fix holes, classify, and construct shell-true holes
List<Geometry> holesFixed = fixHoles(geom);
List<Geometry> holes = new ArrayList<Geometry>();
List<Geometry> shells = new ArrayList<Geometry>();
classifyHoles(fixShell, holesFixed, holes, shells);
Geometry polyWithHoles = difference(fixShell, holes);
if (shells.size() == 0) {
return polyWithHoles;
}
//--- if some holes converted to shells, union all shells
shells.add(polyWithHoles);
Geometry result = union(shells);
return result;
}
private List<Geometry> fixHoles(Polygon geom) {
List<Geometry> holes = new ArrayList<Geometry>();
for (int i = 0; i < geom.getNumInteriorRing(); i++) {
Geometry holeRep = fixRing(geom.getInteriorRingN(i));
if (holeRep != null) {
holes.add(holeRep);
}
}
return holes;
}
private void classifyHoles(Geometry shell, List<Geometry> holesFixed, List<Geometry> holes, List<Geometry> shells) {
PreparedGeometry shellPrep = PreparedGeometryFactory.prepare(shell);
for (Geometry hole : holesFixed) {
if (shellPrep.intersects(hole)) {
holes.add(hole);
}
else {
shells.add(hole);
}
}
}
/**
* Subtracts a list of polygonal geometries from a polygonal geometry.
*
* @param shell polygonal geometry for shell
* @param holes polygonal geometries to subtract
* @return the result geometry
*/
private Geometry difference(Geometry shell, List<Geometry> holes) {
if (holes == null || holes.size() == 0)
return shell;
Geometry holesUnion = union(holes);
return OverlayNGRobust.overlay(shell, holesUnion, OverlayNG.DIFFERENCE);
}
/**
* Unions a list of polygonal geometries.
* Optimizes case of zero or one input geometries.
* Requires that the inputs are net new objects.
*
* @param polys the polygonal geometries to union
* @return the union of the inputs
*/
private Geometry union(List<Geometry> polys) {
if (polys.size() == 0) return factory.createPolygon();
if (polys.size() == 1) {
return polys.get(0);
}
// TODO: replace with holes.union() once OverlayNG is the default
return OverlayNGRobust.union(polys);
}
private Geometry fixRing(LinearRing ring) {
//-- always execute fix, since it may remove repeated/invalid coords etc
// TODO: would it be faster to check ring validity first?
Geometry poly = factory.createPolygon(ring);
return BufferOp.bufferByZero(poly, true);
}
private Geometry fixMultiPolygon(MultiPolygon geom) {
List<Geometry> polys = new ArrayList<Geometry>();
for (int i = 0; i < geom.getNumGeometries(); i++) {
Polygon poly = (Polygon) geom.getGeometryN(i);
Geometry polyFix = fixPolygonElement(poly);
if (polyFix != null && ! polyFix.isEmpty()) {
polys.add(polyFix);
}
}
if (polys.size() == 0) {
return factory.createMultiPolygon();
}
// TODO: replace with polys.union() once OverlayNG is the default
Geometry result = union(polys);
if (this.isKeepMulti && result instanceof Polygon)
result = factory.createMultiPolygon(new Polygon[]{(Polygon) result});
return result;
}
private Geometry fixCollection(GeometryCollection geom) {
Geometry[] geomRep = new Geometry[geom.getNumGeometries()];
for (int i = 0; i < geom.getNumGeometries(); i++) {
geomRep[i] = fix(geom.getGeometryN(i), this.isKeepCollapsed, this.isKeepMulti);
}
return factory.createGeometryCollection(geomRep);
}
private static Geometry fix(Geometry geom, boolean isKeepCollapsed, boolean isKeepMulti) {
GeometryFixer fix = new GeometryFixer(geom);
fix.setKeepCollapsed(isKeepCollapsed);
fix.setKeepMulti(isKeepMulti);
return fix.getResult();
}
}