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

Last change on this file since 10656 was 10656, checked in by Don-vip, 8 years ago

see #12472 - fix warning "ReferenceEquality"

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