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

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

sonar - Unused private method should be removed
sonar - Unused protected methods should be removed
sonar - Sections of code should not be "commented out"
sonar - Empty statements should be removed
sonar - squid:S1172 - Unused method parameters should be removed
sonar - squid:S1481 - Unused local variables should be removed

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