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