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

Last change on this file since 11747 was 11664, checked in by michael2402, 7 years ago

Remove redundant isValid check.

  • Property svn:eol-style set to native
File size: 39.5 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.get(0).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 // Basically, the formula from wikipedia is used:
349 // https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
350 // However, large numbers lead to rounding errors (see #10286).
351 // To avoid this, p1 is first substracted from each of the points:
352 // p1' = 0
353 // p2' = p2 - p1
354 // p3' = p3 - p1
355 // p4' = p4 - p1
356 // In the end, p1 is added to the intersection point of segment p1'/p2'
357 // and segment p3'/p4'.
358
359 // Convert line from (point, point) form to ax+by=c
360 double a1 = p2.getY() - p1.getY();
361 double b1 = p1.getX() - p2.getX();
362
363 double a2 = p4.getY() - p3.getY();
364 double b2 = p3.getX() - p4.getX();
365
366 // Solve the equations
367 double det = a1 * b2 - a2 * b1;
368 if (det == 0)
369 return null; // Lines are parallel
370
371 double c2 = (p4.getX() - p1.getX()) * (p3.getY() - p1.getY()) - (p3.getX() - p1.getX()) * (p4.getY() - p1.getY());
372
373 return new EastNorth(b1 * c2 / det + p1.getX(), -a1 * c2 / det + p1.getY());
374 }
375
376 public static boolean segmentsParallel(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
377
378 CheckParameterUtil.ensureValidCoordinates(p1, "p1");
379 CheckParameterUtil.ensureValidCoordinates(p2, "p2");
380 CheckParameterUtil.ensureValidCoordinates(p3, "p3");
381 CheckParameterUtil.ensureValidCoordinates(p4, "p4");
382
383 // Convert line from (point, point) form to ax+by=c
384 double a1 = p2.getY() - p1.getY();
385 double b1 = p1.getX() - p2.getX();
386
387 double a2 = p4.getY() - p3.getY();
388 double b2 = p3.getX() - p4.getX();
389
390 // Solve the equations
391 double det = a1 * b2 - a2 * b1;
392 // remove influence of of scaling factor
393 det /= Math.sqrt(a1*a1 + b1*b1) * Math.sqrt(a2*a2 + b2*b2);
394 return Math.abs(det) < 1e-3;
395 }
396
397 private static EastNorth closestPointTo(EastNorth p1, EastNorth p2, EastNorth point, boolean segmentOnly) {
398 CheckParameterUtil.ensureParameterNotNull(p1, "p1");
399 CheckParameterUtil.ensureParameterNotNull(p2, "p2");
400 CheckParameterUtil.ensureParameterNotNull(point, "point");
401
402 double ldx = p2.getX() - p1.getX();
403 double ldy = p2.getY() - p1.getY();
404
405 //segment zero length
406 if (ldx == 0 && ldy == 0)
407 return p1;
408
409 double pdx = point.getX() - p1.getX();
410 double pdy = point.getY() - p1.getY();
411
412 double offset = (pdx * ldx + pdy * ldy) / (ldx * ldx + ldy * ldy);
413
414 if (segmentOnly && offset <= 0)
415 return p1;
416 else if (segmentOnly && offset >= 1)
417 return p2;
418 else
419 return new EastNorth(p1.getX() + ldx * offset, p1.getY() + ldy * offset);
420 }
421
422 /**
423 * Calculates closest point to a line segment.
424 * @param segmentP1 First point determining line segment
425 * @param segmentP2 Second point determining line segment
426 * @param point Point for which a closest point is searched on line segment [P1,P2]
427 * @return segmentP1 if it is the closest point, segmentP2 if it is the closest point,
428 * a new point if closest point is between segmentP1 and segmentP2.
429 * @see #closestPointToLine
430 * @since 3650
431 */
432 public static EastNorth closestPointToSegment(EastNorth segmentP1, EastNorth segmentP2, EastNorth point) {
433 return closestPointTo(segmentP1, segmentP2, point, true);
434 }
435
436 /**
437 * Calculates closest point to a line.
438 * @param lineP1 First point determining line
439 * @param lineP2 Second point determining line
440 * @param point Point for which a closest point is searched on line (P1,P2)
441 * @return The closest point found on line. It may be outside the segment [P1,P2].
442 * @see #closestPointToSegment
443 * @since 4134
444 */
445 public static EastNorth closestPointToLine(EastNorth lineP1, EastNorth lineP2, EastNorth point) {
446 return closestPointTo(lineP1, lineP2, point, false);
447 }
448
449 /**
450 * This method tests if secondNode is clockwise to first node.
451 *
452 * The line through the two points commonNode and firstNode divides the
453 * plane into two parts. The test returns true, if secondNode lies in
454 * the part that is to the right when traveling in the direction from
455 * commonNode to firstNode.
456 *
457 * @param commonNode starting point for both vectors
458 * @param firstNode first vector end node
459 * @param secondNode second vector end node
460 * @return true if first vector is clockwise before second vector.
461 */
462 public static boolean angleIsClockwise(EastNorth commonNode, EastNorth firstNode, EastNorth secondNode) {
463
464 CheckParameterUtil.ensureValidCoordinates(commonNode, "commonNode");
465 CheckParameterUtil.ensureValidCoordinates(firstNode, "firstNode");
466 CheckParameterUtil.ensureValidCoordinates(secondNode, "secondNode");
467
468 double dy1 = firstNode.getY() - commonNode.getY();
469 double dy2 = secondNode.getY() - commonNode.getY();
470 double dx1 = firstNode.getX() - commonNode.getX();
471 double dx2 = secondNode.getX() - commonNode.getX();
472
473 return dy1 * dx2 - dx1 * dy2 > 0;
474 }
475
476 /**
477 * Returns the Area of a polygon, from its list of nodes.
478 * @param polygon List of nodes forming polygon
479 * @return Area for the given list of nodes (EastNorth coordinates)
480 * @since 6841
481 */
482 public static Area getArea(List<Node> polygon) {
483 Path2D path = new Path2D.Double();
484
485 boolean begin = true;
486 for (Node n : polygon) {
487 EastNorth en = n.getEastNorth();
488 if (en != null) {
489 if (begin) {
490 path.moveTo(en.getX(), en.getY());
491 begin = false;
492 } else {
493 path.lineTo(en.getX(), en.getY());
494 }
495 }
496 }
497 if (!begin) {
498 path.closePath();
499 }
500
501 return new Area(path);
502 }
503
504 /**
505 * Builds a path from a list of nodes
506 * @param polygon Nodes, forming a closed polygon
507 * @param path2d path to add to; can be null, then a new path is created
508 * @return the path (LatLon coordinates)
509 */
510 public static Path2D buildPath2DLatLon(List<Node> polygon, Path2D path2d) {
511 Path2D path = path2d != null ? path2d : new Path2D.Double();
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 return path;
525 }
526
527 /**
528 * Returns the Area of a polygon, from the multipolygon relation.
529 * @param multipolygon the multipolygon relation
530 * @return Area for the multipolygon (LatLon coordinates)
531 */
532 public static Area getAreaLatLon(Relation multipolygon) {
533 final Multipolygon mp = Main.map == null || Main.map.mapView == null
534 ? new Multipolygon(multipolygon)
535 : MultipolygonCache.getInstance().get(Main.map.mapView, multipolygon);
536 Path2D path = new Path2D.Double();
537 path.setWindingRule(Path2D.WIND_EVEN_ODD);
538 for (Multipolygon.PolyData pd : mp.getCombinedPolygons()) {
539 buildPath2DLatLon(pd.getNodes(), path);
540 for (Multipolygon.PolyData pdInner : pd.getInners()) {
541 buildPath2DLatLon(pdInner.getNodes(), path);
542 }
543 }
544 return new Area(path);
545 }
546
547 /**
548 * Tests if two polygons intersect.
549 * @param first List of nodes forming first polygon
550 * @param second List of nodes forming second polygon
551 * @return intersection kind
552 */
553 public static PolygonIntersection polygonIntersection(List<Node> first, List<Node> second) {
554 Area a1 = getArea(first);
555 Area a2 = getArea(second);
556 return polygonIntersection(a1, a2);
557 }
558
559 /**
560 * Tests if two polygons intersect.
561 * @param a1 Area of first polygon
562 * @param a2 Area of second polygon
563 * @return intersection kind
564 * @since 6841
565 */
566 public static PolygonIntersection polygonIntersection(Area a1, Area a2) {
567 return polygonIntersection(a1, a2, 1.0);
568 }
569
570 /**
571 * Tests if two polygons intersect.
572 * @param a1 Area of first polygon
573 * @param a2 Area of second polygon
574 * @param eps an area threshold, everything below is considered an empty intersection
575 * @return intersection kind
576 */
577 public static PolygonIntersection polygonIntersection(Area a1, Area a2, double eps) {
578
579 Area inter = new Area(a1);
580 inter.intersect(a2);
581
582 Rectangle bounds = inter.getBounds();
583
584 if (inter.isEmpty() || bounds.getHeight()*bounds.getWidth() <= eps) {
585 return PolygonIntersection.OUTSIDE;
586 } else if (a2.getBounds2D().contains(a1.getBounds2D()) && inter.equals(a1)) {
587 return PolygonIntersection.FIRST_INSIDE_SECOND;
588 } else if (a1.getBounds2D().contains(a2.getBounds2D()) && inter.equals(a2)) {
589 return PolygonIntersection.SECOND_INSIDE_FIRST;
590 } else {
591 return PolygonIntersection.CROSSING;
592 }
593 }
594
595 /**
596 * Tests if point is inside a polygon. The polygon can be self-intersecting. In such case the contains function works in xor-like manner.
597 * @param polygonNodes list of nodes from polygon path.
598 * @param point the point to test
599 * @return true if the point is inside polygon.
600 */
601 public static boolean nodeInsidePolygon(Node point, List<Node> polygonNodes) {
602 if (polygonNodes.size() < 2)
603 return false;
604
605 //iterate each side of the polygon, start with the last segment
606 Node oldPoint = polygonNodes.get(polygonNodes.size() - 1);
607
608 if (!oldPoint.isLatLonKnown()) {
609 return false;
610 }
611
612 boolean inside = false;
613 Node p1, p2;
614
615 for (Node newPoint : polygonNodes) {
616 //skip duplicate points
617 if (newPoint.equals(oldPoint)) {
618 continue;
619 }
620
621 if (!newPoint.isLatLonKnown()) {
622 return false;
623 }
624
625 //order points so p1.lat <= p2.lat
626 if (newPoint.getEastNorth().getY() > oldPoint.getEastNorth().getY()) {
627 p1 = oldPoint;
628 p2 = newPoint;
629 } else {
630 p1 = newPoint;
631 p2 = oldPoint;
632 }
633
634 EastNorth pEN = point.getEastNorth();
635 EastNorth opEN = oldPoint.getEastNorth();
636 EastNorth npEN = newPoint.getEastNorth();
637 EastNorth p1EN = p1.getEastNorth();
638 EastNorth p2EN = p2.getEastNorth();
639
640 if (pEN != null && opEN != null && npEN != null && p1EN != null && p2EN != null) {
641 //test if the line is crossed and if so invert the inside flag.
642 if ((npEN.getY() < pEN.getY()) == (pEN.getY() <= opEN.getY())
643 && (pEN.getX() - p1EN.getX()) * (p2EN.getY() - p1EN.getY())
644 < (p2EN.getX() - p1EN.getX()) * (pEN.getY() - p1EN.getY())) {
645 inside = !inside;
646 }
647 }
648
649 oldPoint = newPoint;
650 }
651
652 return inside;
653 }
654
655 /**
656 * Returns area of a closed way in square meters.
657 *
658 * @param way Way to measure, should be closed (first node is the same as last node)
659 * @return area of the closed way.
660 */
661 public static double closedWayArea(Way way) {
662 return getAreaAndPerimeter(way.getNodes(), Projections.getProjectionByCode("EPSG:54008")).getArea();
663 }
664
665 /**
666 * Returns area of a multipolygon in square meters.
667 *
668 * @param multipolygon the multipolygon to measure
669 * @return area of the multipolygon.
670 */
671 public static double multipolygonArea(Relation multipolygon) {
672 double area = 0.0;
673 final Multipolygon mp = Main.map == null || Main.map.mapView == null
674 ? new Multipolygon(multipolygon)
675 : MultipolygonCache.getInstance().get(Main.map.mapView, multipolygon);
676 for (Multipolygon.PolyData pd : mp.getCombinedPolygons()) {
677 area += pd.getAreaAndPerimeter(Projections.getProjectionByCode("EPSG:54008")).getArea();
678 }
679 return area;
680 }
681
682 /**
683 * Computes the area of a closed way and multipolygon in square meters, or {@code null} for other primitives
684 *
685 * @param osm the primitive to measure
686 * @return area of the primitive, or {@code null}
687 */
688 public static Double computeArea(OsmPrimitive osm) {
689 if (osm instanceof Way && ((Way) osm).isClosed()) {
690 return closedWayArea((Way) osm);
691 } else if (osm instanceof Relation && ((Relation) osm).isMultipolygon() && !((Relation) osm).hasIncompleteMembers()) {
692 return multipolygonArea((Relation) osm);
693 } else {
694 return null;
695 }
696 }
697
698 /**
699 * Determines whether a way is oriented clockwise.
700 *
701 * Internals: Assuming a closed non-looping way, compute twice the area
702 * of the polygon using the formula {@code 2 * area = sum (X[n] * Y[n+1] - X[n+1] * Y[n])}.
703 * If the area is negative the way is ordered in a clockwise direction.
704 *
705 * See http://paulbourke.net/geometry/polyarea/
706 *
707 * @param w the way to be checked.
708 * @return true if and only if way is oriented clockwise.
709 * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}).
710 */
711 public static boolean isClockwise(Way w) {
712 return isClockwise(w.getNodes());
713 }
714
715 /**
716 * Determines whether path from nodes list is oriented clockwise.
717 * @param nodes Nodes list to be checked.
718 * @return true if and only if way is oriented clockwise.
719 * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}).
720 * @see #isClockwise(Way)
721 */
722 public static boolean isClockwise(List<Node> nodes) {
723 int nodesCount = nodes.size();
724 if (nodesCount < 3 || nodes.get(0) != nodes.get(nodesCount - 1)) {
725 throw new IllegalArgumentException("Way must be closed to check orientation.");
726 }
727 double area2 = 0.;
728
729 for (int node = 1; node <= /*sic! consider last-first as well*/ nodesCount; node++) {
730 LatLon coorPrev = nodes.get(node - 1).getCoor();
731 LatLon coorCurr = nodes.get(node % nodesCount).getCoor();
732 area2 += coorPrev.lon() * coorCurr.lat();
733 area2 -= coorCurr.lon() * coorPrev.lat();
734 }
735 return area2 < 0;
736 }
737
738 /**
739 * Returns angle of a segment defined with 2 point coordinates.
740 *
741 * @param p1 first point
742 * @param p2 second point
743 * @return Angle in radians (-pi, pi]
744 */
745 public static double getSegmentAngle(EastNorth p1, EastNorth p2) {
746
747 CheckParameterUtil.ensureValidCoordinates(p1, "p1");
748 CheckParameterUtil.ensureValidCoordinates(p2, "p2");
749
750 return Math.atan2(p2.north() - p1.north(), p2.east() - p1.east());
751 }
752
753 /**
754 * Returns angle of a corner defined with 3 point coordinates.
755 *
756 * @param p1 first point
757 * @param p2 Common endpoint
758 * @param p3 third point
759 * @return Angle in radians (-pi, pi]
760 */
761 public static double getCornerAngle(EastNorth p1, EastNorth p2, EastNorth p3) {
762
763 CheckParameterUtil.ensureValidCoordinates(p1, "p1");
764 CheckParameterUtil.ensureValidCoordinates(p2, "p2");
765 CheckParameterUtil.ensureValidCoordinates(p3, "p3");
766
767 Double result = getSegmentAngle(p2, p1) - getSegmentAngle(p2, p3);
768 if (result <= -Math.PI) {
769 result += 2 * Math.PI;
770 }
771
772 if (result > Math.PI) {
773 result -= 2 * Math.PI;
774 }
775
776 return result;
777 }
778
779 /**
780 * Compute the centroid/barycenter of nodes
781 * @param nodes Nodes for which the centroid is wanted
782 * @return the centroid of nodes
783 * @see Geometry#getCenter
784 */
785 public static EastNorth getCentroid(List<Node> nodes) {
786
787 BigDecimal area = BigDecimal.ZERO;
788 BigDecimal north = BigDecimal.ZERO;
789 BigDecimal east = BigDecimal.ZERO;
790
791 // See https://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon for the equation used here
792 for (int i = 0; i < nodes.size(); i++) {
793 EastNorth n0 = nodes.get(i).getEastNorth();
794 EastNorth n1 = nodes.get((i+1) % nodes.size()).getEastNorth();
795
796 if (n0 != null && n1 != null && n0.isValid() && n1.isValid()) {
797 BigDecimal x0 = BigDecimal.valueOf(n0.east());
798 BigDecimal y0 = BigDecimal.valueOf(n0.north());
799 BigDecimal x1 = BigDecimal.valueOf(n1.east());
800 BigDecimal y1 = BigDecimal.valueOf(n1.north());
801
802 BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128));
803
804 area = area.add(k, MathContext.DECIMAL128);
805 east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128));
806 north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128));
807 }
808 }
809
810 BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3
811 area = area.multiply(d, MathContext.DECIMAL128);
812 if (area.compareTo(BigDecimal.ZERO) != 0) {
813 north = north.divide(area, MathContext.DECIMAL128);
814 east = east.divide(area, MathContext.DECIMAL128);
815 }
816
817 return new EastNorth(east.doubleValue(), north.doubleValue());
818 }
819
820 /**
821 * Compute center of the circle closest to different nodes.
822 *
823 * Ensure exact center computation in case nodes are already aligned in circle.
824 * This is done by least square method.
825 * Let be a_i x + b_i y + c_i = 0 equations of bisectors of each edges.
826 * Center must be intersection of all bisectors.
827 * <pre>
828 * [ a1 b1 ] [ -c1 ]
829 * With A = [ ... ... ] and Y = [ ... ]
830 * [ an bn ] [ -cn ]
831 * </pre>
832 * An approximation of center of circle is (At.A)^-1.At.Y
833 * @param nodes Nodes parts of the circle (at least 3)
834 * @return An approximation of the center, of null if there is no solution.
835 * @see Geometry#getCentroid
836 * @since 6934
837 */
838 public static EastNorth getCenter(List<Node> nodes) {
839 int nc = nodes.size();
840 if (nc < 3) return null;
841 /**
842 * Equation of each bisector ax + by + c = 0
843 */
844 double[] a = new double[nc];
845 double[] b = new double[nc];
846 double[] c = new double[nc];
847 // Compute equation of bisector
848 for (int i = 0; i < nc; i++) {
849 EastNorth pt1 = nodes.get(i).getEastNorth();
850 EastNorth pt2 = nodes.get((i+1) % nc).getEastNorth();
851 a[i] = pt1.east() - pt2.east();
852 b[i] = pt1.north() - pt2.north();
853 double d = Math.sqrt(a[i]*a[i] + b[i]*b[i]);
854 if (d == 0) return null;
855 a[i] /= d;
856 b[i] /= d;
857 double xC = (pt1.east() + pt2.east()) / 2;
858 double yC = (pt1.north() + pt2.north()) / 2;
859 c[i] = -(a[i]*xC + b[i]*yC);
860 }
861 // At.A = [aij]
862 double a11 = 0, a12 = 0, a22 = 0;
863 // At.Y = [bi]
864 double b1 = 0, b2 = 0;
865 for (int i = 0; i < nc; i++) {
866 a11 += a[i]*a[i];
867 a12 += a[i]*b[i];
868 a22 += b[i]*b[i];
869 b1 -= a[i]*c[i];
870 b2 -= b[i]*c[i];
871 }
872 // (At.A)^-1 = [invij]
873 double det = a11*a22 - a12*a12;
874 if (Math.abs(det) < 1e-5) return null;
875 double inv11 = a22/det;
876 double inv12 = -a12/det;
877 double inv22 = a11/det;
878 // center (xC, yC) = (At.A)^-1.At.y
879 double xC = inv11*b1 + inv12*b2;
880 double yC = inv12*b1 + inv22*b2;
881 return new EastNorth(xC, yC);
882 }
883
884 /**
885 * Tests if the {@code node} is inside the multipolygon {@code multiPolygon}. The nullable argument
886 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
887 * @param node node
888 * @param multiPolygon multipolygon
889 * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match
890 * @return {@code true} if the node is inside the multipolygon
891 */
892 public static boolean isNodeInsideMultiPolygon(Node node, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
893 return isPolygonInsideMultiPolygon(Collections.singletonList(node), multiPolygon, isOuterWayAMatch);
894 }
895
896 /**
897 * Tests if the polygon formed by {@code nodes} is inside the multipolygon {@code multiPolygon}. The nullable argument
898 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
899 * <p>
900 * If {@code nodes} contains exactly one element, then it is checked whether that one node is inside the multipolygon.
901 * @param nodes nodes forming the polygon
902 * @param multiPolygon multipolygon
903 * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match
904 * @return {@code true} if the polygon formed by nodes is inside the multipolygon
905 */
906 public static boolean isPolygonInsideMultiPolygon(List<Node> nodes, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
907 // Extract outer/inner members from multipolygon
908 final Pair<List<JoinedPolygon>, List<JoinedPolygon>> outerInner;
909 try {
910 outerInner = MultipolygonBuilder.joinWays(multiPolygon);
911 } catch (MultipolygonBuilder.JoinedPolygonCreationException ex) {
912 Main.trace(ex);
913 Main.debug("Invalid multipolygon " + multiPolygon);
914 return false;
915 }
916 // Test if object is inside an outer member
917 for (JoinedPolygon out : outerInner.a) {
918 if (nodes.size() == 1
919 ? nodeInsidePolygon(nodes.get(0), out.getNodes())
920 : EnumSet.of(PolygonIntersection.FIRST_INSIDE_SECOND, PolygonIntersection.CROSSING).contains(
921 polygonIntersection(nodes, out.getNodes()))) {
922 boolean insideInner = false;
923 // If inside an outer, check it is not inside an inner
924 for (JoinedPolygon in : outerInner.b) {
925 if (polygonIntersection(in.getNodes(), out.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND
926 && (nodes.size() == 1
927 ? nodeInsidePolygon(nodes.get(0), in.getNodes())
928 : polygonIntersection(nodes, in.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND)) {
929 insideInner = true;
930 break;
931 }
932 }
933 // Inside outer but not inside inner -> the polygon appears to be inside a the multipolygon
934 if (!insideInner) {
935 // Final check using predicate
936 if (isOuterWayAMatch == null || isOuterWayAMatch.test(out.ways.get(0)
937 /* TODO give a better representation of the outer ring to the predicate */)) {
938 return true;
939 }
940 }
941 }
942 }
943 return false;
944 }
945
946 /**
947 * Data class to hold two double values (area and perimeter of a polygon).
948 */
949 public static class AreaAndPerimeter {
950 private final double area;
951 private final double perimeter;
952
953 public AreaAndPerimeter(double area, double perimeter) {
954 this.area = area;
955 this.perimeter = perimeter;
956 }
957
958 public double getArea() {
959 return area;
960 }
961
962 public double getPerimeter() {
963 return perimeter;
964 }
965 }
966
967 /**
968 * Calculate area and perimeter length of a polygon.
969 *
970 * Uses current projection; units are that of the projected coordinates.
971 *
972 * @param nodes the list of nodes representing the polygon
973 * @return area and perimeter
974 */
975 public static AreaAndPerimeter getAreaAndPerimeter(List<Node> nodes) {
976 return getAreaAndPerimeter(nodes, null);
977 }
978
979 /**
980 * Calculate area and perimeter length of a polygon in the given projection.
981 *
982 * @param nodes the list of nodes representing the polygon
983 * @param projection the projection to use for the calculation, {@code null} defaults to {@link Main#getProjection()}
984 * @return area and perimeter
985 */
986 public static AreaAndPerimeter getAreaAndPerimeter(List<Node> nodes, Projection projection) {
987 CheckParameterUtil.ensureParameterNotNull(nodes, "nodes");
988 double area = 0;
989 double perimeter = 0;
990 if (!nodes.isEmpty()) {
991 boolean closed = nodes.get(0) == nodes.get(nodes.size() - 1);
992 int numSegments = closed ? nodes.size() - 1 : nodes.size();
993 EastNorth p1 = projection == null ? nodes.get(0).getEastNorth() : projection.latlon2eastNorth(nodes.get(0).getCoor());
994 for (int i = 1; i <= numSegments; i++) {
995 final Node node = nodes.get(i == numSegments ? 0 : i);
996 final EastNorth p2 = projection == null ? node.getEastNorth() : projection.latlon2eastNorth(node.getCoor());
997 if (p1 != null && p2 != null) {
998 area += p1.east() * p2.north() - p2.east() * p1.north();
999 perimeter += p1.distance(p2);
1000 }
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.