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

Last change on this file since 11329 was 11243, checked in by Don-vip, 7 years ago

see #10387 - fix unit tests

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