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

Last change on this file since 11366 was 11361, checked in by bastiK, 7 years ago

see #10387 - use path winding rule instead of Area.subtract

  • Property svn:eol-style set to native
File size: 39.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
481 * @return Area for the given list of nodes (EastNorth coordinates)
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 * Builds a path from a list of nodes
508 * @param polygon Nodes, forming a closed polygon
509 * @param path path to add to; can be null, then a new path is created
510 * @return the path (LatLon coordinates)
511 */
512 public static Path2D buildPath2DLatLon(List<Node> polygon, Path2D path) {
513 if (path == null) {
514 path = new Path2D.Double();
515 }
516 boolean begin = true;
517 for (Node n : polygon) {
518 if (begin) {
519 path.moveTo(n.getCoor().lon(), n.getCoor().lat());
520 begin = false;
521 } else {
522 path.lineTo(n.getCoor().lon(), n.getCoor().lat());
523 }
524 }
525 if (!begin) {
526 path.closePath();
527 }
528 return path;
529 }
530
531 /**
532 * Returns the Area of a polygon, from the multipolygon relation.
533 * @param multipolygon the multipolygon relation
534 * @return Area for the multipolygon (LatLon coordinates)
535 */
536 public static Area getAreaLatLon(Relation multipolygon) {
537 final Multipolygon mp = Main.map == null || Main.map.mapView == null
538 ? new Multipolygon(multipolygon)
539 : MultipolygonCache.getInstance().get(Main.map.mapView, multipolygon);
540 Path2D path = new Path2D.Double();
541 path.setWindingRule(Path2D.WIND_EVEN_ODD);
542 for (Multipolygon.PolyData pd : mp.getCombinedPolygons()) {
543 buildPath2DLatLon(pd.getNodes(), path);
544 for (Multipolygon.PolyData pdInner : pd.getInners()) {
545 buildPath2DLatLon(pdInner.getNodes(), path);
546 }
547 }
548 return new Area(path);
549 }
550
551 /**
552 * Tests if two polygons intersect.
553 * @param first List of nodes forming first polygon
554 * @param second List of nodes forming second polygon
555 * @return intersection kind
556 */
557 public static PolygonIntersection polygonIntersection(List<Node> first, List<Node> second) {
558 Area a1 = getArea(first);
559 Area a2 = getArea(second);
560 return polygonIntersection(a1, a2);
561 }
562
563 /**
564 * Tests if two polygons intersect.
565 * @param a1 Area of first polygon
566 * @param a2 Area of second polygon
567 * @return intersection kind
568 * @since 6841
569 */
570 public static PolygonIntersection polygonIntersection(Area a1, Area a2) {
571 return polygonIntersection(a1, a2, 1.0);
572 }
573
574 /**
575 * Tests if two polygons intersect.
576 * @param a1 Area of first polygon
577 * @param a2 Area of second polygon
578 * @param eps an area threshold, everything below is considered an empty intersection
579 * @return intersection kind
580 */
581 public static PolygonIntersection polygonIntersection(Area a1, Area a2, double eps) {
582
583 Area inter = new Area(a1);
584 inter.intersect(a2);
585
586 Rectangle bounds = inter.getBounds();
587
588 if (inter.isEmpty() || bounds.getHeight()*bounds.getWidth() <= eps) {
589 return PolygonIntersection.OUTSIDE;
590 } else if (a2.getBounds2D().contains(a1.getBounds2D()) && inter.equals(a1)) {
591 return PolygonIntersection.FIRST_INSIDE_SECOND;
592 } else if (a1.getBounds2D().contains(a2.getBounds2D()) && inter.equals(a2)) {
593 return PolygonIntersection.SECOND_INSIDE_FIRST;
594 } else {
595 return PolygonIntersection.CROSSING;
596 }
597 }
598
599 /**
600 * Tests if point is inside a polygon. The polygon can be self-intersecting. In such case the contains function works in xor-like manner.
601 * @param polygonNodes list of nodes from polygon path.
602 * @param point the point to test
603 * @return true if the point is inside polygon.
604 */
605 public static boolean nodeInsidePolygon(Node point, List<Node> polygonNodes) {
606 if (polygonNodes.size() < 2)
607 return false;
608
609 //iterate each side of the polygon, start with the last segment
610 Node oldPoint = polygonNodes.get(polygonNodes.size() - 1);
611
612 if (!oldPoint.isLatLonKnown()) {
613 return false;
614 }
615
616 boolean inside = false;
617 Node p1, p2;
618
619 for (Node newPoint : polygonNodes) {
620 //skip duplicate points
621 if (newPoint.equals(oldPoint)) {
622 continue;
623 }
624
625 if (!newPoint.isLatLonKnown()) {
626 return false;
627 }
628
629 //order points so p1.lat <= p2.lat
630 if (newPoint.getEastNorth().getY() > oldPoint.getEastNorth().getY()) {
631 p1 = oldPoint;
632 p2 = newPoint;
633 } else {
634 p1 = newPoint;
635 p2 = oldPoint;
636 }
637
638 EastNorth pEN = point.getEastNorth();
639 EastNorth opEN = oldPoint.getEastNorth();
640 EastNorth npEN = newPoint.getEastNorth();
641 EastNorth p1EN = p1.getEastNorth();
642 EastNorth p2EN = p2.getEastNorth();
643
644 if (pEN != null && opEN != null && npEN != null && p1EN != null && p2EN != null) {
645 //test if the line is crossed and if so invert the inside flag.
646 if ((npEN.getY() < pEN.getY()) == (pEN.getY() <= opEN.getY())
647 && (pEN.getX() - p1EN.getX()) * (p2EN.getY() - p1EN.getY())
648 < (p2EN.getX() - p1EN.getX()) * (pEN.getY() - p1EN.getY())) {
649 inside = !inside;
650 }
651 }
652
653 oldPoint = newPoint;
654 }
655
656 return inside;
657 }
658
659 /**
660 * Returns area of a closed way in square meters.
661 *
662 * @param way Way to measure, should be closed (first node is the same as last node)
663 * @return area of the closed way.
664 */
665 public static double closedWayArea(Way way) {
666 return getAreaAndPerimeter(way.getNodes(), Projections.getProjectionByCode("EPSG:54008")).getArea();
667 }
668
669 /**
670 * Returns area of a multipolygon in square meters.
671 *
672 * @param multipolygon the multipolygon to measure
673 * @return area of the multipolygon.
674 */
675 public static double multipolygonArea(Relation multipolygon) {
676 double area = 0.0;
677 final Multipolygon mp = Main.map == null || Main.map.mapView == null
678 ? new Multipolygon(multipolygon)
679 : MultipolygonCache.getInstance().get(Main.map.mapView, multipolygon);
680 for (Multipolygon.PolyData pd : mp.getCombinedPolygons()) {
681 area += pd.getAreaAndPerimeter(Projections.getProjectionByCode("EPSG:54008")).getArea();
682 }
683 return area;
684 }
685
686 /**
687 * Computes the area of a closed way and multipolygon in square meters, or {@code null} for other primitives
688 *
689 * @param osm the primitive to measure
690 * @return area of the primitive, or {@code null}
691 */
692 public static Double computeArea(OsmPrimitive osm) {
693 if (osm instanceof Way && ((Way) osm).isClosed()) {
694 return closedWayArea((Way) osm);
695 } else if (osm instanceof Relation && ((Relation) osm).isMultipolygon() && !((Relation) osm).hasIncompleteMembers()) {
696 return multipolygonArea((Relation) osm);
697 } else {
698 return null;
699 }
700 }
701
702 /**
703 * Determines whether a way is oriented clockwise.
704 *
705 * Internals: Assuming a closed non-looping way, compute twice the area
706 * of the polygon using the formula {@code 2 * area = sum (X[n] * Y[n+1] - X[n+1] * Y[n])}.
707 * If the area is negative the way is ordered in a clockwise direction.
708 *
709 * See http://paulbourke.net/geometry/polyarea/
710 *
711 * @param w the way to be checked.
712 * @return true if and only if way is oriented clockwise.
713 * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}).
714 */
715 public static boolean isClockwise(Way w) {
716 return isClockwise(w.getNodes());
717 }
718
719 /**
720 * Determines whether path from nodes list is oriented clockwise.
721 * @param nodes Nodes list to be checked.
722 * @return true if and only if way is oriented clockwise.
723 * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}).
724 * @see #isClockwise(Way)
725 */
726 public static boolean isClockwise(List<Node> nodes) {
727 int nodesCount = nodes.size();
728 if (nodesCount < 3 || nodes.get(0) != nodes.get(nodesCount - 1)) {
729 throw new IllegalArgumentException("Way must be closed to check orientation.");
730 }
731 double area2 = 0.;
732
733 for (int node = 1; node <= /*sic! consider last-first as well*/ nodesCount; node++) {
734 LatLon coorPrev = nodes.get(node - 1).getCoor();
735 LatLon coorCurr = nodes.get(node % nodesCount).getCoor();
736 area2 += coorPrev.lon() * coorCurr.lat();
737 area2 -= coorCurr.lon() * coorPrev.lat();
738 }
739 return area2 < 0;
740 }
741
742 /**
743 * Returns angle of a segment defined with 2 point coordinates.
744 *
745 * @param p1 first point
746 * @param p2 second point
747 * @return Angle in radians (-pi, pi]
748 */
749 public static double getSegmentAngle(EastNorth p1, EastNorth p2) {
750
751 CheckParameterUtil.ensureValidCoordinates(p1, "p1");
752 CheckParameterUtil.ensureValidCoordinates(p2, "p2");
753
754 return Math.atan2(p2.north() - p1.north(), p2.east() - p1.east());
755 }
756
757 /**
758 * Returns angle of a corner defined with 3 point coordinates.
759 *
760 * @param p1 first point
761 * @param p2 Common endpoint
762 * @param p3 third point
763 * @return Angle in radians (-pi, pi]
764 */
765 public static double getCornerAngle(EastNorth p1, EastNorth p2, EastNorth p3) {
766
767 CheckParameterUtil.ensureValidCoordinates(p1, "p1");
768 CheckParameterUtil.ensureValidCoordinates(p2, "p2");
769 CheckParameterUtil.ensureValidCoordinates(p3, "p3");
770
771 Double result = getSegmentAngle(p2, p1) - getSegmentAngle(p2, p3);
772 if (result <= -Math.PI) {
773 result += 2 * Math.PI;
774 }
775
776 if (result > Math.PI) {
777 result -= 2 * Math.PI;
778 }
779
780 return result;
781 }
782
783 /**
784 * Compute the centroid/barycenter of nodes
785 * @param nodes Nodes for which the centroid is wanted
786 * @return the centroid of nodes
787 * @see Geometry#getCenter
788 */
789 public static EastNorth getCentroid(List<Node> nodes) {
790
791 BigDecimal area = BigDecimal.ZERO;
792 BigDecimal north = BigDecimal.ZERO;
793 BigDecimal east = BigDecimal.ZERO;
794
795 // See https://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon for the equation used here
796 for (int i = 0; i < nodes.size(); i++) {
797 EastNorth n0 = nodes.get(i).getEastNorth();
798 EastNorth n1 = nodes.get((i+1) % nodes.size()).getEastNorth();
799
800 if (n0 != null && n1 != null && n0.isValid() && n1.isValid()) {
801 BigDecimal x0 = BigDecimal.valueOf(n0.east());
802 BigDecimal y0 = BigDecimal.valueOf(n0.north());
803 BigDecimal x1 = BigDecimal.valueOf(n1.east());
804 BigDecimal y1 = BigDecimal.valueOf(n1.north());
805
806 BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128));
807
808 area = area.add(k, MathContext.DECIMAL128);
809 east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128));
810 north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128));
811 }
812 }
813
814 BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3
815 area = area.multiply(d, MathContext.DECIMAL128);
816 if (area.compareTo(BigDecimal.ZERO) != 0) {
817 north = north.divide(area, MathContext.DECIMAL128);
818 east = east.divide(area, MathContext.DECIMAL128);
819 }
820
821 return new EastNorth(east.doubleValue(), north.doubleValue());
822 }
823
824 /**
825 * Compute center of the circle closest to different nodes.
826 *
827 * Ensure exact center computation in case nodes are already aligned in circle.
828 * This is done by least square method.
829 * Let be a_i x + b_i y + c_i = 0 equations of bisectors of each edges.
830 * Center must be intersection of all bisectors.
831 * <pre>
832 * [ a1 b1 ] [ -c1 ]
833 * With A = [ ... ... ] and Y = [ ... ]
834 * [ an bn ] [ -cn ]
835 * </pre>
836 * An approximation of center of circle is (At.A)^-1.At.Y
837 * @param nodes Nodes parts of the circle (at least 3)
838 * @return An approximation of the center, of null if there is no solution.
839 * @see Geometry#getCentroid
840 * @since 6934
841 */
842 public static EastNorth getCenter(List<Node> nodes) {
843 int nc = nodes.size();
844 if (nc < 3) return null;
845 /**
846 * Equation of each bisector ax + by + c = 0
847 */
848 double[] a = new double[nc];
849 double[] b = new double[nc];
850 double[] c = new double[nc];
851 // Compute equation of bisector
852 for (int i = 0; i < nc; i++) {
853 EastNorth pt1 = nodes.get(i).getEastNorth();
854 EastNorth pt2 = nodes.get((i+1) % nc).getEastNorth();
855 a[i] = pt1.east() - pt2.east();
856 b[i] = pt1.north() - pt2.north();
857 double d = Math.sqrt(a[i]*a[i] + b[i]*b[i]);
858 if (d == 0) return null;
859 a[i] /= d;
860 b[i] /= d;
861 double xC = (pt1.east() + pt2.east()) / 2;
862 double yC = (pt1.north() + pt2.north()) / 2;
863 c[i] = -(a[i]*xC + b[i]*yC);
864 }
865 // At.A = [aij]
866 double a11 = 0, a12 = 0, a22 = 0;
867 // At.Y = [bi]
868 double b1 = 0, b2 = 0;
869 for (int i = 0; i < nc; i++) {
870 a11 += a[i]*a[i];
871 a12 += a[i]*b[i];
872 a22 += b[i]*b[i];
873 b1 -= a[i]*c[i];
874 b2 -= b[i]*c[i];
875 }
876 // (At.A)^-1 = [invij]
877 double det = a11*a22 - a12*a12;
878 if (Math.abs(det) < 1e-5) return null;
879 double inv11 = a22/det;
880 double inv12 = -a12/det;
881 double inv22 = a11/det;
882 // center (xC, yC) = (At.A)^-1.At.y
883 double xC = inv11*b1 + inv12*b2;
884 double yC = inv12*b1 + inv22*b2;
885 return new EastNorth(xC, yC);
886 }
887
888 /**
889 * Tests if the {@code node} is inside the multipolygon {@code multiPolygon}. The nullable argument
890 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
891 * @param node node
892 * @param multiPolygon multipolygon
893 * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match
894 * @return {@code true} if the node is inside the multipolygon
895 */
896 public static boolean isNodeInsideMultiPolygon(Node node, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
897 return isPolygonInsideMultiPolygon(Collections.singletonList(node), multiPolygon, isOuterWayAMatch);
898 }
899
900 /**
901 * Tests if the polygon formed by {@code nodes} is inside the multipolygon {@code multiPolygon}. The nullable argument
902 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
903 * <p>
904 * If {@code nodes} contains exactly one element, then it is checked whether that one node is inside the multipolygon.
905 * @param nodes nodes forming the polygon
906 * @param multiPolygon multipolygon
907 * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match
908 * @return {@code true} if the polygon formed by nodes is inside the multipolygon
909 */
910 public static boolean isPolygonInsideMultiPolygon(List<Node> nodes, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
911 // Extract outer/inner members from multipolygon
912 final Pair<List<JoinedPolygon>, List<JoinedPolygon>> outerInner;
913 try {
914 outerInner = MultipolygonBuilder.joinWays(multiPolygon);
915 } catch (MultipolygonBuilder.JoinedPolygonCreationException ex) {
916 Main.trace(ex);
917 Main.debug("Invalid multipolygon " + multiPolygon);
918 return false;
919 }
920 // Test if object is inside an outer member
921 for (JoinedPolygon out : outerInner.a) {
922 if (nodes.size() == 1
923 ? nodeInsidePolygon(nodes.get(0), out.getNodes())
924 : EnumSet.of(PolygonIntersection.FIRST_INSIDE_SECOND, PolygonIntersection.CROSSING).contains(
925 polygonIntersection(nodes, out.getNodes()))) {
926 boolean insideInner = false;
927 // If inside an outer, check it is not inside an inner
928 for (JoinedPolygon in : outerInner.b) {
929 if (polygonIntersection(in.getNodes(), out.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND
930 && (nodes.size() == 1
931 ? nodeInsidePolygon(nodes.get(0), in.getNodes())
932 : polygonIntersection(nodes, in.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND)) {
933 insideInner = true;
934 break;
935 }
936 }
937 // Inside outer but not inside inner -> the polygon appears to be inside a the multipolygon
938 if (!insideInner) {
939 // Final check using predicate
940 if (isOuterWayAMatch == null || isOuterWayAMatch.test(out.ways.get(0)
941 /* TODO give a better representation of the outer ring to the predicate */)) {
942 return true;
943 }
944 }
945 }
946 }
947 return false;
948 }
949
950 /**
951 * Data class to hold two double values (area and perimeter of a polygon).
952 */
953 public static class AreaAndPerimeter {
954 private final double area;
955 private final double perimeter;
956
957 public AreaAndPerimeter(double area, double perimeter) {
958 this.area = area;
959 this.perimeter = perimeter;
960 }
961
962 public double getArea() {
963 return area;
964 }
965
966 public double getPerimeter() {
967 return perimeter;
968 }
969 }
970
971 /**
972 * Calculate area and perimeter length of a polygon.
973 *
974 * Uses current projection; units are that of the projected coordinates.
975 *
976 * @param nodes the list of nodes representing the polygon
977 * @return area and perimeter
978 */
979 public static AreaAndPerimeter getAreaAndPerimeter(List<Node> nodes) {
980 return getAreaAndPerimeter(nodes, null);
981 }
982
983 /**
984 * Calculate area and perimeter length of a polygon in the given projection.
985 *
986 * @param nodes the list of nodes representing the polygon
987 * @param projection the projection to use for the calculation, {@code null} defaults to {@link Main#getProjection()}
988 * @return area and perimeter
989 */
990 public static AreaAndPerimeter getAreaAndPerimeter(List<Node> nodes, Projection projection) {
991 CheckParameterUtil.ensureParameterNotNull(nodes, "nodes");
992 double area = 0;
993 double perimeter = 0;
994 if (!nodes.isEmpty()) {
995 boolean closed = nodes.get(0) == nodes.get(nodes.size() - 1);
996 int numSegments = closed ? nodes.size() - 1 : nodes.size();
997 EastNorth p1 = projection == null ? nodes.get(0).getEastNorth() : projection.latlon2eastNorth(nodes.get(0).getCoor());
998 for (int i = 1; i <= numSegments; i++) {
999 final Node node = nodes.get(i == numSegments ? 0 : i);
1000 final EastNorth p2 = projection == null ? node.getEastNorth() : projection.latlon2eastNorth(node.getCoor());
1001 if (p1 != null && p2 != null) {
1002 area += p1.east() * p2.north() - p2.east() * p1.north();
1003 perimeter += p1.distance(p2);
1004 }
1005 p1 = p2;
1006 }
1007 }
1008 return new AreaAndPerimeter(Math.abs(area) / 2, perimeter);
1009 }
1010}
Note: See TracBrowser for help on using the repository browser.