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

Last change on this file since 13755 was 13712, checked in by Don-vip, 6 years ago

see #16256 - improve "building with almost square angle" autofix: try to move only the highlighted node

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