001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.math3.geometry.spherical.twod;
018
019import java.util.ArrayList;
020import java.util.Collection;
021import java.util.Collections;
022import java.util.Iterator;
023import java.util.List;
024
025import org.apache.commons.math3.exception.MathIllegalStateException;
026import org.apache.commons.math3.geometry.enclosing.EnclosingBall;
027import org.apache.commons.math3.geometry.enclosing.WelzlEncloser;
028import org.apache.commons.math3.geometry.euclidean.threed.Euclidean3D;
029import org.apache.commons.math3.geometry.euclidean.threed.Rotation;
030import org.apache.commons.math3.geometry.euclidean.threed.SphereGenerator;
031import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
032import org.apache.commons.math3.geometry.partitioning.AbstractRegion;
033import org.apache.commons.math3.geometry.partitioning.BSPTree;
034import org.apache.commons.math3.geometry.partitioning.BoundaryProjection;
035import org.apache.commons.math3.geometry.partitioning.RegionFactory;
036import org.apache.commons.math3.geometry.partitioning.SubHyperplane;
037import org.apache.commons.math3.geometry.spherical.oned.Sphere1D;
038import org.apache.commons.math3.util.FastMath;
039import org.apache.commons.math3.util.MathUtils;
040
041/** This class represents a region on the 2-sphere: a set of spherical polygons.
042 * @since 3.3
043 */
044public class SphericalPolygonsSet extends AbstractRegion<Sphere2D, Sphere1D> {
045
046    /** Boundary defined as an array of closed loops start vertices. */
047    private List<Vertex> loops;
048
049    /** Build a polygons set representing the whole real 2-sphere.
050     * @param tolerance below which points are consider to be identical
051     */
052    public SphericalPolygonsSet(final double tolerance) {
053        super(tolerance);
054    }
055
056    /** Build a polygons set representing a hemisphere.
057     * @param pole pole of the hemisphere (the pole is in the inside half)
058     * @param tolerance below which points are consider to be identical
059     */
060    public SphericalPolygonsSet(final Vector3D pole, final double tolerance) {
061        super(new BSPTree<Sphere2D>(new Circle(pole, tolerance).wholeHyperplane(),
062                                    new BSPTree<Sphere2D>(Boolean.FALSE),
063                                    new BSPTree<Sphere2D>(Boolean.TRUE),
064                                    null),
065              tolerance);
066    }
067
068    /** Build a polygons set representing a regular polygon.
069     * @param center center of the polygon (the center is in the inside half)
070     * @param meridian point defining the reference meridian for first polygon vertex
071     * @param outsideRadius distance of the vertices to the center
072     * @param n number of sides of the polygon
073     * @param tolerance below which points are consider to be identical
074     */
075    public SphericalPolygonsSet(final Vector3D center, final Vector3D meridian,
076                                final double outsideRadius, final int n,
077                                final double tolerance) {
078        this(tolerance, createRegularPolygonVertices(center, meridian, outsideRadius, n));
079    }
080
081    /** Build a polygons set from a BSP tree.
082     * <p>The leaf nodes of the BSP tree <em>must</em> have a
083     * {@code Boolean} attribute representing the inside status of
084     * the corresponding cell (true for inside cells, false for outside
085     * cells). In order to avoid building too many small objects, it is
086     * recommended to use the predefined constants
087     * {@code Boolean.TRUE} and {@code Boolean.FALSE}</p>
088     * @param tree inside/outside BSP tree representing the region
089     * @param tolerance below which points are consider to be identical
090     */
091    public SphericalPolygonsSet(final BSPTree<Sphere2D> tree, final double tolerance) {
092        super(tree, tolerance);
093    }
094
095    /** Build a polygons set from a Boundary REPresentation (B-rep).
096     * <p>The boundary is provided as a collection of {@link
097     * SubHyperplane sub-hyperplanes}. Each sub-hyperplane has the
098     * interior part of the region on its minus side and the exterior on
099     * its plus side.</p>
100     * <p>The boundary elements can be in any order, and can form
101     * several non-connected sets (like for example polygons with holes
102     * or a set of disjoint polygons considered as a whole). In
103     * fact, the elements do not even need to be connected together
104     * (their topological connections are not used here). However, if the
105     * boundary does not really separate an inside open from an outside
106     * open (open having here its topological meaning), then subsequent
107     * calls to the {@link
108     * org.apache.commons.math3.geometry.partitioning.Region#checkPoint(org.apache.commons.math3.geometry.Point)
109     * checkPoint} method will not be meaningful anymore.</p>
110     * <p>If the boundary is empty, the region will represent the whole
111     * space.</p>
112     * @param boundary collection of boundary elements, as a
113     * collection of {@link SubHyperplane SubHyperplane} objects
114     * @param tolerance below which points are consider to be identical
115     */
116    public SphericalPolygonsSet(final Collection<SubHyperplane<Sphere2D>> boundary, final double tolerance) {
117        super(boundary, tolerance);
118    }
119
120    /** Build a polygon from a simple list of vertices.
121     * <p>The boundary is provided as a list of points considering to
122     * represent the vertices of a simple loop. The interior part of the
123     * region is on the left side of this path and the exterior is on its
124     * right side.</p>
125     * <p>This constructor does not handle polygons with a boundary
126     * forming several disconnected paths (such as polygons with holes).</p>
127     * <p>For cases where this simple constructor applies, it is expected to
128     * be numerically more robust than the {@link #SphericalPolygonsSet(Collection,
129     * double) general constructor} using {@link SubHyperplane subhyperplanes}.</p>
130     * <p>If the list is empty, the region will represent the whole
131     * space.</p>
132     * <p>
133     * Polygons with thin pikes or dents are inherently difficult to handle because
134     * they involve circles with almost opposite directions at some vertices. Polygons
135     * whose vertices come from some physical measurement with noise are also
136     * difficult because an edge that should be straight may be broken in lots of
137     * different pieces with almost equal directions. In both cases, computing the
138     * circles intersections is not numerically robust due to the almost 0 or almost
139     * &pi; angle. Such cases need to carefully adjust the {@code hyperplaneThickness}
140     * parameter. A too small value would often lead to completely wrong polygons
141     * with large area wrongly identified as inside or outside. Large values are
142     * often much safer. As a rule of thumb, a value slightly below the size of the
143     * most accurate detail needed is a good value for the {@code hyperplaneThickness}
144     * parameter.
145     * </p>
146     * @param hyperplaneThickness tolerance below which points are considered to
147     * belong to the hyperplane (which is therefore more a slab)
148     * @param vertices vertices of the simple loop boundary
149     */
150    public SphericalPolygonsSet(final double hyperplaneThickness, final S2Point ... vertices) {
151        super(verticesToTree(hyperplaneThickness, vertices), hyperplaneThickness);
152    }
153
154    /** Build the vertices representing a regular polygon.
155     * @param center center of the polygon (the center is in the inside half)
156     * @param meridian point defining the reference meridian for first polygon vertex
157     * @param outsideRadius distance of the vertices to the center
158     * @param n number of sides of the polygon
159     * @return vertices array
160     */
161    private static S2Point[] createRegularPolygonVertices(final Vector3D center, final Vector3D meridian,
162                                                          final double outsideRadius, final int n) {
163        final S2Point[] array = new S2Point[n];
164        final Rotation r0 = new Rotation(Vector3D.crossProduct(center, meridian), outsideRadius);
165        array[0] = new S2Point(r0.applyTo(center));
166
167        final Rotation r = new Rotation(center, MathUtils.TWO_PI / n);
168        for (int i = 1; i < n; ++i) {
169            array[i] = new S2Point(r.applyTo(array[i - 1].getVector()));
170        }
171
172        return array;
173    }
174
175    /** Build the BSP tree of a polygons set from a simple list of vertices.
176     * <p>The boundary is provided as a list of points considering to
177     * represent the vertices of a simple loop. The interior part of the
178     * region is on the left side of this path and the exterior is on its
179     * right side.</p>
180     * <p>This constructor does not handle polygons with a boundary
181     * forming several disconnected paths (such as polygons with holes).</p>
182     * <p>This constructor handles only polygons with edges strictly shorter
183     * than \( \pi \). If longer edges are needed, they need to be broken up
184     * in smaller sub-edges so this constraint holds.</p>
185     * <p>For cases where this simple constructor applies, it is expected to
186     * be numerically more robust than the {@link #PolygonsSet(Collection) general
187     * constructor} using {@link SubHyperplane subhyperplanes}.</p>
188     * @param hyperplaneThickness tolerance below which points are consider to
189     * belong to the hyperplane (which is therefore more a slab)
190     * @param vertices vertices of the simple loop boundary
191     * @return the BSP tree of the input vertices
192     */
193    private static BSPTree<Sphere2D> verticesToTree(final double hyperplaneThickness,
194                                                    final S2Point ... vertices) {
195
196        final int n = vertices.length;
197        if (n == 0) {
198            // the tree represents the whole space
199            return new BSPTree<Sphere2D>(Boolean.TRUE);
200        }
201
202        // build the vertices
203        final Vertex[] vArray = new Vertex[n];
204        for (int i = 0; i < n; ++i) {
205            vArray[i] = new Vertex(vertices[i]);
206        }
207
208        // build the edges
209        List<Edge> edges = new ArrayList<Edge>(n);
210        Vertex end = vArray[n - 1];
211        for (int i = 0; i < n; ++i) {
212
213            // get the endpoints of the edge
214            final Vertex start = end;
215            end = vArray[i];
216
217            // get the circle supporting the edge, taking care not to recreate it
218            // if it was already created earlier due to another edge being aligned
219            // with the current one
220            Circle circle = start.sharedCircleWith(end);
221            if (circle == null) {
222                circle = new Circle(start.getLocation(), end.getLocation(), hyperplaneThickness);
223            }
224
225            // create the edge and store it
226            edges.add(new Edge(start, end,
227                               Vector3D.angle(start.getLocation().getVector(),
228                                              end.getLocation().getVector()),
229                               circle));
230
231            // check if another vertex also happens to be on this circle
232            for (final Vertex vertex : vArray) {
233                if (vertex != start && vertex != end &&
234                    FastMath.abs(circle.getOffset(vertex.getLocation())) <= hyperplaneThickness) {
235                    vertex.bindWith(circle);
236                }
237            }
238
239        }
240
241        // build the tree top-down
242        final BSPTree<Sphere2D> tree = new BSPTree<Sphere2D>();
243        insertEdges(hyperplaneThickness, tree, edges);
244
245        return tree;
246
247    }
248
249    /** Recursively build a tree by inserting cut sub-hyperplanes.
250     * @param hyperplaneThickness tolerance below which points are considered to
251     * belong to the hyperplane (which is therefore more a slab)
252     * @param node current tree node (it is a leaf node at the beginning
253     * of the call)
254     * @param edges list of edges to insert in the cell defined by this node
255     * (excluding edges not belonging to the cell defined by this node)
256     */
257    private static void insertEdges(final double hyperplaneThickness,
258                                    final BSPTree<Sphere2D> node,
259                                    final List<Edge> edges) {
260
261        // find an edge with an hyperplane that can be inserted in the node
262        int index = 0;
263        Edge inserted = null;
264        while (inserted == null && index < edges.size()) {
265            inserted = edges.get(index++);
266            if (!node.insertCut(inserted.getCircle())) {
267                inserted = null;
268            }
269        }
270
271        if (inserted == null) {
272            // no suitable edge was found, the node remains a leaf node
273            // we need to set its inside/outside boolean indicator
274            final BSPTree<Sphere2D> parent = node.getParent();
275            if (parent == null || node == parent.getMinus()) {
276                node.setAttribute(Boolean.TRUE);
277            } else {
278                node.setAttribute(Boolean.FALSE);
279            }
280            return;
281        }
282
283        // we have split the node by inserting an edge as a cut sub-hyperplane
284        // distribute the remaining edges in the two sub-trees
285        final List<Edge> outsideList = new ArrayList<Edge>();
286        final List<Edge> insideList  = new ArrayList<Edge>();
287        for (final Edge edge : edges) {
288            if (edge != inserted) {
289                edge.split(inserted.getCircle(), outsideList, insideList);
290            }
291        }
292
293        // recurse through lower levels
294        if (!outsideList.isEmpty()) {
295            insertEdges(hyperplaneThickness, node.getPlus(), outsideList);
296        } else {
297            node.getPlus().setAttribute(Boolean.FALSE);
298        }
299        if (!insideList.isEmpty()) {
300            insertEdges(hyperplaneThickness, node.getMinus(),  insideList);
301        } else {
302            node.getMinus().setAttribute(Boolean.TRUE);
303        }
304
305    }
306
307    /** {@inheritDoc} */
308    @Override
309    public SphericalPolygonsSet buildNew(final BSPTree<Sphere2D> tree) {
310        return new SphericalPolygonsSet(tree, getTolerance());
311    }
312
313    /** {@inheritDoc}
314     * @exception MathIllegalStateException if the tolerance setting does not allow to build
315     * a clean non-ambiguous boundary
316     */
317    @Override
318    protected void computeGeometricalProperties() throws MathIllegalStateException {
319
320        final BSPTree<Sphere2D> tree = getTree(true);
321
322        if (tree.getCut() == null) {
323
324            // the instance has a single cell without any boundaries
325
326            if (tree.getCut() == null && (Boolean) tree.getAttribute()) {
327                // the instance covers the whole space
328                setSize(4 * FastMath.PI);
329                setBarycenter(new S2Point(0, 0));
330            } else {
331                setSize(0);
332                setBarycenter(S2Point.NaN);
333            }
334
335        } else {
336
337            // the instance has a boundary
338            final PropertiesComputer pc = new PropertiesComputer(getTolerance());
339            tree.visit(pc);
340            setSize(pc.getArea());
341            setBarycenter(pc.getBarycenter());
342
343        }
344
345    }
346
347    /** Get the boundary loops of the polygon.
348     * <p>The polygon boundary can be represented as a list of closed loops,
349     * each loop being given by exactly one of its vertices. From each loop
350     * start vertex, one can follow the loop by finding the outgoing edge,
351     * then the end vertex, then the next outgoing edge ... until the start
352     * vertex of the loop (exactly the same instance) is found again once
353     * the full loop has been visited.</p>
354     * <p>If the polygon has no boundary at all, a zero length loop
355     * array will be returned.</p>
356     * <p>If the polygon is a simple one-piece polygon, then the returned
357     * array will contain a single vertex.
358     * </p>
359     * <p>All edges in the various loops have the inside of the region on
360     * their left side (i.e. toward their pole) and the outside on their
361     * right side (i.e. away from their pole) when moving in the underlying
362     * circle direction. This means that the closed loops obey the direct
363     * trigonometric orientation.</p>
364     * @return boundary of the polygon, organized as an unmodifiable list of loops start vertices.
365     * @exception MathIllegalStateException if the tolerance setting does not allow to build
366     * a clean non-ambiguous boundary
367     * @see Vertex
368     * @see Edge
369     */
370    public List<Vertex> getBoundaryLoops() throws MathIllegalStateException {
371
372        if (loops == null) {
373            if (getTree(false).getCut() == null) {
374                loops = Collections.emptyList();
375            } else {
376
377                // sort the arcs according to their start point
378                final BSPTree<Sphere2D> root = getTree(true);
379                final EdgesBuilder visitor = new EdgesBuilder(root, getTolerance());
380                root.visit(visitor);
381                final List<Edge> edges = visitor.getEdges();
382
383
384                // convert the list of all edges into a list of start vertices
385                loops = new ArrayList<Vertex>();
386                while (!edges.isEmpty()) {
387
388                    // this is an edge belonging to a new loop, store it
389                    Edge edge = edges.get(0);
390                    final Vertex startVertex = edge.getStart();
391                    loops.add(startVertex);
392
393                    // remove all remaining edges in the same loop
394                    do {
395
396                        // remove one edge
397                        for (final Iterator<Edge> iterator = edges.iterator(); iterator.hasNext();) {
398                            if (iterator.next() == edge) {
399                                iterator.remove();
400                                break;
401                            }
402                        }
403
404                        // go to next edge following the boundary loop
405                        edge = edge.getEnd().getOutgoing();
406
407                    } while (edge.getStart() != startVertex);
408
409                }
410
411            }
412        }
413
414        return Collections.unmodifiableList(loops);
415
416    }
417
418    /** Get a spherical cap enclosing the polygon.
419     * <p>
420     * This method is intended as a first test to quickly identify points
421     * that are guaranteed to be outside of the region, hence performing a full
422     * {@link #checkPoint(org.apache.commons.math3.geometry.Vector) checkPoint}
423     * only if the point status remains undecided after the quick check. It is
424     * is therefore mostly useful to speed up computation for small polygons with
425     * complex shapes (say a country boundary on Earth), as the spherical cap will
426     * be small and hence will reliably identify a large part of the sphere as outside,
427     * whereas the full check can be more computing intensive. A typical use case is
428     * therefore:
429     * </p>
430     * <pre>
431     *   // compute region, plus an enclosing spherical cap
432     *   SphericalPolygonsSet complexShape = ...;
433     *   EnclosingBall<Sphere2D, S2Point> cap = complexShape.getEnclosingCap();
434     *
435     *   // check lots of points
436     *   for (Vector3D p : points) {
437     *
438     *     final Location l;
439     *     if (cap.contains(p)) {
440     *       // we cannot be sure where the point is
441     *       // we need to perform the full computation
442     *       l = complexShape.checkPoint(v);
443     *     } else {
444     *       // no need to do further computation,
445     *       // we already know the point is outside
446     *       l = Location.OUTSIDE;
447     *     }
448     *
449     *     // use l ...
450     *
451     *   }
452     * </pre>
453     * <p>
454     * In the special cases of empty or whole sphere polygons, special
455     * spherical caps are returned, with angular radius set to negative
456     * or positive infinity so the {@link
457     * EnclosingBall#contains(org.apache.commons.math3.geometry.Point) ball.contains(point)}
458     * method return always false or true.
459     * </p>
460     * <p>
461     * This method is <em>not</em> guaranteed to return the smallest enclosing cap.
462     * </p>
463     * @return a spherical cap enclosing the polygon
464     */
465    public EnclosingBall<Sphere2D, S2Point> getEnclosingCap() {
466
467        // handle special cases first
468        if (isEmpty()) {
469            return new EnclosingBall<Sphere2D, S2Point>(S2Point.PLUS_K, Double.NEGATIVE_INFINITY);
470        }
471        if (isFull()) {
472            return new EnclosingBall<Sphere2D, S2Point>(S2Point.PLUS_K, Double.POSITIVE_INFINITY);
473        }
474
475        // as the polygons is neither empty nor full, it has some boundaries and cut hyperplanes
476        final BSPTree<Sphere2D> root = getTree(false);
477        if (isEmpty(root.getMinus()) && isFull(root.getPlus())) {
478            // the polygon covers an hemisphere, and its boundary is one 2π long edge
479            final Circle circle = (Circle) root.getCut().getHyperplane();
480            return new EnclosingBall<Sphere2D, S2Point>(new S2Point(circle.getPole()).negate(),
481                                                        0.5 * FastMath.PI);
482        }
483        if (isFull(root.getMinus()) && isEmpty(root.getPlus())) {
484            // the polygon covers an hemisphere, and its boundary is one 2π long edge
485            final Circle circle = (Circle) root.getCut().getHyperplane();
486            return new EnclosingBall<Sphere2D, S2Point>(new S2Point(circle.getPole()),
487                                                        0.5 * FastMath.PI);
488        }
489
490        // gather some inside points, to be used by the encloser
491        final List<Vector3D> points = getInsidePoints();
492
493        // extract points from the boundary loops, to be used by the encloser as well
494        final List<Vertex> boundary = getBoundaryLoops();
495        for (final Vertex loopStart : boundary) {
496            int count = 0;
497            for (Vertex v = loopStart; count == 0 || v != loopStart; v = v.getOutgoing().getEnd()) {
498                ++count;
499                points.add(v.getLocation().getVector());
500            }
501        }
502
503        // find the smallest enclosing 3D sphere
504        final SphereGenerator generator = new SphereGenerator();
505        final WelzlEncloser<Euclidean3D, Vector3D> encloser =
506                new WelzlEncloser<Euclidean3D, Vector3D>(getTolerance(), generator);
507        EnclosingBall<Euclidean3D, Vector3D> enclosing3D = encloser.enclose(points);
508        final Vector3D[] support3D = enclosing3D.getSupport();
509
510        // convert to 3D sphere to spherical cap
511        final double r = enclosing3D.getRadius();
512        final double h = enclosing3D.getCenter().getNorm();
513        if (h < getTolerance()) {
514            // the 3D sphere is centered on the unit sphere and covers it
515            // fall back to a crude approximation, based only on outside convex cells
516            EnclosingBall<Sphere2D, S2Point> enclosingS2 =
517                    new EnclosingBall<Sphere2D, S2Point>(S2Point.PLUS_K, Double.POSITIVE_INFINITY);
518            for (Vector3D outsidePoint : getOutsidePoints()) {
519                final S2Point outsideS2 = new S2Point(outsidePoint);
520                final BoundaryProjection<Sphere2D> projection = projectToBoundary(outsideS2);
521                if (FastMath.PI - projection.getOffset() < enclosingS2.getRadius()) {
522                    enclosingS2 = new EnclosingBall<Sphere2D, S2Point>(outsideS2.negate(),
523                                                                       FastMath.PI - projection.getOffset(),
524                                                                       (S2Point) projection.getProjected());
525                }
526            }
527            return enclosingS2;
528        }
529        final S2Point[] support = new S2Point[support3D.length];
530        for (int i = 0; i < support3D.length; ++i) {
531            support[i] = new S2Point(support3D[i]);
532        }
533
534        final EnclosingBall<Sphere2D, S2Point> enclosingS2 =
535                new EnclosingBall<Sphere2D, S2Point>(new S2Point(enclosing3D.getCenter()),
536                                                     FastMath.acos((1 + h * h - r * r) / (2 * h)),
537                                                     support);
538
539        return enclosingS2;
540
541    }
542
543    /** Gather some inside points.
544     * @return list of points known to be strictly in all inside convex cells
545     */
546    private List<Vector3D> getInsidePoints() {
547        final PropertiesComputer pc = new PropertiesComputer(getTolerance());
548        getTree(true).visit(pc);
549        return pc.getConvexCellsInsidePoints();
550    }
551
552    /** Gather some outside points.
553     * @return list of points known to be strictly in all outside convex cells
554     */
555    private List<Vector3D> getOutsidePoints() {
556        final SphericalPolygonsSet complement =
557                (SphericalPolygonsSet) new RegionFactory<Sphere2D>().getComplement(this);
558        final PropertiesComputer pc = new PropertiesComputer(getTolerance());
559        complement.getTree(true).visit(pc);
560        return pc.getConvexCellsInsidePoints();
561    }
562
563}