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

Last change on this file since 12279 was 12161, checked in by michael2402, 7 years ago

See #13415: Add the ILatLon interface, unify handling of Nodes and CachedLatLon

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