1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import java.awt.geom.Area;
|
---|
5 | import java.awt.geom.Line2D;
|
---|
6 | import java.awt.geom.Path2D;
|
---|
7 | import java.awt.geom.PathIterator;
|
---|
8 | import java.awt.geom.Rectangle2D;
|
---|
9 | import java.math.BigDecimal;
|
---|
10 | import java.math.MathContext;
|
---|
11 | import java.util.ArrayList;
|
---|
12 | import java.util.Collection;
|
---|
13 | import java.util.Collections;
|
---|
14 | import java.util.Comparator;
|
---|
15 | import java.util.Iterator;
|
---|
16 | import java.util.LinkedHashSet;
|
---|
17 | import java.util.List;
|
---|
18 | import java.util.Set;
|
---|
19 | import java.util.TreeSet;
|
---|
20 | import java.util.function.Predicate;
|
---|
21 | import java.util.stream.Collectors;
|
---|
22 |
|
---|
23 | import org.openstreetmap.josm.command.AddCommand;
|
---|
24 | import org.openstreetmap.josm.command.ChangeNodesCommand;
|
---|
25 | import org.openstreetmap.josm.command.Command;
|
---|
26 | import org.openstreetmap.josm.data.coor.EastNorth;
|
---|
27 | import org.openstreetmap.josm.data.coor.ILatLon;
|
---|
28 | import org.openstreetmap.josm.data.osm.BBox;
|
---|
29 | import org.openstreetmap.josm.data.osm.DataSet;
|
---|
30 | import org.openstreetmap.josm.data.osm.INode;
|
---|
31 | import org.openstreetmap.josm.data.osm.IPrimitive;
|
---|
32 | import org.openstreetmap.josm.data.osm.IWay;
|
---|
33 | import org.openstreetmap.josm.data.osm.MultipolygonBuilder;
|
---|
34 | import org.openstreetmap.josm.data.osm.MultipolygonBuilder.JoinedPolygon;
|
---|
35 | import org.openstreetmap.josm.data.osm.Node;
|
---|
36 | import org.openstreetmap.josm.data.osm.NodePositionComparator;
|
---|
37 | import org.openstreetmap.josm.data.osm.OsmPrimitive;
|
---|
38 | import org.openstreetmap.josm.data.osm.Relation;
|
---|
39 | import org.openstreetmap.josm.data.osm.Way;
|
---|
40 | import org.openstreetmap.josm.data.osm.WaySegment;
|
---|
41 | import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon;
|
---|
42 | import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.PolyData;
|
---|
43 | import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
|
---|
44 | import org.openstreetmap.josm.data.projection.Projection;
|
---|
45 | import org.openstreetmap.josm.data.projection.ProjectionRegistry;
|
---|
46 | import org.openstreetmap.josm.data.projection.Projections;
|
---|
47 |
|
---|
48 | /**
|
---|
49 | * Some tools for geometry related tasks.
|
---|
50 | *
|
---|
51 | * @author viesturs
|
---|
52 | */
|
---|
53 | public final class Geometry {
|
---|
54 |
|
---|
55 | private Geometry() {
|
---|
56 | // Hide default constructor for utils classes
|
---|
57 | }
|
---|
58 |
|
---|
59 | /**
|
---|
60 | * The result types for a {@link Geometry#polygonIntersection(Area, Area)} test
|
---|
61 | */
|
---|
62 | public enum PolygonIntersection {
|
---|
63 | /**
|
---|
64 | * The first polygon is inside the second one
|
---|
65 | */
|
---|
66 | FIRST_INSIDE_SECOND,
|
---|
67 | /**
|
---|
68 | * The second one is inside the first
|
---|
69 | */
|
---|
70 | SECOND_INSIDE_FIRST,
|
---|
71 | /**
|
---|
72 | * The polygons do not overlap
|
---|
73 | */
|
---|
74 | OUTSIDE,
|
---|
75 | /**
|
---|
76 | * The polygon borders cross each other
|
---|
77 | */
|
---|
78 | CROSSING
|
---|
79 | }
|
---|
80 |
|
---|
81 | /** threshold value for size of intersection area given in east/north space */
|
---|
82 | public static final double INTERSECTION_EPS_EAST_NORTH = 1e-4;
|
---|
83 |
|
---|
84 | /**
|
---|
85 | * Will find all intersection and add nodes there for list of given ways.
|
---|
86 | * Handles self-intersections too.
|
---|
87 | * And makes commands to add the intersection points to ways.
|
---|
88 | *
|
---|
89 | * Prerequisite: no two nodes have the same coordinates.
|
---|
90 | *
|
---|
91 | * @param ways a list of ways to test
|
---|
92 | * @param test if true, do not build list of Commands, just return nodes
|
---|
93 | * @param cmds list of commands, typically empty when handed to this method.
|
---|
94 | * Will be filled with commands that add intersection nodes to
|
---|
95 | * the ways.
|
---|
96 | * @return list of new nodes, if test is true the list might not contain all intersections
|
---|
97 | */
|
---|
98 | public static Set<Node> addIntersections(List<Way> ways, boolean test, List<Command> cmds) {
|
---|
99 |
|
---|
100 | int n = ways.size();
|
---|
101 | @SuppressWarnings("unchecked")
|
---|
102 | List<Node>[] newNodes = new ArrayList[n];
|
---|
103 | BBox[] wayBounds = new BBox[n];
|
---|
104 | boolean[] changedWays = new boolean[n];
|
---|
105 |
|
---|
106 | Set<Node> intersectionNodes = new LinkedHashSet<>();
|
---|
107 |
|
---|
108 | //copy node arrays for local usage.
|
---|
109 | for (int pos = 0; pos < n; pos++) {
|
---|
110 | newNodes[pos] = new ArrayList<>(ways.get(pos).getNodes());
|
---|
111 | wayBounds[pos] = ways.get(pos).getBBox();
|
---|
112 | changedWays[pos] = false;
|
---|
113 | }
|
---|
114 |
|
---|
115 | DataSet dataset = ways.get(0).getDataSet();
|
---|
116 |
|
---|
117 | //iterate over all way pairs and introduce the intersections
|
---|
118 | Comparator<Node> coordsComparator = new NodePositionComparator();
|
---|
119 | for (int seg1Way = 0; seg1Way < n; seg1Way++) {
|
---|
120 | for (int seg2Way = seg1Way; seg2Way < n; seg2Way++) {
|
---|
121 |
|
---|
122 | //do not waste time on bounds that do not intersect
|
---|
123 | if (!wayBounds[seg1Way].intersects(wayBounds[seg2Way])) {
|
---|
124 | continue;
|
---|
125 | }
|
---|
126 |
|
---|
127 | List<Node> way1Nodes = newNodes[seg1Way];
|
---|
128 | List<Node> way2Nodes = newNodes[seg2Way];
|
---|
129 |
|
---|
130 | //iterate over primary segmemt
|
---|
131 | for (int seg1Pos = 0; seg1Pos + 1 < way1Nodes.size(); seg1Pos++) {
|
---|
132 |
|
---|
133 | //iterate over secondary segment
|
---|
134 | int seg2Start = seg1Way != seg2Way ? 0 : seg1Pos + 2; //skip the adjacent segment
|
---|
135 |
|
---|
136 | for (int seg2Pos = seg2Start; seg2Pos + 1 < way2Nodes.size(); seg2Pos++) {
|
---|
137 |
|
---|
138 | //need to get them again every time, because other segments may be changed
|
---|
139 | Node seg1Node1 = way1Nodes.get(seg1Pos);
|
---|
140 | Node seg1Node2 = way1Nodes.get(seg1Pos + 1);
|
---|
141 | Node seg2Node1 = way2Nodes.get(seg2Pos);
|
---|
142 | Node seg2Node2 = way2Nodes.get(seg2Pos + 1);
|
---|
143 |
|
---|
144 | int commonCount = 0;
|
---|
145 | //test if we have common nodes to add.
|
---|
146 | if (seg1Node1 == seg2Node1 || seg1Node1 == seg2Node2) {
|
---|
147 | commonCount++;
|
---|
148 |
|
---|
149 | if (seg1Way == seg2Way &&
|
---|
150 | seg1Pos == 0 &&
|
---|
151 | seg2Pos == way2Nodes.size() -2) {
|
---|
152 | //do not add - this is first and last segment of the same way.
|
---|
153 | } else {
|
---|
154 | intersectionNodes.add(seg1Node1);
|
---|
155 | }
|
---|
156 | }
|
---|
157 |
|
---|
158 | if (seg1Node2 == seg2Node1 || seg1Node2 == seg2Node2) {
|
---|
159 | commonCount++;
|
---|
160 |
|
---|
161 | intersectionNodes.add(seg1Node2);
|
---|
162 | }
|
---|
163 |
|
---|
164 | //no common nodes - find intersection
|
---|
165 | if (commonCount == 0) {
|
---|
166 | EastNorth intersection = getSegmentSegmentIntersection(
|
---|
167 | seg1Node1.getEastNorth(), seg1Node2.getEastNorth(),
|
---|
168 | seg2Node1.getEastNorth(), seg2Node2.getEastNorth());
|
---|
169 |
|
---|
170 | if (intersection != null) {
|
---|
171 | Node newNode = new Node(ProjectionRegistry.getProjection().eastNorth2latlon(intersection));
|
---|
172 | Node intNode = newNode;
|
---|
173 | boolean insertInSeg1 = false;
|
---|
174 | boolean insertInSeg2 = false;
|
---|
175 | //find if the intersection point is at end point of one of the segments, if so use that point
|
---|
176 |
|
---|
177 | //segment 1
|
---|
178 | if (coordsComparator.compare(newNode, seg1Node1) == 0) {
|
---|
179 | intNode = seg1Node1;
|
---|
180 | } else if (coordsComparator.compare(newNode, seg1Node2) == 0) {
|
---|
181 | intNode = seg1Node2;
|
---|
182 | } else {
|
---|
183 | insertInSeg1 = true;
|
---|
184 | }
|
---|
185 |
|
---|
186 | //segment 2
|
---|
187 | if (coordsComparator.compare(newNode, seg2Node1) == 0) {
|
---|
188 | intNode = seg2Node1;
|
---|
189 | } else if (coordsComparator.compare(newNode, seg2Node2) == 0) {
|
---|
190 | intNode = seg2Node2;
|
---|
191 | } else {
|
---|
192 | insertInSeg2 = true;
|
---|
193 | }
|
---|
194 |
|
---|
195 | if (test) {
|
---|
196 | intersectionNodes.add(intNode);
|
---|
197 | return intersectionNodes;
|
---|
198 | }
|
---|
199 |
|
---|
200 | if (insertInSeg1) {
|
---|
201 | way1Nodes.add(seg1Pos +1, intNode);
|
---|
202 | changedWays[seg1Way] = true;
|
---|
203 |
|
---|
204 | //fix seg2 position, as indexes have changed, seg2Pos is always bigger than seg1Pos on the same segment.
|
---|
205 | if (seg2Way == seg1Way) {
|
---|
206 | seg2Pos++;
|
---|
207 | }
|
---|
208 | }
|
---|
209 |
|
---|
210 | if (insertInSeg2) {
|
---|
211 | way2Nodes.add(seg2Pos +1, intNode);
|
---|
212 | changedWays[seg2Way] = true;
|
---|
213 |
|
---|
214 | //Do not need to compare again to already split segment
|
---|
215 | seg2Pos++;
|
---|
216 | }
|
---|
217 |
|
---|
218 | intersectionNodes.add(intNode);
|
---|
219 |
|
---|
220 | if (intNode == newNode) {
|
---|
221 | cmds.add(new AddCommand(dataset, intNode));
|
---|
222 | }
|
---|
223 | }
|
---|
224 | } else if (test && !intersectionNodes.isEmpty())
|
---|
225 | return intersectionNodes;
|
---|
226 | }
|
---|
227 | }
|
---|
228 | }
|
---|
229 | }
|
---|
230 |
|
---|
231 |
|
---|
232 | for (int pos = 0; pos < ways.size(); pos++) {
|
---|
233 | if (changedWays[pos]) {
|
---|
234 | cmds.add(new ChangeNodesCommand(dataset, ways.get(pos), newNodes[pos]));
|
---|
235 | }
|
---|
236 | }
|
---|
237 |
|
---|
238 | return intersectionNodes;
|
---|
239 | }
|
---|
240 |
|
---|
241 | /**
|
---|
242 | * Tests if given point is to the right side of path consisting of 3 points.
|
---|
243 | *
|
---|
244 | * (Imagine the path is continued beyond the endpoints, so you get two rays
|
---|
245 | * starting from lineP2 and going through lineP1 and lineP3 respectively
|
---|
246 | * which divide the plane into two parts. The test returns true, if testPoint
|
---|
247 | * lies in the part that is to the right when traveling in the direction
|
---|
248 | * lineP1, lineP2, lineP3.)
|
---|
249 | *
|
---|
250 | * @param <N> type of node
|
---|
251 | * @param lineP1 first point in path
|
---|
252 | * @param lineP2 second point in path
|
---|
253 | * @param lineP3 third point in path
|
---|
254 | * @param testPoint point to test
|
---|
255 | * @return true if to the right side, false otherwise
|
---|
256 | */
|
---|
257 | public static <N extends INode> boolean isToTheRightSideOfLine(N lineP1, N lineP2, N lineP3, N testPoint) {
|
---|
258 | boolean pathBendToRight = angleIsClockwise(lineP1, lineP2, lineP3);
|
---|
259 | boolean rightOfSeg1 = angleIsClockwise(lineP1, lineP2, testPoint);
|
---|
260 | boolean rightOfSeg2 = angleIsClockwise(lineP2, lineP3, testPoint);
|
---|
261 |
|
---|
262 | if (pathBendToRight)
|
---|
263 | return rightOfSeg1 && rightOfSeg2;
|
---|
264 | else
|
---|
265 | return !(!rightOfSeg1 && !rightOfSeg2);
|
---|
266 | }
|
---|
267 |
|
---|
268 | /**
|
---|
269 | * This method tests if secondNode is clockwise to first node.
|
---|
270 | * @param <N> type of node
|
---|
271 | * @param commonNode starting point for both vectors
|
---|
272 | * @param firstNode first vector end node
|
---|
273 | * @param secondNode second vector end node
|
---|
274 | * @return true if first vector is clockwise before second vector.
|
---|
275 | */
|
---|
276 | public static <N extends INode> boolean angleIsClockwise(N commonNode, N firstNode, N secondNode) {
|
---|
277 | return angleIsClockwise(commonNode.getEastNorth(), firstNode.getEastNorth(), secondNode.getEastNorth());
|
---|
278 | }
|
---|
279 |
|
---|
280 | /**
|
---|
281 | * Finds the intersection of two line segments.
|
---|
282 | * @param p1 the coordinates of the start point of the first specified line segment
|
---|
283 | * @param p2 the coordinates of the end point of the first specified line segment
|
---|
284 | * @param p3 the coordinates of the start point of the second specified line segment
|
---|
285 | * @param p4 the coordinates of the end point of the second specified line segment
|
---|
286 | * @return EastNorth null if no intersection was found, the EastNorth coordinates of the intersection otherwise
|
---|
287 | */
|
---|
288 | public static EastNorth getSegmentSegmentIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
|
---|
289 |
|
---|
290 | CheckParameterUtil.ensureThat(p1.isValid(), () -> p1 + " invalid");
|
---|
291 | CheckParameterUtil.ensureThat(p2.isValid(), () -> p2 + " invalid");
|
---|
292 | CheckParameterUtil.ensureThat(p3.isValid(), () -> p3 + " invalid");
|
---|
293 | CheckParameterUtil.ensureThat(p4.isValid(), () -> p4 + " invalid");
|
---|
294 |
|
---|
295 | double x1 = p1.getX();
|
---|
296 | double y1 = p1.getY();
|
---|
297 | double x2 = p2.getX();
|
---|
298 | double y2 = p2.getY();
|
---|
299 | double x3 = p3.getX();
|
---|
300 | double y3 = p3.getY();
|
---|
301 | double x4 = p4.getX();
|
---|
302 | double y4 = p4.getY();
|
---|
303 |
|
---|
304 | //TODO: do this locally.
|
---|
305 | //TODO: remove this check after careful testing
|
---|
306 | if (!Line2D.linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return null;
|
---|
307 |
|
---|
308 | // solve line-line intersection in parametric form:
|
---|
309 | // (x1,y1) + (x2-x1,y2-y1)* u = (x3,y3) + (x4-x3,y4-y3)* v
|
---|
310 | // (x2-x1,y2-y1)*u - (x4-x3,y4-y3)*v = (x3-x1,y3-y1)
|
---|
311 | // if 0<= u,v <=1, intersection exists at ( x1+ (x2-x1)*u, y1 + (y2-y1)*u )
|
---|
312 |
|
---|
313 | double a1 = x2 - x1;
|
---|
314 | double b1 = x3 - x4;
|
---|
315 | double c1 = x3 - x1;
|
---|
316 |
|
---|
317 | double a2 = y2 - y1;
|
---|
318 | double b2 = y3 - y4;
|
---|
319 | double c2 = y3 - y1;
|
---|
320 |
|
---|
321 | // Solve the equations
|
---|
322 | double det = a1*b2 - a2*b1;
|
---|
323 |
|
---|
324 | double uu = b2*c1 - b1*c2;
|
---|
325 | double vv = a1*c2 - a2*c1;
|
---|
326 | double mag = Math.abs(uu)+Math.abs(vv);
|
---|
327 |
|
---|
328 | if (Math.abs(det) > 1e-12 * mag) {
|
---|
329 | double u = uu/det, v = vv/det;
|
---|
330 | if (u > -1e-8 && u < 1+1e-8 && v > -1e-8 && v < 1+1e-8) {
|
---|
331 | if (u < 0) u = 0;
|
---|
332 | if (u > 1) u = 1.0;
|
---|
333 | return new EastNorth(x1+a1*u, y1+a2*u);
|
---|
334 | } else {
|
---|
335 | return null;
|
---|
336 | }
|
---|
337 | } else {
|
---|
338 | // parallel lines
|
---|
339 | return null;
|
---|
340 | }
|
---|
341 | }
|
---|
342 |
|
---|
343 | /**
|
---|
344 | * Finds the intersection of two lines of infinite length.
|
---|
345 | *
|
---|
346 | * @param p1 first point on first line
|
---|
347 | * @param p2 second point on first line
|
---|
348 | * @param p3 first point on second line
|
---|
349 | * @param p4 second point on second line
|
---|
350 | * @return EastNorth null if no intersection was found, the coordinates of the intersection otherwise
|
---|
351 | * @throws IllegalArgumentException if a parameter is null or without valid coordinates
|
---|
352 | */
|
---|
353 | public static EastNorth getLineLineIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
|
---|
354 |
|
---|
355 | CheckParameterUtil.ensureThat(p1.isValid(), () -> p1 + " invalid");
|
---|
356 | CheckParameterUtil.ensureThat(p2.isValid(), () -> p2 + " invalid");
|
---|
357 | CheckParameterUtil.ensureThat(p3.isValid(), () -> p3 + " invalid");
|
---|
358 | CheckParameterUtil.ensureThat(p4.isValid(), () -> p4 + " invalid");
|
---|
359 |
|
---|
360 | // Basically, the formula from wikipedia is used:
|
---|
361 | // https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
|
---|
362 | // However, large numbers lead to rounding errors (see #10286).
|
---|
363 | // To avoid this, p1 is first subtracted from each of the points:
|
---|
364 | // p1' = 0
|
---|
365 | // p2' = p2 - p1
|
---|
366 | // p3' = p3 - p1
|
---|
367 | // p4' = p4 - p1
|
---|
368 | // In the end, p1 is added to the intersection point of segment p1'/p2'
|
---|
369 | // and segment p3'/p4'.
|
---|
370 |
|
---|
371 | // Convert line from (point, point) form to ax+by=c
|
---|
372 | double a1 = p2.getY() - p1.getY();
|
---|
373 | double b1 = p1.getX() - p2.getX();
|
---|
374 |
|
---|
375 | double a2 = p4.getY() - p3.getY();
|
---|
376 | double b2 = p3.getX() - p4.getX();
|
---|
377 |
|
---|
378 | // Solve the equations
|
---|
379 | double det = a1 * b2 - a2 * b1;
|
---|
380 | if (det == 0)
|
---|
381 | return null; // Lines are parallel
|
---|
382 |
|
---|
383 | double c2 = (p4.getX() - p1.getX()) * (p3.getY() - p1.getY()) - (p3.getX() - p1.getX()) * (p4.getY() - p1.getY());
|
---|
384 |
|
---|
385 | return new EastNorth(b1 * c2 / det + p1.getX(), -a1 * c2 / det + p1.getY());
|
---|
386 | }
|
---|
387 |
|
---|
388 | /**
|
---|
389 | * Check if the segment p1 - p2 is parallel to p3 - p4
|
---|
390 | * @param p1 First point for first segment
|
---|
391 | * @param p2 Second point for first segment
|
---|
392 | * @param p3 First point for second segment
|
---|
393 | * @param p4 Second point for second segment
|
---|
394 | * @return <code>true</code> if they are parallel or close to parallel
|
---|
395 | */
|
---|
396 | public static boolean segmentsParallel(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
|
---|
397 |
|
---|
398 | CheckParameterUtil.ensureThat(p1.isValid(), () -> p1 + " invalid");
|
---|
399 | CheckParameterUtil.ensureThat(p2.isValid(), () -> p2 + " invalid");
|
---|
400 | CheckParameterUtil.ensureThat(p3.isValid(), () -> p3 + " invalid");
|
---|
401 | CheckParameterUtil.ensureThat(p4.isValid(), () -> p4 + " invalid");
|
---|
402 |
|
---|
403 | // Convert line from (point, point) form to ax+by=c
|
---|
404 | double a1 = p2.getY() - p1.getY();
|
---|
405 | double b1 = p1.getX() - p2.getX();
|
---|
406 |
|
---|
407 | double a2 = p4.getY() - p3.getY();
|
---|
408 | double b2 = p3.getX() - p4.getX();
|
---|
409 |
|
---|
410 | // Solve the equations
|
---|
411 | double det = a1 * b2 - a2 * b1;
|
---|
412 | // remove influence of of scaling factor
|
---|
413 | det /= Math.sqrt(a1*a1 + b1*b1) * Math.sqrt(a2*a2 + b2*b2);
|
---|
414 | return Math.abs(det) < 1e-3;
|
---|
415 | }
|
---|
416 |
|
---|
417 | private static EastNorth closestPointTo(EastNorth p1, EastNorth p2, EastNorth point, boolean segmentOnly) {
|
---|
418 | CheckParameterUtil.ensureParameterNotNull(p1, "p1");
|
---|
419 | CheckParameterUtil.ensureParameterNotNull(p2, "p2");
|
---|
420 | CheckParameterUtil.ensureParameterNotNull(point, "point");
|
---|
421 |
|
---|
422 | double ldx = p2.getX() - p1.getX();
|
---|
423 | double ldy = p2.getY() - p1.getY();
|
---|
424 |
|
---|
425 | //segment zero length
|
---|
426 | if (ldx == 0 && ldy == 0)
|
---|
427 | return p1;
|
---|
428 |
|
---|
429 | double pdx = point.getX() - p1.getX();
|
---|
430 | double pdy = point.getY() - p1.getY();
|
---|
431 |
|
---|
432 | double offset = (pdx * ldx + pdy * ldy) / (ldx * ldx + ldy * ldy);
|
---|
433 |
|
---|
434 | if (segmentOnly && offset <= 0)
|
---|
435 | return p1;
|
---|
436 | else if (segmentOnly && offset >= 1)
|
---|
437 | return p2;
|
---|
438 | else
|
---|
439 | return p1.interpolate(p2, offset);
|
---|
440 | }
|
---|
441 |
|
---|
442 | /**
|
---|
443 | * Calculates closest point to a line segment.
|
---|
444 | * @param segmentP1 First point determining line segment
|
---|
445 | * @param segmentP2 Second point determining line segment
|
---|
446 | * @param point Point for which a closest point is searched on line segment [P1,P2]
|
---|
447 | * @return segmentP1 if it is the closest point, segmentP2 if it is the closest point,
|
---|
448 | * a new point if closest point is between segmentP1 and segmentP2.
|
---|
449 | * @see #closestPointToLine
|
---|
450 | * @since 3650
|
---|
451 | */
|
---|
452 | public static EastNorth closestPointToSegment(EastNorth segmentP1, EastNorth segmentP2, EastNorth point) {
|
---|
453 | return closestPointTo(segmentP1, segmentP2, point, true);
|
---|
454 | }
|
---|
455 |
|
---|
456 | /**
|
---|
457 | * Calculates closest point to a line.
|
---|
458 | * @param lineP1 First point determining line
|
---|
459 | * @param lineP2 Second point determining line
|
---|
460 | * @param point Point for which a closest point is searched on line (P1,P2)
|
---|
461 | * @return The closest point found on line. It may be outside the segment [P1,P2].
|
---|
462 | * @see #closestPointToSegment
|
---|
463 | * @since 4134
|
---|
464 | */
|
---|
465 | public static EastNorth closestPointToLine(EastNorth lineP1, EastNorth lineP2, EastNorth point) {
|
---|
466 | return closestPointTo(lineP1, lineP2, point, false);
|
---|
467 | }
|
---|
468 |
|
---|
469 | /**
|
---|
470 | * This method tests if secondNode is clockwise to first node.
|
---|
471 | *
|
---|
472 | * The line through the two points commonNode and firstNode divides the
|
---|
473 | * plane into two parts. The test returns true, if secondNode lies in
|
---|
474 | * the part that is to the right when traveling in the direction from
|
---|
475 | * commonNode to firstNode.
|
---|
476 | *
|
---|
477 | * @param commonNode starting point for both vectors
|
---|
478 | * @param firstNode first vector end node
|
---|
479 | * @param secondNode second vector end node
|
---|
480 | * @return true if first vector is clockwise before second vector.
|
---|
481 | */
|
---|
482 | public static boolean angleIsClockwise(EastNorth commonNode, EastNorth firstNode, EastNorth secondNode) {
|
---|
483 |
|
---|
484 | CheckParameterUtil.ensureThat(commonNode.isValid(), () -> commonNode + " invalid");
|
---|
485 | CheckParameterUtil.ensureThat(firstNode.isValid(), () -> firstNode + " invalid");
|
---|
486 | CheckParameterUtil.ensureThat(secondNode.isValid(), () -> secondNode + " invalid");
|
---|
487 |
|
---|
488 | double dy1 = firstNode.getY() - commonNode.getY();
|
---|
489 | double dy2 = secondNode.getY() - commonNode.getY();
|
---|
490 | double dx1 = firstNode.getX() - commonNode.getX();
|
---|
491 | double dx2 = secondNode.getX() - commonNode.getX();
|
---|
492 |
|
---|
493 | return dy1 * dx2 - dx1 * dy2 > 0;
|
---|
494 | }
|
---|
495 |
|
---|
496 | /**
|
---|
497 | * Returns the Area of a polygon, from its list of nodes.
|
---|
498 | * @param polygon List of nodes forming polygon
|
---|
499 | * @return Area for the given list of nodes (EastNorth coordinates)
|
---|
500 | * @since 6841
|
---|
501 | */
|
---|
502 | public static Area getArea(List<? extends INode> polygon) {
|
---|
503 | Path2D path = new Path2D.Double();
|
---|
504 |
|
---|
505 | boolean begin = true;
|
---|
506 | for (INode n : polygon) {
|
---|
507 | EastNorth en = n.getEastNorth();
|
---|
508 | if (en != null) {
|
---|
509 | if (begin) {
|
---|
510 | path.moveTo(en.getX(), en.getY());
|
---|
511 | begin = false;
|
---|
512 | } else {
|
---|
513 | path.lineTo(en.getX(), en.getY());
|
---|
514 | }
|
---|
515 | }
|
---|
516 | }
|
---|
517 | if (!begin) {
|
---|
518 | path.closePath();
|
---|
519 | }
|
---|
520 |
|
---|
521 | return new Area(path);
|
---|
522 | }
|
---|
523 |
|
---|
524 | /**
|
---|
525 | * Builds a path from a list of nodes
|
---|
526 | * @param polygon Nodes, forming a closed polygon
|
---|
527 | * @param path2d path to add to; can be null, then a new path is created
|
---|
528 | * @return the path (LatLon coordinates)
|
---|
529 | * @since 13638 (signature)
|
---|
530 | */
|
---|
531 | public static Path2D buildPath2DLatLon(List<? extends ILatLon> polygon, Path2D path2d) {
|
---|
532 | Path2D path = path2d != null ? path2d : new Path2D.Double();
|
---|
533 | boolean begin = true;
|
---|
534 | for (ILatLon n : polygon) {
|
---|
535 | if (begin) {
|
---|
536 | path.moveTo(n.lon(), n.lat());
|
---|
537 | begin = false;
|
---|
538 | } else {
|
---|
539 | path.lineTo(n.lon(), n.lat());
|
---|
540 | }
|
---|
541 | }
|
---|
542 | if (!begin) {
|
---|
543 | path.closePath();
|
---|
544 | }
|
---|
545 | return path;
|
---|
546 | }
|
---|
547 |
|
---|
548 | /**
|
---|
549 | * Calculate area in east/north space for given primitive. Uses {@link MultipolygonCache} for multipolygon relations.
|
---|
550 | * @param p the primitive
|
---|
551 | * @return the area in east/north space, might be empty if the primitive is incomplete or not closed or a node
|
---|
552 | * since 15938
|
---|
553 | */
|
---|
554 | public static Area getAreaEastNorth(IPrimitive p) {
|
---|
555 | if (p instanceof Way && ((Way) p).isClosed()) {
|
---|
556 | return Geometry.getArea(((Way) p).getNodes());
|
---|
557 | }
|
---|
558 | if (p instanceof Relation && p.isMultipolygon() && !p.isIncomplete()) {
|
---|
559 | Multipolygon mp = MultipolygonCache.getInstance().get((Relation) p);
|
---|
560 | if (mp.getOpenEnds().isEmpty()) {
|
---|
561 | Path2D path = new Path2D.Double();
|
---|
562 | path.setWindingRule(Path2D.WIND_EVEN_ODD);
|
---|
563 | for (PolyData pd : mp.getCombinedPolygons()) {
|
---|
564 | path.append(pd.get(), false);
|
---|
565 | }
|
---|
566 | return new Area(path);
|
---|
567 | }
|
---|
568 | }
|
---|
569 | return new Area();
|
---|
570 | }
|
---|
571 |
|
---|
572 | /**
|
---|
573 | * Returns the Area of a polygon, from the multipolygon relation.
|
---|
574 | * @param multipolygon the multipolygon relation
|
---|
575 | * @return Area for the multipolygon (LatLon coordinates)
|
---|
576 | */
|
---|
577 | public static Area getAreaLatLon(Relation multipolygon) {
|
---|
578 | final Multipolygon mp = MultipolygonCache.getInstance().get(multipolygon);
|
---|
579 | Path2D path = new Path2D.Double();
|
---|
580 | path.setWindingRule(Path2D.WIND_EVEN_ODD);
|
---|
581 | for (Multipolygon.PolyData pd : mp.getCombinedPolygons()) {
|
---|
582 | buildPath2DLatLon(pd.getNodes(), path);
|
---|
583 | for (Multipolygon.PolyData pdInner : pd.getInners()) {
|
---|
584 | buildPath2DLatLon(pdInner.getNodes(), path);
|
---|
585 | }
|
---|
586 | }
|
---|
587 | return new Area(path);
|
---|
588 | }
|
---|
589 |
|
---|
590 | /**
|
---|
591 | * Tests if two polygons intersect.
|
---|
592 | * @param first List of nodes forming first polygon
|
---|
593 | * @param second List of nodes forming second polygon
|
---|
594 | * @return intersection kind
|
---|
595 | */
|
---|
596 | public static PolygonIntersection polygonIntersection(List<? extends INode> first, List<? extends INode> second) {
|
---|
597 | Area a1 = getArea(first);
|
---|
598 | Area a2 = getArea(second);
|
---|
599 | return polygonIntersection(a1, a2, INTERSECTION_EPS_EAST_NORTH);
|
---|
600 | }
|
---|
601 |
|
---|
602 | /**
|
---|
603 | * Tests if two polygons intersect. It is assumed that the area is given in East North points.
|
---|
604 | * @param a1 Area of first polygon
|
---|
605 | * @param a2 Area of second polygon
|
---|
606 | * @return intersection kind
|
---|
607 | * @since 6841
|
---|
608 | */
|
---|
609 | public static PolygonIntersection polygonIntersection(Area a1, Area a2) {
|
---|
610 | return polygonIntersection(a1, a2, INTERSECTION_EPS_EAST_NORTH);
|
---|
611 | }
|
---|
612 |
|
---|
613 | /**
|
---|
614 | * Tests if two polygons intersect.
|
---|
615 | * @param a1 Area of first polygon
|
---|
616 | * @param a2 Area of second polygon
|
---|
617 | * @param eps an area threshold, everything below is considered an empty intersection
|
---|
618 | * @return intersection kind
|
---|
619 | */
|
---|
620 | public static PolygonIntersection polygonIntersection(Area a1, Area a2, double eps) {
|
---|
621 | return polygonIntersectionResult(a1, a2, eps).a;
|
---|
622 | }
|
---|
623 |
|
---|
624 | /**
|
---|
625 | * Calculate intersection area and kind of intersection between two polygons.
|
---|
626 | * @param a1 Area of first polygon
|
---|
627 | * @param a2 Area of second polygon
|
---|
628 | * @param eps an area threshold, everything below is considered an empty intersection
|
---|
629 | * @return pair with intersection kind and intersection area (never null, but maybe empty)
|
---|
630 | * @since 15938
|
---|
631 | */
|
---|
632 | public static Pair<PolygonIntersection, Area> polygonIntersectionResult(Area a1, Area a2, double eps) {
|
---|
633 | Area inter = new Area(a1);
|
---|
634 | inter.intersect(a2);
|
---|
635 |
|
---|
636 | if (inter.isEmpty() || !checkIntersection(inter, eps)) {
|
---|
637 | return new Pair<>(PolygonIntersection.OUTSIDE, inter);
|
---|
638 | } else if (a2.getBounds2D().contains(a1.getBounds2D()) && inter.equals(a1)) {
|
---|
639 | return new Pair<>(PolygonIntersection.FIRST_INSIDE_SECOND, inter);
|
---|
640 | } else if (a1.getBounds2D().contains(a2.getBounds2D()) && inter.equals(a2)) {
|
---|
641 | return new Pair<>(PolygonIntersection.SECOND_INSIDE_FIRST, inter);
|
---|
642 | } else {
|
---|
643 | return new Pair<>(PolygonIntersection.CROSSING, inter);
|
---|
644 | }
|
---|
645 | }
|
---|
646 |
|
---|
647 | /**
|
---|
648 | * Check an intersection area which might describe multiple small polygons.
|
---|
649 | * Return true if any of the polygons is bigger than the given threshold.
|
---|
650 | * @param inter the intersection area
|
---|
651 | * @param eps an area threshold, everything below is considered an empty intersection
|
---|
652 | * @return true if any of the polygons is bigger than the given threshold
|
---|
653 | */
|
---|
654 | private static boolean checkIntersection(Area inter, double eps) {
|
---|
655 | PathIterator pit = inter.getPathIterator(null);
|
---|
656 | double[] res = new double[6];
|
---|
657 | Rectangle2D r = new Rectangle2D.Double();
|
---|
658 | while (!pit.isDone()) {
|
---|
659 | int type = pit.currentSegment(res);
|
---|
660 | switch (type) {
|
---|
661 | case PathIterator.SEG_MOVETO:
|
---|
662 | r = new Rectangle2D.Double(res[0], res[1], 0, 0);
|
---|
663 | break;
|
---|
664 | case PathIterator.SEG_LINETO:
|
---|
665 | r.add(res[0], res[1]);
|
---|
666 | break;
|
---|
667 | case PathIterator.SEG_CLOSE:
|
---|
668 | if (r.getWidth() > eps || r.getHeight() > eps)
|
---|
669 | return true;
|
---|
670 | break;
|
---|
671 | default:
|
---|
672 | break;
|
---|
673 | }
|
---|
674 | pit.next();
|
---|
675 | }
|
---|
676 | return false;
|
---|
677 | }
|
---|
678 |
|
---|
679 | /**
|
---|
680 | * Tests if point is inside a polygon. The polygon can be self-intersecting. In such case the contains function works in xor-like manner.
|
---|
681 | * @param polygonNodes list of nodes from polygon path.
|
---|
682 | * @param point the point to test
|
---|
683 | * @return true if the point is inside polygon.
|
---|
684 | */
|
---|
685 | public static boolean nodeInsidePolygon(INode point, List<? extends INode> polygonNodes) {
|
---|
686 | if (polygonNodes.size() < 2)
|
---|
687 | return false;
|
---|
688 |
|
---|
689 | //iterate each side of the polygon, start with the last segment
|
---|
690 | INode oldPoint = polygonNodes.get(polygonNodes.size() - 1);
|
---|
691 |
|
---|
692 | if (!oldPoint.isLatLonKnown()) {
|
---|
693 | return false;
|
---|
694 | }
|
---|
695 |
|
---|
696 | boolean inside = false;
|
---|
697 | INode p1, p2;
|
---|
698 |
|
---|
699 | for (INode newPoint : polygonNodes) {
|
---|
700 | //skip duplicate points
|
---|
701 | if (newPoint.equals(oldPoint)) {
|
---|
702 | continue;
|
---|
703 | }
|
---|
704 |
|
---|
705 | if (!newPoint.isLatLonKnown()) {
|
---|
706 | return false;
|
---|
707 | }
|
---|
708 |
|
---|
709 | //order points so p1.lat <= p2.lat
|
---|
710 | if (newPoint.getEastNorth().getY() > oldPoint.getEastNorth().getY()) {
|
---|
711 | p1 = oldPoint;
|
---|
712 | p2 = newPoint;
|
---|
713 | } else {
|
---|
714 | p1 = newPoint;
|
---|
715 | p2 = oldPoint;
|
---|
716 | }
|
---|
717 |
|
---|
718 | EastNorth pEN = point.getEastNorth();
|
---|
719 | EastNorth opEN = oldPoint.getEastNorth();
|
---|
720 | EastNorth npEN = newPoint.getEastNorth();
|
---|
721 | EastNorth p1EN = p1.getEastNorth();
|
---|
722 | EastNorth p2EN = p2.getEastNorth();
|
---|
723 |
|
---|
724 | if (pEN != null && opEN != null && npEN != null && p1EN != null && p2EN != null) {
|
---|
725 | //test if the line is crossed and if so invert the inside flag.
|
---|
726 | if ((npEN.getY() < pEN.getY()) == (pEN.getY() <= opEN.getY())
|
---|
727 | && (pEN.getX() - p1EN.getX()) * (p2EN.getY() - p1EN.getY())
|
---|
728 | < (p2EN.getX() - p1EN.getX()) * (pEN.getY() - p1EN.getY())) {
|
---|
729 | inside = !inside;
|
---|
730 | }
|
---|
731 | }
|
---|
732 |
|
---|
733 | oldPoint = newPoint;
|
---|
734 | }
|
---|
735 |
|
---|
736 | return inside;
|
---|
737 | }
|
---|
738 |
|
---|
739 | /**
|
---|
740 | * Returns area of a closed way in square meters.
|
---|
741 | *
|
---|
742 | * @param way Way to measure, should be closed (first node is the same as last node)
|
---|
743 | * @return area of the closed way.
|
---|
744 | */
|
---|
745 | public static double closedWayArea(Way way) {
|
---|
746 | return getAreaAndPerimeter(way.getNodes(), Projections.getProjectionByCode("EPSG:54008")).getArea();
|
---|
747 | }
|
---|
748 |
|
---|
749 | /**
|
---|
750 | * Returns area of a multipolygon in square meters.
|
---|
751 | *
|
---|
752 | * @param multipolygon the multipolygon to measure
|
---|
753 | * @return area of the multipolygon.
|
---|
754 | */
|
---|
755 | public static double multipolygonArea(Relation multipolygon) {
|
---|
756 | final Multipolygon mp = MultipolygonCache.getInstance().get(multipolygon);
|
---|
757 | return mp.getCombinedPolygons().stream()
|
---|
758 | .mapToDouble(pd -> pd.getAreaAndPerimeter(Projections.getProjectionByCode("EPSG:54008")).getArea())
|
---|
759 | .sum();
|
---|
760 | }
|
---|
761 |
|
---|
762 | /**
|
---|
763 | * Computes the area of a closed way and multipolygon in square meters, or {@code null} for other primitives
|
---|
764 | *
|
---|
765 | * @param osm the primitive to measure
|
---|
766 | * @return area of the primitive, or {@code null}
|
---|
767 | * @since 13638 (signature)
|
---|
768 | */
|
---|
769 | public static Double computeArea(IPrimitive osm) {
|
---|
770 | if (osm instanceof Way && ((Way) osm).isClosed()) {
|
---|
771 | return closedWayArea((Way) osm);
|
---|
772 | } else if (osm instanceof Relation && ((Relation) osm).isMultipolygon() && !((Relation) osm).hasIncompleteMembers()) {
|
---|
773 | return multipolygonArea((Relation) osm);
|
---|
774 | } else {
|
---|
775 | return null;
|
---|
776 | }
|
---|
777 | }
|
---|
778 |
|
---|
779 | /**
|
---|
780 | * Determines whether a way is oriented clockwise.
|
---|
781 | *
|
---|
782 | * Internals: Assuming a closed non-looping way, compute twice the area
|
---|
783 | * of the polygon using the formula {@code 2 * area = sum (X[n] * Y[n+1] - X[n+1] * Y[n])}.
|
---|
784 | * If the area is negative the way is ordered in a clockwise direction.
|
---|
785 | *
|
---|
786 | * See http://paulbourke.net/geometry/polyarea/
|
---|
787 | *
|
---|
788 | * @param w the way to be checked.
|
---|
789 | * @return true if and only if way is oriented clockwise.
|
---|
790 | * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}).
|
---|
791 | */
|
---|
792 | public static boolean isClockwise(Way w) {
|
---|
793 | return isClockwise(w.getNodes());
|
---|
794 | }
|
---|
795 |
|
---|
796 | /**
|
---|
797 | * Determines whether path from nodes list is oriented clockwise.
|
---|
798 | * @param nodes Nodes list to be checked.
|
---|
799 | * @return true if and only if way is oriented clockwise.
|
---|
800 | * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}).
|
---|
801 | * @see #isClockwise(Way)
|
---|
802 | */
|
---|
803 | public static boolean isClockwise(List<? extends INode> nodes) {
|
---|
804 | int nodesCount = nodes.size();
|
---|
805 | if (nodesCount < 3 || nodes.get(0) != nodes.get(nodesCount - 1)) {
|
---|
806 | throw new IllegalArgumentException("Way must be closed to check orientation.");
|
---|
807 | }
|
---|
808 | double area2 = 0.;
|
---|
809 |
|
---|
810 | for (int node = 1; node <= /*sic! consider last-first as well*/ nodesCount; node++) {
|
---|
811 | INode coorPrev = nodes.get(node - 1);
|
---|
812 | INode coorCurr = nodes.get(node % nodesCount);
|
---|
813 | area2 += coorPrev.lon() * coorCurr.lat();
|
---|
814 | area2 -= coorCurr.lon() * coorPrev.lat();
|
---|
815 | }
|
---|
816 | return area2 < 0;
|
---|
817 | }
|
---|
818 |
|
---|
819 | /**
|
---|
820 | * Returns angle of a segment defined with 2 point coordinates.
|
---|
821 | *
|
---|
822 | * @param p1 first point
|
---|
823 | * @param p2 second point
|
---|
824 | * @return Angle in radians (-pi, pi]
|
---|
825 | */
|
---|
826 | public static double getSegmentAngle(EastNorth p1, EastNorth p2) {
|
---|
827 |
|
---|
828 | CheckParameterUtil.ensureThat(p1.isValid(), () -> p1 + " invalid");
|
---|
829 | CheckParameterUtil.ensureThat(p2.isValid(), () -> p2 + " invalid");
|
---|
830 |
|
---|
831 | return Math.atan2(p2.north() - p1.north(), p2.east() - p1.east());
|
---|
832 | }
|
---|
833 |
|
---|
834 | /**
|
---|
835 | * Returns angle of a corner defined with 3 point coordinates.
|
---|
836 | *
|
---|
837 | * @param p1 first point
|
---|
838 | * @param common Common end point
|
---|
839 | * @param p3 third point
|
---|
840 | * @return Angle in radians (-pi, pi]
|
---|
841 | */
|
---|
842 | public static double getCornerAngle(EastNorth p1, EastNorth common, EastNorth p3) {
|
---|
843 |
|
---|
844 | CheckParameterUtil.ensureThat(p1.isValid(), () -> p1 + " invalid");
|
---|
845 | CheckParameterUtil.ensureThat(common.isValid(), () -> common + " invalid");
|
---|
846 | CheckParameterUtil.ensureThat(p3.isValid(), () -> p3 + " invalid");
|
---|
847 |
|
---|
848 | double result = getSegmentAngle(common, p1) - getSegmentAngle(common, p3);
|
---|
849 | if (result <= -Math.PI) {
|
---|
850 | result += 2 * Math.PI;
|
---|
851 | }
|
---|
852 |
|
---|
853 | if (result > Math.PI) {
|
---|
854 | result -= 2 * Math.PI;
|
---|
855 | }
|
---|
856 |
|
---|
857 | return result;
|
---|
858 | }
|
---|
859 |
|
---|
860 | /**
|
---|
861 | * Get angles in radians and return it's value in range [0, 180].
|
---|
862 | *
|
---|
863 | * @param angle the angle in radians
|
---|
864 | * @return normalized angle in degrees
|
---|
865 | * @since 13670
|
---|
866 | */
|
---|
867 | public static double getNormalizedAngleInDegrees(double angle) {
|
---|
868 | return Math.abs(180 * angle / Math.PI);
|
---|
869 | }
|
---|
870 |
|
---|
871 | /**
|
---|
872 | * Compute the centroid/barycenter of nodes
|
---|
873 | * @param nodes Nodes for which the centroid is wanted
|
---|
874 | * @return the centroid of nodes
|
---|
875 | * @see Geometry#getCenter
|
---|
876 | */
|
---|
877 | public static EastNorth getCentroid(List<? extends INode> nodes) {
|
---|
878 | return getCentroidEN(nodes.stream().map(INode::getEastNorth).collect(Collectors.toList()));
|
---|
879 | }
|
---|
880 |
|
---|
881 | /**
|
---|
882 | * Compute the centroid/barycenter of nodes
|
---|
883 | * @param nodes Coordinates for which the centroid is wanted
|
---|
884 | * @return the centroid of nodes
|
---|
885 | * @since 13712
|
---|
886 | */
|
---|
887 | public static EastNorth getCentroidEN(List<EastNorth> nodes) {
|
---|
888 |
|
---|
889 | final int size = nodes.size();
|
---|
890 | if (size == 1) {
|
---|
891 | return nodes.get(0);
|
---|
892 | } else if (size == 2) {
|
---|
893 | return nodes.get(0).getCenter(nodes.get(1));
|
---|
894 | }
|
---|
895 |
|
---|
896 | BigDecimal area = BigDecimal.ZERO;
|
---|
897 | BigDecimal north = BigDecimal.ZERO;
|
---|
898 | BigDecimal east = BigDecimal.ZERO;
|
---|
899 |
|
---|
900 | // See https://en.wikipedia.org/wiki/Centroid#Of_a_polygon for the equation used here
|
---|
901 | for (int i = 0; i < size; i++) {
|
---|
902 | EastNorth n0 = nodes.get(i);
|
---|
903 | EastNorth n1 = nodes.get((i+1) % size);
|
---|
904 |
|
---|
905 | if (n0 != null && n1 != null && n0.isValid() && n1.isValid()) {
|
---|
906 | BigDecimal x0 = BigDecimal.valueOf(n0.east());
|
---|
907 | BigDecimal y0 = BigDecimal.valueOf(n0.north());
|
---|
908 | BigDecimal x1 = BigDecimal.valueOf(n1.east());
|
---|
909 | BigDecimal y1 = BigDecimal.valueOf(n1.north());
|
---|
910 |
|
---|
911 | BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128));
|
---|
912 |
|
---|
913 | area = area.add(k, MathContext.DECIMAL128);
|
---|
914 | east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128));
|
---|
915 | north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128));
|
---|
916 | }
|
---|
917 | }
|
---|
918 |
|
---|
919 | BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3
|
---|
920 | area = area.multiply(d, MathContext.DECIMAL128);
|
---|
921 | if (area.compareTo(BigDecimal.ZERO) != 0) {
|
---|
922 | north = north.divide(area, MathContext.DECIMAL128);
|
---|
923 | east = east.divide(area, MathContext.DECIMAL128);
|
---|
924 | }
|
---|
925 |
|
---|
926 | return new EastNorth(east.doubleValue(), north.doubleValue());
|
---|
927 | }
|
---|
928 |
|
---|
929 | /**
|
---|
930 | * Compute center of the circle closest to different nodes.
|
---|
931 | *
|
---|
932 | * Ensure exact center computation in case nodes are already aligned in circle.
|
---|
933 | * This is done by least square method.
|
---|
934 | * Let be a_i x + b_i y + c_i = 0 equations of bisectors of each edges.
|
---|
935 | * Center must be intersection of all bisectors.
|
---|
936 | * <pre>
|
---|
937 | * [ a1 b1 ] [ -c1 ]
|
---|
938 | * With A = [ ... ... ] and Y = [ ... ]
|
---|
939 | * [ an bn ] [ -cn ]
|
---|
940 | * </pre>
|
---|
941 | * An approximation of center of circle is (At.A)^-1.At.Y
|
---|
942 | * @param nodes Nodes parts of the circle (at least 3)
|
---|
943 | * @return An approximation of the center, of null if there is no solution.
|
---|
944 | * @see Geometry#getCentroid
|
---|
945 | * @since 6934
|
---|
946 | */
|
---|
947 | public static EastNorth getCenter(List<? extends INode> nodes) {
|
---|
948 | int nc = nodes.size();
|
---|
949 | if (nc < 3) return null;
|
---|
950 | /**
|
---|
951 | * Equation of each bisector ax + by + c = 0
|
---|
952 | */
|
---|
953 | double[] a = new double[nc];
|
---|
954 | double[] b = new double[nc];
|
---|
955 | double[] c = new double[nc];
|
---|
956 | // Compute equation of bisector
|
---|
957 | for (int i = 0; i < nc; i++) {
|
---|
958 | EastNorth pt1 = nodes.get(i).getEastNorth();
|
---|
959 | EastNorth pt2 = nodes.get((i+1) % nc).getEastNorth();
|
---|
960 | a[i] = pt1.east() - pt2.east();
|
---|
961 | b[i] = pt1.north() - pt2.north();
|
---|
962 | double d = Math.sqrt(a[i]*a[i] + b[i]*b[i]);
|
---|
963 | if (d == 0) return null;
|
---|
964 | a[i] /= d;
|
---|
965 | b[i] /= d;
|
---|
966 | double xC = (pt1.east() + pt2.east()) / 2;
|
---|
967 | double yC = (pt1.north() + pt2.north()) / 2;
|
---|
968 | c[i] = -(a[i]*xC + b[i]*yC);
|
---|
969 | }
|
---|
970 | // At.A = [aij]
|
---|
971 | double a11 = 0, a12 = 0, a22 = 0;
|
---|
972 | // At.Y = [bi]
|
---|
973 | double b1 = 0, b2 = 0;
|
---|
974 | for (int i = 0; i < nc; i++) {
|
---|
975 | a11 += a[i]*a[i];
|
---|
976 | a12 += a[i]*b[i];
|
---|
977 | a22 += b[i]*b[i];
|
---|
978 | b1 -= a[i]*c[i];
|
---|
979 | b2 -= b[i]*c[i];
|
---|
980 | }
|
---|
981 | // (At.A)^-1 = [invij]
|
---|
982 | double det = a11*a22 - a12*a12;
|
---|
983 | if (Math.abs(det) < 1e-5) return null;
|
---|
984 | double inv11 = a22/det;
|
---|
985 | double inv12 = -a12/det;
|
---|
986 | double inv22 = a11/det;
|
---|
987 | // center (xC, yC) = (At.A)^-1.At.y
|
---|
988 | double xC = inv11*b1 + inv12*b2;
|
---|
989 | double yC = inv12*b1 + inv22*b2;
|
---|
990 | return new EastNorth(xC, yC);
|
---|
991 | }
|
---|
992 |
|
---|
993 | /**
|
---|
994 | * Tests if the {@code node} is inside the multipolygon {@code multiPolygon}. The nullable argument
|
---|
995 | * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
|
---|
996 | * For repeated tests against {@code multiPolygon} better use {@link Geometry#filterInsideMultipolygon}.
|
---|
997 | * @param node node
|
---|
998 | * @param multiPolygon multipolygon
|
---|
999 | * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match
|
---|
1000 | * @return {@code true} if the node is inside the multipolygon
|
---|
1001 | */
|
---|
1002 | public static boolean isNodeInsideMultiPolygon(INode node, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
|
---|
1003 | return isPolygonInsideMultiPolygon(Collections.singletonList(node), multiPolygon, isOuterWayAMatch);
|
---|
1004 | }
|
---|
1005 |
|
---|
1006 | /**
|
---|
1007 | * Tests if the polygon formed by {@code nodes} is inside the multipolygon {@code multiPolygon}. The nullable argument
|
---|
1008 | * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
|
---|
1009 | * For repeated tests against {@code multiPolygon} better use {@link Geometry#filterInsideMultipolygon}.
|
---|
1010 | * <p>
|
---|
1011 | * If {@code nodes} contains exactly one element, then it is checked whether that one node is inside the multipolygon.
|
---|
1012 | * @param nodes nodes forming the polygon
|
---|
1013 | * @param multiPolygon multipolygon
|
---|
1014 | * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match
|
---|
1015 | * @return {@code true} if the multipolygon is valid and the polygon formed by nodes is inside the multipolygon
|
---|
1016 | */
|
---|
1017 | public static boolean isPolygonInsideMultiPolygon(List<? extends INode> nodes, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
|
---|
1018 | try {
|
---|
1019 | return isPolygonInsideMultiPolygon(nodes, MultipolygonBuilder.joinWays(multiPolygon), isOuterWayAMatch);
|
---|
1020 | } catch (MultipolygonBuilder.JoinedPolygonCreationException ex) {
|
---|
1021 | Logging.trace(ex);
|
---|
1022 | Logging.debug("Invalid multipolygon " + multiPolygon);
|
---|
1023 | return false;
|
---|
1024 | }
|
---|
1025 | }
|
---|
1026 |
|
---|
1027 | /**
|
---|
1028 | * Tests if the polygon formed by {@code nodes} is inside the multipolygon {@code multiPolygon}. The nullable argument
|
---|
1029 | * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
|
---|
1030 | * For repeated tests against {@code multiPolygon} better use {@link Geometry#filterInsideMultipolygon}.
|
---|
1031 | * <p>
|
---|
1032 | * If {@code nodes} contains exactly one element, then it is checked whether that one node is inside the multipolygon.
|
---|
1033 | * @param nodes nodes forming the polygon
|
---|
1034 | * @param outerInner result of {@link MultipolygonBuilder#joinWays(Relation)}
|
---|
1035 | * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match
|
---|
1036 | * @return {@code true} if the multipolygon is valid and the polygon formed by nodes is inside the multipolygon
|
---|
1037 | * @since 15069
|
---|
1038 | */
|
---|
1039 | public static boolean isPolygonInsideMultiPolygon(List<? extends INode> nodes, Pair<List<JoinedPolygon>,
|
---|
1040 | List<JoinedPolygon>> outerInner, Predicate<Way> isOuterWayAMatch) {
|
---|
1041 | Area a1 = nodes.size() == 1 ? null : getArea(nodes);
|
---|
1042 | // Test if object is inside an outer member
|
---|
1043 | for (JoinedPolygon out : outerInner.a) {
|
---|
1044 | if (a1 == null
|
---|
1045 | ? nodeInsidePolygon(nodes.get(0), out.nodes)
|
---|
1046 | : PolygonIntersection.FIRST_INSIDE_SECOND == polygonIntersection(a1, out.area)) {
|
---|
1047 | // If inside an outer, check it is not inside an inner
|
---|
1048 | boolean insideInner = outerInner.b.stream().anyMatch(in -> a1 == null
|
---|
1049 | ? nodeInsidePolygon(nodes.get(0), in.nodes)
|
---|
1050 | : in.area.getBounds2D().contains(a1.getBounds2D())
|
---|
1051 | && polygonIntersection(a1, in.area) == PolygonIntersection.FIRST_INSIDE_SECOND
|
---|
1052 | && polygonIntersection(in.area, out.area) == PolygonIntersection.FIRST_INSIDE_SECOND);
|
---|
1053 | if (!insideInner) {
|
---|
1054 | // Final check using predicate
|
---|
1055 | if (isOuterWayAMatch == null || isOuterWayAMatch.test(out.ways.get(0)
|
---|
1056 | /* TODO give a better representation of the outer ring to the predicate */)) {
|
---|
1057 | return true;
|
---|
1058 | }
|
---|
1059 | }
|
---|
1060 | }
|
---|
1061 | }
|
---|
1062 | return false;
|
---|
1063 | }
|
---|
1064 |
|
---|
1065 | /**
|
---|
1066 | * Find all primitives in the given collection which are inside the given polygon.
|
---|
1067 | *
|
---|
1068 | * @param primitives the primitives
|
---|
1069 | * @param polygon the closed way or multipolygon relation
|
---|
1070 | * @return a new list containing the found primitives, empty if polygon is invalid or nothing was found.
|
---|
1071 | * @see Geometry#filterInsidePolygon
|
---|
1072 | * @see Geometry#filterInsideMultipolygon
|
---|
1073 | * @since 15730
|
---|
1074 | */
|
---|
1075 | public static List<IPrimitive> filterInsideAnyPolygon(Collection<IPrimitive> primitives, IPrimitive polygon) {
|
---|
1076 | if (polygon instanceof IWay<?>) {
|
---|
1077 | return filterInsidePolygon(primitives, (IWay<?>) polygon);
|
---|
1078 | } else if (polygon instanceof Relation && polygon.isMultipolygon()) {
|
---|
1079 | return filterInsideMultipolygon(primitives, (Relation) polygon);
|
---|
1080 | }
|
---|
1081 | return Collections.emptyList();
|
---|
1082 | }
|
---|
1083 |
|
---|
1084 | /**
|
---|
1085 | * Find all primitives in the given collection which are inside the given polygon.
|
---|
1086 | * Unclosed ways and multipolygon relations with unclosed outer rings are ignored.
|
---|
1087 | *
|
---|
1088 | * @param primitives the primitives
|
---|
1089 | * @param polygon the polygon
|
---|
1090 | * @return a new list containing the found primitives, empty if polygon is invalid or nothing was found.
|
---|
1091 | * @since 15069 (for {@link List} of {@code primitives}, 15730 for a {@link Collection} of {@code primitives})
|
---|
1092 | */
|
---|
1093 | public static List<IPrimitive> filterInsidePolygon(Collection<IPrimitive> primitives, IWay<?> polygon) {
|
---|
1094 | List<IPrimitive> res = new ArrayList<>();
|
---|
1095 | if (!polygon.isClosed() || polygon.getNodesCount() <= 3)
|
---|
1096 | return res;
|
---|
1097 | /** polygon area in east north space, calculated only when really needed */
|
---|
1098 | Area polygonArea = null;
|
---|
1099 | for (IPrimitive p : primitives) {
|
---|
1100 | if (p instanceof INode) {
|
---|
1101 | if (nodeInsidePolygon((INode) p, polygon.getNodes())) {
|
---|
1102 | res.add(p);
|
---|
1103 | }
|
---|
1104 | } else if (p instanceof IWay) {
|
---|
1105 | if (((IWay<?>) p).isClosed()) {
|
---|
1106 | if (polygonArea == null) {
|
---|
1107 | polygonArea = getArea(polygon.getNodes());
|
---|
1108 | }
|
---|
1109 | if (PolygonIntersection.FIRST_INSIDE_SECOND == polygonIntersection(getArea(((IWay<?>) p).getNodes()),
|
---|
1110 | polygonArea)) {
|
---|
1111 | res.add(p);
|
---|
1112 | }
|
---|
1113 | }
|
---|
1114 | } else if (p.isMultipolygon()) {
|
---|
1115 | if (polygonArea == null) {
|
---|
1116 | polygonArea = getArea(polygon.getNodes());
|
---|
1117 | }
|
---|
1118 | Multipolygon mp = new Multipolygon((Relation) p);
|
---|
1119 | boolean inside = true;
|
---|
1120 | // a (valid) multipolygon is inside the polygon if all outer rings are inside
|
---|
1121 | for (PolyData outer : mp.getOuterPolygons()) {
|
---|
1122 | if (!outer.isClosed()
|
---|
1123 | || PolygonIntersection.FIRST_INSIDE_SECOND != polygonIntersection(getArea(outer.getNodes()),
|
---|
1124 | polygonArea)) {
|
---|
1125 | inside = false;
|
---|
1126 | break;
|
---|
1127 | }
|
---|
1128 | }
|
---|
1129 | if (inside) {
|
---|
1130 | res.add(p);
|
---|
1131 | }
|
---|
1132 | }
|
---|
1133 | }
|
---|
1134 | return res;
|
---|
1135 | }
|
---|
1136 |
|
---|
1137 | /**
|
---|
1138 | * Find all primitives in the given collection which are inside the given multipolygon. Members of the multipolygon are
|
---|
1139 | * ignored. Unclosed ways and multipolygon relations with unclosed outer rings are ignored.
|
---|
1140 | * @param primitives the primitives
|
---|
1141 | * @param multiPolygon the multipolygon relation
|
---|
1142 | * @return a new list containing the found primitives, empty if multipolygon is invalid or nothing was found.
|
---|
1143 | * @since 15069
|
---|
1144 | */
|
---|
1145 | public static List<IPrimitive> filterInsideMultipolygon(Collection<IPrimitive> primitives, Relation multiPolygon) {
|
---|
1146 | List<IPrimitive> res = new ArrayList<>();
|
---|
1147 | if (primitives.isEmpty())
|
---|
1148 | return res;
|
---|
1149 |
|
---|
1150 | final Pair<List<JoinedPolygon>, List<JoinedPolygon>> outerInner;
|
---|
1151 | try {
|
---|
1152 | outerInner = MultipolygonBuilder.joinWays(multiPolygon);
|
---|
1153 | } catch (MultipolygonBuilder.JoinedPolygonCreationException ex) {
|
---|
1154 | Logging.trace(ex);
|
---|
1155 | Logging.debug("Invalid multipolygon " + multiPolygon);
|
---|
1156 | return res;
|
---|
1157 | }
|
---|
1158 |
|
---|
1159 | Set<OsmPrimitive> members = multiPolygon.getMemberPrimitives();
|
---|
1160 | for (IPrimitive p : primitives) {
|
---|
1161 | if (members.contains(p))
|
---|
1162 | continue;
|
---|
1163 | if (p instanceof Node) {
|
---|
1164 | if (isPolygonInsideMultiPolygon(Collections.singletonList((Node) p), outerInner, null)) {
|
---|
1165 | res.add(p);
|
---|
1166 | }
|
---|
1167 | } else if (p instanceof Way) {
|
---|
1168 | if (((IWay<?>) p).isClosed() && isPolygonInsideMultiPolygon(((Way) p).getNodes(), outerInner, null)) {
|
---|
1169 | res.add(p);
|
---|
1170 | }
|
---|
1171 | } else if (p.isMultipolygon()) {
|
---|
1172 | Multipolygon mp = new Multipolygon((Relation) p);
|
---|
1173 | // a (valid) multipolygon is inside multiPolygon if all outer rings are inside
|
---|
1174 | boolean inside = mp.getOuterPolygons().stream()
|
---|
1175 | .allMatch(outer -> outer.isClosed() && isPolygonInsideMultiPolygon(outer.getNodes(), outerInner, null));
|
---|
1176 | if (inside) {
|
---|
1177 | res.add(p);
|
---|
1178 | }
|
---|
1179 | }
|
---|
1180 | }
|
---|
1181 | return res;
|
---|
1182 | }
|
---|
1183 |
|
---|
1184 | /**
|
---|
1185 | * Data class to hold two double values (area and perimeter of a polygon).
|
---|
1186 | */
|
---|
1187 | public static class AreaAndPerimeter {
|
---|
1188 | private final double area;
|
---|
1189 | private final double perimeter;
|
---|
1190 |
|
---|
1191 | /**
|
---|
1192 | * Create a new {@link AreaAndPerimeter}
|
---|
1193 | * @param area The area
|
---|
1194 | * @param perimeter The perimeter
|
---|
1195 | */
|
---|
1196 | public AreaAndPerimeter(double area, double perimeter) {
|
---|
1197 | this.area = area;
|
---|
1198 | this.perimeter = perimeter;
|
---|
1199 | }
|
---|
1200 |
|
---|
1201 | /**
|
---|
1202 | * Gets the area
|
---|
1203 | * @return The area size
|
---|
1204 | */
|
---|
1205 | public double getArea() {
|
---|
1206 | return area;
|
---|
1207 | }
|
---|
1208 |
|
---|
1209 | /**
|
---|
1210 | * Gets the perimeter
|
---|
1211 | * @return The perimeter length
|
---|
1212 | */
|
---|
1213 | public double getPerimeter() {
|
---|
1214 | return perimeter;
|
---|
1215 | }
|
---|
1216 | }
|
---|
1217 |
|
---|
1218 | /**
|
---|
1219 | * Calculate area and perimeter length of a polygon.
|
---|
1220 | *
|
---|
1221 | * Uses current projection; units are that of the projected coordinates.
|
---|
1222 | *
|
---|
1223 | * @param nodes the list of nodes representing the polygon
|
---|
1224 | * @return area and perimeter
|
---|
1225 | */
|
---|
1226 | public static AreaAndPerimeter getAreaAndPerimeter(List<? extends ILatLon> nodes) {
|
---|
1227 | return getAreaAndPerimeter(nodes, null);
|
---|
1228 | }
|
---|
1229 |
|
---|
1230 | /**
|
---|
1231 | * Calculate area and perimeter length of a polygon in the given projection.
|
---|
1232 | *
|
---|
1233 | * @param nodes the list of nodes representing the polygon
|
---|
1234 | * @param projection the projection to use for the calculation, {@code null} defaults to {@link ProjectionRegistry#getProjection()}
|
---|
1235 | * @return area and perimeter
|
---|
1236 | * @since 13638 (signature)
|
---|
1237 | */
|
---|
1238 | public static AreaAndPerimeter getAreaAndPerimeter(List<? extends ILatLon> nodes, Projection projection) {
|
---|
1239 | CheckParameterUtil.ensureParameterNotNull(nodes, "nodes");
|
---|
1240 | double area = 0;
|
---|
1241 | double perimeter = 0;
|
---|
1242 | Projection useProjection = projection == null ? ProjectionRegistry.getProjection() : projection;
|
---|
1243 |
|
---|
1244 | if (!nodes.isEmpty()) {
|
---|
1245 | boolean closed = nodes.get(0) == nodes.get(nodes.size() - 1);
|
---|
1246 | int numSegments = closed ? nodes.size() - 1 : nodes.size();
|
---|
1247 | EastNorth p1 = nodes.get(0).getEastNorth(useProjection);
|
---|
1248 | for (int i = 1; i <= numSegments; i++) {
|
---|
1249 | final ILatLon node = nodes.get(i == numSegments ? 0 : i);
|
---|
1250 | final EastNorth p2 = node.getEastNorth(useProjection);
|
---|
1251 | if (p1 != null && p2 != null) {
|
---|
1252 | area += p1.east() * p2.north() - p2.east() * p1.north();
|
---|
1253 | perimeter += p1.distance(p2);
|
---|
1254 | }
|
---|
1255 | p1 = p2;
|
---|
1256 | }
|
---|
1257 | }
|
---|
1258 | return new AreaAndPerimeter(Math.abs(area) / 2, perimeter);
|
---|
1259 | }
|
---|
1260 |
|
---|
1261 | /**
|
---|
1262 | * Get the closest primitive to {@code osm} from the collection of
|
---|
1263 | * OsmPrimitive {@code primitives}
|
---|
1264 | *
|
---|
1265 | * The {@code primitives} should be fully downloaded to ensure accuracy.
|
---|
1266 | *
|
---|
1267 | * Note: The complexity of this method is O(n*m), where n is the number of
|
---|
1268 | * children {@code osm} has plus 1, m is the number of children the
|
---|
1269 | * collection of primitives have plus the number of primitives in the
|
---|
1270 | * collection.
|
---|
1271 | *
|
---|
1272 | * @param <T> The return type of the primitive
|
---|
1273 | * @param osm The primitive to get the distances from
|
---|
1274 | * @param primitives The collection of primitives to get the distance to
|
---|
1275 | * @return The closest {@link OsmPrimitive}. This is not determinative.
|
---|
1276 | * To get all primitives that share the same distance, use
|
---|
1277 | * {@link Geometry#getClosestPrimitives}.
|
---|
1278 | * @since 15035
|
---|
1279 | */
|
---|
1280 | public static <T extends OsmPrimitive> T getClosestPrimitive(OsmPrimitive osm, Collection<T> primitives) {
|
---|
1281 | Collection<T> collection = getClosestPrimitives(osm, primitives);
|
---|
1282 | return collection.iterator().next();
|
---|
1283 | }
|
---|
1284 |
|
---|
1285 | /**
|
---|
1286 | * Get the closest primitives to {@code osm} from the collection of
|
---|
1287 | * OsmPrimitive {@code primitives}
|
---|
1288 | *
|
---|
1289 | * The {@code primitives} should be fully downloaded to ensure accuracy.
|
---|
1290 | *
|
---|
1291 | * Note: The complexity of this method is O(n*m), where n is the number of
|
---|
1292 | * children {@code osm} has plus 1, m is the number of children the
|
---|
1293 | * collection of primitives have plus the number of primitives in the
|
---|
1294 | * collection.
|
---|
1295 | *
|
---|
1296 | * @param <T> The return type of the primitive
|
---|
1297 | * @param osm The primitive to get the distances from
|
---|
1298 | * @param primitives The collection of primitives to get the distance to
|
---|
1299 | * @return The closest {@link OsmPrimitive}s. May be empty.
|
---|
1300 | * @since 15035
|
---|
1301 | */
|
---|
1302 | public static <T extends OsmPrimitive> Collection<T> getClosestPrimitives(OsmPrimitive osm, Collection<T> primitives) {
|
---|
1303 | double lowestDistance = Double.MAX_VALUE;
|
---|
1304 | TreeSet<T> closest = new TreeSet<>();
|
---|
1305 | for (T primitive : primitives) {
|
---|
1306 | double distance = getDistance(osm, primitive);
|
---|
1307 | if (Double.isNaN(distance)) continue;
|
---|
1308 | int comp = Double.compare(distance, lowestDistance);
|
---|
1309 | if (comp < 0) {
|
---|
1310 | closest.clear();
|
---|
1311 | lowestDistance = distance;
|
---|
1312 | closest.add(primitive);
|
---|
1313 | } else if (comp == 0) {
|
---|
1314 | closest.add(primitive);
|
---|
1315 | }
|
---|
1316 | }
|
---|
1317 | return closest;
|
---|
1318 | }
|
---|
1319 |
|
---|
1320 | /**
|
---|
1321 | * Get the furthest primitive to {@code osm} from the collection of
|
---|
1322 | * OsmPrimitive {@code primitives}
|
---|
1323 | *
|
---|
1324 | * The {@code primitives} should be fully downloaded to ensure accuracy.
|
---|
1325 | *
|
---|
1326 | * It does NOT give the furthest primitive based off of the furthest
|
---|
1327 | * part of that primitive
|
---|
1328 | *
|
---|
1329 | * Note: The complexity of this method is O(n*m), where n is the number of
|
---|
1330 | * children {@code osm} has plus 1, m is the number of children the
|
---|
1331 | * collection of primitives have plus the number of primitives in the
|
---|
1332 | * collection.
|
---|
1333 | *
|
---|
1334 | * @param <T> The return type of the primitive
|
---|
1335 | * @param osm The primitive to get the distances from
|
---|
1336 | * @param primitives The collection of primitives to get the distance to
|
---|
1337 | * @return The furthest {@link OsmPrimitive}. This is not determinative.
|
---|
1338 | * To get all primitives that share the same distance, use
|
---|
1339 | * {@link Geometry#getFurthestPrimitives}
|
---|
1340 | * @since 15035
|
---|
1341 | */
|
---|
1342 | public static <T extends OsmPrimitive> T getFurthestPrimitive(OsmPrimitive osm, Collection<T> primitives) {
|
---|
1343 | return getFurthestPrimitives(osm, primitives).iterator().next();
|
---|
1344 | }
|
---|
1345 |
|
---|
1346 | /**
|
---|
1347 | * Get the furthest primitives to {@code osm} from the collection of
|
---|
1348 | * OsmPrimitive {@code primitives}
|
---|
1349 | *
|
---|
1350 | * The {@code primitives} should be fully downloaded to ensure accuracy.
|
---|
1351 | *
|
---|
1352 | * It does NOT give the furthest primitive based off of the furthest
|
---|
1353 | * part of that primitive
|
---|
1354 | *
|
---|
1355 | * Note: The complexity of this method is O(n*m), where n is the number of
|
---|
1356 | * children {@code osm} has plus 1, m is the number of children the
|
---|
1357 | * collection of primitives have plus the number of primitives in the
|
---|
1358 | * collection.
|
---|
1359 | *
|
---|
1360 | * @param <T> The return type of the primitive
|
---|
1361 | * @param osm The primitive to get the distances from
|
---|
1362 | * @param primitives The collection of primitives to get the distance to
|
---|
1363 | * @return The furthest {@link OsmPrimitive}s. It may return an empty collection.
|
---|
1364 | * @since 15035
|
---|
1365 | */
|
---|
1366 | public static <T extends OsmPrimitive> Collection<T> getFurthestPrimitives(OsmPrimitive osm, Collection<T> primitives) {
|
---|
1367 | double furthestDistance = Double.NEGATIVE_INFINITY;
|
---|
1368 | TreeSet<T> furthest = new TreeSet<>();
|
---|
1369 | for (T primitive : primitives) {
|
---|
1370 | double distance = getDistance(osm, primitive);
|
---|
1371 | if (Double.isNaN(distance)) continue;
|
---|
1372 | int comp = Double.compare(distance, furthestDistance);
|
---|
1373 | if (comp > 0) {
|
---|
1374 | furthest.clear();
|
---|
1375 | furthestDistance = distance;
|
---|
1376 | furthest.add(primitive);
|
---|
1377 | } else if (comp == 0) {
|
---|
1378 | furthest.add(primitive);
|
---|
1379 | }
|
---|
1380 | }
|
---|
1381 | return furthest;
|
---|
1382 | }
|
---|
1383 |
|
---|
1384 | /**
|
---|
1385 | * Get the distance between different {@link OsmPrimitive}s
|
---|
1386 | * @param one The primitive to get the distance from
|
---|
1387 | * @param two The primitive to get the distance to
|
---|
1388 | * @return The distance between the primitives in meters
|
---|
1389 | * (or the unit of the current projection, see {@link Projection}).
|
---|
1390 | * May return {@link Double#NaN} if one of the primitives is incomplete.
|
---|
1391 | *
|
---|
1392 | * Note: The complexity is O(n*m), where (n,m) are the number of child
|
---|
1393 | * objects the {@link OsmPrimitive}s have.
|
---|
1394 | * @since 15035
|
---|
1395 | */
|
---|
1396 | public static double getDistance(OsmPrimitive one, OsmPrimitive two) {
|
---|
1397 | double rValue = Double.MAX_VALUE;
|
---|
1398 | if (one == null || two == null || one.isIncomplete()
|
---|
1399 | || two.isIncomplete()) return Double.NaN;
|
---|
1400 | if (one instanceof Node && two instanceof Node) {
|
---|
1401 | rValue = ((Node) one).getCoor().greatCircleDistance(((Node) two).getCoor());
|
---|
1402 | } else if (one instanceof Node && two instanceof Way) {
|
---|
1403 | rValue = getDistanceWayNode((Way) two, (Node) one);
|
---|
1404 | } else if (one instanceof Way && two instanceof Node) {
|
---|
1405 | rValue = getDistanceWayNode((Way) one, (Node) two);
|
---|
1406 | } else if (one instanceof Way && two instanceof Way) {
|
---|
1407 | rValue = getDistanceWayWay((Way) one, (Way) two);
|
---|
1408 | } else if (one instanceof Relation && !(two instanceof Relation)) {
|
---|
1409 | for (OsmPrimitive osmPrimitive: ((Relation) one).getMemberPrimitives()) {
|
---|
1410 | double currentDistance = getDistance(osmPrimitive, two);
|
---|
1411 | if (currentDistance < rValue) rValue = currentDistance;
|
---|
1412 | }
|
---|
1413 | } else if (!(one instanceof Relation) && two instanceof Relation) {
|
---|
1414 | rValue = getDistance(two, one);
|
---|
1415 | } else if (one instanceof Relation && two instanceof Relation) {
|
---|
1416 | for (OsmPrimitive osmPrimitive1 : ((Relation) one).getMemberPrimitives()) {
|
---|
1417 | for (OsmPrimitive osmPrimitive2 : ((Relation) two).getMemberPrimitives()) {
|
---|
1418 | double currentDistance = getDistance(osmPrimitive1, osmPrimitive2);
|
---|
1419 | if (currentDistance < rValue) rValue = currentDistance;
|
---|
1420 | }
|
---|
1421 | }
|
---|
1422 | }
|
---|
1423 | return rValue != Double.MAX_VALUE ? rValue : Double.NaN;
|
---|
1424 | }
|
---|
1425 |
|
---|
1426 | /**
|
---|
1427 | * Get the distance between a way and a node
|
---|
1428 | * @param way The way to get the distance from
|
---|
1429 | * @param node The node to get the distance to
|
---|
1430 | * @return The distance between the {@code way} and the {@code node} in
|
---|
1431 | * meters (or the unit of the current projection, see {@link Projection}).
|
---|
1432 | * May return {@link Double#NaN} if the primitives are incomplete.
|
---|
1433 | * @since 15035
|
---|
1434 | */
|
---|
1435 | public static double getDistanceWayNode(Way way, Node node) {
|
---|
1436 | if (way == null || node == null || way.getNodesCount() < 2 || !node.isLatLonKnown())
|
---|
1437 | return Double.NaN;
|
---|
1438 |
|
---|
1439 | double smallest = Double.MAX_VALUE;
|
---|
1440 | EastNorth en0 = node.getEastNorth();
|
---|
1441 | // go through the nodes as if they were paired
|
---|
1442 | Iterator<Node> iter = way.getNodes().iterator();
|
---|
1443 | EastNorth en1 = iter.next().getEastNorth();
|
---|
1444 | while (iter.hasNext()) {
|
---|
1445 | EastNorth en2 = iter.next().getEastNorth();
|
---|
1446 | double distance = getSegmentNodeDistSq(en1, en2, en0);
|
---|
1447 | if (distance < smallest)
|
---|
1448 | smallest = distance;
|
---|
1449 | en1 = en2;
|
---|
1450 | }
|
---|
1451 | return smallest != Double.MAX_VALUE ? Math.sqrt(smallest) : Double.NaN;
|
---|
1452 | }
|
---|
1453 |
|
---|
1454 | /**
|
---|
1455 | * Get the closest {@link WaySegment} from a way to a primitive.
|
---|
1456 | * @param way The {@link Way} to get the distance from and the {@link WaySegment}
|
---|
1457 | * @param primitive The {@link OsmPrimitive} to get the distance to
|
---|
1458 | * @return The {@link WaySegment} that is closest to {@code primitive} from {@code way}.
|
---|
1459 | * If there are multiple {@link WaySegment}s with the same distance, the last
|
---|
1460 | * {@link WaySegment} with the same distance will be returned.
|
---|
1461 | * May return {@code null} if the way has fewer than two nodes or one
|
---|
1462 | * of the primitives is incomplete.
|
---|
1463 | * @since 15035
|
---|
1464 | */
|
---|
1465 | public static WaySegment getClosestWaySegment(Way way, OsmPrimitive primitive) {
|
---|
1466 | if (way == null || primitive == null || way.isIncomplete()
|
---|
1467 | || primitive.isIncomplete()) return null;
|
---|
1468 | double lowestDistance = Double.MAX_VALUE;
|
---|
1469 | Pair<Node, Node> closestNodes = null;
|
---|
1470 | for (Pair<Node, Node> nodes : way.getNodePairs(false)) {
|
---|
1471 | Way tWay = new Way();
|
---|
1472 | tWay.addNode(nodes.a);
|
---|
1473 | tWay.addNode(nodes.b);
|
---|
1474 | double distance = getDistance(tWay, primitive);
|
---|
1475 | if (distance < lowestDistance) {
|
---|
1476 | lowestDistance = distance;
|
---|
1477 | closestNodes = nodes;
|
---|
1478 | }
|
---|
1479 | }
|
---|
1480 | if (closestNodes == null) return null;
|
---|
1481 | return lowestDistance != Double.MAX_VALUE ? WaySegment.forNodePair(way, closestNodes.a, closestNodes.b) : null;
|
---|
1482 | }
|
---|
1483 |
|
---|
1484 | /**
|
---|
1485 | * Get the distance between different ways. Iterates over the nodes of the ways, complexity is O(n*m)
|
---|
1486 | * (n,m giving the number of nodes)
|
---|
1487 | * @param w1 The first {@link Way}
|
---|
1488 | * @param w2 The second {@link Way}
|
---|
1489 | * @return The shortest distance between the ways in meters
|
---|
1490 | * (or the unit of the current projection, see {@link Projection}).
|
---|
1491 | * May return {@link Double#NaN}.
|
---|
1492 | * @since 15035
|
---|
1493 | */
|
---|
1494 | public static double getDistanceWayWay(Way w1, Way w2) {
|
---|
1495 | if (w1 == null || w2 == null || w1.getNodesCount() < 2 || w2.getNodesCount() < 2)
|
---|
1496 | return Double.NaN;
|
---|
1497 | double rValue = Double.MAX_VALUE;
|
---|
1498 | Iterator<Node> iter1 = w1.getNodes().iterator();
|
---|
1499 | Node w1N1 = iter1.next();
|
---|
1500 | while (iter1.hasNext()) {
|
---|
1501 | Node w1N2 = iter1.next();
|
---|
1502 | Iterator<Node> iter2 = w2.getNodes().iterator();
|
---|
1503 | Node w2N1 = iter2.next();
|
---|
1504 | while (iter2.hasNext()) {
|
---|
1505 | Node w2N2 = iter2.next();
|
---|
1506 | double distance = getDistanceSegmentSegment(w1N1, w1N2, w2N1, w2N2);
|
---|
1507 | if (distance < rValue)
|
---|
1508 | rValue = distance;
|
---|
1509 | w2N1 = w2N2;
|
---|
1510 | }
|
---|
1511 | w1N1 = w1N2;
|
---|
1512 | }
|
---|
1513 | return rValue != Double.MAX_VALUE ? rValue : Double.NaN;
|
---|
1514 | }
|
---|
1515 |
|
---|
1516 | /**
|
---|
1517 | * Get the distance between different {@link WaySegment}s
|
---|
1518 | * @param ws1 A {@link WaySegment}
|
---|
1519 | * @param ws2 A {@link WaySegment}
|
---|
1520 | * @return The distance between the two {@link WaySegment}s in meters
|
---|
1521 | * (or the unit of the current projection, see {@link Projection}).
|
---|
1522 | * May return {@link Double#NaN}.
|
---|
1523 | * @since 15035
|
---|
1524 | */
|
---|
1525 | public static double getDistanceSegmentSegment(WaySegment ws1, WaySegment ws2) {
|
---|
1526 | return getDistanceSegmentSegment(ws1.getFirstNode(), ws1.getSecondNode(), ws2.getFirstNode(), ws2.getSecondNode());
|
---|
1527 | }
|
---|
1528 |
|
---|
1529 | /**
|
---|
1530 | * Get the distance between different {@link WaySegment}s
|
---|
1531 | * @param ws1Node1 The first node of the first WaySegment
|
---|
1532 | * @param ws1Node2 The second node of the second WaySegment
|
---|
1533 | * @param ws2Node1 The first node of the second WaySegment
|
---|
1534 | * @param ws2Node2 The second node of the second WaySegment
|
---|
1535 | * @return The distance between the two {@link WaySegment}s in meters
|
---|
1536 | * (or the unit of the current projection, see {@link Projection}).
|
---|
1537 | * May return {@link Double#NaN}.
|
---|
1538 | * @since 15035
|
---|
1539 | */
|
---|
1540 | public static double getDistanceSegmentSegment(Node ws1Node1, Node ws1Node2, Node ws2Node1, Node ws2Node2) {
|
---|
1541 | EastNorth enWs1Node1 = ws1Node1.getEastNorth();
|
---|
1542 | EastNorth enWs1Node2 = ws1Node2.getEastNorth();
|
---|
1543 | EastNorth enWs2Node1 = ws2Node1.getEastNorth();
|
---|
1544 | EastNorth enWs2Node2 = ws2Node2.getEastNorth();
|
---|
1545 | if (enWs1Node1 == null || enWs1Node2 == null || enWs2Node1 == null || enWs2Node2 == null)
|
---|
1546 | return Double.NaN;
|
---|
1547 | if (getSegmentSegmentIntersection(enWs1Node1, enWs1Node2, enWs2Node1, enWs2Node2) != null)
|
---|
1548 | return 0;
|
---|
1549 |
|
---|
1550 | double dist1sq = getSegmentNodeDistSq(enWs1Node1, enWs1Node2, enWs2Node1);
|
---|
1551 | double dist2sq = getSegmentNodeDistSq(enWs1Node1, enWs1Node2, enWs2Node2);
|
---|
1552 | double dist3sq = getSegmentNodeDistSq(enWs2Node1, enWs2Node2, enWs1Node1);
|
---|
1553 | double dist4sq = getSegmentNodeDistSq(enWs2Node1, enWs2Node2, enWs1Node2);
|
---|
1554 | double smallest = Math.min(Math.min(dist1sq, dist2sq), Math.min(dist3sq, dist4sq));
|
---|
1555 | return smallest != Double.MAX_VALUE ? Math.sqrt(smallest) : Double.NaN;
|
---|
1556 | }
|
---|
1557 |
|
---|
1558 | /**
|
---|
1559 | * Calculate closest distance between a line segment s1-s2 and a point p
|
---|
1560 | * @param s1 start of segment
|
---|
1561 | * @param s2 end of segment
|
---|
1562 | * @param p the point
|
---|
1563 | * @return the square of the euclidean distance from p to the closest point on the segment
|
---|
1564 | */
|
---|
1565 | private static double getSegmentNodeDistSq(EastNorth s1, EastNorth s2, EastNorth p) {
|
---|
1566 | EastNorth c1 = closestPointTo(s1, s2, p, true);
|
---|
1567 | return c1.distanceSq(p);
|
---|
1568 | }
|
---|
1569 | }
|
---|