source: josm/trunk/src/org/openstreetmap/josm/tools/Geometry.java@ 15035

Last change on this file since 15035 was 15035, checked in by GerdP, 5 years ago

fix #17616: Add new functions to Geometry.java to find distances between primitives
Patch 17616_v12.patch by taylor.smock

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