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

Last change on this file since 4818 was 4344, checked in by stoecker, 13 years ago

fix #5257 - patch by simon04 - fix way order validator checks

  • Property svn:eol-style set to native
File size: 20.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import java.awt.geom.Line2D;
5import java.util.ArrayList;
6import java.util.Comparator;
7import java.util.HashSet;
8import java.util.LinkedHashSet;
9import java.util.List;
10import java.util.Set;
11
12import org.openstreetmap.josm.Main;
13import org.openstreetmap.josm.command.AddCommand;
14import org.openstreetmap.josm.command.ChangeCommand;
15import org.openstreetmap.josm.command.Command;
16import org.openstreetmap.josm.data.coor.EastNorth;
17import org.openstreetmap.josm.data.coor.LatLon;
18import org.openstreetmap.josm.data.osm.BBox;
19import org.openstreetmap.josm.data.osm.Node;
20import org.openstreetmap.josm.data.osm.NodePositionComparator;
21import org.openstreetmap.josm.data.osm.Way;
22
23/**
24 * Some tools for geometry related tasks.
25 *
26 * @author viesturs
27 */
28public class Geometry {
29 public enum PolygonIntersection {FIRST_INSIDE_SECOND, SECOND_INSIDE_FIRST, OUTSIDE, CROSSING}
30
31 /**
32 * Will find all intersection and add nodes there for list of given ways. Handles self-intersections too.
33 * And make commands to add the intersection points to ways.
34 * @param List<Way> - a list of ways to test
35 * @return ArrayList<Node> List of new nodes
36 * Prerequisite: no two nodes have the same coordinates.
37 */
38 public static Set<Node> addIntersections(List<Way> ways, boolean test, List<Command> cmds) {
39
40 //stupid java, cannot instantiate array of generic classes..
41 @SuppressWarnings("unchecked")
42 ArrayList<Node>[] newNodes = new ArrayList[ways.size()];
43 BBox[] wayBounds = new BBox[ways.size()];
44 boolean[] changedWays = new boolean[ways.size()];
45
46 Set<Node> intersectionNodes = new LinkedHashSet<Node>();
47
48 //copy node arrays for local usage.
49 for (int pos = 0; pos < ways.size(); pos ++) {
50 newNodes[pos] = new ArrayList<Node>(ways.get(pos).getNodes());
51 wayBounds[pos] = getNodesBounds(newNodes[pos]);
52 changedWays[pos] = false;
53 }
54
55 //iterate over all way pairs and introduce the intersections
56 Comparator<Node> coordsComparator = new NodePositionComparator();
57
58 WayLoop: for (int seg1Way = 0; seg1Way < ways.size(); seg1Way ++) {
59 for (int seg2Way = seg1Way; seg2Way < ways.size(); seg2Way ++) {
60
61 //do not waste time on bounds that do not intersect
62 if (!wayBounds[seg1Way].intersects(wayBounds[seg2Way])) {
63 continue;
64 }
65
66 ArrayList<Node> way1Nodes = newNodes[seg1Way];
67 ArrayList<Node> way2Nodes = newNodes[seg2Way];
68
69 //iterate over primary segmemt
70 for (int seg1Pos = 0; seg1Pos + 1 < way1Nodes.size(); seg1Pos ++) {
71
72 //iterate over secondary segment
73 int seg2Start = seg1Way != seg2Way ? 0: seg1Pos + 2;//skip the adjacent segment
74
75 for (int seg2Pos = seg2Start; seg2Pos + 1< way2Nodes.size(); seg2Pos ++) {
76
77 //need to get them again every time, because other segments may be changed
78 Node seg1Node1 = way1Nodes.get(seg1Pos);
79 Node seg1Node2 = way1Nodes.get(seg1Pos + 1);
80 Node seg2Node1 = way2Nodes.get(seg2Pos);
81 Node seg2Node2 = way2Nodes.get(seg2Pos + 1);
82
83 int commonCount = 0;
84 //test if we have common nodes to add.
85 if (seg1Node1 == seg2Node1 || seg1Node1 == seg2Node2) {
86 commonCount ++;
87
88 if (seg1Way == seg2Way &&
89 seg1Pos == 0 &&
90 seg2Pos == way2Nodes.size() -2) {
91 //do not add - this is first and last segment of the same way.
92 } else {
93 intersectionNodes.add(seg1Node1);
94 }
95 }
96
97 if (seg1Node2 == seg2Node1 || seg1Node2 == seg2Node2) {
98 commonCount ++;
99
100 intersectionNodes.add(seg1Node2);
101 }
102
103 //no common nodes - find intersection
104 if (commonCount == 0) {
105 EastNorth intersection = getSegmentSegmentIntersection(
106 seg1Node1.getEastNorth(), seg1Node2.getEastNorth(),
107 seg2Node1.getEastNorth(), seg2Node2.getEastNorth());
108
109 if (intersection != null) {
110 if (test) {
111 intersectionNodes.add(seg2Node1);
112 return intersectionNodes;
113 }
114
115 Node newNode = new Node(Main.getProjection().eastNorth2latlon(intersection));
116 Node intNode = newNode;
117 boolean insertInSeg1 = false;
118 boolean insertInSeg2 = false;
119
120 //find if the intersection point is at end point of one of the segments, if so use that point
121
122 //segment 1
123 if (coordsComparator.compare(newNode, seg1Node1) == 0) {
124 intNode = seg1Node1;
125 } else if (coordsComparator.compare(newNode, seg1Node2) == 0) {
126 intNode = seg1Node2;
127 } else {
128 insertInSeg1 = true;
129 }
130
131 //segment 2
132 if (coordsComparator.compare(newNode, seg2Node1) == 0) {
133 intNode = seg2Node1;
134 } else if (coordsComparator.compare(newNode, seg2Node2) == 0) {
135 intNode = seg2Node2;
136 } else {
137 insertInSeg2 = true;
138 }
139
140 if (insertInSeg1) {
141 way1Nodes.add(seg1Pos +1, intNode);
142 changedWays[seg1Way] = true;
143
144 //fix seg2 position, as indexes have changed, seg2Pos is always bigger than seg1Pos on the same segment.
145 if (seg2Way == seg1Way) {
146 seg2Pos ++;
147 }
148 }
149
150 if (insertInSeg2) {
151 way2Nodes.add(seg2Pos +1, intNode);
152 changedWays[seg2Way] = true;
153
154 //Do not need to compare again to already split segment
155 seg2Pos ++;
156 }
157
158 intersectionNodes.add(intNode);
159
160 if (intNode == newNode) {
161 cmds.add(new AddCommand(intNode));
162 }
163 }
164 }
165 else if (test && intersectionNodes.size() > 0)
166 return intersectionNodes;
167 }
168 }
169 }
170 }
171
172
173 for (int pos = 0; pos < ways.size(); pos ++) {
174 if (changedWays[pos] == false) {
175 continue;
176 }
177
178 Way way = ways.get(pos);
179 Way newWay = new Way(way);
180 newWay.setNodes(newNodes[pos]);
181
182 cmds.add(new ChangeCommand(way, newWay));
183 }
184
185 return intersectionNodes;
186 }
187
188 private static BBox getNodesBounds(ArrayList<Node> nodes) {
189
190 BBox bounds = new BBox(nodes.get(0));
191 for(Node n: nodes) {
192 bounds.add(n.getCoor());
193 }
194 return bounds;
195 }
196
197 /**
198 * Tests if given point is to the right side of path consisting of 3 points.
199 * @param lineP1 first point in path
200 * @param lineP2 second point in path
201 * @param lineP3 third point in path
202 * @param testPoint
203 * @return true if to the right side, false otherwise
204 */
205 public static boolean isToTheRightSideOfLine(Node lineP1, Node lineP2, Node lineP3, Node testPoint) {
206 boolean pathBendToRight = angleIsClockwise(lineP1, lineP2, lineP3);
207 boolean rightOfSeg1 = angleIsClockwise(lineP1, lineP2, testPoint);
208 boolean rightOfSeg2 = angleIsClockwise(lineP2, lineP3, testPoint);
209
210 if (pathBendToRight)
211 return rightOfSeg1 && rightOfSeg2;
212 else
213 return !(!rightOfSeg1 && !rightOfSeg2);
214 }
215
216 /**
217 * This method tests if secondNode is clockwise to first node.
218 * @param commonNode starting point for both vectors
219 * @param firstNode first vector end node
220 * @param secondNode second vector end node
221 * @return true if first vector is clockwise before second vector.
222 */
223 public static boolean angleIsClockwise(Node commonNode, Node firstNode, Node secondNode) {
224 return angleIsClockwise(commonNode.getEastNorth(), firstNode.getEastNorth(), secondNode.getEastNorth());
225 }
226
227 /**
228 * Finds the intersection of two line segments
229 * @return EastNorth null if no intersection was found, the EastNorth coordinates of the intersection otherwise
230 */
231 public static EastNorth getSegmentSegmentIntersection(
232 EastNorth p1, EastNorth p2,
233 EastNorth p3, EastNorth p4) {
234 double x1 = p1.getX();
235 double y1 = p1.getY();
236 double x2 = p2.getX();
237 double y2 = p2.getY();
238 double x3 = p3.getX();
239 double y3 = p3.getY();
240 double x4 = p4.getX();
241 double y4 = p4.getY();
242
243 //TODO: do this locally.
244 if (!Line2D.linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return null;
245
246 // Convert line from (point, point) form to ax+by=c
247 double a1 = y2 - y1;
248 double b1 = x1 - x2;
249 double c1 = x2*y1 - x1*y2;
250
251 double a2 = y4 - y3;
252 double b2 = x3 - x4;
253 double c2 = x4*y3 - x3*y4;
254
255 // Solve the equations
256 double det = a1*b2 - a2*b1;
257 if (det == 0) return null; // Lines are parallel
258
259 double x = (b1*c2 - b2*c1)/det;
260 double y = (a2*c1 -a1*c2)/det;
261
262 return new EastNorth(x, y);
263 }
264
265 /**
266 * Finds the intersection of two lines of infinite length.
267 * @return EastNorth null if no intersection was found, the coordinates of the intersection otherwise
268 */
269 public static EastNorth getLineLineIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
270
271 // Convert line from (point, point) form to ax+by=c
272 double a1 = p2.getY() - p1.getY();
273 double b1 = p1.getX() - p2.getX();
274 double c1 = p2.getX() * p1.getY() - p1.getX() * p2.getY();
275
276 double a2 = p4.getY() - p3.getY();
277 double b2 = p3.getX() - p4.getX();
278 double c2 = p4.getX() * p3.getY() - p3.getX() * p4.getY();
279
280 // Solve the equations
281 double det = a1 * b2 - a2 * b1;
282 if (det == 0)
283 return null; // Lines are parallel
284
285 return new EastNorth((b1 * c2 - b2 * c1) / det, (a2 * c1 - a1 * c2) / det);
286 }
287
288 public static boolean segmentsParallel(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
289 // Convert line from (point, point) form to ax+by=c
290 double a1 = p2.getY() - p1.getY();
291 double b1 = p1.getX() - p2.getX();
292
293 double a2 = p4.getY() - p3.getY();
294 double b2 = p3.getX() - p4.getX();
295
296 // Solve the equations
297 double det = a1 * b2 - a2 * b1;
298 // remove influence of of scaling factor
299 det /= Math.sqrt(a1*a1 + b1*b1) * Math.sqrt(a2*a2 + b2*b2);
300 return Math.abs(det) < 1e-3;
301 }
302
303 /**
304 * Calculates closest point to a line segment.
305 * @param segmentP1
306 * @param segmentP2
307 * @param point
308 * @return segmentP1 if it is the closest point, segmentP2 if it is the closest point,
309 * a new point if closest point is between segmentP1 and segmentP2.
310 */
311 public static EastNorth closestPointToSegment(EastNorth segmentP1, EastNorth segmentP2, EastNorth point) {
312
313 double ldx = segmentP2.getX() - segmentP1.getX();
314 double ldy = segmentP2.getY() - segmentP1.getY();
315
316 if (ldx == 0 && ldy == 0) //segment zero length
317 return segmentP1;
318
319 double pdx = point.getX() - segmentP1.getX();
320 double pdy = point.getY() - segmentP1.getY();
321
322 double offset = (pdx * ldx + pdy * ldy) / (ldx * ldx + ldy * ldy);
323
324 if (offset <= 0)
325 return segmentP1;
326 else if (offset >= 1)
327 return segmentP2;
328 else
329 return new EastNorth(segmentP1.getX() + ldx * offset, segmentP1.getY() + ldy * offset);
330 }
331
332 public static EastNorth closestPointToLine(EastNorth lineP1, EastNorth lineP2, EastNorth point) {
333 double ldx = lineP2.getX() - lineP1.getX();
334 double ldy = lineP2.getY() - lineP1.getY();
335
336 if (ldx == 0 && ldy == 0) //segment zero length
337 return lineP1;
338
339 double pdx = point.getX() - lineP1.getX();
340 double pdy = point.getY() - lineP1.getY();
341
342 double offset = (pdx * ldx + pdy * ldy) / (ldx * ldx + ldy * ldy);
343 return new EastNorth(lineP1.getX() + ldx * offset, lineP1.getY() + ldy * offset);
344 }
345
346 /**
347 * This method tests if secondNode is clockwise to first node.
348 * @param commonNode starting point for both vectors
349 * @param firstNode first vector end node
350 * @param secondNode second vector end node
351 * @return true if first vector is clockwise before second vector.
352 */
353 public static boolean angleIsClockwise(EastNorth commonNode, EastNorth firstNode, EastNorth secondNode) {
354 double dy1 = (firstNode.getY() - commonNode.getY());
355 double dy2 = (secondNode.getY() - commonNode.getY());
356 double dx1 = (firstNode.getX() - commonNode.getX());
357 double dx2 = (secondNode.getX() - commonNode.getX());
358
359 return dy1 * dx2 - dx1 * dy2 > 0;
360 }
361
362 /**
363 * Tests if two polygons intersect.
364 * @param first
365 * @param second
366 * @return intersection kind
367 * TODO: test segments, not only points
368 * TODO: is O(N*M), should use sweep for better performance.
369 */
370 public static PolygonIntersection polygonIntersection(List<Node> first, List<Node> second) {
371 Set<Node> firstSet = new HashSet<Node>(first);
372 Set<Node> secondSet = new HashSet<Node>(second);
373
374 int nodesInsideSecond = 0;
375 int nodesOutsideSecond = 0;
376 int nodesInsideFirst = 0;
377 int nodesOutsideFirst = 0;
378
379 for (Node insideNode : first) {
380 if (secondSet.contains(insideNode)) {
381 continue;
382 //ignore touching nodes.
383 }
384
385 if (nodeInsidePolygon(insideNode, second)) {
386 nodesInsideSecond ++;
387 }
388 else {
389 nodesOutsideSecond ++;
390 }
391 }
392
393 for (Node insideNode : second) {
394 if (firstSet.contains(insideNode)) {
395 continue;
396 //ignore touching nodes.
397 }
398
399 if (nodeInsidePolygon(insideNode, first)) {
400 nodesInsideFirst ++;
401 }
402 else {
403 nodesOutsideFirst ++;
404 }
405 }
406
407 if (nodesInsideFirst == 0) {
408 if (nodesInsideSecond == 0){
409 if (nodesOutsideFirst + nodesInsideSecond > 0)
410 return PolygonIntersection.OUTSIDE;
411 else
412 //all nodes common
413 return PolygonIntersection.CROSSING;
414 } else
415 return PolygonIntersection.FIRST_INSIDE_SECOND;
416 }
417 else
418 {
419 if (nodesInsideSecond == 0)
420 return PolygonIntersection.SECOND_INSIDE_FIRST;
421 else
422 return PolygonIntersection.CROSSING;
423 }
424 }
425
426 /**
427 * Tests if point is inside a polygon. The polygon can be self-intersecting. In such case the contains function works in xor-like manner.
428 * @param polygonNodes list of nodes from polygon path.
429 * @param point the point to test
430 * @return true if the point is inside polygon.
431 */
432 public static boolean nodeInsidePolygon(Node point, List<Node> polygonNodes) {
433 if (polygonNodes.size() < 2)
434 return false;
435
436 boolean inside = false;
437 Node p1, p2;
438
439 //iterate each side of the polygon, start with the last segment
440 Node oldPoint = polygonNodes.get(polygonNodes.size() - 1);
441
442 for (Node newPoint : polygonNodes) {
443 //skip duplicate points
444 if (newPoint.equals(oldPoint)) {
445 continue;
446 }
447
448 //order points so p1.lat <= p2.lat;
449 if (newPoint.getEastNorth().getY() > oldPoint.getEastNorth().getY()) {
450 p1 = oldPoint;
451 p2 = newPoint;
452 } else {
453 p1 = newPoint;
454 p2 = oldPoint;
455 }
456
457 //test if the line is crossed and if so invert the inside flag.
458 if ((newPoint.getEastNorth().getY() < point.getEastNorth().getY()) == (point.getEastNorth().getY() <= oldPoint.getEastNorth().getY())
459 && (point.getEastNorth().getX() - p1.getEastNorth().getX()) * (p2.getEastNorth().getY() - p1.getEastNorth().getY())
460 < (p2.getEastNorth().getX() - p1.getEastNorth().getX()) * (point.getEastNorth().getY() - p1.getEastNorth().getY()))
461 {
462 inside = !inside;
463 }
464
465 oldPoint = newPoint;
466 }
467
468 return inside;
469 }
470
471 /**
472 * returns area of a closed way in square meters
473 * (approximate(?), but should be OK for small areas)
474 */
475 public static double closedWayArea(Way way) {
476
477 //http://local.wasp.uwa.edu.au/~pbourke/geometry/polyarea/
478 double area = 0;
479 Node lastN = null;
480 for (Node n : way.getNodes()) {
481 if (lastN != null) {
482 n.getEastNorth().getX();
483
484 area += (calcX(n) * calcY(lastN)) - (calcY(n) * calcX(lastN));
485 }
486 lastN = n;
487 }
488 return Math.abs(area/2);
489 }
490
491 protected static double calcX(Node p1){
492 double lat1, lon1, lat2, lon2;
493 double dlon, dlat;
494
495 lat1 = p1.getCoor().lat() * Math.PI / 180.0;
496 lon1 = p1.getCoor().lon() * Math.PI / 180.0;
497 lat2 = lat1;
498 lon2 = 0;
499
500 dlon = lon2 - lon1;
501 dlat = lat2 - lat1;
502
503 double a = (Math.pow(Math.sin(dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2), 2));
504 double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
505 return 6367000 * c;
506 }
507
508 protected static double calcY(Node p1){
509 double lat1, lon1, lat2, lon2;
510 double dlon, dlat;
511
512 lat1 = p1.getCoor().lat() * Math.PI / 180.0;
513 lon1 = p1.getCoor().lon() * Math.PI / 180.0;
514 lat2 = 0;
515 lon2 = lon1;
516
517 dlon = lon2 - lon1;
518 dlat = lat2 - lat1;
519
520 double a = (Math.pow(Math.sin(dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2), 2));
521 double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
522 return 6367000 * c;
523 }
524
525 /**
526 * Determines whether a way is oriented clockwise.
527 *
528 * Internals: Assuming a closed non-looping way, compute twice the area
529 * of the polygon using the formula {@code 2 * area = sum (X[n] * Y[n+1] - X[n+1] * Y[n])}.
530 * If the area is negative the way is ordered in a clockwise direction.
531 *
532 * @param w the way to be checked.
533 * @return true if and only if way is oriented clockwise.
534 * @throws IllegalArgumentException if way is not closed (see {@see Way#isClosed}).
535 * @see http://paulbourke.net/geometry/polyarea/
536 */
537 public static boolean isClockwise(Way w) {
538 if (!w.isClosed()) {
539 throw new IllegalArgumentException("Way must be closed to check orientation.");
540 }
541
542 double area2 = 0.;
543 int nodesCount = w.getNodesCount();
544
545 for (int node = 1; node <= /*sic! consider last-first as well*/ nodesCount; node++) {
546 LatLon coorPrev = w.getNode(node - 1).getCoor();
547 LatLon coorCurr = w.getNode(node % nodesCount).getCoor();
548 area2 += coorPrev.lon() * coorCurr.lat();
549 area2 -= coorCurr.lon() * coorPrev.lat();
550 }
551 return area2 < 0;
552 }
553}
Note: See TracBrowser for help on using the repository browser.