View Javadoc

    1   /*
    2    * Licensed to the Apache Software Foundation (ASF) under one or more
    3    * contributor license agreements.  See the NOTICE file distributed with
    4    * this work for additional information regarding copyright ownership.
    5    * The ASF licenses this file to You under the Apache License, Version 2.0
    6    * (the "License"); you may not use this file except in compliance with
    7    * the License.  You may obtain a copy of the License at
    8    *
    9    *      http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  package org.apache.commons.geometry.spherical.twod;
    18
    19  import java.util.Comparator;
    20
    21  import org.apache.commons.geometry.core.Point;
    22  import org.apache.commons.geometry.core.internal.SimpleTupleFormat;
    23  import org.apache.commons.geometry.euclidean.threed.SphericalCoordinates;
    24  import org.apache.commons.geometry.euclidean.threed.Vector3D;
    25  import org.apache.commons.geometry.euclidean.threed.rotation.QuaternionRotation;
    26  import org.apache.commons.numbers.core.Precision;
    27
    28  /** This class represents a point on the 2-sphere.
    29   * <p>Instances of this class are guaranteed to be immutable.</p>
    30   */
    31  public final class Point2S implements Point<Point2S> {
    32
    33      /** +I (coordinates: ( azimuth = 0, polar = pi/2 )). */
    34      public static final Point2S PLUS_I = new Point2S(0, 0.5 * Math.PI, Vector3D.Unit.PLUS_X);
    35
    36      /** +J (coordinates: ( azimuth = pi/2, polar = pi/2 ))). */
    37      public static final Point2S PLUS_J = new Point2S(0.5 * Math.PI, 0.5 * Math.PI, Vector3D.Unit.PLUS_Y);
    38
    39      /** +K (coordinates: ( azimuth = any angle, polar = 0 )). */
    40      public static final Point2S PLUS_K = new Point2S(0, 0, Vector3D.Unit.PLUS_Z);
    41
    42      /** -I (coordinates: ( azimuth = pi, polar = pi/2 )). */
    43      public static final Point2S MINUS_I = new Point2S(Math.PI, 0.5 * Math.PI, Vector3D.Unit.MINUS_X);
    44
    45      /** -J (coordinates: ( azimuth = 3pi/2, polar = pi/2 )). */
    46      public static final Point2S MINUS_J = new Point2S(1.5 * Math.PI, 0.5 * Math.PI, Vector3D.Unit.MINUS_Y);
    47
    48      /** -K (coordinates: ( azimuth = any angle, polar = pi )). */
    49      public static final Point2S MINUS_K = new Point2S(0, Math.PI, Vector3D.Unit.MINUS_Z);
    50
    51      /** A point with all coordinates set to NaN. */
    52      public static final Point2S NaN = new Point2S(Double.NaN, Double.NaN, null);
    53
    54      /** Comparator that sorts points in component-wise ascending order, first sorting
    55       * by polar value and then by azimuth value. Points are only considered equal if
    56       * their components match exactly. Null arguments are evaluated as being greater
    57       * than non-null arguments.
    58       */
    59      public static final Comparator<Point2S> POLAR_AZIMUTH_ASCENDING_ORDER = (a, b) -> {
    60          int cmp = 0;
    61
    62          if (a != null && b != null) {
    63              cmp = Double.compare(a.getPolar(), b.getPolar());
    64
    65              if (cmp == 0) {
    66                  cmp = Double.compare(a.getAzimuth(), b.getAzimuth());
    67              }
    68          } else if (a != null) {
    69              cmp = -1;
    70          } else if (b != null) {
    71              cmp = 1;
    72          }
    73
    74          return cmp;
    75      };
    76      /** Azimuthal angle in the x-y plane. */
    77      private final double azimuth;
    78
    79      /** Polar angle. */
    80      private final double polar;
    81
    82      /** Corresponding 3D normalized vector. */
    83      private final Vector3D.Unit vector;
    84
    85      /** Build a point from its internal components.
    86       * @param azimuth azimuthal angle in the x-y plane
    87       * @param polar polar angle
    88       * @param vector corresponding vector; if null, the vector is computed
    89       */
    90      private Point2S(final double azimuth, final double polar, final Vector3D.Unit vector) {
    91          this.azimuth = SphericalCoordinates.normalizeAzimuth(azimuth);
    92          this.polar = SphericalCoordinates.normalizePolar(polar);
    93          this.vector = (vector != null) ?
    94                  vector :
    95                  computeVector(azimuth, polar);
    96      }
    97
    98      /** Get the azimuth angle in the x-y plane in the range {@code [0, 2pi)}.
    99       * @return azimuth angle in the x-y plane in the range {@code [0, 2pi)}.
    100      * @see Point2S#of(double, double)
    101      */
    102     public double getAzimuth() {
    103         return azimuth;
    104     }
    105
    106     /** Get the polar angle in the range {@code [0, pi)}.
    107      * @return polar angle in the range {@code [0, pi)}.
    108      * @see Point2S#of(double, double)
    109      */
    110     public double getPolar() {
    111         return polar;
    112     }
    113
    114     /** Get the corresponding normalized vector in 3D Euclidean space.
    115      * This value will be null if the spherical coordinates of the point
    116      * are infinite or NaN.
    117      * @return normalized vector
    118      */
    119     public Vector3D.Unit getVector() {
    120         return vector;
    121     }
    122
    123     /** {@inheritDoc} */
    124     @Override
    125     public int getDimension() {
    126         return 2;
    127     }
    128
    129     /** {@inheritDoc} */
    130     @Override
    131     public boolean isNaN() {
    132         return Double.isNaN(azimuth) || Double.isNaN(polar);
    133     }
    134
    135     /** {@inheritDoc} */
    136     @Override
    137     public boolean isInfinite() {
    138         return !isNaN() && (Double.isInfinite(azimuth) || Double.isInfinite(polar));
    139     }
    140
    141     /** {@inheritDoc} */
    142     @Override
    143     public boolean isFinite() {
    144         return Double.isFinite(azimuth) && Double.isFinite(polar);
    145     }
    146
    147     /** Get the point exactly opposite this point on the sphere. The returned
    148      * point is {@code pi} distance away from the current instance.
    149      * @return the point exactly opposite this point on the sphere
    150      */
    151     public Point2S antipodal() {
    152         return from(vector.negate());
    153     }
    154
    155     /** {@inheritDoc} */
    156     @Override
    157     public double distance(final Point2S point) {
    158         return distance(this, point);
    159     }
    160
    161     /** Spherically interpolate a point along the shortest arc between this point and
    162      * the given point. The parameter {@code t} controls the interpolation and is expected
    163      * to be in the range {@code [0, 1]}, with {@code 0} returning a point equivalent to the
    164      * current instance {@code 1} returning a point equivalent to the given instance. If the
    165      * points are antipodal, then an arbitrary arc is chosen from the infinite number available.
    166      * @param other other point to interpolate with
    167      * @param t interpolation parameter
    168      * @return spherically interpolated point
    169      * @see QuaternionRotation#slerp(QuaternionRotation)
    170      * @see QuaternionRotation#createVectorRotation(Vector3D, Vector3D)
    171      */
    172     public Point2S slerp(final Point2S other, final double t) {
    173         final QuaternionRotation start = QuaternionRotation.identity();
    174         final QuaternionRotation end = QuaternionRotation.createVectorRotation(getVector(), other.getVector());
    175
    176         final QuaternionRotation quat = start.slerp(end).apply(t);
    177
    178         return Point2S.from(quat.apply(getVector()));
    179     }
    180
    181     /** Return true if this point should be considered equivalent to the argument using the
    182      * given precision context. This will be true if the distance between the points is
    183      * equivalent to zero as evaluated by the precision context.
    184      * @param point point to compare with
    185      * @param precision precision context used to perform floating point comparisons
    186      * @return true if this point should be considered equivalent to the argument using the
    187      *      given precision context
    188      */
    189     public boolean eq(final Point2S point, final Precision.DoubleEquivalence precision) {
    190         return precision.eqZero(distance(point));
    191     }
    192
    193     /** Get a hashCode for the point.
    194      * .
    195      * <p>All NaN values have the same hash code.</p>
    196      *
    197      * @return a hash code value for this object
    198      */
    199     @Override
    200     public int hashCode() {
    201         if (isNaN()) {
    202             return 542;
    203         }
    204         return 134 * (37 * Double.hashCode(azimuth) +  Double.hashCode(polar));
    205     }
    206
    207     /** Test for the equality of two points.
    208      *
    209      * <p>If all spherical coordinates of two points are exactly the same, and none are
    210      * <code>Double.NaN</code>, the two points are considered to be equal. Note
    211      * that the comparison is made using the azimuth and polar coordinates only; the
    212      * corresponding 3D vectors are not compared. This is significant at the poles,
    213      * where an infinite number of points share the same underlying 3D vector but may
    214      * have different spherical coordinates. For example, the points {@code (0, 0)}
    215      * and {@code (1, 0)} (both located at a pole but with different azimuths) will
    216      * <em>not</em> be considered equal by this method, even though they share the
    217      * exact same underlying 3D vector.</p>
    218      *
    219      * <p>
    220      * <code>NaN</code> coordinates are considered to affect the point globally
    221      * and be equals to each other - i.e, if either (or all) coordinates of the
    222      * point are equal to <code>Double.NaN</code>, the point is equal to
    223      * {@link #NaN}.
    224      * </p>
    225      *
    226      * @param other Object to test for equality to this
    227      * @return true if two points on the 2-sphere objects are exactly equal, false if
    228      *         object is null, not an instance of Point2S, or
    229      *         not equal to this Point2S instance
    230      */
    231     @Override
    232     public boolean equals(final Object other) {
    233         if (this == other) {
    234             return true;
    235         }
    236         if (!(other instanceof Point2S)) {
    237             return false;
    238         }
    239
    240         final Point2S rhs = (Point2S) other;
    241         if (rhs.isNaN()) {
    242             return this.isNaN();
    243         }
    244
    245         return Double.compare(azimuth, rhs.azimuth) == 0 &&
    246                 Double.compare(polar, rhs.polar) == 0;
    247     }
    248
    249     /** {@inheritDoc} */
    250     @Override
    251     public String toString() {
    252         return SimpleTupleFormat.getDefault().format(getAzimuth(), getPolar());
    253     }
    254
    255     /** Build a vector from its spherical coordinates.
    256      * @param azimuth azimuthal angle in the x-y plane
    257      * @param polar polar angle
    258      * @return point instance with the given coordinates
    259      * @see #getAzimuth()
    260      * @see #getPolar()
    261      */
    262     public static Point2S of(final double azimuth, final double polar) {
    263         return new Point2S(azimuth, polar, null);
    264     }
    265
    266     /** Build a point from its underlying 3D vector.
    267      * @param vector 3D vector
    268      * @return point instance with the coordinates determined by the given 3D vector
    269      * @exception IllegalStateException if vector norm is zero
    270      */
    271     public static Point2S from(final Vector3D vector) {
    272         final SphericalCoordinates coords = SphericalCoordinates.fromCartesian(vector);
    273
    274         return new Point2S(coords.getAzimuth(), coords.getPolar(), vector.normalize());
    275     }
    276
    277     /** Parses the given string and returns a new point instance. The expected string
    278      * format is the same as that returned by {@link #toString()}.
    279      * @param str the string to parse
    280      * @return point instance represented by the string
    281      * @throws IllegalArgumentException if the given string has an invalid format
    282      */
    283     public static Point2S parse(final String str) {
    284         return SimpleTupleFormat.getDefault().parse(str, Point2S::of);
    285     }
    286
    287     /** Compute the distance (angular separation) between two points.
    288      * @param p1 first vector
    289      * @param p2 second vector
    290      * @return the angular separation between p1 and p2
    291      */
    292     public static double distance(final Point2S p1, final Point2S p2) {
    293         return p1.vector.angle(p2.vector);
    294     }
    295
    296     /** Compute the 3D Euclidean vector associated with the given spherical coordinates.
    297      * Null is returned if the coordinates are infinite or NaN.
    298      * @param azimuth azimuth value
    299      * @param polar polar value
    300      * @return the 3D Euclidean vector associated with the given spherical coordinates
    301      *      or null if either of the arguments are infinite or NaN.
    302      */
    303     private static Vector3D.Unit computeVector(final double azimuth, final double polar) {
    304         if (Double.isFinite(azimuth) && Double.isFinite(polar)) {
    305             return SphericalCoordinates.toCartesian(1, azimuth, polar).normalize();
    306         }
    307         return null;
    308     }
    309 }