001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.tools; 003 004import java.awt.geom.Area; 005import java.awt.geom.Line2D; 006import java.awt.geom.Path2D; 007import java.awt.geom.PathIterator; 008import java.awt.geom.Rectangle2D; 009import java.math.BigDecimal; 010import java.math.MathContext; 011import java.util.ArrayList; 012import java.util.Collections; 013import java.util.Comparator; 014import java.util.LinkedHashSet; 015import java.util.List; 016import java.util.Set; 017import java.util.function.Predicate; 018import java.util.stream.Collectors; 019 020import org.openstreetmap.josm.command.AddCommand; 021import org.openstreetmap.josm.command.ChangeCommand; 022import org.openstreetmap.josm.command.Command; 023import org.openstreetmap.josm.data.coor.EastNorth; 024import org.openstreetmap.josm.data.coor.ILatLon; 025import org.openstreetmap.josm.data.osm.BBox; 026import org.openstreetmap.josm.data.osm.DataSet; 027import org.openstreetmap.josm.data.osm.INode; 028import org.openstreetmap.josm.data.osm.IPrimitive; 029import org.openstreetmap.josm.data.osm.MultipolygonBuilder; 030import org.openstreetmap.josm.data.osm.MultipolygonBuilder.JoinedPolygon; 031import org.openstreetmap.josm.data.osm.Node; 032import org.openstreetmap.josm.data.osm.NodePositionComparator; 033import org.openstreetmap.josm.data.osm.Relation; 034import org.openstreetmap.josm.data.osm.Way; 035import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon; 036import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache; 037import org.openstreetmap.josm.data.projection.Projection; 038import org.openstreetmap.josm.data.projection.ProjectionRegistry; 039import org.openstreetmap.josm.data.projection.Projections; 040 041/** 042 * Some tools for geometry related tasks. 043 * 044 * @author viesturs 045 */ 046public final class Geometry { 047 048 private Geometry() { 049 // Hide default constructor for utils classes 050 } 051 052 /** 053 * The result types for a {@link Geometry#polygonIntersection(Area, Area)} test 054 */ 055 public enum PolygonIntersection { 056 /** 057 * The first polygon is inside the second one 058 */ 059 FIRST_INSIDE_SECOND, 060 /** 061 * The second one is inside the first 062 */ 063 SECOND_INSIDE_FIRST, 064 /** 065 * The polygons do not overlap 066 */ 067 OUTSIDE, 068 /** 069 * The polygon borders cross each other 070 */ 071 CROSSING 072 } 073 074 /** threshold value for size of intersection area given in east/north space */ 075 public static final double INTERSECTION_EPS_EAST_NORTH = 1e-4; 076 077 /** 078 * Will find all intersection and add nodes there for list of given ways. 079 * Handles self-intersections too. 080 * And makes commands to add the intersection points to ways. 081 * 082 * Prerequisite: no two nodes have the same coordinates. 083 * 084 * @param ways a list of ways to test 085 * @param test if false, do not build list of Commands, just return nodes 086 * @param cmds list of commands, typically empty when handed to this method. 087 * Will be filled with commands that add intersection nodes to 088 * the ways. 089 * @return list of new nodes 090 */ 091 public static Set<Node> addIntersections(List<Way> ways, boolean test, List<Command> cmds) { 092 093 int n = ways.size(); 094 @SuppressWarnings("unchecked") 095 List<Node>[] newNodes = new ArrayList[n]; 096 BBox[] wayBounds = new BBox[n]; 097 boolean[] changedWays = new boolean[n]; 098 099 Set<Node> intersectionNodes = new LinkedHashSet<>(); 100 101 //copy node arrays for local usage. 102 for (int pos = 0; pos < n; pos++) { 103 newNodes[pos] = new ArrayList<>(ways.get(pos).getNodes()); 104 wayBounds[pos] = getNodesBounds(newNodes[pos]); 105 changedWays[pos] = false; 106 } 107 108 DataSet dataset = ways.get(0).getDataSet(); 109 110 //iterate over all way pairs and introduce the intersections 111 Comparator<Node> coordsComparator = new NodePositionComparator(); 112 for (int seg1Way = 0; seg1Way < n; seg1Way++) { 113 for (int seg2Way = seg1Way; seg2Way < n; seg2Way++) { 114 115 //do not waste time on bounds that do not intersect 116 if (!wayBounds[seg1Way].intersects(wayBounds[seg2Way])) { 117 continue; 118 } 119 120 List<Node> way1Nodes = newNodes[seg1Way]; 121 List<Node> way2Nodes = newNodes[seg2Way]; 122 123 //iterate over primary segmemt 124 for (int seg1Pos = 0; seg1Pos + 1 < way1Nodes.size(); seg1Pos++) { 125 126 //iterate over secondary segment 127 int seg2Start = seg1Way != seg2Way ? 0 : seg1Pos + 2; //skip the adjacent segment 128 129 for (int seg2Pos = seg2Start; seg2Pos + 1 < way2Nodes.size(); seg2Pos++) { 130 131 //need to get them again every time, because other segments may be changed 132 Node seg1Node1 = way1Nodes.get(seg1Pos); 133 Node seg1Node2 = way1Nodes.get(seg1Pos + 1); 134 Node seg2Node1 = way2Nodes.get(seg2Pos); 135 Node seg2Node2 = way2Nodes.get(seg2Pos + 1); 136 137 int commonCount = 0; 138 //test if we have common nodes to add. 139 if (seg1Node1 == seg2Node1 || seg1Node1 == seg2Node2) { 140 commonCount++; 141 142 if (seg1Way == seg2Way && 143 seg1Pos == 0 && 144 seg2Pos == way2Nodes.size() -2) { 145 //do not add - this is first and last segment of the same way. 146 } else { 147 intersectionNodes.add(seg1Node1); 148 } 149 } 150 151 if (seg1Node2 == seg2Node1 || seg1Node2 == seg2Node2) { 152 commonCount++; 153 154 intersectionNodes.add(seg1Node2); 155 } 156 157 //no common nodes - find intersection 158 if (commonCount == 0) { 159 EastNorth intersection = getSegmentSegmentIntersection( 160 seg1Node1.getEastNorth(), seg1Node2.getEastNorth(), 161 seg2Node1.getEastNorth(), seg2Node2.getEastNorth()); 162 163 if (intersection != null) { 164 if (test) { 165 intersectionNodes.add(seg2Node1); 166 return intersectionNodes; 167 } 168 169 Node newNode = new Node(ProjectionRegistry.getProjection().eastNorth2latlon(intersection)); 170 Node intNode = newNode; 171 boolean insertInSeg1 = false; 172 boolean insertInSeg2 = false; 173 //find if the intersection point is at end point of one of the segments, if so use that point 174 175 //segment 1 176 if (coordsComparator.compare(newNode, seg1Node1) == 0) { 177 intNode = seg1Node1; 178 } else if (coordsComparator.compare(newNode, seg1Node2) == 0) { 179 intNode = seg1Node2; 180 } else { 181 insertInSeg1 = true; 182 } 183 184 //segment 2 185 if (coordsComparator.compare(newNode, seg2Node1) == 0) { 186 intNode = seg2Node1; 187 } else if (coordsComparator.compare(newNode, seg2Node2) == 0) { 188 intNode = seg2Node2; 189 } else { 190 insertInSeg2 = true; 191 } 192 193 if (insertInSeg1) { 194 way1Nodes.add(seg1Pos +1, intNode); 195 changedWays[seg1Way] = true; 196 197 //fix seg2 position, as indexes have changed, seg2Pos is always bigger than seg1Pos on the same segment. 198 if (seg2Way == seg1Way) { 199 seg2Pos++; 200 } 201 } 202 203 if (insertInSeg2) { 204 way2Nodes.add(seg2Pos +1, intNode); 205 changedWays[seg2Way] = true; 206 207 //Do not need to compare again to already split segment 208 seg2Pos++; 209 } 210 211 intersectionNodes.add(intNode); 212 213 if (intNode == newNode) { 214 cmds.add(new AddCommand(dataset, intNode)); 215 } 216 } 217 } else if (test && !intersectionNodes.isEmpty()) 218 return intersectionNodes; 219 } 220 } 221 } 222 } 223 224 225 for (int pos = 0; pos < ways.size(); pos++) { 226 if (!changedWays[pos]) { 227 continue; 228 } 229 230 Way way = ways.get(pos); 231 Way newWay = new Way(way); 232 newWay.setNodes(newNodes[pos]); 233 234 cmds.add(new ChangeCommand(dataset, way, newWay)); 235 } 236 237 return intersectionNodes; 238 } 239 240 private static BBox getNodesBounds(List<Node> nodes) { 241 242 BBox bounds = new BBox(nodes.get(0)); 243 for (Node n: nodes) { 244 bounds.add(n); 245 } 246 return bounds; 247 } 248 249 /** 250 * Tests if given point is to the right side of path consisting of 3 points. 251 * 252 * (Imagine the path is continued beyond the endpoints, so you get two rays 253 * starting from lineP2 and going through lineP1 and lineP3 respectively 254 * which divide the plane into two parts. The test returns true, if testPoint 255 * lies in the part that is to the right when traveling in the direction 256 * lineP1, lineP2, lineP3.) 257 * 258 * @param <N> type of node 259 * @param lineP1 first point in path 260 * @param lineP2 second point in path 261 * @param lineP3 third point in path 262 * @param testPoint point to test 263 * @return true if to the right side, false otherwise 264 */ 265 public static <N extends INode> boolean isToTheRightSideOfLine(N lineP1, N lineP2, N lineP3, N testPoint) { 266 boolean pathBendToRight = angleIsClockwise(lineP1, lineP2, lineP3); 267 boolean rightOfSeg1 = angleIsClockwise(lineP1, lineP2, testPoint); 268 boolean rightOfSeg2 = angleIsClockwise(lineP2, lineP3, testPoint); 269 270 if (pathBendToRight) 271 return rightOfSeg1 && rightOfSeg2; 272 else 273 return !(!rightOfSeg1 && !rightOfSeg2); 274 } 275 276 /** 277 * This method tests if secondNode is clockwise to first node. 278 * @param <N> type of node 279 * @param commonNode starting point for both vectors 280 * @param firstNode first vector end node 281 * @param secondNode second vector end node 282 * @return true if first vector is clockwise before second vector. 283 */ 284 public static <N extends INode> boolean angleIsClockwise(N commonNode, N firstNode, N secondNode) { 285 return angleIsClockwise(commonNode.getEastNorth(), firstNode.getEastNorth(), secondNode.getEastNorth()); 286 } 287 288 /** 289 * Finds the intersection of two line segments. 290 * @param p1 the coordinates of the start point of the first specified line segment 291 * @param p2 the coordinates of the end point of the first specified line segment 292 * @param p3 the coordinates of the start point of the second specified line segment 293 * @param p4 the coordinates of the end point of the second specified line segment 294 * @return EastNorth null if no intersection was found, the EastNorth coordinates of the intersection otherwise 295 */ 296 public static EastNorth getSegmentSegmentIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) { 297 298 CheckParameterUtil.ensure(p1, "p1", EastNorth::isValid); 299 CheckParameterUtil.ensure(p2, "p2", EastNorth::isValid); 300 CheckParameterUtil.ensure(p3, "p3", EastNorth::isValid); 301 CheckParameterUtil.ensure(p4, "p4", EastNorth::isValid); 302 303 double x1 = p1.getX(); 304 double y1 = p1.getY(); 305 double x2 = p2.getX(); 306 double y2 = p2.getY(); 307 double x3 = p3.getX(); 308 double y3 = p3.getY(); 309 double x4 = p4.getX(); 310 double y4 = p4.getY(); 311 312 //TODO: do this locally. 313 //TODO: remove this check after careful testing 314 if (!Line2D.linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return null; 315 316 // solve line-line intersection in parametric form: 317 // (x1,y1) + (x2-x1,y2-y1)* u = (x3,y3) + (x4-x3,y4-y3)* v 318 // (x2-x1,y2-y1)*u - (x4-x3,y4-y3)*v = (x3-x1,y3-y1) 319 // if 0<= u,v <=1, intersection exists at ( x1+ (x2-x1)*u, y1 + (y2-y1)*u ) 320 321 double a1 = x2 - x1; 322 double b1 = x3 - x4; 323 double c1 = x3 - x1; 324 325 double a2 = y2 - y1; 326 double b2 = y3 - y4; 327 double c2 = y3 - y1; 328 329 // Solve the equations 330 double det = a1*b2 - a2*b1; 331 332 double uu = b2*c1 - b1*c2; 333 double vv = a1*c2 - a2*c1; 334 double mag = Math.abs(uu)+Math.abs(vv); 335 336 if (Math.abs(det) > 1e-12 * mag) { 337 double u = uu/det, v = vv/det; 338 if (u > -1e-8 && u < 1+1e-8 && v > -1e-8 && v < 1+1e-8) { 339 if (u < 0) u = 0; 340 if (u > 1) u = 1.0; 341 return new EastNorth(x1+a1*u, y1+a2*u); 342 } else { 343 return null; 344 } 345 } else { 346 // parallel lines 347 return null; 348 } 349 } 350 351 /** 352 * Finds the intersection of two lines of infinite length. 353 * 354 * @param p1 first point on first line 355 * @param p2 second point on first line 356 * @param p3 first point on second line 357 * @param p4 second point on second line 358 * @return EastNorth null if no intersection was found, the coordinates of the intersection otherwise 359 * @throws IllegalArgumentException if a parameter is null or without valid coordinates 360 */ 361 public static EastNorth getLineLineIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) { 362 363 CheckParameterUtil.ensure(p1, "p1", EastNorth::isValid); 364 CheckParameterUtil.ensure(p2, "p2", EastNorth::isValid); 365 CheckParameterUtil.ensure(p3, "p3", EastNorth::isValid); 366 CheckParameterUtil.ensure(p4, "p4", EastNorth::isValid); 367 368 // Basically, the formula from wikipedia is used: 369 // https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection 370 // However, large numbers lead to rounding errors (see #10286). 371 // To avoid this, p1 is first subtracted from each of the points: 372 // p1' = 0 373 // p2' = p2 - p1 374 // p3' = p3 - p1 375 // p4' = p4 - p1 376 // In the end, p1 is added to the intersection point of segment p1'/p2' 377 // and segment p3'/p4'. 378 379 // Convert line from (point, point) form to ax+by=c 380 double a1 = p2.getY() - p1.getY(); 381 double b1 = p1.getX() - p2.getX(); 382 383 double a2 = p4.getY() - p3.getY(); 384 double b2 = p3.getX() - p4.getX(); 385 386 // Solve the equations 387 double det = a1 * b2 - a2 * b1; 388 if (det == 0) 389 return null; // Lines are parallel 390 391 double c2 = (p4.getX() - p1.getX()) * (p3.getY() - p1.getY()) - (p3.getX() - p1.getX()) * (p4.getY() - p1.getY()); 392 393 return new EastNorth(b1 * c2 / det + p1.getX(), -a1 * c2 / det + p1.getY()); 394 } 395 396 /** 397 * Check if the segment p1 - p2 is parallel to p3 - p4 398 * @param p1 First point for first segment 399 * @param p2 Second point for first segment 400 * @param p3 First point for second segment 401 * @param p4 Second point for second segment 402 * @return <code>true</code> if they are parallel or close to parallel 403 */ 404 public static boolean segmentsParallel(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) { 405 406 CheckParameterUtil.ensure(p1, "p1", EastNorth::isValid); 407 CheckParameterUtil.ensure(p2, "p2", EastNorth::isValid); 408 CheckParameterUtil.ensure(p3, "p3", EastNorth::isValid); 409 CheckParameterUtil.ensure(p4, "p4", EastNorth::isValid); 410 411 // Convert line from (point, point) form to ax+by=c 412 double a1 = p2.getY() - p1.getY(); 413 double b1 = p1.getX() - p2.getX(); 414 415 double a2 = p4.getY() - p3.getY(); 416 double b2 = p3.getX() - p4.getX(); 417 418 // Solve the equations 419 double det = a1 * b2 - a2 * b1; 420 // remove influence of of scaling factor 421 det /= Math.sqrt(a1*a1 + b1*b1) * Math.sqrt(a2*a2 + b2*b2); 422 return Math.abs(det) < 1e-3; 423 } 424 425 private static EastNorth closestPointTo(EastNorth p1, EastNorth p2, EastNorth point, boolean segmentOnly) { 426 CheckParameterUtil.ensureParameterNotNull(p1, "p1"); 427 CheckParameterUtil.ensureParameterNotNull(p2, "p2"); 428 CheckParameterUtil.ensureParameterNotNull(point, "point"); 429 430 double ldx = p2.getX() - p1.getX(); 431 double ldy = p2.getY() - p1.getY(); 432 433 //segment zero length 434 if (ldx == 0 && ldy == 0) 435 return p1; 436 437 double pdx = point.getX() - p1.getX(); 438 double pdy = point.getY() - p1.getY(); 439 440 double offset = (pdx * ldx + pdy * ldy) / (ldx * ldx + ldy * ldy); 441 442 if (segmentOnly && offset <= 0) 443 return p1; 444 else if (segmentOnly && offset >= 1) 445 return p2; 446 else 447 return p1.interpolate(p2, offset); 448 } 449 450 /** 451 * Calculates closest point to a line segment. 452 * @param segmentP1 First point determining line segment 453 * @param segmentP2 Second point determining line segment 454 * @param point Point for which a closest point is searched on line segment [P1,P2] 455 * @return segmentP1 if it is the closest point, segmentP2 if it is the closest point, 456 * a new point if closest point is between segmentP1 and segmentP2. 457 * @see #closestPointToLine 458 * @since 3650 459 */ 460 public static EastNorth closestPointToSegment(EastNorth segmentP1, EastNorth segmentP2, EastNorth point) { 461 return closestPointTo(segmentP1, segmentP2, point, true); 462 } 463 464 /** 465 * Calculates closest point to a line. 466 * @param lineP1 First point determining line 467 * @param lineP2 Second point determining line 468 * @param point Point for which a closest point is searched on line (P1,P2) 469 * @return The closest point found on line. It may be outside the segment [P1,P2]. 470 * @see #closestPointToSegment 471 * @since 4134 472 */ 473 public static EastNorth closestPointToLine(EastNorth lineP1, EastNorth lineP2, EastNorth point) { 474 return closestPointTo(lineP1, lineP2, point, false); 475 } 476 477 /** 478 * This method tests if secondNode is clockwise to first node. 479 * 480 * The line through the two points commonNode and firstNode divides the 481 * plane into two parts. The test returns true, if secondNode lies in 482 * the part that is to the right when traveling in the direction from 483 * commonNode to firstNode. 484 * 485 * @param commonNode starting point for both vectors 486 * @param firstNode first vector end node 487 * @param secondNode second vector end node 488 * @return true if first vector is clockwise before second vector. 489 */ 490 public static boolean angleIsClockwise(EastNorth commonNode, EastNorth firstNode, EastNorth secondNode) { 491 492 CheckParameterUtil.ensure(commonNode, "commonNode", EastNorth::isValid); 493 CheckParameterUtil.ensure(firstNode, "firstNode", EastNorth::isValid); 494 CheckParameterUtil.ensure(secondNode, "secondNode", EastNorth::isValid); 495 496 double dy1 = firstNode.getY() - commonNode.getY(); 497 double dy2 = secondNode.getY() - commonNode.getY(); 498 double dx1 = firstNode.getX() - commonNode.getX(); 499 double dx2 = secondNode.getX() - commonNode.getX(); 500 501 return dy1 * dx2 - dx1 * dy2 > 0; 502 } 503 504 /** 505 * Returns the Area of a polygon, from its list of nodes. 506 * @param polygon List of nodes forming polygon 507 * @return Area for the given list of nodes (EastNorth coordinates) 508 * @since 6841 509 */ 510 public static Area getArea(List<? extends INode> polygon) { 511 Path2D path = new Path2D.Double(); 512 513 boolean begin = true; 514 for (INode n : polygon) { 515 EastNorth en = n.getEastNorth(); 516 if (en != null) { 517 if (begin) { 518 path.moveTo(en.getX(), en.getY()); 519 begin = false; 520 } else { 521 path.lineTo(en.getX(), en.getY()); 522 } 523 } 524 } 525 if (!begin) { 526 path.closePath(); 527 } 528 529 return new Area(path); 530 } 531 532 /** 533 * Builds a path from a list of nodes 534 * @param polygon Nodes, forming a closed polygon 535 * @param path2d path to add to; can be null, then a new path is created 536 * @return the path (LatLon coordinates) 537 * @since 13638 (signature) 538 */ 539 public static Path2D buildPath2DLatLon(List<? extends ILatLon> polygon, Path2D path2d) { 540 Path2D path = path2d != null ? path2d : new Path2D.Double(); 541 boolean begin = true; 542 for (ILatLon n : polygon) { 543 if (begin) { 544 path.moveTo(n.lon(), n.lat()); 545 begin = false; 546 } else { 547 path.lineTo(n.lon(), n.lat()); 548 } 549 } 550 if (!begin) { 551 path.closePath(); 552 } 553 return path; 554 } 555 556 /** 557 * Returns the Area of a polygon, from the multipolygon relation. 558 * @param multipolygon the multipolygon relation 559 * @return Area for the multipolygon (LatLon coordinates) 560 */ 561 public static Area getAreaLatLon(Relation multipolygon) { 562 final Multipolygon mp = MultipolygonCache.getInstance().get(multipolygon); 563 Path2D path = new Path2D.Double(); 564 path.setWindingRule(Path2D.WIND_EVEN_ODD); 565 for (Multipolygon.PolyData pd : mp.getCombinedPolygons()) { 566 buildPath2DLatLon(pd.getNodes(), path); 567 for (Multipolygon.PolyData pdInner : pd.getInners()) { 568 buildPath2DLatLon(pdInner.getNodes(), path); 569 } 570 } 571 return new Area(path); 572 } 573 574 /** 575 * Tests if two polygons intersect. 576 * @param first List of nodes forming first polygon 577 * @param second List of nodes forming second polygon 578 * @return intersection kind 579 */ 580 public static PolygonIntersection polygonIntersection(List<? extends INode> first, List<? extends INode> second) { 581 Area a1 = getArea(first); 582 Area a2 = getArea(second); 583 return polygonIntersection(a1, a2, INTERSECTION_EPS_EAST_NORTH); 584 } 585 586 /** 587 * Tests if two polygons intersect. It is assumed that the area is given in East North points. 588 * @param a1 Area of first polygon 589 * @param a2 Area of second polygon 590 * @return intersection kind 591 * @since 6841 592 */ 593 public static PolygonIntersection polygonIntersection(Area a1, Area a2) { 594 return polygonIntersection(a1, a2, INTERSECTION_EPS_EAST_NORTH); 595 } 596 597 /** 598 * Tests if two polygons intersect. 599 * @param a1 Area of first polygon 600 * @param a2 Area of second polygon 601 * @param eps an area threshold, everything below is considered an empty intersection 602 * @return intersection kind 603 */ 604 public static PolygonIntersection polygonIntersection(Area a1, Area a2, double eps) { 605 606 Area inter = new Area(a1); 607 inter.intersect(a2); 608 609 if (inter.isEmpty() || !checkIntersection(inter, eps)) { 610 return PolygonIntersection.OUTSIDE; 611 } else if (a2.getBounds2D().contains(a1.getBounds2D()) && inter.equals(a1)) { 612 return PolygonIntersection.FIRST_INSIDE_SECOND; 613 } else if (a1.getBounds2D().contains(a2.getBounds2D()) && inter.equals(a2)) { 614 return PolygonIntersection.SECOND_INSIDE_FIRST; 615 } else { 616 return PolygonIntersection.CROSSING; 617 } 618 } 619 620 /** 621 * Check an intersection area which might describe multiple small polygons. 622 * Return true if any of the polygons is bigger than the given threshold. 623 * @param inter the intersection area 624 * @param eps an area threshold, everything below is considered an empty intersection 625 * @return true if any of the polygons is bigger than the given threshold 626 */ 627 private static boolean checkIntersection(Area inter, double eps) { 628 PathIterator pit = inter.getPathIterator(null); 629 double[] res = new double[6]; 630 Rectangle2D r = new Rectangle2D.Double(); 631 while (!pit.isDone()) { 632 int type = pit.currentSegment(res); 633 switch (type) { 634 case PathIterator.SEG_MOVETO: 635 r = new Rectangle2D.Double(res[0], res[1], 0, 0); 636 break; 637 case PathIterator.SEG_LINETO: 638 r.add(res[0], res[1]); 639 break; 640 case PathIterator.SEG_CLOSE: 641 if (r.getWidth() > eps || r.getHeight() > eps) 642 return true; 643 break; 644 default: 645 break; 646 } 647 pit.next(); 648 } 649 return false; 650 } 651 652 /** 653 * Tests if point is inside a polygon. The polygon can be self-intersecting. In such case the contains function works in xor-like manner. 654 * @param polygonNodes list of nodes from polygon path. 655 * @param point the point to test 656 * @return true if the point is inside polygon. 657 */ 658 public static boolean nodeInsidePolygon(INode point, List<? extends INode> polygonNodes) { 659 if (polygonNodes.size() < 2) 660 return false; 661 662 //iterate each side of the polygon, start with the last segment 663 INode oldPoint = polygonNodes.get(polygonNodes.size() - 1); 664 665 if (!oldPoint.isLatLonKnown()) { 666 return false; 667 } 668 669 boolean inside = false; 670 INode p1, p2; 671 672 for (INode newPoint : polygonNodes) { 673 //skip duplicate points 674 if (newPoint.equals(oldPoint)) { 675 continue; 676 } 677 678 if (!newPoint.isLatLonKnown()) { 679 return false; 680 } 681 682 //order points so p1.lat <= p2.lat 683 if (newPoint.getEastNorth().getY() > oldPoint.getEastNorth().getY()) { 684 p1 = oldPoint; 685 p2 = newPoint; 686 } else { 687 p1 = newPoint; 688 p2 = oldPoint; 689 } 690 691 EastNorth pEN = point.getEastNorth(); 692 EastNorth opEN = oldPoint.getEastNorth(); 693 EastNorth npEN = newPoint.getEastNorth(); 694 EastNorth p1EN = p1.getEastNorth(); 695 EastNorth p2EN = p2.getEastNorth(); 696 697 if (pEN != null && opEN != null && npEN != null && p1EN != null && p2EN != null) { 698 //test if the line is crossed and if so invert the inside flag. 699 if ((npEN.getY() < pEN.getY()) == (pEN.getY() <= opEN.getY()) 700 && (pEN.getX() - p1EN.getX()) * (p2EN.getY() - p1EN.getY()) 701 < (p2EN.getX() - p1EN.getX()) * (pEN.getY() - p1EN.getY())) { 702 inside = !inside; 703 } 704 } 705 706 oldPoint = newPoint; 707 } 708 709 return inside; 710 } 711 712 /** 713 * Returns area of a closed way in square meters. 714 * 715 * @param way Way to measure, should be closed (first node is the same as last node) 716 * @return area of the closed way. 717 */ 718 public static double closedWayArea(Way way) { 719 return getAreaAndPerimeter(way.getNodes(), Projections.getProjectionByCode("EPSG:54008")).getArea(); 720 } 721 722 /** 723 * Returns area of a multipolygon in square meters. 724 * 725 * @param multipolygon the multipolygon to measure 726 * @return area of the multipolygon. 727 */ 728 public static double multipolygonArea(Relation multipolygon) { 729 double area = 0.0; 730 final Multipolygon mp = MultipolygonCache.getInstance().get(multipolygon); 731 for (Multipolygon.PolyData pd : mp.getCombinedPolygons()) { 732 area += pd.getAreaAndPerimeter(Projections.getProjectionByCode("EPSG:54008")).getArea(); 733 } 734 return area; 735 } 736 737 /** 738 * Computes the area of a closed way and multipolygon in square meters, or {@code null} for other primitives 739 * 740 * @param osm the primitive to measure 741 * @return area of the primitive, or {@code null} 742 * @since 13638 (signature) 743 */ 744 public static Double computeArea(IPrimitive osm) { 745 if (osm instanceof Way && ((Way) osm).isClosed()) { 746 return closedWayArea((Way) osm); 747 } else if (osm instanceof Relation && ((Relation) osm).isMultipolygon() && !((Relation) osm).hasIncompleteMembers()) { 748 return multipolygonArea((Relation) osm); 749 } else { 750 return null; 751 } 752 } 753 754 /** 755 * Determines whether a way is oriented clockwise. 756 * 757 * Internals: Assuming a closed non-looping way, compute twice the area 758 * of the polygon using the formula {@code 2 * area = sum (X[n] * Y[n+1] - X[n+1] * Y[n])}. 759 * If the area is negative the way is ordered in a clockwise direction. 760 * 761 * See http://paulbourke.net/geometry/polyarea/ 762 * 763 * @param w the way to be checked. 764 * @return true if and only if way is oriented clockwise. 765 * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}). 766 */ 767 public static boolean isClockwise(Way w) { 768 return isClockwise(w.getNodes()); 769 } 770 771 /** 772 * Determines whether path from nodes list is oriented clockwise. 773 * @param nodes Nodes list to be checked. 774 * @return true if and only if way is oriented clockwise. 775 * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}). 776 * @see #isClockwise(Way) 777 */ 778 public static boolean isClockwise(List<? extends INode> nodes) { 779 int nodesCount = nodes.size(); 780 if (nodesCount < 3 || nodes.get(0) != nodes.get(nodesCount - 1)) { 781 throw new IllegalArgumentException("Way must be closed to check orientation."); 782 } 783 double area2 = 0.; 784 785 for (int node = 1; node <= /*sic! consider last-first as well*/ nodesCount; node++) { 786 INode coorPrev = nodes.get(node - 1); 787 INode coorCurr = nodes.get(node % nodesCount); 788 area2 += coorPrev.lon() * coorCurr.lat(); 789 area2 -= coorCurr.lon() * coorPrev.lat(); 790 } 791 return area2 < 0; 792 } 793 794 /** 795 * Returns angle of a segment defined with 2 point coordinates. 796 * 797 * @param p1 first point 798 * @param p2 second point 799 * @return Angle in radians (-pi, pi] 800 */ 801 public static double getSegmentAngle(EastNorth p1, EastNorth p2) { 802 803 CheckParameterUtil.ensure(p1, "p1", EastNorth::isValid); 804 CheckParameterUtil.ensure(p2, "p2", EastNorth::isValid); 805 806 return Math.atan2(p2.north() - p1.north(), p2.east() - p1.east()); 807 } 808 809 /** 810 * Returns angle of a corner defined with 3 point coordinates. 811 * 812 * @param p1 first point 813 * @param common Common end point 814 * @param p3 third point 815 * @return Angle in radians (-pi, pi] 816 */ 817 public static double getCornerAngle(EastNorth p1, EastNorth common, EastNorth p3) { 818 819 CheckParameterUtil.ensure(p1, "p1", EastNorth::isValid); 820 CheckParameterUtil.ensure(common, "p2", EastNorth::isValid); 821 CheckParameterUtil.ensure(p3, "p3", EastNorth::isValid); 822 823 double result = getSegmentAngle(common, p1) - getSegmentAngle(common, p3); 824 if (result <= -Math.PI) { 825 result += 2 * Math.PI; 826 } 827 828 if (result > Math.PI) { 829 result -= 2 * Math.PI; 830 } 831 832 return result; 833 } 834 835 /** 836 * Get angles in radians and return it's value in range [0, 180]. 837 * 838 * @param angle the angle in radians 839 * @return normalized angle in degrees 840 * @since 13670 841 */ 842 public static double getNormalizedAngleInDegrees(double angle) { 843 return Math.abs(180 * angle / Math.PI); 844 } 845 846 /** 847 * Compute the centroid/barycenter of nodes 848 * @param nodes Nodes for which the centroid is wanted 849 * @return the centroid of nodes 850 * @see Geometry#getCenter 851 */ 852 public static EastNorth getCentroid(List<? extends INode> nodes) { 853 return getCentroidEN(nodes.stream().map(INode::getEastNorth).collect(Collectors.toList())); 854 } 855 856 /** 857 * Compute the centroid/barycenter of nodes 858 * @param nodes Coordinates for which the centroid is wanted 859 * @return the centroid of nodes 860 * @since 13712 861 */ 862 public static EastNorth getCentroidEN(List<EastNorth> nodes) { 863 864 final int size = nodes.size(); 865 if (size == 1) { 866 return nodes.get(0); 867 } else if (size == 2) { 868 return nodes.get(0).getCenter(nodes.get(1)); 869 } 870 871 BigDecimal area = BigDecimal.ZERO; 872 BigDecimal north = BigDecimal.ZERO; 873 BigDecimal east = BigDecimal.ZERO; 874 875 // See https://en.wikipedia.org/wiki/Centroid#Of_a_polygon for the equation used here 876 for (int i = 0; i < size; i++) { 877 EastNorth n0 = nodes.get(i); 878 EastNorth n1 = nodes.get((i+1) % size); 879 880 if (n0 != null && n1 != null && n0.isValid() && n1.isValid()) { 881 BigDecimal x0 = BigDecimal.valueOf(n0.east()); 882 BigDecimal y0 = BigDecimal.valueOf(n0.north()); 883 BigDecimal x1 = BigDecimal.valueOf(n1.east()); 884 BigDecimal y1 = BigDecimal.valueOf(n1.north()); 885 886 BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128)); 887 888 area = area.add(k, MathContext.DECIMAL128); 889 east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128)); 890 north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128)); 891 } 892 } 893 894 BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3 895 area = area.multiply(d, MathContext.DECIMAL128); 896 if (area.compareTo(BigDecimal.ZERO) != 0) { 897 north = north.divide(area, MathContext.DECIMAL128); 898 east = east.divide(area, MathContext.DECIMAL128); 899 } 900 901 return new EastNorth(east.doubleValue(), north.doubleValue()); 902 } 903 904 /** 905 * Compute center of the circle closest to different nodes. 906 * 907 * Ensure exact center computation in case nodes are already aligned in circle. 908 * This is done by least square method. 909 * Let be a_i x + b_i y + c_i = 0 equations of bisectors of each edges. 910 * Center must be intersection of all bisectors. 911 * <pre> 912 * [ a1 b1 ] [ -c1 ] 913 * With A = [ ... ... ] and Y = [ ... ] 914 * [ an bn ] [ -cn ] 915 * </pre> 916 * An approximation of center of circle is (At.A)^-1.At.Y 917 * @param nodes Nodes parts of the circle (at least 3) 918 * @return An approximation of the center, of null if there is no solution. 919 * @see Geometry#getCentroid 920 * @since 6934 921 */ 922 public static EastNorth getCenter(List<? extends INode> nodes) { 923 int nc = nodes.size(); 924 if (nc < 3) return null; 925 /** 926 * Equation of each bisector ax + by + c = 0 927 */ 928 double[] a = new double[nc]; 929 double[] b = new double[nc]; 930 double[] c = new double[nc]; 931 // Compute equation of bisector 932 for (int i = 0; i < nc; i++) { 933 EastNorth pt1 = nodes.get(i).getEastNorth(); 934 EastNorth pt2 = nodes.get((i+1) % nc).getEastNorth(); 935 a[i] = pt1.east() - pt2.east(); 936 b[i] = pt1.north() - pt2.north(); 937 double d = Math.sqrt(a[i]*a[i] + b[i]*b[i]); 938 if (d == 0) return null; 939 a[i] /= d; 940 b[i] /= d; 941 double xC = (pt1.east() + pt2.east()) / 2; 942 double yC = (pt1.north() + pt2.north()) / 2; 943 c[i] = -(a[i]*xC + b[i]*yC); 944 } 945 // At.A = [aij] 946 double a11 = 0, a12 = 0, a22 = 0; 947 // At.Y = [bi] 948 double b1 = 0, b2 = 0; 949 for (int i = 0; i < nc; i++) { 950 a11 += a[i]*a[i]; 951 a12 += a[i]*b[i]; 952 a22 += b[i]*b[i]; 953 b1 -= a[i]*c[i]; 954 b2 -= b[i]*c[i]; 955 } 956 // (At.A)^-1 = [invij] 957 double det = a11*a22 - a12*a12; 958 if (Math.abs(det) < 1e-5) return null; 959 double inv11 = a22/det; 960 double inv12 = -a12/det; 961 double inv22 = a11/det; 962 // center (xC, yC) = (At.A)^-1.At.y 963 double xC = inv11*b1 + inv12*b2; 964 double yC = inv12*b1 + inv22*b2; 965 return new EastNorth(xC, yC); 966 } 967 968 /** 969 * Tests if the {@code node} is inside the multipolygon {@code multiPolygon}. The nullable argument 970 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match. 971 * @param node node 972 * @param multiPolygon multipolygon 973 * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match 974 * @return {@code true} if the node is inside the multipolygon 975 */ 976 public static boolean isNodeInsideMultiPolygon(INode node, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) { 977 return isPolygonInsideMultiPolygon(Collections.singletonList(node), multiPolygon, isOuterWayAMatch); 978 } 979 980 /** 981 * Tests if the polygon formed by {@code nodes} is inside the multipolygon {@code multiPolygon}. The nullable argument 982 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match. 983 * <p> 984 * If {@code nodes} contains exactly one element, then it is checked whether that one node is inside the multipolygon. 985 * @param nodes nodes forming the polygon 986 * @param multiPolygon multipolygon 987 * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match 988 * @return {@code true} if the polygon formed by nodes is inside the multipolygon 989 */ 990 public static boolean isPolygonInsideMultiPolygon(List<? extends INode> nodes, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) { 991 // Extract outer/inner members from multipolygon 992 final Pair<List<JoinedPolygon>, List<JoinedPolygon>> outerInner; 993 try { 994 outerInner = MultipolygonBuilder.joinWays(multiPolygon); 995 } catch (MultipolygonBuilder.JoinedPolygonCreationException ex) { 996 Logging.trace(ex); 997 Logging.debug("Invalid multipolygon " + multiPolygon); 998 return false; 999 } 1000 // Test if object is inside an outer member 1001 for (JoinedPolygon out : outerInner.a) { 1002 if (nodes.size() == 1 1003 ? nodeInsidePolygon(nodes.get(0), out.getNodes()) 1004 : PolygonIntersection.FIRST_INSIDE_SECOND == polygonIntersection(nodes, out.getNodes())) { 1005 boolean insideInner = false; 1006 // If inside an outer, check it is not inside an inner 1007 for (JoinedPolygon in : outerInner.b) { 1008 if (nodes.size() == 1 ? nodeInsidePolygon(nodes.get(0), in.getNodes()) 1009 : polygonIntersection(nodes, in.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND 1010 && polygonIntersection(in.getNodes(), 1011 out.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND) { 1012 insideInner = true; 1013 break; 1014 } 1015 } 1016 // Inside outer but not inside inner -> the polygon appears to be inside a the multipolygon 1017 if (!insideInner) { 1018 // Final check using predicate 1019 if (isOuterWayAMatch == null || isOuterWayAMatch.test(out.ways.get(0) 1020 /* TODO give a better representation of the outer ring to the predicate */)) { 1021 return true; 1022 } 1023 } 1024 } 1025 } 1026 return false; 1027 } 1028 1029 /** 1030 * Data class to hold two double values (area and perimeter of a polygon). 1031 */ 1032 public static class AreaAndPerimeter { 1033 private final double area; 1034 private final double perimeter; 1035 1036 /** 1037 * Create a new {@link AreaAndPerimeter} 1038 * @param area The area 1039 * @param perimeter The perimeter 1040 */ 1041 public AreaAndPerimeter(double area, double perimeter) { 1042 this.area = area; 1043 this.perimeter = perimeter; 1044 } 1045 1046 /** 1047 * Gets the area 1048 * @return The area size 1049 */ 1050 public double getArea() { 1051 return area; 1052 } 1053 1054 /** 1055 * Gets the perimeter 1056 * @return The perimeter length 1057 */ 1058 public double getPerimeter() { 1059 return perimeter; 1060 } 1061 } 1062 1063 /** 1064 * Calculate area and perimeter length of a polygon. 1065 * 1066 * Uses current projection; units are that of the projected coordinates. 1067 * 1068 * @param nodes the list of nodes representing the polygon 1069 * @return area and perimeter 1070 */ 1071 public static AreaAndPerimeter getAreaAndPerimeter(List<? extends ILatLon> nodes) { 1072 return getAreaAndPerimeter(nodes, null); 1073 } 1074 1075 /** 1076 * Calculate area and perimeter length of a polygon in the given projection. 1077 * 1078 * @param nodes the list of nodes representing the polygon 1079 * @param projection the projection to use for the calculation, {@code null} defaults to {@link ProjectionRegistry#getProjection()} 1080 * @return area and perimeter 1081 * @since 13638 (signature) 1082 */ 1083 public static AreaAndPerimeter getAreaAndPerimeter(List<? extends ILatLon> nodes, Projection projection) { 1084 CheckParameterUtil.ensureParameterNotNull(nodes, "nodes"); 1085 double area = 0; 1086 double perimeter = 0; 1087 Projection useProjection = projection == null ? ProjectionRegistry.getProjection() : projection; 1088 1089 if (!nodes.isEmpty()) { 1090 boolean closed = nodes.get(0) == nodes.get(nodes.size() - 1); 1091 int numSegments = closed ? nodes.size() - 1 : nodes.size(); 1092 EastNorth p1 = nodes.get(0).getEastNorth(useProjection); 1093 for (int i = 1; i <= numSegments; i++) { 1094 final ILatLon node = nodes.get(i == numSegments ? 0 : i); 1095 final EastNorth p2 = node.getEastNorth(useProjection); 1096 if (p1 != null && p2 != null) { 1097 area += p1.east() * p2.north() - p2.east() * p1.north(); 1098 perimeter += p1.distance(p2); 1099 } 1100 p1 = p2; 1101 } 1102 } 1103 return new AreaAndPerimeter(Math.abs(area) / 2, perimeter); 1104 } 1105}