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