Skip to content

Apache Lucene open-source search software

LUCENE-6196: Geo3d initial checkin

David Wayne Smileybde056c76323
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/Geo3dShape.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/Geo3dShape.java
new file mode 100644
index 00000000000..e80e5b67eae
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/Geo3dShape.java
@@ -0,0 +1,162 @@
+package org.apache.lucene.spatial.spatial4j;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import com.spatial4j.core.context.SpatialContext;
+import com.spatial4j.core.shape.Point;
+import com.spatial4j.core.shape.Rectangle;
+import com.spatial4j.core.shape.Shape;
+import com.spatial4j.core.shape.SpatialRelation;
+import com.spatial4j.core.shape.impl.RectangleImpl;
+import org.apache.lucene.spatial.spatial4j.geo3d.Bounds;
+import org.apache.lucene.spatial.spatial4j.geo3d.GeoArea;
+import org.apache.lucene.spatial.spatial4j.geo3d.GeoAreaFactory;
+import org.apache.lucene.spatial.spatial4j.geo3d.GeoPoint;
+import org.apache.lucene.spatial.spatial4j.geo3d.GeoShape;
+
+/** A 3D planar geometry based Spatial4j Shape implementation. */
+public class Geo3dShape implements Shape {
+
+ public final SpatialContext ctx;
+ public final GeoShape shape;
+
+ private Rectangle boundingBox = null;
+
+ public final static double RADIANS_PER_DEGREE = Math.PI / 180.0;
+ public final static double DEGREES_PER_RADIAN = 1.0 / RADIANS_PER_DEGREE;
+
+ public Geo3dShape(GeoShape shape, SpatialContext ctx) {
+ if (!ctx.isGeo()) {
+ throw new IllegalArgumentException("SpatialContext.isGeo() must be true");
+ }
+ this.ctx = ctx;
+ this.shape = shape;
+ }
+
+ @Override
+ public SpatialRelation relate(Shape other) {
+ if (other instanceof Rectangle)
+ return relate((Rectangle)other);
+ else if (other instanceof Point)
+ return relate((Point)other);
+ else
+ throw new RuntimeException("Unimplemented shape relationship determination: " + other.getClass());
+ }
+
+ protected SpatialRelation relate(Rectangle r) {
+ // Construct the right kind of GeoArea first
+ GeoArea geoArea = GeoAreaFactory.makeGeoArea(r.getMaxY() * RADIANS_PER_DEGREE,
+ r.getMinY() * RADIANS_PER_DEGREE,
+ r.getMinX() * RADIANS_PER_DEGREE,
+ r.getMaxX() * RADIANS_PER_DEGREE);
+ int relationship = geoArea.getRelationship(shape);
+ if (relationship == GeoArea.WITHIN)
+ return SpatialRelation.WITHIN;
+ else if (relationship == GeoArea.CONTAINS)
+ return SpatialRelation.CONTAINS;
+ else if (relationship == GeoArea.OVERLAPS)
+ return SpatialRelation.INTERSECTS;
+ else if (relationship == GeoArea.DISJOINT)
+ return SpatialRelation.DISJOINT;
+ else
+ throw new RuntimeException("Unknown relationship returned: "+relationship);
+ }
+
+ protected SpatialRelation relate(Point p) {
+ // Create a GeoPoint
+ GeoPoint point = new GeoPoint(p.getY()*RADIANS_PER_DEGREE, p.getX()*RADIANS_PER_DEGREE);
+ if (shape.isWithin(point)) {
+ // Point within shape
+ return SpatialRelation.CONTAINS;
+ }
+ return SpatialRelation.DISJOINT;
+ }
+
+ @Override
+ public Rectangle getBoundingBox() {
+ if (boundingBox == null) {
+ Bounds bounds = shape.getBounds(null);
+ double leftLon;
+ double rightLon;
+ if (bounds.checkNoLongitudeBound()) {
+ leftLon = -180.0;
+ rightLon = 180.0;
+ } else {
+ leftLon = bounds.getLeftLongitude().doubleValue() * DEGREES_PER_RADIAN;
+ rightLon = bounds.getRightLongitude().doubleValue() * DEGREES_PER_RADIAN;
+ }
+ double minLat;
+ if (bounds.checkNoBottomLatitudeBound()) {
+ minLat = -90.0;
+ } else {
+ minLat = bounds.getMinLatitude().doubleValue() * DEGREES_PER_RADIAN;
+ }
+ double maxLat;
+ if (bounds.checkNoTopLatitudeBound()) {
+ maxLat = 90.0;
+ } else {
+ maxLat = bounds.getMaxLatitude().doubleValue() * DEGREES_PER_RADIAN;
+ }
+ boundingBox = new RectangleImpl(leftLon, rightLon, minLat, maxLat, ctx);
+ }
+ return boundingBox;
+ }
+
+ @Override
+ public boolean hasArea() {
+ return true;
+ }
+
+ @Override
+ public double getArea(SpatialContext ctx) {
+ throw new RuntimeException("Unimplemented");
+ }
+
+ @Override
+ public Point getCenter() {
+ throw new RuntimeException("Unimplemented");
+ }
+
+ @Override
+ public Shape getBuffered(double distance, SpatialContext ctx) {
+ return this;
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return "Geo3dShape{" + shape + '}';
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof Geo3dShape))
+ return false;
+ Geo3dShape tr = (Geo3dShape)other;
+ return tr.shape.equals(shape);
+ }
+
+ @Override
+ public int hashCode() {
+ return shape.hashCode();
+ }
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Bounds.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Bounds.java
new file mode 100755
index 00000000000..ea9f6b4352f
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Bounds.java
@@ -0,0 +1,290 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** An object for accumulating bounds information.
+* The bounds object is initially empty. Bounding points
+* are then applied by supplying (x,y,z) tuples. It is also
+* possible to indicate the following edge cases:
+* (1) No longitude bound possible
+* (2) No upper latitude bound possible
+* (3) No lower latitude bound possible
+* When any of these have been applied, further application of
+* points cannot override that decision.
+ */
+public class Bounds
+{
+ protected boolean noLongitudeBound = false;
+ protected boolean noTopLatitudeBound = false;
+ protected boolean noBottomLatitudeBound = false;
+
+ protected Double minLatitude = null;
+ protected Double maxLatitude = null;
+
+ // For longitude bounds, this class needs to worry about keeping track of the distinction
+ // between left-side bounds and right-side bounds. Points are always submitted in pairs
+ // which have a maximum longitude separation of Math.PI. It's therefore always possible
+ // to determine which point represents a left bound, and which point represents a right
+ // bound.
+ //
+ // The next problem is how to compare two of the same kind of bound, e.g. two left bounds.
+ // We need to keep track of the leftmost longitude of the shape, but since this is a circle,
+ // this is arbitrary. What we could try to do instead would be to find a pair of (left,right) bounds such
+ // that:
+ // (1) all other bounds are within, and
+ // (2) the left minus right distance is minimized
+ // Unfortunately, there are still shapes that cannot be summarized in this way correctly.
+ // For example. consider a spiral that entirely circles the globe; we might arbitrarily choose
+ // lat/lon bounds that do not in fact circle the globe.
+ //
+ // One way to handle the longitude issue correctly is therefore to stipulate that we
+ // walk the bounds of the shape in some kind of connected order. Each point or circle is therefore
+ // added in a sequence. We also need an interior point to make sure we have the right
+ // choice of longitude bounds. But even with this, we still can't always choose whether the actual shape
+ // goes right or left.
+ //
+ // We can make the specification truly general by submitting the following in order:
+ // addSide(PlaneSide side, Membership... constraints)
+ // ...
+ // This is unambiguous, but I still can't see yet how this would help compute the bounds. The plane
+ // solution would in general seem to boil down to the same logic that relies on points along the path
+ // to define the shape boundaries. I guess the one thing that you do know for a bounded edge is that
+ // the endpoints are actually connected. But it is not clear whether relationship helps in any way.
+ //
+ // In any case, if we specify shapes by a sequence of planes, we should stipulate that multiple sequences
+ // are allowed, provided they progressively tile an area of the sphere that is connected and sequential.
+ // For example, paths do alternating rectangles and circles, in sequence. Each sequence member is
+ // described by a sequence of planes. I think it would also be reasonable to insist that the first segment
+ // of a shape overlap or adjoin the previous shape.
+ //
+ // Here's a way to think about it that might help: Traversing every edge should grow the longitude bounds
+ // in the direction of the traversal. So if the traversal is always known to be less than PI in total longitude
+ // angle, then it is possible to use the endpoints to determine the unambiguous extension of the envelope.
+ // For example, say you are currently at longitude -0.5. The next point is at longitude PI-0.1. You could say
+ // that the difference in longitude going one way around would be beter than the distance the other way
+ // around, and therefore the longitude envelope should be extended accordingly. But in practice, when an
+ // edge goes near a pole and may be inclined as well, the longer longitude change might be the right path, even
+ // if the arc length is short. So this too doesn't work.
+ //
+ // Given we have a hard time making an exact match, here's the current proposal. The proposal is a
+ // heuristic, based on the idea that most areas are small compared to the circumference of the globe.
+ // We keep track of the last point we saw, and take each point as it arrives, and compute its longitude.
+ // Then, we have a choice as to which way to expand the envelope: we can expand by going to the left or
+ // to the right. We choose the direction with the least longitude difference. (If we aren't sure,
+ // and can recognize that, we can set "unconstrained in longitude".)
+
+ protected Double leftLongitude = null;
+ protected Double rightLongitude = null;
+
+ public Bounds() {
+ }
+
+ public Double getMaxLatitude() {
+ return maxLatitude;
+ }
+
+ public Double getMinLatitude() {
+ return minLatitude;
+ }
+
+ public Double getLeftLongitude() {
+ return leftLongitude;
+ }
+
+ public Double getRightLongitude() {
+ return rightLongitude;
+ }
+
+ public boolean checkNoLongitudeBound() {
+ return noLongitudeBound;
+ }
+
+ public boolean checkNoTopLatitudeBound() {
+ return noTopLatitudeBound;
+ }
+
+ public boolean checkNoBottomLatitudeBound() {
+ return noBottomLatitudeBound;
+ }
+
+ public Bounds addHorizontalCircle(double z) {
+ if (!noTopLatitudeBound || !noBottomLatitudeBound) {
+ // Compute a latitude value
+ double latitude = Math.asin(z);
+ addLatitudeBound(latitude);
+ }
+ return this;
+ }
+
+ public Bounds addLatitudeZone(double latitude) {
+ if (!noTopLatitudeBound || !noBottomLatitudeBound) {
+ addLatitudeBound(latitude);
+ }
+ return this;
+ }
+
+ public Bounds addLongitudeSlice(double newLeftLongitude, double newRightLongitude) {
+ if (!noLongitudeBound) {
+ addLongitudeBound(newLeftLongitude,newRightLongitude);
+ }
+ return this;
+ }
+
+ protected void addLatitudeBound(double latitude) {
+ if (!noTopLatitudeBound && (maxLatitude == null || latitude > maxLatitude))
+ maxLatitude = latitude;
+ if (!noBottomLatitudeBound && (minLatitude == null || latitude < minLatitude))
+ minLatitude = latitude;
+ }
+
+ protected void addLongitudeBound(double newLeftLongitude, double newRightLongitude) {
+ if (leftLongitude == null && rightLongitude == null) {
+ leftLongitude = newLeftLongitude;
+ rightLongitude = newRightLongitude;
+ } else {
+ // Map the current range to something monotonically increasing
+ double currentLeftLongitude = leftLongitude;
+ double currentRightLongitude = rightLongitude;
+ if (currentRightLongitude < currentLeftLongitude)
+ currentRightLongitude += 2.0 * Math.PI;
+ double adjustedLeftLongitude = newLeftLongitude;
+ double adjustedRightLongitude = newRightLongitude;
+ if (adjustedRightLongitude < adjustedLeftLongitude)
+ adjustedRightLongitude += 2.0 * Math.PI;
+ // Compare to see what the relationship is
+ if (currentLeftLongitude <= adjustedLeftLongitude && currentRightLongitude >= adjustedRightLongitude) {
+ // No adjustment needed.
+ } else if (currentLeftLongitude >= adjustedLeftLongitude && currentRightLongitude <= adjustedRightLongitude) {
+ // New longitude entirely contains old one
+ leftLongitude = newLeftLongitude;
+ rightLongitude = newRightLongitude;
+ } else {
+ if (currentLeftLongitude > adjustedLeftLongitude) {
+ // New left longitude needed
+ leftLongitude = newLeftLongitude;
+ }
+ if (currentRightLongitude < adjustedRightLongitude) {
+ // New right longitude needed
+ rightLongitude = newRightLongitude;
+ }
+ }
+ }
+ double testRightLongitude = rightLongitude;
+ if (testRightLongitude < leftLongitude)
+ testRightLongitude += Math.PI * 2.0;
+ if (testRightLongitude - leftLongitude >= Math.PI * 2.0) {
+ noLongitudeBound = true;
+ leftLongitude = null;
+ rightLongitude = null;
+ }
+ }
+
+ protected void addLongitudeBound(double longitude) {
+ // If this point is within the current bounds, we're done; otherwise
+ // expand one side or the other.
+ if (leftLongitude == null && rightLongitude == null) {
+ leftLongitude = longitude;
+ rightLongitude = longitude;
+ } else {
+ // Compute whether we're to the right of the left value. But the left value may be greater than
+ // the right value.
+ double currentLeftLongitude = leftLongitude;
+ double currentRightLongitude = rightLongitude;
+ if (currentRightLongitude < currentLeftLongitude)
+ currentRightLongitude += 2.0 * Math.PI;
+ // We have a range to look at that's going in the right way.
+ // Now, do the same trick with the computed longitude.
+ if (longitude < currentLeftLongitude)
+ longitude += 2.0 * Math.PI;
+
+ if (longitude < currentLeftLongitude || longitude > currentRightLongitude) {
+ // Outside of current bounds. Consider carefully how we'll expand.
+ double leftExtensionAmt;
+ double rightExtensionAmt;
+ if (longitude < currentLeftLongitude) {
+ leftExtensionAmt = currentLeftLongitude - longitude;
+ } else {
+ leftExtensionAmt = currentLeftLongitude + 2.0 * Math.PI - longitude;
+ }
+ if (longitude > currentRightLongitude) {
+ rightExtensionAmt = longitude - currentRightLongitude;
+ } else {
+ rightExtensionAmt = longitude + 2.0 * Math.PI - currentRightLongitude;
+ }
+ if (leftExtensionAmt < rightExtensionAmt) {
+ currentLeftLongitude = leftLongitude - leftExtensionAmt;
+ while (currentLeftLongitude <= -Math.PI) {
+ currentLeftLongitude += 2.0 * Math.PI;
+ }
+ leftLongitude = currentLeftLongitude;
+ } else {
+ currentRightLongitude = rightLongitude + rightExtensionAmt;
+ while (currentRightLongitude > Math.PI) {
+ currentRightLongitude -= 2.0 * Math.PI;
+ }
+ rightLongitude = currentRightLongitude;
+ }
+ }
+ }
+ double testRightLongitude = rightLongitude;
+ if (testRightLongitude < leftLongitude)
+ testRightLongitude += Math.PI * 2.0;
+ if (testRightLongitude - leftLongitude >= Math.PI * 2.0) {
+ noLongitudeBound = true;
+ leftLongitude = null;
+ rightLongitude = null;
+ }
+ }
+
+ public Bounds addPoint(Vector v) {
+ return addPoint(v.x, v.y, v.z);
+ }
+
+ public Bounds addPoint(double x, double y, double z) {
+ if (!noLongitudeBound) {
+ // Get a longitude value
+ double longitude = Math.atan2(y,x);
+ addLongitudeBound(longitude);
+ }
+ if (!noTopLatitudeBound || !noBottomLatitudeBound) {
+ // Compute a latitude value
+ double latitude = Math.asin(z);
+ addLatitudeBound(latitude);
+ }
+ return this;
+ }
+
+ public Bounds noLongitudeBound() {
+ noLongitudeBound = true;
+ leftLongitude = null;
+ rightLongitude = null;
+ return this;
+ }
+
+ public Bounds noTopLatitudeBound() {
+ noTopLatitudeBound = true;
+ maxLatitude = null;
+ return this;
+ }
+
+ public Bounds noBottomLatitudeBound() {
+ noBottomLatitudeBound = true;
+ minLatitude = null;
+ return this;
+ }
+}
\ No newline at end of file
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoArea.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoArea.java
new file mode 100755
index 00000000000..f7e07993308
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoArea.java
@@ -0,0 +1,45 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** A GeoArea represents a standard 2-D breakdown of a part of sphere. It can
+* be bounded in latitude, or bounded in both latitude and longitude, or not
+* bounded at all. The purpose of the interface is to describe bounding shapes used for
+* computation of geo hashes. */
+public interface GeoArea extends Membership {
+ // Since we don't know what each GeoArea's constraints are,
+ // we put the onus on the GeoArea implementation to do the right thing.
+ // This will, of course, rely heavily on methods provided by
+ // the underlying GeoShape class.
+
+ public static final int CONTAINS = 0;
+ public static final int WITHIN = 1;
+ public static final int OVERLAPS = 2;
+ public static final int DISJOINT = 3;
+
+ /** Find the spatial relationship between a shape and the current geo area.
+ * Note: return value is how the GeoShape relates to the GeoArea, not the
+ * other way around. For example, if this GeoArea is entirely within the
+ * shape, then CONTAINS should be returned. If the shape is entirely enclosed
+ * by this GeoArea, then WITHIN should be returned.
+ *@param shape is the shape to consider.
+ *@return the relationship, from the perspective of the shape.
+ */
+ public int getRelationship(GeoShape shape);
+}
+
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoAreaFactory.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoAreaFactory.java
new file mode 100755
index 00000000000..62c391e6567
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoAreaFactory.java
@@ -0,0 +1,36 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+public class GeoAreaFactory
+{
+ private GeoAreaFactory() {
+ }
+
+ /** Create a GeoArea of the right kind given the specified bounds.
+ *@param topLat is the top latitude
+ *@param bottomLat is the bottom latitude
+ *@param leftLon is the left longitude
+ *@param rightLon is the right longitude
+ *@return a GeoArea corresponding to what was specified.
+ */
+ public static GeoArea makeGeoArea(double topLat, double bottomLat, double leftLon, double rightLon) {
+ return GeoBBoxFactory.makeGeoBBox(topLat, bottomLat, leftLon, rightLon);
+ }
+
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoBBox.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoBBox.java
new file mode 100755
index 00000000000..ea92c7457b1
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoBBox.java
@@ -0,0 +1,32 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** All bounding box shapes have this interface in common.
+* This describes methods that bounding boxes have above and beyond
+* GeoMembershipShape's.
+*/
+public interface GeoBBox extends GeoMembershipShape, GeoSizeable, GeoArea {
+
+ /** Expand box by specified angle.
+ *@param angle is the angle amount to expand the GeoBBox by.
+ *@return a new GeoBBox.
+ */
+ public GeoBBox expand(double angle);
+
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoBBoxFactory.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoBBoxFactory.java
new file mode 100755
index 00000000000..58e332122be
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoBBoxFactory.java
@@ -0,0 +1,59 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+public class GeoBBoxFactory
+{
+ private GeoBBoxFactory() {
+ }
+
+ /** Create a geobbox of the right kind given the specified bounds.
+ *@param topLat is the top latitude
+ *@param bottomLat is the bottom latitude
+ *@param leftLon is the left longitude
+ *@param rightLon is the right longitude
+ *@return a GeoBBox corresponding to what was specified.
+ */
+ public static GeoBBox makeGeoBBox(double topLat, double bottomLat, double leftLon, double rightLon) {
+ if (topLat > Math.PI * 0.5)
+ topLat = Math.PI * 0.5;
+ if (bottomLat < -Math.PI * 0.5)
+ bottomLat = -Math.PI * 0.5;
+ if (leftLon < -Math.PI)
+ leftLon = -Math.PI;
+ if (rightLon > Math.PI)
+ rightLon = Math.PI;
+ if (leftLon == -Math.PI && rightLon == Math.PI) {
+ if (topLat == Math.PI * 0.5 && bottomLat == -Math.PI * 0.5)
+ return new GeoWorld();
+ return new GeoLatitudeZone(topLat, bottomLat);
+ }
+ double extent = rightLon - leftLon;
+ if (extent < 0.0)
+ extent += Math.PI * 2.0;
+ if (topLat == Math.PI * 0.5 && bottomLat == -Math.PI * 0.5) {
+ if (extent >= Math.PI)
+ return new GeoWideLongitudeSlice(leftLon, rightLon);
+ return new GeoLongitudeSlice(leftLon, rightLon);
+ }
+ if (extent >= Math.PI)
+ return new GeoWideRectangle(topLat, bottomLat, leftLon, rightLon);
+ return new GeoRectangle(topLat, bottomLat, leftLon, rightLon);
+ }
+
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoBaseExtendedShape.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoBaseExtendedShape.java
new file mode 100755
index 00000000000..35f93c681d1
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoBaseExtendedShape.java
@@ -0,0 +1,84 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Base extended shape object.
+*/
+public abstract class GeoBaseExtendedShape implements GeoShape
+{
+ protected final static GeoPoint NORTH_POLE = new GeoPoint(0.0,0.0,1.0);
+ protected final static GeoPoint SOUTH_POLE = new GeoPoint(0.0,0.0,-1.0);
+
+ public GeoBaseExtendedShape()
+ {
+ }
+
+ /** Check if a point is within this shape.
+ *@param point is the point to check.
+ *@return true if the point is within this shape
+ */
+ @Override
+ public abstract boolean isWithin(Vector point);
+
+ /** Check if a point is within this shape.
+ *@param x is x coordinate of point to check.
+ *@param y is y coordinate of point to check.
+ *@param z is z coordinate of point to check.
+ *@return true if the point is within this shape
+ */
+ @Override
+ public abstract boolean isWithin(double x, double y, double z);
+
+ /** Return a sample point that is inside the shape.
+ *@return an interior point.
+ */
+ @Override
+ public abstract GeoPoint getInteriorPoint();
+
+ /** Assess whether a plane, within the provided bounds, intersects
+ * with the shape.
+ *@param plane is the plane to assess for intersection with the shape's edges or
+ * bounding curves.
+ *@param bounds are a set of bounds that define an area that an
+ * intersection must be within in order to qualify (provided by a GeoArea).
+ *@return true if there's such an intersection, false if not.
+ */
+ @Override
+ public abstract boolean intersects(Plane plane, Membership... bounds);
+
+ /** Compute longitude/latitude bounds for the shape.
+ *@param bounds is the optional input bounds object. If this is null,
+ * a bounds object will be created. Otherwise, the input object will be modified.
+ *@return a Bounds object describing the shape's bounds. If the bounds cannot
+ * be computed, then return a Bounds object with noLongitudeBound,
+ * noTopLatitudeBound, and noBottomLatitudeBound.
+ */
+ @Override
+ public Bounds getBounds(Bounds bounds)
+ {
+ if (bounds == null)
+ bounds = new Bounds();
+ if (isWithin(NORTH_POLE)) {
+ bounds.noTopLatitudeBound().noLongitudeBound();
+ }
+ if (isWithin(SOUTH_POLE)) {
+ bounds.noBottomLatitudeBound().noLongitudeBound();
+ }
+ return bounds;
+ }
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoCircle.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoCircle.java
new file mode 100755
index 00000000000..29ac2064e88
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoCircle.java
@@ -0,0 +1,224 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Circular area with a center and radius.
+*/
+public class GeoCircle extends GeoBaseExtendedShape implements GeoDistanceShape, GeoSizeable
+{
+ public final GeoPoint center;
+ public final double cutoffAngle;
+ public final double cutoffNormalDistance;
+ public final double cutoffLinearDistance;
+ public final SidedPlane circlePlane;
+
+ public GeoCircle(double lat, double lon, double cutoffAngle)
+ {
+ super();
+ if (lat < -Math.PI * 0.5 || lat > Math.PI * 0.5)
+ throw new IllegalArgumentException("Latitude out of bounds");
+ if (lon < -Math.PI || lon > Math.PI)
+ throw new IllegalArgumentException("Longitude out of bounds");
+ if (cutoffAngle < 0.0 || cutoffAngle > Math.PI)
+ throw new IllegalArgumentException("Cutoff angle out of bounds");
+ double sinAngle = Math.sin(cutoffAngle);
+ double cosAngle = Math.cos(cutoffAngle);
+ this.center = new GeoPoint(lat,lon);
+ this.cutoffNormalDistance = sinAngle;
+ // Need the chord distance. This is just the chord distance: sqrt((1 - cos(angle))^2 + (sin(angle))^2).
+ double xDiff = 1.0 - cosAngle;
+ this.cutoffLinearDistance = Math.sqrt(xDiff * xDiff + sinAngle * sinAngle);
+ this.cutoffAngle = cutoffAngle;
+ this.circlePlane = new SidedPlane(center, center, -cosAngle);
+ }
+
+ @Override
+ public double getRadius() {
+ return cutoffAngle;
+ }
+
+ /** Compute an estimate of "distance" to the GeoPoint.
+ * A return value of Double.MAX_VALUE should be returned for
+ * points outside of the shape.
+ */
+ @Override
+ public double computeNormalDistance(GeoPoint point)
+ {
+ double normalDistance = this.center.normalDistance(point);
+ if (normalDistance > cutoffNormalDistance)
+ return Double.MAX_VALUE;
+ return normalDistance;
+ }
+
+ /** Compute an estimate of "distance" to the GeoPoint.
+ * A return value of Double.MAX_VALUE should be returned for
+ * points outside of the shape.
+ */
+ @Override
+ public double computeNormalDistance(double x, double y, double z)
+ {
+ double normalDistance = this.center.normalDistance(x,y,z);
+ if (normalDistance > cutoffNormalDistance)
+ return Double.MAX_VALUE;
+ return normalDistance;
+ }
+
+ /** Compute a squared estimate of the "distance" to the
+ * GeoPoint. Double.MAX_VALUE indicates a point outside of the
+ * shape.
+ */
+ @Override
+ public double computeSquaredNormalDistance(GeoPoint point)
+ {
+ double normalDistanceSquared = this.center.normalDistanceSquared(point);
+ if (normalDistanceSquared > cutoffNormalDistance * cutoffNormalDistance)
+ return Double.MAX_VALUE;
+ return normalDistanceSquared;
+ }
+
+ /** Compute a squared estimate of the "distance" to the
+ * GeoPoint. Double.MAX_VALUE indicates a point outside of the
+ * shape.
+ */
+ @Override
+ public double computeSquaredNormalDistance(double x, double y, double z)
+ {
+ double normalDistanceSquared = this.center.normalDistanceSquared(x,y,z);
+ if (normalDistanceSquared > cutoffNormalDistance * cutoffNormalDistance)
+ return Double.MAX_VALUE;
+ return normalDistanceSquared;
+ }
+
+ /** Compute a linear distance to the vector.
+ * return Double.MAX_VALUE for points outside the shape.
+ */
+ @Override
+ public double computeLinearDistance(GeoPoint point)
+ {
+ double linearDistance = this.center.linearDistance(point);
+ if (linearDistance > cutoffLinearDistance)
+ return Double.MAX_VALUE;
+ return linearDistance;
+ }
+
+ /** Compute a linear distance to the vector.
+ * return Double.MAX_VALUE for points outside the shape.
+ */
+ @Override
+ public double computeLinearDistance(double x, double y, double z)
+ {
+ double linearDistance = this.center.linearDistance(x,y,z);
+ if (linearDistance > cutoffLinearDistance)
+ return Double.MAX_VALUE;
+ return linearDistance;
+ }
+
+ /** Compute a squared linear distance to the vector.
+ */
+ @Override
+ public double computeSquaredLinearDistance(GeoPoint point)
+ {
+ double linearDistanceSquared = this.center.linearDistanceSquared(point);
+ if (linearDistanceSquared > cutoffLinearDistance * cutoffLinearDistance)
+ return Double.MAX_VALUE;
+ return linearDistanceSquared;
+ }
+
+ /** Compute a squared linear distance to the vector.
+ */
+ @Override
+ public double computeSquaredLinearDistance(double x, double y, double z)
+ {
+ double linearDistanceSquared = this.center.linearDistanceSquared(x,y,z);
+ if (linearDistanceSquared > cutoffLinearDistance * cutoffLinearDistance)
+ return Double.MAX_VALUE;
+ return linearDistanceSquared;
+ }
+
+ /** Compute a true, accurate, great-circle distance.
+ * Double.MAX_VALUE indicates a point is outside of the shape.
+ */
+ @Override
+ public double computeArcDistance(GeoPoint point)
+ {
+ double dist = this.center.arcDistance(point);
+ if (dist > cutoffAngle)
+ return Double.MAX_VALUE;
+ return dist;
+ }
+
+ @Override
+ public boolean isWithin(Vector point)
+ {
+ // Fastest way of determining membership
+ return circlePlane.isWithin(point);
+ }
+
+ @Override
+ public boolean isWithin(double x, double y, double z)
+ {
+ // Fastest way of determining membership
+ return circlePlane.isWithin(x,y,z);
+ }
+
+ @Override
+ public GeoPoint getInteriorPoint()
+ {
+ return center;
+ }
+
+ @Override
+ public boolean intersects(Plane p, Membership... bounds)
+ {
+ return circlePlane.intersects(p, bounds);
+ }
+
+ /** Compute longitude/latitude bounds for the shape.
+ *@param bounds is the optional input bounds object. If this is null,
+ * a bounds object will be created. Otherwise, the input object will be modified.
+ *@return a Bounds object describing the shape's bounds. If the bounds cannot
+ * be computed, then return a Bounds object with noLongitudeBound,
+ * noTopLatitudeBound, and noBottomLatitudeBound.
+ */
+ @Override
+ public Bounds getBounds(Bounds bounds)
+ {
+ bounds = super.getBounds(bounds);
+ circlePlane.recordBounds(bounds);
+ return bounds;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof GeoCircle))
+ return false;
+ GeoCircle other = (GeoCircle)o;
+ return other.center.equals(center) && other.cutoffAngle == cutoffAngle;
+ }
+
+ @Override
+ public int hashCode() {
+ int result;
+ long temp;
+ result = center.hashCode();
+ temp = Double.doubleToLongBits(cutoffAngle);
+ result = 31 * result + (int) (temp ^ (temp >>> 32));
+ return result;
+ }
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoCompositeMembershipShape.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoCompositeMembershipShape.java
new file mode 100755
index 00000000000..d08087f551a
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoCompositeMembershipShape.java
@@ -0,0 +1,118 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.util.*;
+
+/** GeoComposite is a set of GeoMembershipShape's, treated as a unit.
+*/
+public class GeoCompositeMembershipShape implements GeoMembershipShape
+{
+ protected final List<GeoMembershipShape> shapes = new ArrayList<GeoMembershipShape>();
+
+ public GeoCompositeMembershipShape()
+ {
+ }
+
+ /** Add a shape to the composite.
+ */
+ public void addShape(GeoMembershipShape shape) {
+ shapes.add(shape);
+ }
+
+ @Override
+ public boolean isWithin(Vector point)
+ {
+ for (GeoMembershipShape shape : shapes) {
+ if (shape.isWithin(point))
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean isWithin(double x, double y, double z)
+ {
+ for (GeoMembershipShape shape : shapes) {
+ if (shape.isWithin(x,y,z))
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public GeoPoint getInteriorPoint()
+ {
+ return shapes.get(0).getInteriorPoint();
+ }
+
+ @Override
+ public boolean intersects(Plane p, Membership... bounds)
+ {
+ for (GeoMembershipShape shape : shapes) {
+ if (shape.intersects(p,bounds))
+ return true;
+ }
+ return false;
+ }
+
+ /** Compute longitude/latitude bounds for the shape.
+ *@param bounds is the optional input bounds object. If this is null,
+ * a bounds object will be created. Otherwise, the input object will be modified.
+ *@return a Bounds object describing the shape's bounds. If the bounds cannot
+ * be computed, then return a Bounds object with noLongitudeBound,
+ * noTopLatitudeBound, and noBottomLatitudeBound.
+ */
+ @Override
+ public Bounds getBounds(Bounds bounds)
+ {
+ if (bounds == null)
+ bounds = new Bounds();
+ for (GeoMembershipShape shape : shapes) {
+ bounds = shape.getBounds(bounds);
+ }
+ return bounds;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof GeoCompositeMembershipShape))
+ return false;
+ GeoCompositeMembershipShape other = (GeoCompositeMembershipShape)o;
+ if (other.shapes.size() != shapes.size())
+ return false;
+
+ for (int i = 0; i < shapes.size(); i++) {
+ if (!other.shapes.get(i).equals(shapes.get(i)))
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ return shapes.hashCode();//TODO cache
+ }
+
+ @Override
+ public String toString() {
+ return "GeoCompositeMembershipShape{" + shapes + '}';
+ }
+}
+
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoConvexPolygon.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoConvexPolygon.java
new file mode 100755
index 00000000000..c0bbd6c19d7
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoConvexPolygon.java
@@ -0,0 +1,248 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.util.*;
+
+/** GeoConvexPolygon objects are generic building blocks of more complex structures.
+* The only restrictions on these objects are: (1) they must be convex; (2) they must have
+* a maximum extent no larger than PI. Violating either one of these limits will
+* cause the logic to fail.
+*/
+public class GeoConvexPolygon extends GeoBaseExtendedShape implements GeoMembershipShape
+{
+ protected final List<GeoPoint> points;
+ protected SidedPlane[] edges = null;
+ protected GeoPoint interiorPoint = null;
+
+ /** Create a convex polygon from a list of points.
+ */
+ public GeoConvexPolygon(List<GeoPoint> pointList) {
+ this.points = pointList;
+ donePoints();
+ }
+
+ /** Create a convex polygon, with a starting latitude and longitude.
+ * Accepts only values in the following ranges: lat: {@code -PI/2 -> PI/2}, lon: {@code -PI -> PI}
+ */
+ public GeoConvexPolygon(double startLatitude, double startLongitude)
+ {
+ points = new ArrayList<GeoPoint>();
+ // Argument checking
+ if (startLatitude > Math.PI * 0.5 || startLatitude < -Math.PI * 0.5)
+ throw new IllegalArgumentException("Latitude out of range");
+ if (startLongitude < -Math.PI || startLongitude > Math.PI)
+ throw new IllegalArgumentException("Longitude out of range");
+
+ GeoPoint p = new GeoPoint(startLatitude, startLongitude);
+ points.add(p);
+ }
+
+ /** Add a point to the polygon.
+ * Accepts only values in the following ranges: lat: {@code -PI/2 -> PI/2}, lon: {@code -PI -> PI}
+ */
+ public void addPoint(double latitude, double longitude) {
+ // Argument checking
+ if (latitude > Math.PI * 0.5 || latitude < -Math.PI * 0.5)
+ throw new IllegalArgumentException("Latitude out of range");
+ if (longitude < -Math.PI || longitude > Math.PI)
+ throw new IllegalArgumentException("Longitude out of range");
+
+ GeoPoint p = new GeoPoint(latitude, longitude);
+ points.add(p);
+ }
+
+ /** Finish the polygon, by connecting the last added point with the starting point.
+ */
+ public void donePoints() {
+ // If fewer than 3 points, can't do it.
+ if (points.size() < 3)
+ throw new IllegalArgumentException("Polygon needs at least three points.");
+ // Time to construct the planes. If the polygon is truly convex, then any adjacent point
+ edges = new SidedPlane[points.size()];
+ // to a segment can provide an interior measurement.
+ for (int i = 0; i < points.size(); i++) {
+ GeoPoint start = points.get(i);
+ GeoPoint end = points.get(legalIndex(i+1));
+ GeoPoint check = points.get(legalIndex(i+2));
+ SidedPlane sp = new SidedPlane(check,start,end);
+ //System.out.println("Created edge "+sp+" using start="+start+" end="+end+" check="+check);
+ edges[i] = sp;
+ }
+
+ // In order to naively confirm that the polygon is convex, I would need to
+ // check every edge, and verify that every point (other than the edge endpoints)
+ // is within the edge's sided plane. This is an order n^2 operation. That's still
+ // not wrong, though, because everything else about polygons has a similar cost.
+ for (int edgeIndex = 0; edgeIndex < edges.length; edgeIndex++) {
+ SidedPlane edge = edges[edgeIndex];
+ for (int pointIndex =0; pointIndex < points.size(); pointIndex++) {
+ if (pointIndex != edgeIndex && pointIndex != legalIndex(edgeIndex+1)) {
+ if (!edge.isWithin(points.get(pointIndex)))
+ throw new IllegalArgumentException("Polygon is not convex: Point "+points.get(pointIndex)+" Edge "+edge);
+ }
+ }
+ }
+
+ // Finally, we need to compute a single interior point that will satisfy
+ // all edges. If the polygon is convex, we know that such a point exists.
+
+ // This is actually surprisingly hard. I believe merely averaging the x, y, and z
+ // values of the points will produce a point inside the shape, but it won't be
+ // on the unit sphere, and it may be in fact degenerate and have a zero magnitude.
+ // In that case, an alternate algorithm would be required. But since such cases
+ // are very special (or very contrived), I'm just going to not worry about that
+ // for the moment.
+ double sumX = 0.0;
+ double sumY = 0.0;
+ double sumZ = 0.0;
+ for (GeoPoint p : points) {
+ sumX += p.x;
+ sumY += p.y;
+ sumZ += p.z;
+ }
+ double denom = 1.0 / (double)points.size();
+ sumX *= denom;
+ sumY *= denom;
+ sumZ *= denom;
+ double magnitude = Math.sqrt(sumX * sumX + sumY * sumY + sumZ * sumZ);
+ if (magnitude < 1.0e-10)
+ throw new IllegalArgumentException("Polygon interior point cannot be determined");
+ denom = 1.0/magnitude;
+
+ interiorPoint = new GeoPoint(sumX*denom,sumY*denom,sumZ*denom);
+
+ // Let's be sure that our interior point is really inside
+ for (SidedPlane sp : edges) {
+ if (!sp.isWithin(interiorPoint))
+ throw new IllegalArgumentException("Interior point logic failed to produce an interior point");
+ }
+ }
+
+ protected int legalIndex(int index) {
+ while (index >= points.size())
+ index -= points.size();
+ return index;
+ }
+
+ @Override
+ public boolean isWithin(Vector point)
+ {
+ for (SidedPlane edge : edges) {
+ if (!edge.isWithin(point))
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public boolean isWithin(double x, double y, double z)
+ {
+ for (SidedPlane edge : edges) {
+ if (!edge.isWithin(x,y,z))
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public GeoPoint getInteriorPoint()
+ {
+ return interiorPoint;
+ }
+
+ @Override
+ public boolean intersects(Plane p, Membership... bounds)
+ {
+ for (int edgeIndex = 0; edgeIndex < edges.length; edgeIndex++) {
+ SidedPlane edge = edges[edgeIndex];
+ // Construct boundaries
+ Membership[] membershipBounds = new Membership[edges.length-1];
+ int count = 0;
+ for (int otherIndex = 0; otherIndex < edges.length; otherIndex++) {
+ if (otherIndex != edgeIndex) {
+ membershipBounds[count++] = edges[otherIndex];
+ }
+ }
+ if (edge.intersects(p,bounds,membershipBounds))
+ return true;
+ }
+ return false;
+ }
+
+ /** Compute longitude/latitude bounds for the shape.
+ *@param bounds is the optional input bounds object. If this is null,
+ * a bounds object will be created. Otherwise, the input object will be modified.
+ *@return a Bounds object describing the shape's bounds. If the bounds cannot
+ * be computed, then return a Bounds object with noLongitudeBound,
+ * noTopLatitudeBound, and noBottomLatitudeBound.
+ */
+ @Override
+ public Bounds getBounds(Bounds bounds)
+ {
+ bounds = super.getBounds(bounds);
+
+ // Add all the points
+ for (GeoPoint point : points) {
+ bounds.addPoint(point);
+ }
+
+ // Add planes with membership.
+ for (int edgeIndex = 0; edgeIndex < edges.length; edgeIndex++) {
+ SidedPlane edge = edges[edgeIndex];
+ // Construct boundaries
+ Membership[] membershipBounds = new Membership[edges.length-1];
+ int count = 0;
+ for (int otherIndex = 0; otherIndex < edges.length; otherIndex++) {
+ if (otherIndex != edgeIndex) {
+ membershipBounds[count++] = edges[otherIndex];
+ }
+ }
+ edge.recordBounds(bounds,membershipBounds);
+ }
+
+ return bounds;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof GeoConvexPolygon))
+ return false;
+ GeoConvexPolygon other = (GeoConvexPolygon)o;
+ if (other.points.size() != points.size())
+ return false;
+
+ for (int i = 0; i < points.size(); i++) {
+ if (!other.points.get(i).equals(points.get(i)))
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ return points.hashCode();
+ }
+
+ @Override
+ public String toString() {
+ return "GeoConvexPolygon{" + points + "}";
+ }
+}
+
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoDistance.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoDistance.java
new file mode 100755
index 00000000000..4d73b3a32dc
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoDistance.java
@@ -0,0 +1,132 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Generic geo-distance-capable shape class description. An implementer
+* of this interface is capable of computing the described "distance" values,
+* which are meant to provide both actual distance values, as well as
+* distance estimates that can be computed more cheaply.
+*/
+public interface GeoDistance extends Membership {
+ /** Compute this shape's normal "distance" to the GeoPoint.
+ * A return value of Double.MAX_VALUE should be returned for
+ * points outside of the shape.
+ *@param point is the point to compute the distance to.
+ *@return the normal distance, defined as the perpendicular distance from
+ * from the point to one of the shape's bounding plane. Normal
+ * distances can therefore typically only go up to PI/2, except
+ * when they represent the sum of a sequence of normal distances.
+ */
+ public double computeNormalDistance(GeoPoint point);
+
+ /** Compute this shape's normal "distance" to the GeoPoint.
+ * A return value of Double.MAX_VALUE should be returned for
+ * points outside of the shape.
+ *@param x is the point's unit x coordinate (using U.S. convention).
+ *@param y is the point's unit y coordinate (using U.S. convention).
+ *@param z is the point's unit z coordinate (using U.S. convention).
+ *@return the normal distance, defined as the perpendicular distance from
+ * from the point to one of the shape's bounding plane. Normal
+ * distances can therefore typically only go up to PI/2, except
+ * when they represent the sum of a sequence of normal distances.
+ */
+ public double computeNormalDistance(double x, double y, double z);
+
+ /** Compute the square of this shape's normal "distance" to the GeoPoint.
+ * A return value of Double.MAX_VALUE should be returned for
+ * points outside of the shape.
+ *@param point is the point to compute the distance to.
+ *@return the square of the normal distance, defined as the perpendicular
+ * distance from
+ * from the point to one of the shape's bounding plane. Normal
+ * distances can therefore typically only go up to PI/2, except
+ * when they represent the sum of a sequence of normal distances.
+ */
+ public double computeSquaredNormalDistance(GeoPoint point);
+
+ /** Compute the square of this shape's normal "distance" to the GeoPoint.
+ * A return value of Double.MAX_VALUE should be returned for
+ * points outside of the shape.
+ *@param x is the point's unit x coordinate (using U.S. convention).
+ *@param y is the point's unit y coordinate (using U.S. convention).
+ *@param z is the point's unit z coordinate (using U.S. convention).
+ *@return the square of the normal distance, defined as the perpendicular
+ * distance from
+ * from the point to one of the shape's bounding plane. Normal
+ * distances can therefore typically only go up to PI/2, except
+ * when they represent the sum of a sequence of normal distances.
+ */
+ public double computeSquaredNormalDistance(double x, double y, double z);
+
+ /** Compute this shape's linear "distance" to the GeoPoint.
+ * A return value of Double.MAX_VALUE should be returned for
+ * points outside of the shape.
+ *@param point is the point to compute the distance to.
+ *@return the linear (or chord) distance, defined as the distance from
+ * from the point to the nearest point on the unit sphere and on one of the shape's
+ * bounding planes. Linear distances can therefore typically go up to PI,
+ * except when they represent the sum of a sequence of linear distances.
+ */
+ public double computeLinearDistance(GeoPoint point);
+
+ /** Compute this shape's linear "distance" to the GeoPoint.
+ * A return value of Double.MAX_VALUE should be returned for
+ * points outside of the shape.
+ *@param x is the point's unit x coordinate (using U.S. convention).
+ *@param y is the point's unit y coordinate (using U.S. convention).
+ *@param z is the point's unit z coordinate (using U.S. convention).
+ *@return the linear (or chord) distance, defined as the distance from
+ * from the point to the nearest point on the unit sphere and on one of the shape's
+ * bounding planes. Linear distances can therefore typically go up to PI,
+ * except when they represent the sum of a sequence of linear distances.
+ */
+ public double computeLinearDistance(double x, double y, double z);
+
+ /** Compute the square of this shape's linear "distance" to the GeoPoint.
+ * A return value of Double.MAX_VALUE should be returned for
+ * points outside of the shape.
+ *@param point is the point to compute the distance to.
+ *@return the square of the linear (or chord) distance, defined as the
+ * distance from
+ * from the point to the nearest point on the unit sphere and on one of the shape's
+ * bounding planes. Linear distances can therefore typically go up to PI,
+ * except when they represent the sum of a sequence of linear distances.
+ */
+ public double computeSquaredLinearDistance(GeoPoint point);
+
+ /** Compute the square of this shape's linear "distance" to the GeoPoint.
+ * A return value of Double.MAX_VALUE should be returned for
+ * points outside of the shape.
+ *@param x is the point's unit x coordinate (using U.S. convention).
+ *@param y is the point's unit y coordinate (using U.S. convention).
+ *@param z is the point's unit z coordinate (using U.S. convention).
+ *@return the square of the linear (or chord) distance, defined as the distance from
+ * from the point to the nearest point on the unit sphere and on one of the shape's
+ * bounding planes. Linear distances can therefore typically go up to PI,
+ * except when they represent the sum of a sequence of linear distances.
+ */
+ public double computeSquaredLinearDistance(double x, double y, double z);
+
+ /** Compute a true, accurate, great-circle distance to a point.
+ * Double.MAX_VALUE indicates a point is outside of the shape.
+ *@param point is the point.
+ *@return the distance.
+ */
+ public double computeArcDistance(GeoPoint point);
+
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoDistanceShape.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoDistanceShape.java
new file mode 100755
index 00000000000..85f50093b69
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoDistanceShape.java
@@ -0,0 +1,25 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Distance shapes have capabilities of both geohashing and distance
+ * computation (which also includes point membership determination).
+ */
+public interface GeoDistanceShape extends GeoMembershipShape, GeoDistance {
+
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoLatitudeZone.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoLatitudeZone.java
new file mode 100755
index 00000000000..8d8dc736e37
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoLatitudeZone.java
@@ -0,0 +1,152 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** This GeoBBox represents an area rectangle limited only in latitude.
+*/
+public class GeoLatitudeZone implements GeoBBox
+{
+ public final double topLat;
+ public final double bottomLat;
+ public final double cosTopLat;
+ public final double cosBottomLat;
+ public final SidedPlane topPlane;
+ public final SidedPlane bottomPlane;
+ public final GeoPoint interiorPoint;
+
+ public GeoLatitudeZone(double topLat, double bottomLat)
+ {
+ this.topLat = topLat;
+ this.bottomLat = bottomLat;
+
+ double sinTopLat = Math.sin(topLat);
+ double sinBottomLat = Math.sin(bottomLat);
+ cosTopLat = Math.cos(topLat);
+ cosBottomLat = Math.cos(bottomLat);
+
+ // Construct sample points, so we get our sidedness right
+ Vector topPoint = new Vector(0.0,0.0,sinTopLat);
+ Vector bottomPoint = new Vector(0.0,0.0,sinBottomLat);
+
+ this.topPlane = new SidedPlane(bottomPoint,sinTopLat);
+ this.bottomPlane = new SidedPlane(topPoint,sinBottomLat);
+
+ // Compute an interior point. Pick one whose lat is between top and bottom.
+ double sinMiddleLat = (topLat + bottomLat) * 0.5;
+ interiorPoint = new GeoPoint(Math.sqrt(1.0 - sinMiddleLat * sinMiddleLat),0.0,sinMiddleLat);
+ }
+
+ @Override
+ public GeoBBox expand(double angle)
+ {
+ double newTopLat = topLat + angle;
+ double newBottomLat = bottomLat - angle;
+ return GeoBBoxFactory.makeGeoBBox(newTopLat, newBottomLat, -Math.PI, Math.PI);
+ }
+
+ @Override
+ public boolean isWithin(Vector point)
+ {
+ return topPlane.isWithin(point) &&
+ bottomPlane.isWithin(point);
+ }
+
+ @Override
+ public boolean isWithin(double x, double y, double z)
+ {
+ return topPlane.isWithin(x,y,z) &&
+ bottomPlane.isWithin(x,y,z);
+ }
+
+ @Override
+ public double getRadius()
+ {
+ // This is a bit tricky. I guess we should interpret this as meaning the angle of a circle that
+ // would contain all the bounding box points, when starting in the "center".
+ if (topLat > 0.0 && bottomLat < 0.0)
+ return Math.PI;
+ double maxCosLat = cosTopLat;
+ if (maxCosLat < cosBottomLat)
+ maxCosLat = cosBottomLat;
+ return maxCosLat * Math.PI;
+ }
+
+ @Override
+ public GeoPoint getInteriorPoint()
+ {
+ return interiorPoint;
+ }
+
+ @Override
+ public boolean intersects(Plane p, Membership... bounds)
+ {
+ return p.intersects(topPlane,bounds,bottomPlane) ||
+ p.intersects(bottomPlane,bounds,topPlane);
+ }
+
+ /** Compute longitude/latitude bounds for the shape.
+ *@param bounds is the optional input bounds object. If this is null,
+ * a bounds object will be created. Otherwise, the input object will be modified.
+ *@return a Bounds object describing the shape's bounds. If the bounds cannot
+ * be computed, then return a Bounds object with noLongitudeBound,
+ * noTopLatitudeBound, and noBottomLatitudeBound.
+ */
+ @Override
+ public Bounds getBounds(Bounds bounds)
+ {
+ if (bounds == null)
+ bounds = new Bounds();
+ bounds.noLongitudeBound().addLatitudeZone(topLat).addLatitudeZone(bottomLat);
+ return bounds;
+ }
+
+ @Override
+ public int getRelationship(GeoShape path) {
+ // First observation: The only way you can draw a path that
+ // contains this area is to have an unbounded path that circles the globe.
+ // So we will never return CONTAINS.
+
+ // Second, the shortcut of seeing whether endpoints are in/out is not going to
+ // work with no area endpoints. So we rely entirely on intersections.
+
+ if (path.intersects(topPlane,bottomPlane) ||
+ path.intersects(bottomPlane,topPlane))
+ return OVERLAPS;
+
+ if (isWithin(path.getInteriorPoint()))
+ return WITHIN;
+
+ return DISJOINT;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof GeoLatitudeZone))
+ return false;
+ GeoLatitudeZone other = (GeoLatitudeZone)o;
+ return other.topPlane.equals(topPlane) && other.bottomPlane.equals(bottomPlane);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = topPlane.hashCode();
+ result = 31 * result + bottomPlane.hashCode();
+ return result;
+ }
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoLongitudeSlice.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoLongitudeSlice.java
new file mode 100755
index 00000000000..90782cdfb6e
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoLongitudeSlice.java
@@ -0,0 +1,176 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Bounding box limited on left and right.
+* The left-right maximum extent for this shape is PI; for anything larger, use
+* GeoWideLongitudeSlice.
+*/
+public class GeoLongitudeSlice implements GeoBBox
+{
+ public final double leftLon;
+ public final double rightLon;
+
+ public final SidedPlane leftPlane;
+ public final SidedPlane rightPlane;
+
+ public final GeoPoint centerPoint;
+
+ /** Accepts only values in the following ranges: lon: {@code -PI -> PI} */
+ public GeoLongitudeSlice(double leftLon, double rightLon)
+ {
+ // Argument checking
+ if (leftLon < -Math.PI || leftLon > Math.PI)
+ throw new IllegalArgumentException("Left longitude out of range");
+ if (rightLon < -Math.PI || rightLon > Math.PI)
+ throw new IllegalArgumentException("Right longitude out of range");
+ double extent = rightLon - leftLon;
+ if (extent < 0.0) {
+ extent += 2.0 * Math.PI;
+ }
+ if (extent > Math.PI)
+ throw new IllegalArgumentException("Width of rectangle too great");
+
+ this.leftLon = leftLon;
+ this.rightLon = rightLon;
+
+ double sinLeftLon = Math.sin(leftLon);
+ double cosLeftLon = Math.cos(leftLon);
+ double sinRightLon = Math.sin(rightLon);
+ double cosRightLon = Math.cos(rightLon);
+
+ double middleLon = (leftLon + rightLon) * 0.5;
+ centerPoint = new GeoPoint(0.0,middleLon);
+
+ this.leftPlane = new SidedPlane(centerPoint,cosLeftLon,sinLeftLon);
+ this.rightPlane = new SidedPlane(centerPoint,cosRightLon,sinRightLon);
+
+ }
+
+ @Override
+ public GeoBBox expand(double angle)
+ {
+ // Figuring out when we escalate to a special case requires some prefiguring
+ double currentLonSpan = rightLon - leftLon;
+ if (currentLonSpan < 0.0)
+ currentLonSpan += Math.PI * 2.0;
+ double newLeftLon = leftLon - angle;
+ double newRightLon = rightLon + angle;
+ if (currentLonSpan + 2.0 * angle >= Math.PI * 2.0) {
+ newLeftLon = -Math.PI;
+ newRightLon = Math.PI;
+ }
+ return GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5,-Math.PI * 0.5,newLeftLon,newRightLon);
+ }
+
+ @Override
+ public boolean isWithin(Vector point)
+ {
+ return leftPlane.isWithin(point) &&
+ rightPlane.isWithin(point);
+ }
+
+ @Override
+ public boolean isWithin(double x, double y, double z)
+ {
+ return leftPlane.isWithin(x,y,z) &&
+ rightPlane.isWithin(x,y,z);
+ }
+
+ @Override
+ public double getRadius()
+ {
+ // Compute the extent and divide by two
+ double extent = rightLon - leftLon;
+ if (extent < 0.0)
+ extent += Math.PI * 2.0;
+ return Math.max(Math.PI * 0.5, extent * 0.5);
+ }
+
+ @Override
+ public GeoPoint getInteriorPoint()
+ {
+ return centerPoint;
+ }
+
+ @Override
+ public boolean intersects(Plane p, Membership... bounds)
+ {
+ return p.intersects(leftPlane,bounds,rightPlane) ||
+ p.intersects(rightPlane,bounds,leftPlane);
+ }
+
+ /** Compute longitude/latitude bounds for the shape.
+ *@param bounds is the optional input bounds object. If this is null,
+ * a bounds object will be created. Otherwise, the input object will be modified.
+ *@return a Bounds object describing the shape's bounds. If the bounds cannot
+ * be computed, then return a Bounds object with noLongitudeBound,
+ * noTopLatitudeBound, and noBottomLatitudeBound.
+ */
+ @Override
+ public Bounds getBounds(Bounds bounds)
+ {
+ if (bounds == null)
+ bounds = new Bounds();
+ bounds.noTopLatitudeBound().noBottomLatitudeBound();
+ bounds.addLongitudeSlice(leftLon,rightLon);
+ return bounds;
+ }
+
+ @Override
+ public int getRelationship(GeoShape path) {
+ // It's possible to contain this area. The way we do this is to
+ // see whether the shape contains both the north and south poles. If it does,
+ // we make the assumption that it contains the entire shape (which is
+ // a convenient approximation that, at worst, increases our computation).
+ if (path.isWithin(0.0,0.0,Math.PI * 0.5) &&
+ path.isWithin(0.0,0.0,-Math.PI * 0.5))
+ return CONTAINS;
+
+ // Next, look for intersections.
+ if (path.intersects(leftPlane,rightPlane) ||
+ path.intersects(rightPlane,leftPlane))
+ return OVERLAPS;
+
+ if (isWithin(path.getInteriorPoint()))
+ return WITHIN;
+
+ return DISJOINT;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof GeoLongitudeSlice))
+ return false;
+ GeoLongitudeSlice other = (GeoLongitudeSlice)o;
+ return other.leftLon == leftLon && other.rightLon == rightLon;
+ }
+
+ @Override
+ public int hashCode() {
+ int result;
+ long temp;
+ temp = Double.doubleToLongBits(leftLon);
+ result = (int) (temp ^ (temp >>> 32));
+ temp = Double.doubleToLongBits(rightLon);
+ result = 31 * result + (int) (temp ^ (temp >>> 32));
+ return result;
+ }
+}
+
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoMembershipShape.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoMembershipShape.java
new file mode 100755
index 00000000000..d06b871f891
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoMembershipShape.java
@@ -0,0 +1,25 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Membership shapes have capabilities of both geohashing and membership
+ * determination.
+ */
+public interface GeoMembershipShape extends GeoShape, Membership {
+
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoPath.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoPath.java
new file mode 100755
index 00000000000..8fa512c0bfc
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoPath.java
@@ -0,0 +1,565 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.util.*;
+
+/** GeoSearchableShape representing a path across the surface of the globe,
+* with a specified half-width. Path is described by a series of points.
+* Distances are measured from the starting point along the path, and then at right
+* angles to the path.
+*/
+public class GeoPath extends GeoBaseExtendedShape implements GeoDistanceShape
+{
+ public final double cutoffAngle;
+ public final double cutoffOffset;
+ public final double originDistance;
+ public final double chordDistance;
+
+ public final List<SegmentEndpoint> points = new ArrayList<SegmentEndpoint>();
+ public final List<PathSegment> segments = new ArrayList<PathSegment>();
+
+ public GeoPath(double cutoffAngle)
+ {
+ super();
+ if (cutoffAngle < 0.0 || cutoffAngle > Math.PI * 0.5)
+ throw new IllegalArgumentException("Cutoff angle out of bounds");
+ this.cutoffAngle = cutoffAngle;
+ double cosAngle = Math.cos(cutoffAngle);
+ double sinAngle = Math.sin(cutoffAngle);
+ // Cutoff offset is the linear distance given the angle
+ this.cutoffOffset = sinAngle;
+ this.originDistance = cosAngle;
+ // Compute chord distance
+ double xDiff = 1.0 - cosAngle;
+ this.chordDistance = Math.sqrt(xDiff * xDiff + sinAngle * sinAngle);
+ }
+
+ public void addPoint(double lat, double lon)
+ {
+ if (lat < -Math.PI * 0.5 || lat > Math.PI * 0.5)
+ throw new IllegalArgumentException("Latitude out of range");
+ if (lon < -Math.PI || lon > Math.PI)
+ throw new IllegalArgumentException("Longitude out of range");
+ GeoPoint end = new GeoPoint(lat,lon);
+ if (points.size() > 0) {
+ GeoPoint start = points.get(points.size()-1).point;
+ PathSegment ps = new PathSegment(start,end,cutoffOffset,cutoffAngle,chordDistance);
+ // Check for degeneracy; if the segment is degenerate, don't include the point
+ if (ps.isDegenerate())
+ return;
+ segments.add(ps);
+ }
+ SegmentEndpoint se = new SegmentEndpoint(end, originDistance, cutoffOffset, cutoffAngle, chordDistance);
+ points.add(se);
+ }
+
+ /** Compute an estimate of "distance" to the GeoPoint.
+ * A return value of Double.MAX_VALUE should be returned for
+ * points outside of the shape.
+ */
+ @Override
+ public double computeNormalDistance(GeoPoint point)
+ {
+ // Algorithm:
+ // (1) If the point is within any of the segments along the path, return that value.
+ // (2) If the point is within any of the segment end circles along the path, return that value.
+ double currentDistance = 0.0;
+ for (PathSegment segment : segments) {
+ double distance = segment.pathNormalDistance(point);
+ if (distance != Double.MAX_VALUE)
+ return currentDistance + distance;
+ currentDistance += segment.fullNormalDistance;
+ }
+
+ int segmentIndex = 0;
+ currentDistance = 0.0;
+ for (SegmentEndpoint endpoint : points) {
+ double distance = endpoint.pathNormalDistance(point);
+ if (distance != Double.MAX_VALUE)
+ return currentDistance + distance;
+ if (segmentIndex < segments.size())
+ currentDistance += segments.get(segmentIndex++).fullNormalDistance;
+ }
+
+ return Double.MAX_VALUE;
+ }
+
+ /** Compute an estimate of "distance" to the GeoPoint.
+ * A return value of Double.MAX_VALUE should be returned for
+ * points outside of the shape.
+ */
+ @Override
+ public double computeNormalDistance(double x, double y, double z)
+ {
+ return computeNormalDistance(new GeoPoint(x,y,z));
+ }
+
+ /** Compute a squared estimate of the "distance" to the
+ * GeoPoint. Double.MAX_VALUE indicates a point outside of the
+ * shape.
+ */
+ @Override
+ public double computeSquaredNormalDistance(GeoPoint point)
+ {
+ double pd = computeNormalDistance(point);
+ if (pd == Double.MAX_VALUE)
+ return pd;
+ return pd * pd;
+ }
+
+ /** Compute a squared estimate of the "distance" to the
+ * GeoPoint. Double.MAX_VALUE indicates a point outside of the
+ * shape.
+ */
+ @Override
+ public double computeSquaredNormalDistance(double x, double y, double z)
+ {
+ return computeSquaredNormalDistance(new GeoPoint(x,y,z));
+ }
+
+ /** Compute a linear distance to the point.
+ */
+ @Override
+ public double computeLinearDistance(GeoPoint point)
+ {
+ // Algorithm:
+ // (1) If the point is within any of the segments along the path, return that value.
+ // (2) If the point is within any of the segment end circles along the path, return that value.
+ double currentDistance = 0.0;
+ for (PathSegment segment : segments) {
+ double distance = segment.pathLinearDistance(point);
+ if (distance != Double.MAX_VALUE)
+ return currentDistance + distance;
+ currentDistance += segment.fullLinearDistance;
+ }
+
+ int segmentIndex = 0;
+ currentDistance = 0.0;
+ for (SegmentEndpoint endpoint : points) {
+ double distance = endpoint.pathLinearDistance(point);
+ if (distance != Double.MAX_VALUE)
+ return currentDistance + distance;
+ if (segmentIndex < segments.size())
+ currentDistance += segments.get(segmentIndex++).fullLinearDistance;
+ }
+
+ return Double.MAX_VALUE;
+ }
+
+ /** Compute a linear distance to the point.
+ */
+ @Override
+ public double computeLinearDistance(double x, double y, double z)
+ {
+ return computeLinearDistance(new GeoPoint(x,y,z));
+ }
+
+ /** Compute a squared linear distance to the vector.
+ */
+ @Override
+ public double computeSquaredLinearDistance(GeoPoint point)
+ {
+ double pd = computeLinearDistance(point);
+ if (pd == Double.MAX_VALUE)
+ return pd;
+ return pd * pd;
+ }
+
+ /** Compute a squared linear distance to the vector.
+ */
+ @Override
+ public double computeSquaredLinearDistance(double x, double y, double z)
+ {
+ return computeSquaredLinearDistance(new GeoPoint(x,y,z));
+ }
+
+ /** Compute a true, accurate, great-circle distance.
+ * Double.MAX_VALUE indicates a point is outside of the shape.
+ */
+ @Override
+ public double computeArcDistance(GeoPoint point)
+ {
+ // Algorithm:
+ // (1) If the point is within any of the segments along the path, return that value.
+ // (2) If the point is within any of the segment end circles along the path, return that value.
+ double currentDistance = 0.0;
+ for (PathSegment segment : segments) {
+ double distance = segment.pathDistance(point);
+ if (distance != Double.MAX_VALUE)
+ return currentDistance + distance;
+ currentDistance += segment.fullDistance;
+ }
+
+ int segmentIndex = 0;
+ currentDistance = 0.0;
+ for (SegmentEndpoint endpoint : points) {
+ double distance = endpoint.pathDistance(point);
+ if (distance != Double.MAX_VALUE)
+ return currentDistance + distance;
+ if (segmentIndex < segments.size())
+ currentDistance += segments.get(segmentIndex++).fullDistance;
+ }
+
+ return Double.MAX_VALUE;
+ }
+
+ @Override
+ public boolean isWithin(Vector point)
+ {
+ for (SegmentEndpoint pathPoint : points) {
+ if (pathPoint.isWithin(point))
+ return true;
+ }
+ for (PathSegment pathSegment : segments) {
+ if (pathSegment.isWithin(point))
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean isWithin(double x, double y, double z)
+ {
+ for (SegmentEndpoint pathPoint : points) {
+ if (pathPoint.isWithin(x,y,z))
+ return true;
+ }
+ for (PathSegment pathSegment : segments) {
+ if (pathSegment.isWithin(x,y,z))
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public GeoPoint getInteriorPoint()
+ {
+ return points.get(0).point;
+ }
+
+ @Override
+ public boolean intersects(Plane plane, Membership... bounds)
+ {
+ // We look for an intersection with any of the exterior edges of the path.
+ // We also have to look for intersections with the cones described by the endpoints.
+ // Return "true" if any such intersections are found.
+
+ // For plane intersections, the basic idea is to come up with an equation of the line that is
+ // the intersection (if any). Then, find the intersections with the unit sphere (if any). If
+ // any of the intersection points are within the bounds, then we've detected an intersection.
+
+ for (SegmentEndpoint pathPoint : points) {
+ if (pathPoint.intersects(plane, bounds))
+ return true;
+ }
+ for (PathSegment pathSegment : segments) {
+ if (pathSegment.intersects(plane, bounds))
+ return true;
+ }
+
+ return false;
+ }
+
+ /** Compute longitude/latitude bounds for the shape.
+ *@param bounds is the optional input bounds object. If this is null,
+ * a bounds object will be created. Otherwise, the input object will be modified.
+ *@return a Bounds object describing the shape's bounds. If the bounds cannot
+ * be computed, then return a Bounds object with noLongitudeBound,
+ * noTopLatitudeBound, and noBottomLatitudeBound.
+ */
+ @Override
+ public Bounds getBounds(Bounds bounds)
+ {
+ bounds = super.getBounds(bounds);
+ for (SegmentEndpoint pathPoint : points) {
+ pathPoint.getBounds(bounds);
+ }
+ for (PathSegment pathSegment : segments) {
+ pathSegment.getBounds(bounds);
+ }
+ return bounds;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof GeoPath))
+ return false;
+ GeoPath p = (GeoPath)o;
+ if (points.size() != p.points.size())
+ return false;
+ if (cutoffAngle != p.cutoffAngle)
+ return false;
+ for (int i = 0; i < points.size(); i++) {
+ SegmentEndpoint point = points.get(i);
+ SegmentEndpoint point2 = p.points.get(i);
+ if (!point.equals(point2))
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result;
+ long temp;
+ temp = Double.doubleToLongBits(cutoffAngle);
+ result = (int) (temp ^ (temp >>> 32));
+ result = 31 * result + points.hashCode();
+ return result;
+ }
+
+ /** This is precalculated data for segment endpoint.
+ */
+ public static class SegmentEndpoint
+ {
+ public final GeoPoint point;
+ public final SidedPlane circlePlane;
+ public final double cutoffNormalDistance;
+ public final double cutoffAngle;
+ public final double chordDistance;
+
+ public SegmentEndpoint(GeoPoint point, double originDistance, double cutoffOffset, double cutoffAngle, double chordDistance)
+ {
+ this.point = point;
+ this.cutoffNormalDistance = cutoffOffset;
+ this.cutoffAngle = cutoffAngle;
+ this.chordDistance = chordDistance;
+ this.circlePlane = new SidedPlane(point, point, -originDistance);
+ }
+
+ public boolean isWithin(Vector point)
+ {
+ return circlePlane.isWithin(point);
+ }
+
+ public boolean isWithin(double x, double y, double z)
+ {
+ return circlePlane.isWithin(x,y,z);
+ }
+
+ public double pathDistance(GeoPoint point)
+ {
+ double dist = this.point.arcDistance(point);
+ if (dist > cutoffAngle)
+ return Double.MAX_VALUE;
+ return dist;
+ }
+
+ public double pathNormalDistance(GeoPoint point)
+ {
+ double dist = this.point.normalDistance(point);
+ if (dist > cutoffNormalDistance)
+ return Double.MAX_VALUE;
+ return dist;
+ }
+
+ public double pathLinearDistance(GeoPoint point)
+ {
+ double dist = this.point.linearDistance(point);
+ if (dist > chordDistance)
+ return Double.MAX_VALUE;
+ return dist;
+ }
+
+ public boolean intersects(Plane p, Membership[] bounds)
+ {
+ return circlePlane.intersects(p, bounds);
+ }
+
+ public void getBounds(Bounds bounds)
+ {
+ circlePlane.recordBounds(bounds);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof SegmentEndpoint))
+ return false;
+ SegmentEndpoint other = (SegmentEndpoint)o;
+ return point.equals(other.point);
+ }
+
+ @Override
+ public int hashCode() {
+ return point.hashCode();
+ }
+ }
+
+ /** This is the precalculated data for a path segment.
+ */
+ public static class PathSegment
+ {
+ public final GeoPoint start;
+ public final GeoPoint end;
+ public final double fullDistance;
+ public final double fullNormalDistance;
+ public final double fullLinearDistance;
+ public final Plane normalizedConnectingPlane;
+ public final SidedPlane upperConnectingPlane;
+ public final SidedPlane lowerConnectingPlane;
+ public final SidedPlane startCutoffPlane;
+ public final SidedPlane endCutoffPlane;
+ public final double planeBoundingOffset;
+ public final double arcWidth;
+ public final double chordDistance;
+
+ public PathSegment(GeoPoint start, GeoPoint end, double planeBoundingOffset, double arcWidth, double chordDistance)
+ {
+ this.start = start;
+ this.end = end;
+ this.planeBoundingOffset = planeBoundingOffset;
+ this.arcWidth = arcWidth;
+ this.chordDistance = chordDistance;
+
+ fullDistance = start.arcDistance(end);
+ fullNormalDistance = start.normalDistance(end);
+ fullLinearDistance = start.linearDistance(end);
+ normalizedConnectingPlane = new Plane(start,end).normalize();
+ if (normalizedConnectingPlane == null) {
+ upperConnectingPlane = null;
+ lowerConnectingPlane = null;
+ startCutoffPlane = null;
+ endCutoffPlane = null;
+ } else {
+ // Either start or end should be on the correct side
+ upperConnectingPlane = new SidedPlane(start,normalizedConnectingPlane,-planeBoundingOffset);
+ lowerConnectingPlane = new SidedPlane(start,normalizedConnectingPlane,planeBoundingOffset);
+ // Cutoff planes use opposite endpoints as correct side examples
+ startCutoffPlane = new SidedPlane(end,normalizedConnectingPlane,start);
+ endCutoffPlane = new SidedPlane(start,normalizedConnectingPlane,end);
+ }
+ }
+
+ public boolean isDegenerate()
+ {
+ return normalizedConnectingPlane == null;
+ }
+
+ public boolean isWithin(Vector point)
+ {
+ return startCutoffPlane.isWithin(point) &&
+ endCutoffPlane.isWithin(point) &&
+ upperConnectingPlane.isWithin(point) &&
+ lowerConnectingPlane.isWithin(point);
+ }
+
+ public boolean isWithin(double x, double y, double z)
+ {
+ return startCutoffPlane.isWithin(x,y,z) &&
+ endCutoffPlane.isWithin(x,y,z) &&
+ upperConnectingPlane.isWithin(x,y,z) &&
+ lowerConnectingPlane.isWithin(x,y,z);
+ }
+
+ public double pathDistance(GeoPoint point)
+ {
+ if (!isWithin(point))
+ return Double.MAX_VALUE;
+
+ // Compute the distance, filling in both components.
+ double perpDistance = Math.PI * 0.5 - Tools.safeAcos(Math.abs(normalizedConnectingPlane.evaluate(point)));
+ Plane normalizedPerpPlane = new Plane(normalizedConnectingPlane,point).normalize();
+ double pathDistance = Math.PI * 0.5 - Tools.safeAcos(Math.abs(normalizedPerpPlane.evaluate(start)));
+ return perpDistance + pathDistance;
+ }
+
+ public double pathNormalDistance(GeoPoint point)
+ {
+ if (!isWithin(point))
+ return Double.MAX_VALUE;
+
+ double pointEval = Math.abs(normalizedConnectingPlane.evaluate(point));
+
+ // Want no allocations or expensive operations! so we do this the hard way
+ double perpX = normalizedConnectingPlane.y * point.z - normalizedConnectingPlane.z * point.y;
+ double perpY = normalizedConnectingPlane.z * point.x - normalizedConnectingPlane.x * point.z;
+ double perpZ = normalizedConnectingPlane.x * point.y - normalizedConnectingPlane.y * point.x;
+
+ // If we have a degenerate line, then just compute the normal distance from point x to the start
+ if (perpX < 1e-10 && perpY < 1e-10 && perpZ < 1e-10)
+ return point.normalDistance(start);
+
+ double normFactor = 1.0 / Math.sqrt(perpX * perpX + perpY * perpY + perpZ * perpZ);
+ double perpEval = Math.abs(perpX * start.x + perpY * start.y + perpZ * start.z);
+ return perpEval * normFactor + pointEval;
+ }
+
+ public double pathLinearDistance(GeoPoint point)
+ {
+ if (!isWithin(point))
+ return Double.MAX_VALUE;
+
+ // We have a normalized connecting plane.
+ // First, compute the perpendicular plane.
+ // Want no allocations or expensive operations! so we do this the hard way
+ double perpX = normalizedConnectingPlane.y * point.z - normalizedConnectingPlane.z * point.y;
+ double perpY = normalizedConnectingPlane.z * point.x - normalizedConnectingPlane.x * point.z;
+ double perpZ = normalizedConnectingPlane.x * point.y - normalizedConnectingPlane.y * point.x;
+
+ // If we have a degenerate line, then just compute the normal distance from point x to the start
+ if (Math.abs(perpX) < 1e-10 && Math.abs(perpY) < 1e-10 && Math.abs(perpZ) < 1e-10)
+ return point.linearDistance(start);
+
+ // Next, we need the vector of the line, which is the cross product of the normalized connecting plane
+ // and the perpendicular plane that we just calculated.
+ double lineX = normalizedConnectingPlane.y * perpZ - normalizedConnectingPlane.z * perpY;
+ double lineY = normalizedConnectingPlane.z * perpX - normalizedConnectingPlane.x * perpZ;
+ double lineZ = normalizedConnectingPlane.x * perpY - normalizedConnectingPlane.y * perpX;
+
+ // Now, compute a normalization factor
+ double normalizer = 1.0/Math.sqrt(lineX * lineX + lineY * lineY + lineZ * lineZ);
+
+ // Pick which point by using bounding planes
+ double normLineX = lineX * normalizer;
+ double normLineY = lineY * normalizer;
+ double normLineZ = lineZ * normalizer;
+ if (!startCutoffPlane.isWithin(normLineX,normLineY,normLineZ) ||
+ !endCutoffPlane.isWithin(normLineX,normLineY,normLineZ))
+ {
+ normLineX = -normLineX;
+ normLineY = -normLineY;
+ normLineZ = -normLineZ;
+ }
+
+ // Compute linear distance for the two points
+ return point.linearDistance(normLineX,normLineY,normLineZ) + start.linearDistance(normLineX,normLineY,normLineZ);
+ }
+
+ public boolean intersects(Plane p, Membership[] bounds)
+ {
+ return upperConnectingPlane.intersects(p, bounds, lowerConnectingPlane, startCutoffPlane, endCutoffPlane) ||
+ lowerConnectingPlane.intersects(p, bounds, upperConnectingPlane, startCutoffPlane, endCutoffPlane);
+ }
+
+ public void getBounds(Bounds bounds)
+ {
+ // We need to do all bounding planes as well as corner points
+ upperConnectingPlane.recordBounds(startCutoffPlane, bounds, lowerConnectingPlane, endCutoffPlane);
+ startCutoffPlane.recordBounds(lowerConnectingPlane, bounds, endCutoffPlane, upperConnectingPlane);
+ lowerConnectingPlane.recordBounds(endCutoffPlane, bounds, upperConnectingPlane, startCutoffPlane);
+ endCutoffPlane.recordBounds(upperConnectingPlane, bounds, startCutoffPlane, lowerConnectingPlane);
+ upperConnectingPlane.recordBounds(bounds, lowerConnectingPlane, startCutoffPlane, endCutoffPlane);
+ lowerConnectingPlane.recordBounds(bounds, upperConnectingPlane, startCutoffPlane, endCutoffPlane);
+ startCutoffPlane.recordBounds(bounds, endCutoffPlane, upperConnectingPlane, lowerConnectingPlane);
+ endCutoffPlane.recordBounds(bounds, startCutoffPlane, upperConnectingPlane, lowerConnectingPlane);
+ }
+
+ }
+
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoPoint.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoPoint.java
new file mode 100755
index 00000000000..f3b5f1955e6
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoPoint.java
@@ -0,0 +1,44 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** This class represents a point on the surface of a unit sphere.
+*/
+public class GeoPoint extends Vector
+{
+ public GeoPoint(double sinLat, double sinLon, double cosLat, double cosLon)
+ {
+ super(cosLat*cosLon,cosLat*sinLon,sinLat);
+ }
+
+ public GeoPoint(double lat, double lon)
+ {
+ this(Math.sin(lat),Math.sin(lon),Math.cos(lat),Math.cos(lon));
+ }
+
+ public GeoPoint(double x, double y, double z)
+ {
+ super(x,y,z);
+ }
+
+ public double arcDistance(GeoPoint v)
+ {
+ return Tools.safeAcos(evaluate(v));
+ }
+
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoPolygonFactory.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoPolygonFactory.java
new file mode 100755
index 00000000000..3f872713a95
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoPolygonFactory.java
@@ -0,0 +1,156 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.util.List;
+import java.util.ArrayList;
+
+/** Class which constructs a GeoMembershipShape representing an arbitrary polygon.
+*/
+public class GeoPolygonFactory
+{
+ private GeoPolygonFactory() {
+ }
+
+ /** Create a GeoMembershipShape of the right kind given the specified bounds.
+ *@param pointList is a list of the GeoPoints to build an arbitrary polygon out of.
+ *@param convexPointIndex is the index of a single convex point whose conformation with
+ * its neighbors determines inside/outside for the entire polygon.
+ *@return a GeoMembershipShape corresponding to what was specified.
+ */
+ public static GeoMembershipShape makeGeoPolygon(List<GeoPoint> pointList, int convexPointIndex) {
+ // The basic operation uses a set of points, two points determining one particular edge, and a sided plane
+ // describing membership.
+ return buildPolygonShape(pointList, convexPointIndex, getLegalIndex(convexPointIndex+1,pointList.size()),
+ new SidedPlane(pointList.get(getLegalIndex(convexPointIndex-1,pointList.size())),
+ pointList.get(convexPointIndex), pointList.get(getLegalIndex(convexPointIndex+1,pointList.size()))));
+ }
+
+ public static GeoMembershipShape buildPolygonShape(List<GeoPoint> pointsList, int startPointIndex, int endPointIndex, SidedPlane startingEdge) {
+ // Algorithm as follows:
+ // Start with sided edge. Go through all points in some order. For each new point, determine if the point is within all edges considered so far.
+ // If not, put it into a list of points for recursion. If it is within, add new edge and keep going.
+ // Once we detect a point that is within, if there are points put aside for recursion, then call recursively.
+
+ // Current composite. This is what we'll actually be returning.
+ GeoCompositeMembershipShape rval = new GeoCompositeMembershipShape();
+
+ List<GeoPoint> recursionList = new ArrayList<GeoPoint>();
+ List<GeoPoint> currentList = new ArrayList<GeoPoint>();
+ List<SidedPlane> currentPlanes = new ArrayList<SidedPlane>();
+
+ // Initialize the current list and current planes
+ currentList.add(pointsList.get(startPointIndex));
+ currentList.add(pointsList.get(endPointIndex));
+ currentPlanes.add(startingEdge);
+
+ // Now, scan all remaining points, in order. We'll use an index and just add to it.
+ for (int i = 0; i < pointsList.size() - 2; i++) {
+ GeoPoint newPoint = pointsList.get(getLegalIndex(i + endPointIndex + 1, pointsList.size()));
+ if (isWithin(newPoint, currentPlanes)) {
+ // Construct a sided plane based on the last two points, and the previous point
+ SidedPlane newBoundary = new SidedPlane(currentList.get(currentList.size()-2),newPoint,currentList.get(currentList.size()-1));
+ // Construct a sided plane based on the return trip
+ SidedPlane returnBoundary = new SidedPlane(currentList.get(currentList.size()-1),currentList.get(0),newPoint);
+ // Verify that none of the points beyond the new point in the list are inside the polygon we'd
+ // be creating if we stopped making the current polygon right now.
+ boolean pointInside = false;
+ for (int j = i + 1; j < pointsList.size() - 2; j++) {
+ GeoPoint checkPoint = pointsList.get(getLegalIndex(j + endPointIndex + 1, pointsList.size()));
+ boolean isInside = true;
+ if (isInside && !newBoundary.isWithin(checkPoint))
+ isInside = false;
+ if (isInside && !returnBoundary.isWithin(checkPoint))
+ isInside = false;
+ if (isInside) {
+ for (SidedPlane plane : currentPlanes) {
+ if (!plane.isWithin(checkPoint)) {
+ isInside = false;
+ break;
+ }
+ }
+ }
+ if (isInside) {
+ pointInside = true;
+ break;
+ }
+ }
+ if (!pointInside) {
+ // Any excluded points?
+ if (recursionList.size() > 0) {
+ // Handle exclusion
+ recursionList.add(newPoint);
+ recursionList.add(currentList.get(currentList.size()-1));
+ // We want the other side for the recursion
+ SidedPlane otherSideNewBoundary = new SidedPlane(newBoundary);
+ rval.addShape(buildPolygonShape(recursionList,recursionList.size()-2,recursionList.size()-1,otherSideNewBoundary));
+ recursionList.clear();
+ }
+ currentList.add(newPoint);
+ currentPlanes.add(newBoundary);
+ } else {
+ recursionList.add(newPoint);
+ }
+ } else {
+ recursionList.add(newPoint);
+ }
+ }
+
+ if (recursionList.size() > 0) {
+ // The last step back to the start point had a recursion, so take care of that before we complete our work
+ recursionList.add(currentList.get(0));
+ recursionList.add(currentList.get(currentList.size()-1));
+ // Construct a sided plane based on these two points, and the previous point
+ SidedPlane newBoundary = new SidedPlane(currentList.get(currentList.size()-2),currentList.get(0),currentList.get(currentList.size()-1));
+ // We want the other side for the recursion
+ SidedPlane otherSideNewBoundary = new SidedPlane(newBoundary);
+ rval.addShape(buildPolygonShape(recursionList,recursionList.size()-2,recursionList.size()-1,otherSideNewBoundary));
+ recursionList.clear();
+ }
+
+ // Now, add in the current shape.
+ /*
+ System.out.println("Creating polygon:");
+ for (GeoPoint p : currentList) {
+ System.out.println(" "+p);
+ }
+ */
+ rval.addShape(new GeoConvexPolygon(currentList));
+ //System.out.println("Done creating polygon");
+ return rval;
+ }
+
+ protected static boolean isWithin(GeoPoint newPoint, List<SidedPlane> currentPlanes) {
+ for (SidedPlane p : currentPlanes) {
+ if (!p.isWithin(newPoint))
+ return false;
+ }
+ return true;
+ }
+
+ protected static int getLegalIndex(int index, int size) {
+ while (index < 0) {
+ index += size;
+ }
+ while (index >= size) {
+ index -= size;
+ }
+ return index;
+ }
+
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoRectangle.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoRectangle.java
new file mode 100755
index 00000000000..007beeef6ef
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoRectangle.java
@@ -0,0 +1,234 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Bounding box limited on four sides (top lat, bottom lat, left lon, right lon).
+* The left-right maximum extent for this shape is PI; for anything larger, use
+* GeoWideRectangle.
+*/
+public class GeoRectangle implements GeoBBox
+{
+ public final double topLat;
+ public final double bottomLat;
+ public final double leftLon;
+ public final double rightLon;
+
+ public final double cosMiddleLat;
+
+ public final GeoPoint ULHC;
+ public final GeoPoint URHC;
+ public final GeoPoint LRHC;
+ public final GeoPoint LLHC;
+
+ public final SidedPlane topPlane;
+ public final SidedPlane bottomPlane;
+ public final SidedPlane leftPlane;
+ public final SidedPlane rightPlane;
+
+ public final GeoPoint centerPoint;
+
+ /** Accepts only values in the following ranges: lat: {@code -PI/2 -> PI/2}, lon: {@code -PI -> PI} */
+ public GeoRectangle(double topLat, double bottomLat, double leftLon, double rightLon)
+ {
+ // Argument checking
+ if (topLat > Math.PI * 0.5 || topLat < -Math.PI * 0.5)
+ throw new IllegalArgumentException("Top latitude out of range");
+ if (bottomLat > Math.PI * 0.5 || bottomLat < -Math.PI * 0.5)
+ throw new IllegalArgumentException("Bottom latitude out of range");
+ if (topLat < bottomLat)
+ throw new IllegalArgumentException("Top latitude less than bottom latitude");
+ if (leftLon < -Math.PI || leftLon > Math.PI)
+ throw new IllegalArgumentException("Left longitude out of range");
+ if (rightLon < -Math.PI || rightLon > Math.PI)
+ throw new IllegalArgumentException("Right longitude out of range");
+ double extent = rightLon - leftLon;
+ if (extent < 0.0) {
+ extent += 2.0 * Math.PI;
+ }
+ if (extent > Math.PI)
+ throw new IllegalArgumentException("Width of rectangle too great");
+
+ this.topLat = topLat;
+ this.bottomLat = bottomLat;
+ this.leftLon = leftLon;
+ this.rightLon = rightLon;
+
+ double sinTopLat = Math.sin(topLat);
+ double cosTopLat = Math.cos(topLat);
+ double sinBottomLat = Math.sin(bottomLat);
+ double cosBottomLat = Math.cos(bottomLat);
+ double sinLeftLon = Math.sin(leftLon);
+ double cosLeftLon = Math.cos(leftLon);
+ double sinRightLon = Math.sin(rightLon);
+ double cosRightLon = Math.cos(rightLon);
+
+ // Now build the four points
+ this.ULHC = new GeoPoint(sinTopLat,sinLeftLon,cosTopLat,cosLeftLon);
+ this.URHC = new GeoPoint(sinTopLat,sinRightLon,cosTopLat,cosRightLon);
+ this.LRHC = new GeoPoint(sinBottomLat,sinRightLon,cosBottomLat,cosRightLon);
+ this.LLHC = new GeoPoint(sinBottomLat,sinLeftLon,cosBottomLat,cosLeftLon);
+
+ this.topPlane = new SidedPlane(LRHC,sinTopLat);
+ this.bottomPlane = new SidedPlane(ULHC,sinBottomLat);
+ this.leftPlane = new SidedPlane(LRHC,cosLeftLon,sinLeftLon);
+ this.rightPlane = new SidedPlane(LLHC,cosRightLon,sinRightLon);
+
+ double middleLat = (topLat + bottomLat) * 0.5;
+ double sinMiddleLat = Math.sin(middleLat);
+ cosMiddleLat = Math.cos(middleLat);
+ double middleLon = (leftLon + rightLon) * 0.5;
+ double sinMiddleLon = Math.sin(middleLon);
+ double cosMiddleLon = Math.cos(middleLon);
+
+ centerPoint = new GeoPoint(sinMiddleLat,sinMiddleLon,cosMiddleLat,cosMiddleLon);
+ }
+
+ @Override
+ public GeoBBox expand(double angle)
+ {
+ double newTopLat = topLat + angle;
+ double newBottomLat = bottomLat - angle;
+ // Figuring out when we escalate to a special case requires some prefiguring
+ double currentLonSpan = rightLon - leftLon;
+ if (currentLonSpan < 0.0)
+ currentLonSpan += Math.PI * 2.0;
+ double newLeftLon = leftLon - angle;
+ double newRightLon = rightLon + angle;
+ if (currentLonSpan + 2.0 * angle >= Math.PI * 2.0) {
+ newLeftLon = -Math.PI;
+ newRightLon = Math.PI;
+ }
+ return GeoBBoxFactory.makeGeoBBox(newTopLat,newBottomLat,newLeftLon,newRightLon);
+ }
+
+ @Override
+ public boolean isWithin(Vector point)
+ {
+ return topPlane.isWithin(point) &&
+ bottomPlane.isWithin(point) &&
+ leftPlane.isWithin(point) &&
+ rightPlane.isWithin(point);
+ }
+
+ @Override
+ public boolean isWithin(double x, double y, double z)
+ {
+ return topPlane.isWithin(x,y,z) &&
+ bottomPlane.isWithin(x,y,z) &&
+ leftPlane.isWithin(x,y,z) &&
+ rightPlane.isWithin(x,y,z);
+ }
+
+ @Override
+ public double getRadius()
+ {
+ // Here we compute the distance from the middle point to one of the corners. However, we need to be careful
+ // to use the longest of three distances: the distance to a corner on the top; the distnace to a corner on the bottom, and
+ // the distance to the right or left edge from the center.
+ double centerAngle = (rightLon - (rightLon + leftLon) * 0.5) * cosMiddleLat;
+ double topAngle = centerPoint.arcDistance(URHC);
+ double bottomAngle = centerPoint.arcDistance(LLHC);
+ return Math.max(centerAngle,Math.max(topAngle,bottomAngle));
+ }
+
+ @Override
+ public GeoPoint getInteriorPoint()
+ {
+ return centerPoint;
+ }
+
+ @Override
+ public boolean intersects(Plane p, Membership... bounds)
+ {
+ return p.intersects(topPlane,bounds,bottomPlane,leftPlane,rightPlane) ||
+ p.intersects(bottomPlane,bounds,topPlane,leftPlane,rightPlane) ||
+ p.intersects(leftPlane,bounds,rightPlane,topPlane,bottomPlane) ||
+ p.intersects(rightPlane,bounds,leftPlane,topPlane,bottomPlane);
+ }
+
+ /** Compute longitude/latitude bounds for the shape.
+ *@param bounds is the optional input bounds object. If this is null,
+ * a bounds object will be created. Otherwise, the input object will be modified.
+ *@return a Bounds object describing the shape's bounds. If the bounds cannot
+ * be computed, then return a Bounds object with noLongitudeBound,
+ * noTopLatitudeBound, and noBottomLatitudeBound.
+ */
+ @Override
+ public Bounds getBounds(Bounds bounds)
+ {
+ if (bounds == null)
+ bounds = new Bounds();
+ bounds.addLatitudeZone(topLat).addLatitudeZone(bottomLat)
+ .addLongitudeSlice(leftLon,rightLon);
+ return bounds;
+ }
+
+ @Override
+ public int getRelationship(GeoShape path) {
+ // There are many cases here. I'll go through them in order
+ boolean ulhcWithin = path.isWithin(ULHC);
+ boolean urhcWithin = path.isWithin(URHC);
+ boolean lrhcWithin = path.isWithin(LRHC);
+ boolean llhcWithin = path.isWithin(LLHC);
+
+ // If there are some that are in, and some that are out, we've got overlap. Otherwise, things are different.
+ if (ulhcWithin && urhcWithin && lrhcWithin && llhcWithin) {
+ // It's not precisely correct, but at this point we CHOOSE to claim that the entire rectangle is within the path.
+ // This in practice will mean that we generate more geotokens than are strictly needed, but otherwise this case
+ // would be expensive to disentangle.
+ return CONTAINS;
+ }
+
+ if (ulhcWithin || urhcWithin || lrhcWithin || llhcWithin) {
+ // Some are in, some are out: definite overlap
+ return OVERLAPS;
+ }
+
+ // All rectangle endpoints are outside the path. The three possible cases are WITHIN, OVERLAPS, and DISJOINT.
+ // The only way to distinguish between them is to look at whether any of the four rectangle sides intersect
+ // the path edges. If there is no intersection, AND any path point is within the rectangle, THEN return WITHIN.
+
+ if (path.intersects(topPlane,bottomPlane,leftPlane,rightPlane) ||
+ path.intersects(bottomPlane,topPlane,leftPlane,rightPlane) ||
+ path.intersects(leftPlane,topPlane,bottomPlane,rightPlane) ||
+ path.intersects(rightPlane,leftPlane,topPlane,bottomPlane))
+ return OVERLAPS;
+
+ if (isWithin(path.getInteriorPoint()))
+ return WITHIN;
+
+ return DISJOINT;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof GeoRectangle))
+ return false;
+ GeoRectangle other = (GeoRectangle)o;
+ return other.ULHC.equals(ULHC) && other.LRHC.equals(LRHC);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = ULHC.hashCode();
+ result = 31 * result + LRHC.hashCode();
+ return result;
+ }
+}
+
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoShape.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoShape.java
new file mode 100755
index 00000000000..d353184f665
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoShape.java
@@ -0,0 +1,52 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Generic shape. This describes methods that help GeoAreas figure out
+* how they interact with a shape, for the purposes of coming up with a
+* set of geo hash values.
+*/
+public interface GeoShape extends Membership {
+
+ /** Return a sample point that is inside the shape.
+ *@return an interior point.
+ */
+ public GeoPoint getInteriorPoint();
+
+ /** Assess whether a plane, within the provided bounds, intersects
+ * with the shape.
+ *@param plane is the plane to assess for intersection with the shape's edges or
+ * bounding curves.
+ *@param bounds are a set of bounds that define an area that an
+ * intersection must be within in order to qualify (provided by a GeoArea).
+ *@return true if there's such an intersection, false if not.
+ */
+ public boolean intersects(Plane plane, Membership... bounds);
+
+ /** Compute longitude/latitude bounds for the shape.
+ *@param bounds is the optional input bounds object. If this is null,
+ * a bounds object will be created. Otherwise, the input object will be modified.
+ *@return a Bounds object describing the shape's bounds. If the bounds cannot
+ * be computed, then return a Bounds object with noLongitudeBound,
+ * noTopLatitudeBound, and noBottomLatitudeBound.
+ */
+ public Bounds getBounds(Bounds bounds);
+
+ /** Equals */
+ public boolean equals(Object o);
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoSizeable.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoSizeable.java
new file mode 100755
index 00000000000..91ecf3bfd41
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoSizeable.java
@@ -0,0 +1,30 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Some shapes can compute radii of a geocircle in which they are inscribed.
+*/
+public interface GeoSizeable
+{
+ /** Returns the radius of a circle into which the GeoSizeable area can
+ * be inscribed.
+ *@return the radius.
+ */
+ public double getRadius();
+
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoWideLongitudeSlice.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoWideLongitudeSlice.java
new file mode 100755
index 00000000000..957c54f7a6e
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoWideLongitudeSlice.java
@@ -0,0 +1,178 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Bounding box wider than PI but limited on left and right sides (
+* left lon, right lon).
+*/
+public class GeoWideLongitudeSlice implements GeoBBox
+{
+ public final double leftLon;
+ public final double rightLon;
+
+ public final SidedPlane leftPlane;
+ public final SidedPlane rightPlane;
+
+ public final GeoPoint centerPoint;
+
+ /** Accepts only values in the following ranges: lon: {@code -PI -> PI}.
+ * Horizantal angle must be greater than or equal to PI.
+ */
+ public GeoWideLongitudeSlice(double leftLon, double rightLon)
+ {
+ // Argument checking
+ if (leftLon < -Math.PI || leftLon > Math.PI)
+ throw new IllegalArgumentException("Left longitude out of range");
+ if (rightLon < -Math.PI || rightLon > Math.PI)
+ throw new IllegalArgumentException("Right longitude out of range");
+ double extent = rightLon - leftLon;
+ if (extent < 0.0) {
+ extent += 2.0 * Math.PI;
+ }
+ if (extent < Math.PI)
+ throw new IllegalArgumentException("Width of rectangle too small");
+
+ this.leftLon = leftLon;
+ this.rightLon = rightLon;
+
+ double sinLeftLon = Math.sin(leftLon);
+ double cosLeftLon = Math.cos(leftLon);
+ double sinRightLon = Math.sin(rightLon);
+ double cosRightLon = Math.cos(rightLon);
+
+ double middleLon = (leftLon + rightLon) * 0.5;
+ centerPoint = new GeoPoint(0.0,middleLon);
+
+ this.leftPlane = new SidedPlane(centerPoint,cosLeftLon,sinLeftLon);
+ this.rightPlane = new SidedPlane(centerPoint,cosRightLon,sinRightLon);
+ }
+
+ @Override
+ public GeoBBox expand(double angle)
+ {
+ // Figuring out when we escalate to a special case requires some prefiguring
+ double currentLonSpan = rightLon - leftLon;
+ if (currentLonSpan < 0.0)
+ currentLonSpan += Math.PI * 2.0;
+ double newLeftLon = leftLon - angle;
+ double newRightLon = rightLon + angle;
+ if (currentLonSpan + 2.0 * angle >= Math.PI * 2.0) {
+ newLeftLon = -Math.PI;
+ newRightLon = Math.PI;
+ }
+ return GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5,-Math.PI * 0.5,newLeftLon,newRightLon);
+ }
+
+ @Override
+ public boolean isWithin(Vector point)
+ {
+ return leftPlane.isWithin(point) ||
+ rightPlane.isWithin(point);
+ }
+
+ @Override
+ public boolean isWithin(double x, double y, double z)
+ {
+ return leftPlane.isWithin(x,y,z) ||
+ rightPlane.isWithin(x,y,z);
+ }
+
+ @Override
+ public double getRadius()
+ {
+ // Compute the extent and divide by two
+ double extent = rightLon - leftLon;
+ if (extent < 0.0)
+ extent += Math.PI * 2.0;
+ return Math.max(Math.PI * 0.5, extent * 0.5);
+ }
+
+ @Override
+ public GeoPoint getInteriorPoint()
+ {
+ return centerPoint;
+ }
+
+ @Override
+ public boolean intersects(Plane p, Membership... bounds)
+ {
+ // Right and left bounds are essentially independent hemispheres; crossing into the wrong part of one
+ // requires crossing into the right part of the other. So intersection can ignore the left/right bounds.
+ return p.intersects(leftPlane,bounds) ||
+ p.intersects(rightPlane,bounds);
+ }
+
+ /** Compute longitude/latitude bounds for the shape.
+ *@param bounds is the optional input bounds object. If this is null,
+ * a bounds object will be created. Otherwise, the input object will be modified.
+ *@return a Bounds object describing the shape's bounds. If the bounds cannot
+ * be computed, then return a Bounds object with noLongitudeBound,
+ * noTopLatitudeBound, and noBottomLatitudeBound.
+ */
+ @Override
+ public Bounds getBounds(Bounds bounds)
+ {
+ if (bounds == null)
+ bounds = new Bounds();
+ bounds.noTopLatitudeBound().noBottomLatitudeBound();
+ bounds.addLongitudeSlice(leftLon,rightLon);
+ return bounds;
+ }
+
+ @Override
+ public int getRelationship(GeoShape path) {
+ // It's possible to contain this area. The way we do this is to
+ // see whether the shape contains both the north and south poles. If it does,
+ // we make the assumption that it contains the entire shape (which is
+ // a convenient approximation that, at worst, increases our computation).
+ if (path.isWithin(0.0,0.0,Math.PI * 0.5) &&
+ path.isWithin(0.0,0.0,-Math.PI * 0.5))
+ return CONTAINS;
+
+ // Next, look for intersections. No bounds because it is a wide variant.
+ if (path.intersects(leftPlane) ||
+ path.intersects(rightPlane))
+ return OVERLAPS;
+
+ if (isWithin(path.getInteriorPoint()))
+ return WITHIN;
+
+ return DISJOINT;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof GeoWideLongitudeSlice))
+ return false;
+ GeoWideLongitudeSlice other = (GeoWideLongitudeSlice)o;
+ return other.leftLon == leftLon && other.rightLon == rightLon;
+ }
+
+ @Override
+ public int hashCode() {
+ int result;
+ long temp;
+ temp = Double.doubleToLongBits(leftLon);
+ result = (int) (temp ^ (temp >>> 32));
+ temp = Double.doubleToLongBits(rightLon);
+ result = 31 * result + (int) (temp ^ (temp >>> 32));
+ return result;
+ }
+}
+
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoWideRectangle.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoWideRectangle.java
new file mode 100755
index 00000000000..1c01dcd448d
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoWideRectangle.java
@@ -0,0 +1,256 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Bounding box wider than PI but limited on four sides (top lat,
+* bottom lat, left lon, right lon).
+*/
+public class GeoWideRectangle implements GeoBBox
+{
+ public final double topLat;
+ public final double bottomLat;
+ public final double leftLon;
+ public final double rightLon;
+
+ public final double cosMiddleLat;
+
+ public final GeoPoint ULHC;
+ public final GeoPoint URHC;
+ public final GeoPoint LRHC;
+ public final GeoPoint LLHC;
+
+ public final SidedPlane topPlane;
+ public final SidedPlane bottomPlane;
+ public final SidedPlane leftPlane;
+ public final SidedPlane rightPlane;
+
+ public final GeoPoint centerPoint;
+
+ public final EitherBound eitherBound;
+
+ /** Accepts only values in the following ranges: lat: {@code -PI/2 -> PI/2}, lon: {@code -PI -> PI}.
+ * Horizontal angle must be greater than or equal to PI.
+ */
+ public GeoWideRectangle(double topLat, double bottomLat, double leftLon, double rightLon)
+ {
+ // Argument checking
+ if (topLat > Math.PI * 0.5 || topLat < -Math.PI * 0.5)
+ throw new IllegalArgumentException("Top latitude out of range");
+ if (bottomLat > Math.PI * 0.5 || bottomLat < -Math.PI * 0.5)
+ throw new IllegalArgumentException("Bottom latitude out of range");
+ if (topLat < bottomLat)
+ throw new IllegalArgumentException("Top latitude less than bottom latitude");
+ if (leftLon < -Math.PI || leftLon > Math.PI)
+ throw new IllegalArgumentException("Left longitude out of range");
+ if (rightLon < -Math.PI || rightLon > Math.PI)
+ throw new IllegalArgumentException("Right longitude out of range");
+ double extent = rightLon - leftLon;
+ if (extent < 0.0) {
+ extent += 2.0 * Math.PI;
+ }
+ if (extent < Math.PI)
+ throw new IllegalArgumentException("Width of rectangle too small");
+
+ this.topLat = topLat;
+ this.bottomLat = bottomLat;
+ this.leftLon = leftLon;
+ this.rightLon = rightLon;
+
+ double sinTopLat = Math.sin(topLat);
+ double cosTopLat = Math.cos(topLat);
+ double sinBottomLat = Math.sin(bottomLat);
+ double cosBottomLat = Math.cos(bottomLat);
+ double sinLeftLon = Math.sin(leftLon);
+ double cosLeftLon = Math.cos(leftLon);
+ double sinRightLon = Math.sin(rightLon);
+ double cosRightLon = Math.cos(rightLon);
+
+ // Now build the four points
+ this.ULHC = new GeoPoint(sinTopLat,sinLeftLon,cosTopLat,cosLeftLon);
+ this.URHC = new GeoPoint(sinTopLat,sinRightLon,cosTopLat,cosRightLon);
+ this.LRHC = new GeoPoint(sinBottomLat,sinRightLon,cosBottomLat,cosRightLon);
+ this.LLHC = new GeoPoint(sinBottomLat,sinLeftLon,cosBottomLat,cosLeftLon);
+
+ this.topPlane = new SidedPlane(LRHC,sinTopLat);
+ this.bottomPlane = new SidedPlane(ULHC,sinBottomLat);
+ this.leftPlane = new SidedPlane(LRHC,cosLeftLon,sinLeftLon);
+ this.rightPlane = new SidedPlane(LLHC,cosRightLon,sinRightLon);
+
+ double middleLat = (topLat + bottomLat) * 0.5;
+ double sinMiddleLat = Math.sin(middleLat);
+ cosMiddleLat = Math.cos(middleLat);
+ double middleLon = (leftLon + rightLon) * 0.5;
+ double sinMiddleLon = Math.sin(middleLon);
+ double cosMiddleLon = Math.cos(middleLon);
+
+ centerPoint = new GeoPoint(sinMiddleLat,sinMiddleLon,cosMiddleLat,cosMiddleLon);
+
+ this.eitherBound = new EitherBound();
+ }
+
+ @Override
+ public GeoBBox expand(double angle)
+ {
+ double newTopLat = topLat + angle;
+ double newBottomLat = bottomLat - angle;
+ // Figuring out when we escalate to a special case requires some prefiguring
+ double currentLonSpan = rightLon - leftLon;
+ if (currentLonSpan < 0.0)
+ currentLonSpan += Math.PI * 2.0;
+ double newLeftLon = leftLon - angle;
+ double newRightLon = rightLon + angle;
+ if (currentLonSpan + 2.0 * angle >= Math.PI * 2.0) {
+ newLeftLon = -Math.PI;
+ newRightLon = Math.PI;
+ }
+ return GeoBBoxFactory.makeGeoBBox(newTopLat,newBottomLat,newLeftLon,newRightLon);
+ }
+
+ @Override
+ public boolean isWithin(Vector point)
+ {
+ return topPlane.isWithin(point) &&
+ bottomPlane.isWithin(point) &&
+ (leftPlane.isWithin(point) ||
+ rightPlane.isWithin(point));
+ }
+
+ @Override
+ public boolean isWithin(double x, double y, double z)
+ {
+ return topPlane.isWithin(x,y,z) &&
+ bottomPlane.isWithin(x,y,z) &&
+ (leftPlane.isWithin(x,y,z) ||
+ rightPlane.isWithin(x,y,z));
+ }
+
+ @Override
+ public double getRadius()
+ {
+ // Here we compute the distance from the middle point to one of the corners. However, we need to be careful
+ // to use the longest of three distances: the distance to a corner on the top; the distnace to a corner on the bottom, and
+ // the distance to the right or left edge from the center.
+ double centerAngle = (rightLon - (rightLon + leftLon) * 0.5) * cosMiddleLat;
+ double topAngle = centerPoint.arcDistance(URHC);
+ double bottomAngle = centerPoint.arcDistance(LLHC);
+ return Math.max(centerAngle,Math.max(topAngle,bottomAngle));
+ }
+
+ @Override
+ public GeoPoint getInteriorPoint()
+ {
+ return centerPoint;
+ }
+
+ @Override
+ public boolean intersects(Plane p, Membership... bounds)
+ {
+ // Right and left bounds are essentially independent hemispheres; crossing into the wrong part of one
+ // requires crossing into the right part of the other. So intersection can ignore the left/right bounds.
+ return p.intersects(topPlane,bounds,bottomPlane,leftPlane,rightPlane) ||
+ p.intersects(bottomPlane,bounds,topPlane,leftPlane,rightPlane) ||
+ p.intersects(leftPlane,bounds,topPlane,bottomPlane) ||
+ p.intersects(rightPlane,bounds,topPlane,bottomPlane);
+ }
+
+ /** Compute longitude/latitude bounds for the shape.
+ *@param bounds is the optional input bounds object. If this is null,
+ * a bounds object will be created. Otherwise, the input object will be modified.
+ *@return a Bounds object describing the shape's bounds. If the bounds cannot
+ * be computed, then return a Bounds object with noLongitudeBound,
+ * noTopLatitudeBound, and noBottomLatitudeBound.
+ */
+ @Override
+ public Bounds getBounds(Bounds bounds)
+ {
+ if (bounds == null)
+ bounds = new Bounds();
+ bounds.addLatitudeZone(topLat).addLatitudeZone(bottomLat)
+ .addLongitudeSlice(leftLon,rightLon);
+ return bounds;
+ }
+
+ @Override
+ public int getRelationship(GeoShape path) {
+ // There are many cases here. I'll go through them in order
+ boolean ulhcWithin = path.isWithin(ULHC);
+ boolean urhcWithin = path.isWithin(URHC);
+ boolean lrhcWithin = path.isWithin(LRHC);
+ boolean llhcWithin = path.isWithin(LLHC);
+
+ // If there are some that are in, and some that are out, we've got overlap. Otherwise, things are different.
+ if (ulhcWithin && urhcWithin && lrhcWithin && llhcWithin) {
+ // It's not precisely correct, but at this point we CHOOSE to claim that the entire rectangle is within the path.
+ // This in practice will mean that we generate more geotokens than are strictly needed, but otherwise this case
+ // would be expensive to disentangle.
+ return CONTAINS;
+ }
+
+ if (ulhcWithin || urhcWithin || lrhcWithin || llhcWithin) {
+ // Some are in, some are out: definite overlap
+ return OVERLAPS;
+ }
+
+ // All rectangle endpoints are outside the path. The three possible cases are WITHIN, OVERLAPS, and DISJOINT.
+ // The only way to distinguish between them is to look at whether any of the four rectangle sides intersect
+ // the path edges. If there is no intersection, AND any path point is within the rectangle, THEN return WITHIN.
+
+ if (path.intersects(topPlane,bottomPlane,eitherBound) ||
+ path.intersects(bottomPlane,topPlane,eitherBound) ||
+ path.intersects(leftPlane,topPlane,bottomPlane) ||
+ path.intersects(rightPlane,topPlane,bottomPlane))
+ return OVERLAPS;
+
+ if (isWithin(path.getInteriorPoint()))
+ return WITHIN;
+
+ return DISJOINT;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof GeoWideRectangle))
+ return false;
+ GeoWideRectangle other = (GeoWideRectangle)o;
+ return other.ULHC.equals(ULHC) && other.LRHC.equals(LRHC);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = ULHC.hashCode();
+ result = 31 * result + LRHC.hashCode();
+ return result;
+ }
+
+ protected class EitherBound implements Membership {
+ public EitherBound() {
+ }
+
+ @Override
+ public boolean isWithin(Vector v) {
+ return leftPlane.isWithin(v) || rightPlane.isWithin(v);
+ }
+
+ @Override
+ public boolean isWithin(double x, double y, double z) {
+ return leftPlane.isWithin(x,y,z) || rightPlane.isWithin(x,y,z);
+ }
+ }
+}
+
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoWorld.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoWorld.java
new file mode 100755
index 00000000000..937b1e83277
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/GeoWorld.java
@@ -0,0 +1,100 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Bounding box including the entire world.
+*/
+public class GeoWorld implements GeoBBox
+{
+ protected final static GeoPoint originPoint = new GeoPoint(1.0,0.0,0.0);
+
+ public GeoWorld()
+ {
+ }
+
+ @Override
+ public GeoBBox expand(double angle)
+ {
+ return this;
+ }
+
+ @Override
+ public double getRadius()
+ {
+ return Math.PI;
+ }
+
+ @Override
+ public boolean isWithin(Vector point)
+ {
+ return true;
+ }
+
+ @Override
+ public boolean isWithin(double x, double y, double z)
+ {
+ return true;
+ }
+
+ @Override
+ public GeoPoint getInteriorPoint()
+ {
+ return originPoint;
+ }
+
+ @Override
+ public boolean intersects(Plane p, Membership... bounds)
+ {
+ return false;
+ }
+
+ /** Compute longitude/latitude bounds for the shape.
+ *@param bounds is the optional input bounds object. If this is null,
+ * a bounds object will be created. Otherwise, the input object will be modified.
+ *@return a Bounds object describing the shape's bounds. If the bounds cannot
+ * be computed, then return a Bounds object with noLongitudeBound,
+ * noTopLatitudeBound, and noBottomLatitudeBound.
+ */
+ @Override
+ public Bounds getBounds(Bounds bounds)
+ {
+ if (bounds == null)
+ bounds = new Bounds();
+ bounds.noLongitudeBound().noTopLatitudeBound().noBottomLatitudeBound();
+ return bounds;
+ }
+
+ @Override
+ public int getRelationship(GeoShape path) {
+ // Path is always within the world
+ return WITHIN;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof GeoWorld))
+ return false;
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ return 0;
+ }
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Membership.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Membership.java
new file mode 100755
index 00000000000..42d1b57f99f
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Membership.java
@@ -0,0 +1,38 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Interface describing 3d shape membership methods.
+*/
+public interface Membership {
+
+ /** Check if a point is within this shape.
+ *@param point is the point to check.
+ *@return true if the point is within this shape
+ */
+ public boolean isWithin(Vector point);
+
+ /** Check if a point is within this shape.
+ *@param x is x coordinate of point to check.
+ *@param y is y coordinate of point to check.
+ *@param z is z coordinate of point to check.
+ *@return true if the point is within this shape
+ */
+ public boolean isWithin(double x, double y, double z);
+
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Plane.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Plane.java
new file mode 100755
index 00000000000..807512f631d
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Plane.java
@@ -0,0 +1,665 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** We know about three kinds of planes. First kind: general plain through two points and origin
+* Second kind: horizontal plane at specified height. Third kind: vertical plane with specified x and y value, through origin.
+*/
+public class Plane extends Vector
+{
+ public final double D;
+
+ /** Construct a plane through two points and origin.
+ *@param A is the first point (origin based).
+ *@param B is the second point (origin based).
+ */
+ public Plane(Vector A, Vector B) {
+ super(A,B);
+ D = 0.0;
+ }
+
+ /** Construct a horizontal plane at a specified Z.
+ *@param height is the specified Z coordinate.
+ */
+ public Plane(double height) {
+ super(0.0,0.0,1.0);
+ D = -height;
+ }
+
+ /** Construct a vertical plane through a specified
+ * x, y and origin.
+ *@param x is the specified x value.
+ *@param y is the specified y value.
+ */
+ public Plane(double x, double y) {
+ super(y,-x,0.0);
+ D = 0.0;
+ }
+
+ /** Construct a plane with a specific vector, and D offset
+ * from origin.
+ *@param D is the D offset from the origin.
+ */
+ public Plane(Vector v, double D) {
+ super(v.x,v.y,v.z);
+ this.D = D;
+ }
+
+ /** Evaluate the plane equation for a given point, as represented
+ * by a vector.
+ *@param v is the vector.
+ *@return the result of the evaluation.
+ */
+ public double evaluate(Vector v) {
+ return super.evaluate(v) + D;
+ }
+
+ /** Build a normalized plane, so that the vector is normalized.
+ *@return the normalized plane object, or null if the plane is indeterminate.
+ */
+ public Plane normalize() {
+ Vector normVect = super.normalize();
+ if (normVect == null)
+ return null;
+ return new Plane(normVect,this.D);
+ }
+
+ /** Find the intersection points between two planes, given a set of bounds.
+ *@param q is the plane to intersect with.
+ *@param bounds is the set of bounds.
+ *@param moreBounds is another set of bounds.
+ *@return the intersection point(s) on the unit sphere, if there are any.
+ */
+ protected GeoPoint[] findIntersections(Plane q, Membership[] bounds, Membership[] moreBounds) {
+ Vector lineVector = new Vector(this,q);
+ if (lineVector.x == 0.0 && lineVector.y == 0.0 && lineVector.z == 0.0) {
+ // Degenerate case: parallel planes
+ return new GeoPoint[0];
+ }
+
+ // The line will have the equation: A t + A0 = x, B t + B0 = y, C t + C0 = z.
+ // We have A, B, and C. In order to come up with A0, B0, and C0, we need to find a point that is on both planes.
+ // To do this, we find the largest vector value (either x, y, or z), and look for a point that solves both plane equations
+ // simultaneous. For example, let's say that the vector is (0.5,0.5,1), and the two plane equations are:
+ // 0.7 x + 0.3 y + 0.1 z + 0.0 = 0
+ // and
+ // 0.9 x - 0.1 y + 0.2 z + 4.0 = 0
+ // Then we'd pick z = 0, so the equations to solve for x and y would be:
+ // 0.7 x + 0.3y = 0.0
+ // 0.9 x - 0.1y = -4.0
+ // ... which can readily be solved using standard linear algebra. Generally:
+ // Q0 x + R0 y = S0
+ // Q1 x + R1 y = S1
+ // ... can be solved by Cramer's rule:
+ // x = det(S0 R0 / S1 R1) / det(Q0 R0 / Q1 R1)
+ // y = det(Q0 S0 / Q1 S1) / det(Q0 R0 / Q1 R1)
+ // ... where det( a b / c d ) = ad - bc, so:
+ // x = (S0 * R1 - R0 * S1) / (Q0 * R1 - R0 * Q1)
+ // y = (Q0 * S1 - S0 * Q1) / (Q0 * R1 - R0 * Q1)
+ double x0;
+ double y0;
+ double z0;
+ // We try to maximize the determinant in the denominator
+ double denomYZ = this.y*q.z - this.z*q.y;
+ double denomXZ = this.x*q.z - this.z*q.x;
+ double denomXY = this.x*q.y - this.y*q.x;
+ if (Math.abs(denomYZ) >= Math.abs(denomXZ) && Math.abs(denomYZ) >= Math.abs(denomXY)) {
+ // X is the biggest, so our point will have x0 = 0.0
+ if (Math.abs(denomYZ) < 1.0e-35)
+ return new GeoPoint[0];
+ double denom = 1.0 / denomYZ;
+ x0 = 0.0;
+ y0 = (-this.D * q.z - this.z * -q.D) * denom;
+ z0 = (this.y * -q.D + this.D * q.y) * denom;
+ } else if (Math.abs(denomXZ) >= Math.abs(denomXY) && Math.abs(denomXZ) >= Math.abs(denomYZ)) {
+ // Y is the biggest, so y0 = 0.0
+ if (Math.abs(denomXZ) < 1.0e-35)
+ return new GeoPoint[0];
+ double denom = 1.0 / denomXZ;
+ x0 = (-this.D * q.z - this.z * -q.D) * denom;
+ y0 = 0.0;
+ z0 = (this.x * -q.D + this.D * q.x) * denom;
+ } else {
+ // Z is the biggest, so Z0 = 0.0
+ if (Math.abs(denomXY) < 1.0e-35)
+ return new GeoPoint[0];
+ double denom = 1.0 / denomXY;
+ x0 = (-this.D * q.y - this.y * -q.D) * denom;
+ y0 = (this.x * -q.D + this.D * q.x) * denom;
+ z0 = 0.0;
+ }
+
+ // Once an intersecting line is determined, the next step is to intersect that line with the unit sphere, which
+ // will yield zero, one, or two points.
+ // The equation of the sphere is: 1.0 = x^2 + y^2 + z^2. Plugging in the parameterized line values yields:
+ // 1.0 = (At+A0)^2 + (Bt+B0)^2 + (Ct+C0)^2
+ // A^2 t^2 + 2AA0t + A0^2 + B^2 t^2 + 2BB0t + B0^2 + C^2 t^2 + 2CC0t + C0^2 - 1,0 = 0.0
+ // [A^2 + B^2 + C^2] t^2 + [2AA0 + 2BB0 + 2CC0] t + [A0^2 + B0^2 + C0^2 - 1,0] = 0.0
+ // Use the quadratic formula to determine t values and candidate point(s)
+ double A = lineVector.x * lineVector.x + lineVector.y * lineVector.y + lineVector.z * lineVector.z;
+ double B = 2.0*(lineVector.x * x0 + lineVector.y * y0 + lineVector.z * z0);
+ double C = x0*x0 + y0*y0 + z0*z0 - 1.0;
+
+ double BsquaredMinus = B * B - 4.0 * A * C;
+ if (BsquaredMinus < 0.0)
+ return new GeoPoint[0];
+ double inverse2A = 1.0 / (2.0 * A);
+ if (BsquaredMinus == 0.0) {
+ // One solution only
+ double t = -B * inverse2A;
+ GeoPoint point = new GeoPoint(lineVector.x * t + x0, lineVector.y * t + y0, lineVector.z * t + z0);
+ if (point.isWithin(bounds,moreBounds))
+ return new GeoPoint[]{point};
+ return new GeoPoint[0];
+ } else {
+ // Two solutions
+ double sqrtTerm = Math.sqrt(BsquaredMinus);
+ double t1 = (-B + sqrtTerm) * inverse2A;
+ double t2 = (-B - sqrtTerm) * inverse2A;
+ GeoPoint point1 = new GeoPoint(lineVector.x * t1 + x0, lineVector.y * t1 + y0, lineVector.z * t1 + z0);
+ GeoPoint point2 = new GeoPoint(lineVector.x * t2 + x0, lineVector.y * t2 + y0, lineVector.z * t2 + z0);
+ if (point1.isWithin(bounds,moreBounds)) {
+ if (point2.isWithin(bounds,moreBounds))
+ return new GeoPoint[]{point1,point2};
+ return new GeoPoint[]{point1};
+ }
+ if (point2.isWithin(bounds,moreBounds))
+ return new GeoPoint[]{point2};
+ return new GeoPoint[0];
+ }
+ }
+
+ /** Accumulate bounds information for this plane, intersected with another plane
+ * and with the unit sphere.
+ * Updates both latitude and longitude information, using max/min points found
+ * within the specified bounds.
+ *@param q is the plane to intersect with.
+ *@param boundsInfo is the info to update with additional bounding information.
+ *@param bounds are the surfaces delineating what's inside the shape.
+ */
+ public void recordBounds(Plane q, Bounds boundsInfo, Membership... bounds) {
+ GeoPoint[] intersectionPoints = findIntersections(q,bounds,new Membership[0]);
+ for (GeoPoint intersectionPoint : intersectionPoints) {
+ boundsInfo.addPoint(intersectionPoint);
+ }
+ }
+
+ /** Accumulate bounds information for this plane, intersected with the unit sphere.
+ * Updates both latitude and longitude information, using max/min points found
+ * within the specified bounds.
+ *@param boundsInfo is the info to update with additional bounding information.
+ *@param bounds are the surfaces delineating what's inside the shape.
+ */
+ public void recordBounds(Bounds boundsInfo, Membership... bounds) {
+ // For clarity, load local variables with good names
+ double A = this.x;
+ double B = this.y;
+ double C = this.z;
+
+ // Now compute latitude min/max points
+ if (!boundsInfo.checkNoTopLatitudeBound() || !boundsInfo.checkNoBottomLatitudeBound()) {
+ if ((Math.abs(A) >= 1e-10 || Math.abs(B) >= 1e-10)) {
+ //System.out.println("A = "+A+" B = "+B+" C = "+C+" D = "+D);
+ // sin (phi) = z
+ // cos (theta - phi) = D
+ // sin (theta) = C (the dot product of (0,0,1) and (A,B,C) )
+ // Q: what is z?
+ //
+ // cos (theta-phi) = cos(theta)cos(phi) + sin(theta)sin(phi) = D
+
+ if (Math.abs(C) < 1.0e-10) {
+ // Special case: circle is vertical.
+ //System.out.println("Degenerate case; it's vertical circle");
+ // cos(phi) = D, and we want sin(phi) = z
+ // There are two solutions for phi given cos(phi) = D: a positive solution and a negative solution.
+ // So, when we compute z = sqrt(1-D^2), it's really z = +/- sqrt(1-D^2) .
+
+ double z;
+ double x;
+ double y;
+
+ double denom = 1.0 / (A*A + B*B);
+
+ z = Math.sqrt(1.0 - D*D);
+ y = -B * D * denom;
+ x = -A * D * denom;
+ addPoint(boundsInfo, bounds, x, y, z);
+
+ z = -z;
+ addPoint(boundsInfo, bounds, x, y, z);
+ } else {
+ // We might be able to identify a specific new latitude maximum or minimum.
+ //
+ // cos (theta-phi) = cos(theta)cos(phi) + sin(theta)sin(phi) = D
+ //
+ // This is tricky. If cos(phi) = something, and we want to figure out
+ // what sin(phi) is, in order to capture all solutions we need to recognize
+ // that sin(phi) = +/- sqrt(1 - cos(phi)^2). Basically, this means that
+ // whatever solution we find we have to mirror it across the x-y plane,
+ // and include both +z and -z solutions.
+ //
+ // cos (phi) = +/- sqrt(1-sin(phi)^2) = +/- sqrt(1-z^2)
+ // cos (theta) = +/- sqrt(1-sin(theta)^2) = +/- sqrt(1-C^2)
+ //
+ // D = cos(theta)cos(phi) + sin(theta)sin(phi)
+ // Substitute:
+ // D = sqrt(1-C^2) * sqrt(1-z^2) + C * z
+ // Solve for z...
+ // D-Cz = sqrt(1-C^2)*sqrt(1-z^2) = sqrt(1 - z^2 - C^2 + z^2*C^2)
+ // Square both sides.
+ // (D-Cz)^2 = 1 - z^2 - C^2 + z^2*C^2
+ // D^2 - 2DCz + C^2*z^2 = 1 - z^2 - C^2 + z^2*C^2
+ // D^2 - 2DCz = 1 - C^2 - z^2
+ // 0 = z^2 - 2DCz + (C^2 +D^2-1) = 0
+ //
+ // z = (2DC +/- sqrt(4*D^2*C^2 - 4*(C^2+D^2-1))) / (2)
+ // z = DC +/- sqrt(D^2*C^2 + 1 - C^2 - D^2 )
+ // = DC +/- sqrt(D^2*C^2 + 1 - C^2 - D^2)
+
+ double z;
+ double x;
+ double y;
+
+ double sqrtValue = D*D*C*C + 1.0 - C*C - D*D;
+ if (sqrtValue >= 0.0) {
+ // y = -B[D+Cz] / [A^2 + B^2]
+ // x = -A[D+Cz] / [A^2 + B^2]
+ double denom = 1.0 / (A*A + B*B);
+ if (sqrtValue == 0.0) {
+ //System.out.println("Zero sqrt term");
+ z = D*C;
+ // Since we squared both sides of the equation, we may have introduced spurious solutions, so we have to check.
+ if (Math.abs(D-C*z - Math.sqrt(1.0 - z*z - C*C + z*z*C*C)) < 1.0e-10) {
+ y = -B * (D + C*z) * denom;
+ x = -A * (D + C*z) * denom;
+ addPoint(boundsInfo, bounds, x, y, z);
+ }
+ z = -D*C;
+ // Since we squared both sides of the equation, we may have introduced spurious solutions, so we have to check.
+ if (Math.abs(D+C*z + Math.sqrt(1.0 - z*z - C*C + z*z*C*C)) < 1.0e-10) {
+ y = -B * (D + C*z) * denom;
+ x = -A * (D + C*z) * denom;
+ addPoint(boundsInfo, bounds, x, y, z);
+ }
+ } else {
+ double sqrtResult = Math.sqrt(sqrtValue);
+ z = D*C + sqrtResult;
+ //System.out.println("z= "+z+" D-C*z = " + (D-C*z) + " Math.sqrt(1.0 - z*z - C*C + z*z*C*C) = "+(Math.sqrt(1.0 - z*z - C*C + z*z*C*C)));
+ // Since we squared both sides of the equation, we may have introduced spurios solutions, so we have to check.
+ if (Math.abs(D-C*z - Math.sqrt(1.0 - z*z - C*C + z*z*C*C)) < 1.0e-10) {
+ //System.out.println("found a point; z = "+z);
+ y = -B * (D + C*z) * denom;
+ x = -A * (D + C*z) * denom;
+ addPoint(boundsInfo, bounds, x, y, z);
+ }
+ z = D*C - sqrtResult;
+ //System.out.println("z= "+z+" D-C*z = " + (D-C*z) + " Math.sqrt(1.0 - z*z - C*C + z*z*C*C) = "+(Math.sqrt(1.0 - z*z - C*C + z*z*C*C)));
+ // Since we squared both sides of the equation, we may have introduced spurios solutions, so we have to check.
+ if (Math.abs(D-C*z - Math.sqrt(1.0 - z*z - C*C + z*z*C*C)) < 1.0e-10) {
+ //System.out.println("found a point; z="+z);
+ y = -B * (D + C*z) * denom;
+ x = -A * (D + C*z) * denom;
+ addPoint(boundsInfo, bounds, x, y, z);
+ }
+ z = -(D*C + sqrtResult);
+ //System.out.println("z= "+z+" D+C*z = " + (D+C*z) + " -Math.sqrt(1.0 - z*z - C*C + z*z*C*C) = "+(-Math.sqrt(1.0 - z*z - C*C + z*z*C*C)));
+ // Since we squared both sides of the equation, we may have introduced spurios solutions, so we have to check.
+ if (Math.abs(D+C*z + Math.sqrt(1.0 - z*z - C*C + z*z*C*C)) < 1.0e-10) {
+ //System.out.println("found a point; z = "+z);
+ y = -B * (D + C*z) * denom;
+ x = -A * (D + C*z) * denom;
+ addPoint(boundsInfo, bounds, x, y, z);
+ }
+ z = -(D*C - sqrtResult);
+ //System.out.println("z= "+z+" D+C*z = " + (D+C*z) + " -Math.sqrt(1.0 - z*z - C*C + z*z*C*C) = "+(-Math.sqrt(1.0 - z*z - C*C + z*z*C*C)));
+ // Since we squared both sides of the equation, we may have introduced spurios solutions, so we have to check.
+ if (Math.abs(D+C*z + Math.sqrt(1 - z*z - C*C + z*z*C*C)) < 1.0e-10) {
+ //System.out.println("found a point; z="+z);
+ y = -B * (D + C*z) * denom;
+ x = -A * (D + C*z) * denom;
+ addPoint(boundsInfo, bounds, x, y, z);
+ }
+ }
+ }
+ }
+ } else {
+ // Horizontal circle.
+ // Since the recordBounds() method will be called ONLY for planes that constitute edges of a shape,
+ // we can be sure that some part of the horizontal circle will be part of the boundary, so we don't need
+ // to check Membership objects.
+ boundsInfo.addHorizontalCircle(-D * C);
+ }
+ }
+
+ // First, figure out our longitude bounds, unless we no longer need to consider that
+ if (!boundsInfo.checkNoLongitudeBound()) {
+
+ //System.out.println("A = "+A+" B = "+B+" C = "+C+" D = "+D);
+ // Compute longitude bounds
+
+ double a;
+ double b;
+ double c;
+
+ if (Math.abs(C) < 1e-10) {
+ // Degenerate; the equation describes a line
+ //System.out.println("It's a zero-width ellipse");
+ // Ax + By + D = 0
+ if (Math.abs(D) >= 1e-10) {
+ if (Math.abs(A) > Math.abs(B)) {
+ // Use equation suitable for A != 0
+ // We need to find the endpoints of the zero-width ellipse.
+ // Geometrically, we have a line segment in x-y space. We need to locate the endpoints
+ // of that line. But luckily, we know some things: specifically, since it is a
+ // degenerate situation in projection, the C value had to have been 0. That
+ // means that our line's endpoints will coincide with the unit circle. All we
+ // need to do then is to find the intersection of the unit circle and the line
+ // equation:
+ //
+ // A x + B y + D = 0
+ //
+ // Since A != 0:
+ // x = (-By - D)/A
+ //
+ // The unit circle:
+ // x^2 + y^2 - 1 = 0
+ // Substitute:
+ // [(-By-D)/A]^2 + y^2 -1 = 0
+ // Multiply through by A^2:
+ // [-By - D]^2 + A^2*y^2 - A^2 = 0
+ // Multiply out:
+ // B^2*y^2 + 2BDy + D^2 + A^2*y^2 - A^2 = 0
+ // Group:
+ // y^2 * [B^2 + A^2] + y [2BD] + [D^2-A^2] = 0
+
+ a = B * B + A * A;
+ b = 2.0 * B * D;
+ c = D * D - A * A;
+
+ double sqrtClause = b * b - 4.0 * a * c;
+
+ if (sqrtClause >= 0.0) {
+ if (sqrtClause == 0.0) {
+ double y0 = -b / (2.0 * a);
+ double x0 = (-D - B * y0) / A;
+ double z0 = 0.0;
+ addPoint(boundsInfo, bounds, x0, y0, z0);
+ } else {
+ double sqrtResult = Math.sqrt(sqrtClause);
+ double denom = 1.0 / (2.0 * a);
+ double Hdenom = 1.0 / A;
+
+ double y0a = (-b + sqrtResult ) * denom;
+ double y0b = (-b - sqrtResult ) * denom;
+
+ double x0a = (-D - B * y0a) * Hdenom;
+ double x0b = (-D - B * y0b) * Hdenom;
+
+ double z0a = 0.0;
+ double z0b = 0.0;
+
+ addPoint(boundsInfo, bounds, x0a, y0a, z0a);
+ addPoint(boundsInfo, bounds, x0b, y0b, z0b);
+ }
+ }
+
+ } else {
+ // Use equation suitable for B != 0
+ // Since I != 0, we rewrite:
+ // y = (-Ax - D)/B
+ a = B * B + A * A;
+ b = 2.0 * A * D;
+ c = D * D - B * B;
+
+ double sqrtClause = b * b - 4.0 * a * c;
+
+ if (sqrtClause >= 0.0) {
+
+ if (sqrtClause == 0.0) {
+ double x0 = -b / (2.0 * a);
+ double y0 = (- D - A * x0) / B;
+ double z0 = 0.0;
+ addPoint(boundsInfo, bounds, x0, y0, z0);
+ } else {
+ double sqrtResult = Math.sqrt(sqrtClause);
+ double denom = 1.0 / (2.0 * a);
+ double Idenom = 1.0 / B;
+
+ double x0a = (-b + sqrtResult ) * denom;
+ double x0b = (-b - sqrtResult ) * denom;
+ double y0a = (- D - A * x0a) * Idenom;
+ double y0b = (- D - A * x0b) * Idenom;
+ double z0a = 0.0;
+ double z0b = 0.0;
+
+ addPoint(boundsInfo, bounds, x0a, y0a, z0a);
+ addPoint(boundsInfo, bounds, x0b, y0b, z0b);
+ }
+ }
+ }
+ }
+
+ } else {
+
+ // (1) Intersect the plane and the unit sphere, and project the results into the x-y plane:
+ // From plane:
+ // z = (-Ax - By - D) / C
+ // From unit sphere:
+ // x^2 + y^2 + [(-Ax - By - D) / C]^2 = 1
+ // Simplify/expand:
+ // C^2*x^2 + C^2*y^2 + (-Ax - By - D)^2 = C^2
+ //
+ // x^2 * C^2 + y^2 * C^2 + x^2 * (A^2 + ABxy + ADx) + (ABxy + y^2 * B^2 + BDy) + (ADx + BDy + D^2) = C^2
+ // Group:
+ // [A^2 + C^2] x^2 + [B^2 + C^2] y^2 + [2AB]xy + [2AD]x + [2BD]y + [D^2-C^2] = 0
+ // For convenience, introduce post-projection coefficient variables to make life easier.
+ // E x^2 + F y^2 + G xy + H x + I y + J = 0
+ double E = A * A + C * C;
+ double F = B * B + C * C;
+ double G = 2.0 * A * B;
+ double H = 2.0 * A * D;
+ double I = 2.0 * B * D;
+ double J = D * D - C * C;
+
+ //System.out.println("E = " + E + " F = " + F + " G = " + G + " H = "+ H + " I = " + I + " J = " + J);
+
+ // Check if the origin is within, by substituting x = 0, y = 0 and seeing if less than zero
+ if (J > 0.0) {
+ // The derivative of the curve above is:
+ // 2Exdx + 2Fydy + G(xdy+ydx) + Hdx + Idy = 0
+ // (2Ex + Gy + H)dx + (2Fy + Gx + I)dy = 0
+ // dy/dx = - (2Ex + Gy + H) / (2Fy + Gx + I)
+ //
+ // The equation of a line going through the origin with the slope dy/dx is:
+ // y = dy/dx x
+ // y = - (2Ex + Gy + H) / (2Fy + Gx + I) x
+ // Rearrange:
+ // (2Fy + Gx + I) y + (2Ex + Gy + H) x = 0
+ // 2Fy^2 + Gxy + Iy + 2Ex^2 + Gxy + Hx = 0
+ // 2Ex^2 + 2Fy^2 + 2Gxy + Hx + Iy = 0
+ //
+ // Multiply the original equation by 2:
+ // 2E x^2 + 2F y^2 + 2G xy + 2H x + 2I y + 2J = 0
+ // Subtract one from the other, to remove the high-order terms:
+ // Hx + Iy + 2J = 0
+ // Now, we can substitute either x = or y = into the derivative equation, or into the original equation.
+ // But we will need to base this on which coefficient is non-zero
+
+ if (Math.abs(H) > Math.abs(I)) {
+ //System.out.println("Using the y quadratic");
+ // x = (-2J - Iy)/H
+
+ // Plug into the original equation:
+ // E [(-2J - Iy)/H]^2 + F y^2 + G [(-2J - Iy)/H]y + H [(-2J - Iy)/H] + I y + J = 0
+ // E [(-2J - Iy)/H]^2 + F y^2 + G [(-2J - Iy)/H]y - J = 0
+ // Same equation as derivative equation, except for a factor of 2! So it doesn't matter which we pick.
+
+ // Plug into derivative equation:
+ // 2E[(-2J - Iy)/H]^2 + 2Fy^2 + 2G[(-2J - Iy)/H]y + H[(-2J - Iy)/H] + Iy = 0
+ // 2E[(-2J - Iy)/H]^2 + 2Fy^2 + 2G[(-2J - Iy)/H]y - 2J = 0
+ // E[(-2J - Iy)/H]^2 + Fy^2 + G[(-2J - Iy)/H]y - J = 0
+
+ // Multiply by H^2 to make manipulation easier
+ // E[(-2J - Iy)]^2 + F*H^2*y^2 + GH[(-2J - Iy)]y - J*H^2 = 0
+ // Do the square
+ // E[4J^2 + 4IJy + I^2*y^2] + F*H^2*y^2 + GH(-2Jy - I*y^2) - J*H^2 = 0
+
+ // Multiply it out
+ // 4E*J^2 + 4EIJy + E*I^2*y^2 + H^2*Fy^2 - 2GHJy - GH*I*y^2 - J*H^2 = 0
+ // Group:
+ // y^2 [E*I^2 - GH*I + F*H^2] + y [4EIJ - 2GHJ] + [4E*J^2 - J*H^2] = 0
+
+ a = E * I * I - G * H * I + F*H*H;
+ b = 4.0 * E * I * J - 2.0 * G * H * J;
+ c = 4.0 * E * J * J - J * H * H;
+
+ //System.out.println("a="+a+" b="+b+" c="+c);
+ double sqrtClause = b * b - 4.0 * a * c;
+ //System.out.println("sqrtClause="+sqrtClause);
+
+ if (sqrtClause >= 0.0) {
+ if (sqrtClause == 0.0) {
+ //System.out.println("One solution");
+ double y0 = -b / (2.0 * a);
+ double x0 = (-2.0 * J - I * y0) / H;
+ double z0 = (-A*x0 - B*y0 - D)/C;
+
+ addPoint(boundsInfo, bounds, x0, y0, z0);
+ } else {
+ //System.out.println("Two solutions");
+ double sqrtResult = Math.sqrt(sqrtClause);
+ double denom = 1.0 / (2.0 * a);
+ double Hdenom = 1.0 / H;
+ double Cdenom = 1.0 / C;
+
+ double y0a = (-b + sqrtResult ) * denom;
+ double y0b = (-b - sqrtResult ) * denom;
+ double x0a = (-2.0 * J - I * y0a) * Hdenom;
+ double x0b = (-2.0 * J - I * y0b) * Hdenom;
+ double z0a = (-A*x0a - B*y0a - D) * Cdenom;
+ double z0b = (-A*x0b - B*y0b - D) * Cdenom;
+
+ addPoint(boundsInfo, bounds, x0a, y0a, z0a);
+ addPoint(boundsInfo, bounds, x0b, y0b, z0b);
+ }
+ }
+
+ } else {
+ //System.out.println("Using the x quadratic");
+ // y = (-2J - Hx)/I
+
+ // Plug into the original equation:
+ // E x^2 + F [(-2J - Hx)/I]^2 + G x[(-2J - Hx)/I] - J = 0
+
+ // Multiply by I^2 to make manipulation easier
+ // E * I^2 * x^2 + F [(-2J - Hx)]^2 + GIx[(-2J - Hx)] - J * I^2 = 0
+ // Do the square
+ // E * I^2 * x^2 + F [ 4J^2 + 4JHx + H^2*x^2] + GI[(-2Jx - H*x^2)] - J * I^2 = 0
+
+ // Multiply it out
+ // E * I^2 * x^2 + 4FJ^2 + 4FJHx + F*H^2*x^2 - 2GIJx - HGI*x^2 - J * I^2 = 0
+ // Group:
+ // x^2 [E*I^2 - GHI + F*H^2] + x [4FJH - 2GIJ] + [4FJ^2 - J*I^2] = 0
+
+ a = E * I * I - G * H * I + F*H*H;
+ b = 4.0 * F * H * J - 2.0 * G * I * J;
+ c = 4.0 * F * J * J - J * I * I;
+
+ //System.out.println("a="+a+" b="+b+" c="+c);
+ double sqrtClause = b * b - 4.0 * a * c;
+ //System.out.println("sqrtClause="+sqrtClause);
+
+ if (sqrtClause >= 0.0) {
+
+ if (sqrtClause == 0.0) {
+ //System.out.println("One solution");
+ double x0 = -b / (2.0 * a);
+ double y0 = (-2.0 * J - H * x0) / I;
+ double z0 = (-A*x0 - B*y0 - D)/C;
+ addPoint(boundsInfo, bounds, x0, y0, z0);
+ } else {
+ //System.out.println("Two solutions");
+ double sqrtResult = Math.sqrt(sqrtClause);
+ double denom = 1.0 / (2.0 * a);
+ double Idenom = 1.0 / I;
+ double Cdenom = 1.0 / C;
+
+ double x0a = (-b + sqrtResult ) * denom;
+ double x0b = (-b - sqrtResult ) * denom;
+ double y0a = (-2.0 * J - H * x0a) * Idenom;
+ double y0b = (-2.0 * J - H * x0b) * Idenom;
+ double z0a = (-A*x0a - B*y0a - D) * Cdenom;
+ double z0b = (-A*x0b - B*y0b - D) * Cdenom;
+
+ addPoint(boundsInfo, bounds, x0a, y0a, z0a);
+ addPoint(boundsInfo, bounds, x0b, y0b, z0b);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ }
+
+ protected static void addPoint(Bounds boundsInfo, Membership[] bounds, double x, double y, double z) {
+ // Make sure the discovered point is within the bounds
+ for (Membership bound : bounds) {
+ if (!bound.isWithin(x,y,z))
+ return;
+ }
+ // Add the point
+ //System.out.println("Adding point x="+x+" y="+y+" z="+z);
+ boundsInfo.addPoint(x,y,z);
+ }
+
+ /** Determine whether the plane intersects another plane within the
+ * bounds provided.
+ *@param q is the other plane.
+ *@param bounds is one part of the bounds.
+ *@param moreBounds are more bounds.
+ *@return true if there's an intersection.
+ */
+ public boolean intersects(Plane q, Membership[] bounds, Membership... moreBounds) {
+ return findIntersections(q,bounds,moreBounds).length > 0;
+ }
+
+ @Override
+ public String toString() {
+ return "[A="+x+", B="+y+"; C="+z+"; D="+D+"]";
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!super.equals(o))
+ return false;
+ if (!(o instanceof Plane))
+ return false;
+ Plane other = (Plane)o;
+ return other.D == D;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = super.hashCode();
+ long temp;
+ temp = Double.doubleToLongBits(D);
+ result = 31 * result + (int) (temp ^ (temp >>> 32));
+ return result;
+ }
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/SidedPlane.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/SidedPlane.java
new file mode 100755
index 00000000000..eb215a6f37f
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/SidedPlane.java
@@ -0,0 +1,107 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Combination of a plane, and a sign value indicating what evaluation values are on the correct
+* side of the plane.
+*/
+public class SidedPlane extends Plane implements Membership
+{
+ public final double sigNum;
+
+ /** Construct a SidedPlane identical to an existing one, but reversed.
+ *@param sidedPlane is the existing plane.
+ */
+ public SidedPlane(SidedPlane sidedPlane) {
+ super(sidedPlane,sidedPlane.D);
+ this.sigNum = -sidedPlane.sigNum;
+ }
+
+ /** Construct a sided plane from a pair of vectors describing points, and including
+ * origin, plus a point p which describes the side.
+ *@param p point to evaluate
+ *@param A is the first in-plane point
+ *@param B is the second in-plane point
+ */
+ public SidedPlane(Vector p, Vector A, Vector B) {
+ super(A,B);
+ sigNum = Math.signum(evaluate(p));
+ }
+
+ /** Construct a sided plane from a point and a Z coordinate.
+ *@param p point to evaluate.
+ *@param height is the Z coordinate of the plane.
+ */
+ public SidedPlane(Vector p, double height) {
+ super(height);
+ sigNum = Math.signum(evaluate(p));
+ }
+
+ /** Construct a sided vertical plane from a point and specified x and y coordinates.
+ *@param p point to evaluate.
+ *@param x is the specified x.
+ *@param y is the specified y.
+ */
+ public SidedPlane(Vector p, double x, double y) {
+ super(x,y);
+ sigNum = Math.signum(evaluate(p));
+ }
+
+ /** Construct a sided plane with a normal vector and offset.
+ *@param p point to evaluate.
+ *@param v is the normal vector.
+ *@param D is the origin offset for the plan.
+ */
+ public SidedPlane(Vector p, Vector v, double D) {
+ super(v,D);
+ sigNum = Math.signum(evaluate(p));
+ }
+
+ /** Check if a point is within this shape.
+ *@param point is the point to check.
+ *@return true if the point is within this shape
+ */
+ @Override
+ public boolean isWithin(Vector point)
+ {
+ double sigNum = Math.signum(evaluate(point));
+ if (sigNum == 0.0)
+ return true;
+ return sigNum == this.sigNum;
+ }
+
+ /** Check if a point is within this shape.
+ *@param x is x coordinate of point to check.
+ *@param y is y coordinate of point to check.
+ *@param z is z coordinate of point to check.
+ *@return true if the point is within this shape
+ */
+ @Override
+ public boolean isWithin(double x, double y, double z)
+ {
+ double sigNum = Math.signum(this.x * x + this.y * y + this.z * z);
+ return sigNum == this.sigNum;
+ }
+
+
+ @Override
+ public String toString() {
+ return "[A="+x+", B="+y+", C="+z+", D="+D+", side="+sigNum+"]";
+ }
+}
+
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Tools.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Tools.java
new file mode 100755
index 00000000000..090e27bcf3e
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Tools.java
@@ -0,0 +1,40 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Static methods globally useful for 3d geometric work.
+ */
+public class Tools
+{
+ private Tools()
+ {
+ }
+
+ /** Java acos yields a NAN if you take an arc-cos of an
+ * angle that's just a tiny bit greater than 1.0, so
+ * here's a more resilient version.
+ */
+ public static double safeAcos(double value) {
+ if (value > 1.0)
+ value = 1.0;
+ else if (value < -1.0)
+ value = -1.0;
+ return Math.acos(value);
+ }
+
+}
\ No newline at end of file
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Vector.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Vector.java
new file mode 100755
index 00000000000..7a14e76d382
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/Vector.java
@@ -0,0 +1,237 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** A 3d vector in space, not necessarily
+ * going through the origin. */
+public class Vector
+{
+ public final double x;
+ public final double y;
+ public final double z;
+
+ /** Construct from (U.S.) x,y,z coordinates.
+ */
+ public Vector(double x, double y, double z)
+ {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ }
+
+ /** Construct a vector that is perpendicular to
+ * two other (non-zero) vectors. If the vectors are parallel,
+ * the result vector will have magnitude 0.
+ *@param A is the first vector
+ *@param B is the second
+ */
+ public Vector(Vector A, Vector B) {
+ // x = u2v3 - u3v2
+ // y = u3v1 - u1v3
+ // z = u1v2 - u2v1
+
+ this(A.y * B.z - A.z * B.y,
+ A.z * B.x - A.x * B.z,
+ A.x * B.y - A.y * B.x);
+ }
+
+ /** Compute a normalized unit vector based on the current vector.
+ *@return the normalized vector, or null if the current vector has
+ * a magnitude of zero.
+ */
+ public Vector normalize() {
+ double denom = magnitude();
+ if (denom < 1e-10)
+ // Degenerate, can't normalize
+ return null;
+ double normFactor = 1.0/denom;
+ return new Vector(x*normFactor,y*normFactor,z*normFactor);
+ }
+
+ /** Evaluate a vector (do a dot product).
+ *@param v is the vector to evaluate.
+ *@return the result.
+ */
+ public double evaluate(Vector v) {
+ return this.x * v.x + this.y * v.y + this.z * v.z;
+ }
+
+ /** Evaluate a vector (do a dot product).
+ *@param x is the x value of the vector to evaluate.
+ *@param y is the x value of the vector to evaluate.
+ *@param z is the x value of the vector to evaluate.
+ *@return the result.
+ */
+ public double evaluate(double x, double y, double z) {
+ return this.x * x + this.y * y + this.z * z;
+ }
+
+ /** Determine if this vector, taken from the origin,
+ * describes a point within a set of planes.
+ *@param bounds is the first part of the set of planes.
+ *@param moreBounds is the second part of the set of planes.
+ *@return true if the point is within the bounds.
+ */
+ public boolean isWithin(Membership[] bounds, Membership[] moreBounds) {
+ // Return true if the point described is within all provided bounds
+ for (Membership bound : bounds) {
+ if (!bound.isWithin(this))
+ return false;
+ }
+ for (Membership bound : moreBounds) {
+ if (!bound.isWithin(this))
+ return false;
+ }
+ return true;
+ }
+
+ /** Compute the square of a straight-line distance to a point described by the
+ * vector taken from the origin.
+ * Monotonically increasing for arc distances up to PI.
+ *@param v is the vector to compute a distance to.
+ *@return the square of the linear distance.
+ */
+ public double linearDistanceSquared(Vector v) {
+ double deltaX = this.x - v.x;
+ double deltaY = this.y - v.y;
+ double deltaZ = this.z - v.z;
+ return deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
+ }
+
+ /** Compute the square of a straight-line distance to a point described by the
+ * vector taken from the origin.
+ * Monotonically increasing for arc distances up to PI.
+ *@param x is the x part of the vector to compute a distance to.
+ *@param y is the y part of the vector to compute a distance to.
+ *@param z is the z part of the vector to compute a distance to.
+ *@return the square of the linear distance.
+ */
+ public double linearDistanceSquared(double x, double y, double z) {
+ double deltaX = this.x - x;
+ double deltaY = this.y - y;
+ double deltaZ = this.z - z;
+ return deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
+ }
+
+ /** Compute the straight-line distance to a point described by the
+ * vector taken from the origin.
+ * Monotonically increasing for arc distances up to PI.
+ *@param v is the vector to compute a distance to.
+ *@return the linear distance.
+ */
+ public double linearDistance(Vector v) {
+ return Math.sqrt(linearDistanceSquared(v));
+ }
+
+ /** Compute the straight-line distance to a point described by the
+ * vector taken from the origin.
+ * Monotonically increasing for arc distances up to PI.
+ *@param x is the x part of the vector to compute a distance to.
+ *@param y is the y part of the vector to compute a distance to.
+ *@param z is the z part of the vector to compute a distance to.
+ *@return the linear distance.
+ */
+ public double linearDistance(double x, double y, double z) {
+ return Math.sqrt(linearDistanceSquared(x,y,z));
+ }
+
+ /** Compute the square of the normal distance to a vector described by a
+ * vector taken from the origin.
+ * Monotonically increasing for arc distances up to PI/2.
+ *@param v is the vector to compute a distance to.
+ *@return the square of the normal distance.
+ */
+ public double normalDistanceSquared(Vector v) {
+ double t = this.evaluate(v);
+ double deltaX = this.x * t - v.x;
+ double deltaY = this.y * t - v.y;
+ double deltaZ = this.z * t - v.z;
+ return deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
+ }
+
+ /** Compute the square of the normal distance to a vector described by a
+ * vector taken from the origin.
+ * Monotonically increasing for arc distances up to PI/2.
+ *@param x is the x part of the vector to compute a distance to.
+ *@param y is the y part of the vector to compute a distance to.
+ *@param z is the z part of the vector to compute a distance to.
+ *@return the square of the normal distance.
+ */
+ public double normalDistanceSquared(double x, double y, double z) {
+ double t = this.evaluate(x,y,z);
+ double deltaX = this.x * t - x;
+ double deltaY = this.y * t - y;
+ double deltaZ = this.z * t - z;
+ return deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
+ }
+
+ /** Compute the normal (perpendicular) distance to a vector described by a
+ * vector taken from the origin.
+ * Monotonically increasing for arc distances up to PI/2.
+ *@param v is the vector to compute a distance to.
+ *@return the normal distance.
+ */
+ public double normalDistance(Vector v) {
+ return Math.sqrt(normalDistanceSquared(v));
+ }
+
+ /** Compute the normal (perpendicular) distance to a vector described by a
+ * vector taken from the origin.
+ * Monotonically increasing for arc distances up to PI/2.
+ *@param x is the x part of the vector to compute a distance to.
+ *@param y is the y part of the vector to compute a distance to.
+ *@param z is the z part of the vector to compute a distance to.
+ *@return the normal distance.
+ */
+ public double normalDistance(double x, double y, double z) {
+ return Math.sqrt(normalDistanceSquared(x,y,z));
+ }
+
+ /** Compute the magnitude of this vector.
+ *@return the magnitude.
+ */
+ public double magnitude() {
+ return Math.sqrt(x * x + y * y + z * z);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof Vector))
+ return false;
+ Vector other = (Vector)o;
+ return (other.x == x && other.y == y && other.z == z);
+ }
+
+ @Override
+ public int hashCode() {
+ int result;
+ long temp;
+ temp = Double.doubleToLongBits(x);
+ result = (int) (temp ^ (temp >>> 32));
+ temp = Double.doubleToLongBits(y);
+ result = 31 * result + (int) (temp ^ (temp >>> 32));
+ temp = Double.doubleToLongBits(z);
+ result = 31 * result + (int) (temp ^ (temp >>> 32));
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "[X="+x+", Y="+y+", Z="+z+"]";
+ }
+}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/package-info.java b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/package-info.java
new file mode 100644
index 00000000000..6faf9fac0fd
--- /dev/null
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/spatial4j/geo3d/package-info.java
@@ -0,0 +1,2 @@
+/** Shapes implemented using 3D planar geometry. */
+package org.apache.lucene.spatial.spatial4j.geo3d;
\ No newline at end of file
diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/RandomSpatialOpStrategyTestCase.java b/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/RandomSpatialOpStrategyTestCase.java
index 512cf715123..41806635a1e 100644
--- a/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/RandomSpatialOpStrategyTestCase.java
+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/RandomSpatialOpStrategyTestCase.java
@@ -113,12 +113,12 @@ public abstract class RandomSpatialOpStrategyTestCase extends StrategyTestCase {
for (SearchResult result : got.results) {
String id = result.getId();
if (!remainingExpectedIds.remove(id)) {
- fail("Shouldn't match", id, indexedShapes, queryShape, operation);
+ fail("qIdx:" + queryIdx + " Shouldn't match", id, indexedShapes, queryShape, operation);
}
}
if (!remainingExpectedIds.isEmpty()) {
String id = remainingExpectedIds.iterator().next();
- fail("Should have matched", id, indexedShapes, queryShape, operation);
+ fail("qIdx:" + queryIdx + " Should have matched", id, indexedShapes, queryShape, operation);
}
}
}
diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/Geo3dRptTest.java b/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/Geo3dRptTest.java
new file mode 100644
index 00000000000..450f40b9018
--- /dev/null
+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/Geo3dRptTest.java
@@ -0,0 +1,128 @@
+package org.apache.lucene.spatial.spatial4j;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.carrotsearch.randomizedtesting.annotations.Repeat;
+import com.carrotsearch.randomizedtesting.annotations.Seed;
+import com.spatial4j.core.context.SpatialContext;
+import com.spatial4j.core.distance.DistanceUtils;
+import com.spatial4j.core.shape.Point;
+import com.spatial4j.core.shape.Rectangle;
+import com.spatial4j.core.shape.Shape;
+import com.spatial4j.core.shape.SpatialRelation;
+import org.apache.lucene.spatial.composite.CompositeSpatialStrategy;
+import org.apache.lucene.spatial.prefix.RandomSpatialOpStrategyTestCase;
+import org.apache.lucene.spatial.prefix.RecursivePrefixTreeStrategy;
+import org.apache.lucene.spatial.prefix.tree.GeohashPrefixTree;
+import org.apache.lucene.spatial.prefix.tree.SpatialPrefixTree;
+import org.apache.lucene.spatial.query.SpatialOperation;
+import org.apache.lucene.spatial.serialized.SerializedDVStrategy;
+import org.apache.lucene.spatial.spatial4j.Geo3dShape;
+import org.apache.lucene.spatial.spatial4j.geo3d.GeoPoint;
+import org.apache.lucene.spatial.spatial4j.geo3d.GeoPolygonFactory;
+import org.apache.lucene.spatial.spatial4j.geo3d.GeoShape;
+import org.junit.Test;
+
+import static com.spatial4j.core.distance.DistanceUtils.DEGREES_TO_RADIANS;
+
+public class Geo3dRptTest extends RandomSpatialOpStrategyTestCase {
+
+ private SpatialPrefixTree grid;
+ private RecursivePrefixTreeStrategy rptStrategy;
+ {
+ this.ctx = SpatialContext.GEO;
+ }
+
+ private void setupGeohashGrid() {
+ this.grid = new GeohashPrefixTree(ctx, 2);//A fairly shallow grid
+ this.rptStrategy = newRPT();
+ }
+
+ protected RecursivePrefixTreeStrategy newRPT() {
+ final RecursivePrefixTreeStrategy rpt = new RecursivePrefixTreeStrategy(this.grid,
+ getClass().getSimpleName() + "_rpt");
+ rpt.setDistErrPct(0.10);//not too many cells
+ return rpt;
+ }
+
+ @Override
+ protected boolean needsDocValues() {
+ return true;//due to SerializedDVStrategy
+ }
+
+ private void setupStrategy() {
+ //setup
+ setupGeohashGrid();
+
+ SerializedDVStrategy serializedDVStrategy = new SerializedDVStrategy(ctx, getClass().getSimpleName() + "_sdv");
+ this.strategy = new CompositeSpatialStrategy("composite_" + getClass().getSimpleName(),
+ rptStrategy, serializedDVStrategy);
+ }
+
+ @Test
+ @Repeat(iterations = 20)
+ //Seed("A9C215F48F200BB0")
+ public void testOperations() throws IOException {
+ setupStrategy();
+
+ testOperationRandomShapes(SpatialOperation.Intersects);
+ }
+
+ @Test
+ public void testTriangleDisjointRect2() throws IOException {
+ final Rectangle rect = ctx.makeRectangle(-176, -176, -37, -34);
+ final Shape triangle = makeTriangle(116, 45, 169, 7, 92, -63);
+ //these shouldn't intersect
+ assertEquals(SpatialRelation.DISJOINT, triangle.relate(rect));
+ }
+
+ private Shape makeTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
+ final List<GeoPoint> geoPoints = new ArrayList<>();
+ geoPoints.add(new GeoPoint(y1 * DEGREES_TO_RADIANS, x1 * DEGREES_TO_RADIANS));
+ geoPoints.add(new GeoPoint(y2 * DEGREES_TO_RADIANS, x2 * DEGREES_TO_RADIANS));
+ geoPoints.add(new GeoPoint(y3 * DEGREES_TO_RADIANS, x3 * DEGREES_TO_RADIANS));
+ final int convexPointIndex = 0;
+ final GeoShape shape = GeoPolygonFactory.makeGeoPolygon(geoPoints, convexPointIndex);
+ return new Geo3dShape(shape, ctx);
+ }
+
+ @Override
+ protected Shape randomIndexedShape() {
+ return randomRectangle();
+ }
+
+ @Override
+ protected Shape randomQueryShape() {
+ //random triangle
+ final List<GeoPoint> geoPoints = new ArrayList<>();
+ while (geoPoints.size() < 3) {
+ final Point point = randomPoint();
+ final GeoPoint gPt = new GeoPoint(point.getY() * DEGREES_TO_RADIANS, point.getX() * DEGREES_TO_RADIANS);
+ if (geoPoints.contains(gPt) == false) {
+ geoPoints.add(gPt);
+ }
+ }
+ final int convexPointIndex = random().nextInt(3);
+ final GeoShape shape = GeoPolygonFactory.makeGeoPolygon(geoPoints, convexPointIndex);
+ return new Geo3dShape(shape, ctx);
+ }
+}
diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoBBoxTest.java b/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoBBoxTest.java
new file mode 100755
index 00000000000..ddd39de9abf
--- /dev/null
+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoBBoxTest.java
@@ -0,0 +1,244 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+public class GeoBBoxTest {
+
+
+ @Test
+ public void testBBoxPointWithin() {
+ GeoBBox box;
+ GeoPoint gp;
+ // Standard normal Rect box, not crossing dateline
+ box = GeoBBoxFactory.makeGeoBBox(0.0,-Math.PI * 0.25, -1.0, 1.0);
+ gp = new GeoPoint(-0.1,0.0);
+ assertTrue(box.isWithin(gp));
+ gp = new GeoPoint(0.1,0.0);
+ assertFalse(box.isWithin(gp));
+ gp = new GeoPoint(-Math.PI * 0.5,0.0);
+ assertFalse(box.isWithin(gp));
+ gp = new GeoPoint(-0.1,1.1);
+ assertFalse(box.isWithin(gp));
+ gp = new GeoPoint(-0.1,-1.1);
+ assertFalse(box.isWithin(gp));
+ // Standard normal Rect box, crossing dateline
+ box = GeoBBoxFactory.makeGeoBBox(0.0,-Math.PI * 0.25, Math.PI-1.0, -Math.PI+1.0);
+ gp = new GeoPoint(-0.1,-Math.PI);
+ assertTrue(box.isWithin(gp));
+ gp = new GeoPoint(0.1,-Math.PI);
+ assertFalse(box.isWithin(gp));
+ gp = new GeoPoint(-Math.PI * 0.5,-Math.PI);
+ assertFalse(box.isWithin(gp));
+ gp = new GeoPoint(-0.1,-Math.PI+1.1);
+ assertFalse(box.isWithin(gp));
+ gp = new GeoPoint(-0.1,-Math.PI-1.1);
+ assertFalse(box.isWithin(gp));
+ // Latitude zone rectangle
+ box = GeoBBoxFactory.makeGeoBBox(0.0,-Math.PI * 0.25, -Math.PI, Math.PI);
+ gp = new GeoPoint(-0.1,-Math.PI);
+ assertTrue(box.isWithin(gp));
+ gp = new GeoPoint(0.1,-Math.PI);
+ assertFalse(box.isWithin(gp));
+ gp = new GeoPoint(-Math.PI * 0.5,-Math.PI);
+ assertFalse(box.isWithin(gp));
+ gp = new GeoPoint(-0.1,-Math.PI+1.1);
+ assertTrue(box.isWithin(gp));
+ gp = new GeoPoint(-0.1,-Math.PI-1.1);
+ assertTrue(box.isWithin(gp));
+ // World
+ box = GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5,-Math.PI * 0.5, -Math.PI, Math.PI);
+ gp = new GeoPoint(-0.1,-Math.PI);
+ assertTrue(box.isWithin(gp));
+ gp = new GeoPoint(0.1,-Math.PI);
+ assertTrue(box.isWithin(gp));
+ gp = new GeoPoint(-Math.PI * 0.5,-Math.PI);
+ assertTrue(box.isWithin(gp));
+ gp = new GeoPoint(-0.1,-Math.PI+1.1);
+ assertTrue(box.isWithin(gp));
+ gp = new GeoPoint(-0.1,-Math.PI-1.1);
+ assertTrue(box.isWithin(gp));
+
+ }
+
+ @Test
+ public void testBBoxExpand() {
+ GeoBBox box;
+ GeoPoint gp;
+ // Standard normal Rect box, not crossing dateline
+ box = GeoBBoxFactory.makeGeoBBox(0.0,-Math.PI * 0.25, -1.0, 1.0);
+ box = box.expand(0.1);
+ gp = new GeoPoint(0.05,0.0);
+ assertTrue(box.isWithin(gp));
+ gp = new GeoPoint(0.15,0.0);
+ assertFalse(box.isWithin(gp));
+ gp = new GeoPoint(-Math.PI * 0.25 - 0.05,0.0);
+ assertTrue(box.isWithin(gp));
+ gp = new GeoPoint(-Math.PI * 0.25 - 0.15,0.0);
+ assertFalse(box.isWithin(gp));
+ gp = new GeoPoint(-0.1,-1.05);
+ assertTrue(box.isWithin(gp));
+ gp = new GeoPoint(-0.1,-1.15);
+ assertFalse(box.isWithin(gp));
+ gp = new GeoPoint(-0.1,1.05);
+ assertTrue(box.isWithin(gp));
+ gp = new GeoPoint(-0.1,1.15);
+ assertFalse(box.isWithin(gp));
+ }
+
+ @Test
+ public void testBBoxBounds() {
+ GeoBBox c;
+ Bounds b;
+
+ c = GeoBBoxFactory.makeGeoBBox(0.0,-Math.PI * 0.25, -1.0, 1.0);
+
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(-1.0,b.getLeftLongitude(),0.000001);
+ assertEquals(1.0,b.getRightLongitude(),0.000001);
+ assertEquals(-Math.PI * 0.25,b.getMinLatitude(),0.000001);
+ assertEquals(0.0,b.getMaxLatitude(),0.000001);
+
+ c = GeoBBoxFactory.makeGeoBBox(0.0,-Math.PI * 0.25, 1.0, -1.0);
+
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(1.0,b.getLeftLongitude(),0.000001);
+ assertEquals(-1.0,b.getRightLongitude(),0.000001);
+ assertEquals(-Math.PI * 0.25,b.getMinLatitude(),0.000001);
+ assertEquals(0.0,b.getMaxLatitude(),0.000001);
+
+ c = GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5, -Math.PI * 0.5, -1.0, 1.0);
+
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertTrue(b.checkNoTopLatitudeBound());
+ assertTrue(b.checkNoBottomLatitudeBound());
+ assertEquals(-1.0,b.getLeftLongitude(),0.000001);
+ assertEquals(1.0,b.getRightLongitude(),0.000001);
+
+ c = GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5, -Math.PI * 0.5, 1.0, -1.0);
+
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertTrue(b.checkNoTopLatitudeBound());
+ assertTrue(b.checkNoBottomLatitudeBound());
+ assertEquals(1.0,b.getLeftLongitude(),0.000001);
+ assertEquals(-1.0,b.getRightLongitude(),0.000001);
+
+ // Check wide variants of rectangle and longitude slice
+
+ c = GeoBBoxFactory.makeGeoBBox(0.0,-Math.PI * 0.25, -Math.PI+0.1, Math.PI-0.1);
+
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(-Math.PI+0.1,b.getLeftLongitude(),0.000001);
+ assertEquals(Math.PI-0.1,b.getRightLongitude(),0.000001);
+ assertEquals(-Math.PI * 0.25,b.getMinLatitude(),0.000001);
+ assertEquals(0.0,b.getMaxLatitude(),0.000001);
+
+ c = GeoBBoxFactory.makeGeoBBox(0.0,-Math.PI * 0.25, Math.PI-0.1, -Math.PI+0.1);
+
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(Math.PI-0.1,b.getLeftLongitude(),0.000001);
+ assertEquals(-Math.PI+0.1,b.getRightLongitude(),0.000001);
+ assertEquals(-Math.PI * 0.25,b.getMinLatitude(),0.000001);
+ assertEquals(0.0,b.getMaxLatitude(),0.000001);
+
+ c = GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5, -Math.PI * 0.5, -Math.PI+0.1, Math.PI-0.1);
+
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertTrue(b.checkNoTopLatitudeBound());
+ assertTrue(b.checkNoBottomLatitudeBound());
+ assertEquals(-Math.PI+0.1,b.getLeftLongitude(),0.000001);
+ assertEquals(Math.PI-0.1,b.getRightLongitude(),0.000001);
+
+ c = GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5, -Math.PI * 0.5, Math.PI-0.1, -Math.PI+0.1);
+
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertTrue(b.checkNoTopLatitudeBound());
+ assertTrue(b.checkNoBottomLatitudeBound());
+ assertEquals(Math.PI-0.1,b.getLeftLongitude(),0.000001);
+ assertEquals(-Math.PI+0.1,b.getRightLongitude(),0.000001);
+
+ // Check latitude zone
+ c = GeoBBoxFactory.makeGeoBBox(1.0, -1.0, -Math.PI, Math.PI);
+
+ b = c.getBounds(null);
+ assertTrue(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(-1.0,b.getMinLatitude(),0.000001);
+ assertEquals(1.0,b.getMaxLatitude(),0.000001);
+
+ // Now, combine a few things to test the bounds object
+ GeoBBox c1;
+ GeoBBox c2;
+
+ c1 = GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5, -Math.PI * 0.5, -Math.PI, 0.0);
+ c2 = GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5, -Math.PI * 0.5, 0.0, Math.PI);
+
+ b = new Bounds();
+ b = c1.getBounds(b);
+ b = c2.getBounds(b);
+ assertTrue(b.checkNoLongitudeBound());
+ assertTrue(b.checkNoTopLatitudeBound());
+ assertTrue(b.checkNoBottomLatitudeBound());
+
+ c1 = GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5, -Math.PI * 0.5, -Math.PI, 0.0);
+ c2 = GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5, -Math.PI * 0.5, 0.0, Math.PI*0.5);
+
+ b = new Bounds();
+ b = c1.getBounds(b);
+ b = c2.getBounds(b);
+ assertFalse(b.checkNoLongitudeBound());
+ assertTrue(b.checkNoTopLatitudeBound());
+ assertTrue(b.checkNoBottomLatitudeBound());
+ assertEquals(-Math.PI,b.getLeftLongitude(),0.000001);
+ assertEquals(Math.PI*0.5,b.getRightLongitude(),0.000001);
+
+ c1 = GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5, -Math.PI * 0.5, -Math.PI * 0.5, 0.0);
+ c2 = GeoBBoxFactory.makeGeoBBox(Math.PI * 0.5, -Math.PI * 0.5, 0.0, Math.PI);
+
+ b = new Bounds();
+ b = c1.getBounds(b);
+ b = c2.getBounds(b);
+ assertFalse(b.checkNoLongitudeBound());
+ assertTrue(b.checkNoTopLatitudeBound());
+ assertTrue(b.checkNoBottomLatitudeBound());
+ assertEquals(-Math.PI * 0.5,b.getLeftLongitude(),0.000001);
+ assertEquals(Math.PI,b.getRightLongitude(),0.000001);
+
+ }
+
+}
diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoCircleTest.java b/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoCircleTest.java
new file mode 100755
index 00000000000..a2678d749e7
--- /dev/null
+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoCircleTest.java
@@ -0,0 +1,217 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+public class GeoCircleTest {
+
+
+ @Test
+ public void testCircleDistance() {
+ GeoCircle c;
+ GeoPoint gp;
+ c = new GeoCircle(0.0,-0.5,0.1);
+ gp = new GeoPoint(0.0,0.0);
+ assertEquals(Double.MAX_VALUE, c.computeArcDistance(gp), 0.0);
+ assertEquals(Double.MAX_VALUE, c.computeLinearDistance(gp), 0.0);
+ assertEquals(Double.MAX_VALUE, c.computeNormalDistance(gp), 0.0);
+ gp = new GeoPoint(0.0,-0.5);
+ assertEquals(0.0, c.computeArcDistance(gp), 0.000001);
+ assertEquals(0.0, c.computeLinearDistance(gp), 0.000001);
+ assertEquals(0.0, c.computeNormalDistance(gp), 0.000001);
+ gp = new GeoPoint(0.05,-0.5);
+ assertEquals(0.05, c.computeArcDistance(gp), 0.000001);
+ assertEquals(0.049995, c.computeLinearDistance(gp), 0.000001);
+ assertEquals(0.049979, c.computeNormalDistance(gp), 0.000001);
+ }
+
+ @Test
+ public void testCirclePointWithin() {
+ GeoCircle c;
+ GeoPoint gp;
+ c = new GeoCircle(0.0,-0.5,0.1);
+ gp = new GeoPoint(0.0,0.0);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(0.0,-0.5);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(0.0,-0.55);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(0.0,-0.45);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(Math.PI * 0.5,0.0);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(0.0,Math.PI);
+ assertFalse(c.isWithin(gp));
+ }
+
+ @Test
+ public void testCircleBounds() {
+ GeoCircle c;
+ Bounds b;
+
+
+ // Vertical circle cases
+ c = new GeoCircle(0.0,-0.5,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(-0.6,b.getLeftLongitude(),0.000001);
+ assertEquals(-0.4,b.getRightLongitude(),0.000001);
+ assertEquals(-0.1,b.getMinLatitude(),0.000001);
+ assertEquals(0.1,b.getMaxLatitude(),0.000001);
+ c = new GeoCircle(0.0,0.5,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(0.4,b.getLeftLongitude(),0.000001);
+ assertEquals(0.6,b.getRightLongitude(),0.000001);
+ assertEquals(-0.1,b.getMinLatitude(),0.000001);
+ assertEquals(0.1,b.getMaxLatitude(),0.000001);
+ c = new GeoCircle(0.0,0.0,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(-0.1,b.getLeftLongitude(),0.000001);
+ assertEquals(0.1,b.getRightLongitude(),0.000001);
+ assertEquals(-0.1,b.getMinLatitude(),0.000001);
+ assertEquals(0.1,b.getMaxLatitude(),0.000001);
+ c = new GeoCircle(0.0,Math.PI,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(Math.PI-0.1,b.getLeftLongitude(),0.000001);
+ assertEquals(-Math.PI+0.1,b.getRightLongitude(),0.000001);
+ assertEquals(-0.1,b.getMinLatitude(),0.000001);
+ assertEquals(0.1,b.getMaxLatitude(),0.000001);
+ // Horizontal circle cases
+ c = new GeoCircle(Math.PI * 0.5,0.0,0.1);
+ b = c.getBounds(null);
+ assertTrue(b.checkNoLongitudeBound());
+ assertTrue(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(Math.PI * 0.5 - 0.1,b.getMinLatitude(),0.000001);
+ c = new GeoCircle(-Math.PI * 0.5,0.0,0.1);
+ b = c.getBounds(null);
+ assertTrue(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertTrue(b.checkNoBottomLatitudeBound());
+ assertEquals(-Math.PI * 0.5 + 0.1,b.getMaxLatitude(),0.000001);
+
+ // Now do a somewhat tilted plane, facing different directions.
+ c = new GeoCircle(0.01,0.0,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(0.11,b.getMaxLatitude(),0.000001);
+ assertEquals(-0.09,b.getMinLatitude(),0.000001);
+ assertEquals(-0.1,b.getLeftLongitude(),0.00001);
+ assertEquals(0.1,b.getRightLongitude(),0.00001);
+
+ c = new GeoCircle(0.01,Math.PI,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(0.11,b.getMaxLatitude(),0.000001);
+ assertEquals(-0.09,b.getMinLatitude(),0.000001);
+ assertEquals(Math.PI-0.1,b.getLeftLongitude(),0.00001);
+ assertEquals(-Math.PI+0.1,b.getRightLongitude(),0.00001);
+
+ c = new GeoCircle(0.01,Math.PI * 0.5,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(0.11,b.getMaxLatitude(),0.000001);
+ assertEquals(-0.09,b.getMinLatitude(),0.000001);
+ assertEquals(Math.PI * 0.5 - 0.1,b.getLeftLongitude(),0.00001);
+ assertEquals(Math.PI * 0.5 + 0.1,b.getRightLongitude(),0.00001);
+
+ c = new GeoCircle(0.01,-Math.PI * 0.5,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(0.11,b.getMaxLatitude(),0.000001);
+ assertEquals(-0.09,b.getMinLatitude(),0.000001);
+ assertEquals(-Math.PI * 0.5 - 0.1,b.getLeftLongitude(),0.00001);
+ assertEquals(-Math.PI * 0.5 + 0.1,b.getRightLongitude(),0.00001);
+
+ // Slightly tilted, PI/4 direction.
+ c = new GeoCircle(0.01,Math.PI * 0.25,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(0.11,b.getMaxLatitude(),0.000001);
+ assertEquals(-0.09,b.getMinLatitude(),0.000001);
+ assertEquals(Math.PI * 0.25 - 0.1,b.getLeftLongitude(),0.00001);
+ assertEquals(Math.PI * 0.25 + 0.1,b.getRightLongitude(),0.00001);
+
+ c = new GeoCircle(0.01,-Math.PI * 0.25,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(0.11,b.getMaxLatitude(),0.000001);
+ assertEquals(-0.09,b.getMinLatitude(),0.000001);
+ assertEquals(-Math.PI * 0.25 - 0.1,b.getLeftLongitude(),0.00001);
+ assertEquals(-Math.PI * 0.25 + 0.1,b.getRightLongitude(),0.00001);
+
+ c = new GeoCircle(-0.01,Math.PI * 0.25,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(0.09,b.getMaxLatitude(),0.000001);
+ assertEquals(-0.11,b.getMinLatitude(),0.000001);
+ assertEquals(Math.PI * 0.25 - 0.1,b.getLeftLongitude(),0.00001);
+ assertEquals(Math.PI * 0.25 + 0.1,b.getRightLongitude(),0.00001);
+
+ c = new GeoCircle(-0.01,-Math.PI * 0.25,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(0.09,b.getMaxLatitude(),0.000001);
+ assertEquals(-0.11,b.getMinLatitude(),0.000001);
+ assertEquals(-Math.PI * 0.25 - 0.1,b.getLeftLongitude(),0.00001);
+ assertEquals(-Math.PI * 0.25 + 0.1,b.getRightLongitude(),0.00001);
+
+ // Now do a somewhat tilted plane.
+ c = new GeoCircle(0.01,-0.5,0.1);
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(0.11,b.getMaxLatitude(),0.000001);
+ assertEquals(-0.09,b.getMinLatitude(),0.000001);
+ assertEquals(-0.6,b.getLeftLongitude(),0.00001);
+ assertEquals(-0.4,b.getRightLongitude(),0.00001);
+
+ }
+
+}
diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoConvexPolygonTest.java b/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoConvexPolygonTest.java
new file mode 100755
index 00000000000..9b551da5b9b
--- /dev/null
+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoConvexPolygonTest.java
@@ -0,0 +1,86 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+public class GeoConvexPolygonTest {
+
+
+ @Test
+ public void testPolygonPointWithin() {
+ GeoConvexPolygon c;
+ GeoPoint gp;
+ c = new GeoConvexPolygon(-0.1,-0.5);
+ c.addPoint(0.0,-0.6);
+ c.addPoint(0.1,-0.5);
+ c.addPoint(0.0,-0.4);
+ c.donePoints();
+ // Sample some points within
+ gp = new GeoPoint(0.0,-0.5);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(0.0,-0.55);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(0.0,-0.45);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(-0.05,-0.5);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(0.05,-0.5);
+ assertTrue(c.isWithin(gp));
+ // Sample some nearby points outside
+ gp = new GeoPoint(0.0,-0.65);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(0.0,-0.35);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(-0.15,-0.5);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(0.15,-0.5);
+ assertFalse(c.isWithin(gp));
+ // Random points outside
+ gp = new GeoPoint(0.0,0.0);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(Math.PI * 0.5,0.0);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(0.0,Math.PI);
+ assertFalse(c.isWithin(gp));
+ }
+
+ @Test
+ public void testPolygonBounds() {
+ GeoConvexPolygon c;
+ Bounds b;
+
+ c = new GeoConvexPolygon(-0.1,-0.5);
+ c.addPoint(0.0,-0.6);
+ c.addPoint(0.1,-0.5);
+ c.addPoint(0.0,-0.4);
+ c.donePoints();
+
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(-0.6,b.getLeftLongitude(),0.000001);
+ assertEquals(-0.4,b.getRightLongitude(),0.000001);
+ assertEquals(-0.1,b.getMinLatitude(),0.000001);
+ assertEquals(0.1,b.getMaxLatitude(),0.000001);
+ }
+
+}
diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoPathTest.java b/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoPathTest.java
new file mode 100755
index 00000000000..0e1610bf42a
--- /dev/null
+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoPathTest.java
@@ -0,0 +1,175 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+public class GeoPathTest {
+
+ @Test
+ public void testPathDistance() {
+ // Start with a really simple case
+ GeoPath p;
+ GeoPoint gp;
+ p = new GeoPath(0.1);
+ p.addPoint(0.0,0.0);
+ p.addPoint(0.0,0.1);
+ p.addPoint(0.0,0.2);
+ gp = new GeoPoint(Math.PI * 0.5,0.15);
+ assertEquals(Double.MAX_VALUE, p.computeArcDistance(gp), 0.0);
+ gp = new GeoPoint(0.05,0.15);
+ assertEquals(0.15 + 0.05, p.computeArcDistance(gp), 0.000001);
+ gp = new GeoPoint(0.0,0.12);
+ assertEquals(0.12 + 0.0, p.computeArcDistance(gp), 0.000001);
+ gp = new GeoPoint(-0.15,0.05);
+ assertEquals(Double.MAX_VALUE, p.computeArcDistance(gp), 0.000001);
+ gp = new GeoPoint(0.0,0.25);
+ assertEquals(0.20 + 0.05, p.computeArcDistance(gp), 0.000001);
+ gp = new GeoPoint(0.0,-0.05);
+ assertEquals(0.0 + 0.05, p.computeArcDistance(gp), 0.000001);
+
+ // Compute path distances now
+ p = new GeoPath(0.1);
+ p.addPoint(0.0,0.0);
+ p.addPoint(0.0,0.1);
+ p.addPoint(0.0,0.2);
+ gp = new GeoPoint(0.05,0.15);
+ assertEquals(0.15 + 0.05, p.computeArcDistance(gp), 0.000001);
+ gp = new GeoPoint(0.0,0.12);
+ assertEquals(0.12, p.computeArcDistance(gp), 0.000001);
+
+ // Now try a vertical path, and make sure distances are as expected
+ p = new GeoPath(0.1);
+ p.addPoint(-Math.PI * 0.25,-0.5);
+ p.addPoint(Math.PI * 0.25,-0.5);
+ gp = new GeoPoint(0.0,0.0);
+ assertEquals(Double.MAX_VALUE, p.computeArcDistance(gp), 0.0);
+ gp = new GeoPoint(-0.1,-1.0);
+ assertEquals(Double.MAX_VALUE, p.computeArcDistance(gp), 0.0);
+ gp = new GeoPoint(Math.PI*0.25+0.05,-0.5);
+ assertEquals(Math.PI * 0.5 + 0.05, p.computeArcDistance(gp), 0.000001);
+ gp = new GeoPoint(-Math.PI*0.25-0.05,-0.5);
+ assertEquals(0.0 + 0.05, p.computeArcDistance(gp), 0.000001);
+ }
+
+ @Test
+ public void testPathPointWithin() {
+ // Tests whether we can properly detect whether a point is within a path or not
+ GeoPath p;
+ GeoPoint gp;
+ p = new GeoPath(0.1);
+ // Build a diagonal path crossing the equator
+ p.addPoint(-0.2,-0.2);
+ p.addPoint(0.2,0.2);
+ // Test points on the path
+ gp = new GeoPoint(-0.2,-0.2);
+ assertTrue(p.isWithin(gp));
+ gp = new GeoPoint(0.0,0.0);
+ assertTrue(p.isWithin(gp));
+ gp = new GeoPoint(0.1,0.1);
+ assertTrue(p.isWithin(gp));
+ // Test points off the path
+ gp = new GeoPoint(-0.2,0.2);
+ assertFalse(p.isWithin(gp));
+ gp = new GeoPoint(-Math.PI*0.5,0.0);
+ assertFalse(p.isWithin(gp));
+ gp = new GeoPoint(0.2,-0.2);
+ assertFalse(p.isWithin(gp));
+ gp = new GeoPoint(0.0,Math.PI);
+ assertFalse(p.isWithin(gp));
+ // Repeat the test, but across the terminator
+ p = new GeoPath(0.1);
+ // Build a diagonal path crossing the equator
+ p.addPoint(-0.2,Math.PI-0.2);
+ p.addPoint(0.2,-Math.PI+0.2);
+ // Test points on the path
+ gp = new GeoPoint(-0.2,Math.PI-0.2);
+ assertTrue(p.isWithin(gp));
+ gp = new GeoPoint(0.0,Math.PI);
+ assertTrue(p.isWithin(gp));
+ gp = new GeoPoint(0.1,-Math.PI+0.1);
+ assertTrue(p.isWithin(gp));
+ // Test points off the path
+ gp = new GeoPoint(-0.2,-Math.PI+0.2);
+ assertFalse(p.isWithin(gp));
+ gp = new GeoPoint(-Math.PI*0.5,0.0);
+ assertFalse(p.isWithin(gp));
+ gp = new GeoPoint(0.2,Math.PI-0.2);
+ assertFalse(p.isWithin(gp));
+ gp = new GeoPoint(0.0,0.0);
+ assertFalse(p.isWithin(gp));
+
+ }
+
+ @Test
+ public void testGetRelationship() {
+ GeoArea rect;
+ GeoPath p;
+
+ // Start by testing the basic kinds of relationship, increasing in order of difficulty.
+
+ p = new GeoPath(0.1);
+ p.addPoint(-0.3,-0.3);
+ p.addPoint(0.3,0.3);
+ // Easiest: The path is wholly contains the georect
+ rect = new GeoRectangle(0.05,-0.05,-0.05,0.05);
+ assertEquals(GeoArea.CONTAINS, rect.getRelationship(p));
+ // Next easiest: Some endpoints of the rectangle are inside, and some are outside.
+ rect = new GeoRectangle(0.05,-0.05,-0.05,0.5);
+ assertEquals(GeoArea.OVERLAPS, rect.getRelationship(p));
+ // Now, all points are outside, but the figures intersect
+ rect = new GeoRectangle(0.05,-0.05,-0.5,0.5);
+ assertEquals(GeoArea.OVERLAPS, rect.getRelationship(p));
+ // Finally, all points are outside, and the figures *do not* intersect
+ rect = new GeoRectangle(0.5,-0.5,-0.5,0.5);
+ assertEquals(GeoArea.WITHIN, rect.getRelationship(p));
+ // Check that segment edge overlap detection works
+ rect = new GeoRectangle(0.1,0.0,-0.1,0.0);
+ assertEquals(GeoArea.OVERLAPS, rect.getRelationship(p));
+ rect = new GeoRectangle(0.2,0.1,-0.2,-0.1);
+ assertEquals(GeoArea.DISJOINT, rect.getRelationship(p));
+ // Check if overlap at endpoints behaves as expected next
+ rect = new GeoRectangle(0.5,-0.5,-0.5,-0.35);
+ assertEquals(GeoArea.OVERLAPS, rect.getRelationship(p));
+ rect = new GeoRectangle(0.5,-0.5,-0.5,-0.45);
+ assertEquals(GeoArea.DISJOINT, rect.getRelationship(p));
+
+ }
+
+ @Test
+ public void testPathBounds() {
+ GeoPath c;
+ Bounds b;
+
+ c = new GeoPath(0.1);
+ c.addPoint(-0.3,-0.3);
+ c.addPoint(0.3,0.3);
+
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(-0.4046919,b.getLeftLongitude(),0.000001);
+ assertEquals(0.4046919,b.getRightLongitude(),0.000001);
+ assertEquals(-0.3999999,b.getMinLatitude(),0.000001);
+ assertEquals(0.3999999,b.getMaxLatitude(),0.000001);
+ }
+
+}
diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoPolygonTest.java b/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoPolygonTest.java
new file mode 100755
index 00000000000..621271a4f0d
--- /dev/null
+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/spatial4j/geo3d/GeoPolygonTest.java
@@ -0,0 +1,142 @@
+package org.apache.lucene.spatial.spatial4j.geo3d;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.util.*;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+public class GeoPolygonTest {
+
+
+ @Test
+ public void testPolygonPointWithin() {
+ GeoMembershipShape c;
+ GeoPoint gp;
+ List<GeoPoint> points;
+
+ points = new ArrayList<GeoPoint>();
+ points.add(new GeoPoint(-0.1,-0.5));
+ points.add(new GeoPoint(0.0,-0.6));
+ points.add(new GeoPoint(0.1,-0.5));
+ points.add(new GeoPoint(0.0,-0.4));
+
+ c = GeoPolygonFactory.makeGeoPolygon(points,0);
+ // Sample some points within
+ gp = new GeoPoint(0.0,-0.5);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(0.0,-0.55);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(0.0,-0.45);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(-0.05,-0.5);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(0.05,-0.5);
+ assertTrue(c.isWithin(gp));
+ // Sample some nearby points outside
+ gp = new GeoPoint(0.0,-0.65);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(0.0,-0.35);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(-0.15,-0.5);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(0.15,-0.5);
+ assertFalse(c.isWithin(gp));
+ // Random points outside
+ gp = new GeoPoint(0.0,0.0);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(Math.PI * 0.5,0.0);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(0.0,Math.PI);
+ assertFalse(c.isWithin(gp));
+
+ points = new ArrayList<GeoPoint>();
+ points.add(new GeoPoint(-0.1,-0.5));
+ points.add(new GeoPoint(-0.01,-0.6));
+ points.add(new GeoPoint(-0.1,-0.7));
+ points.add(new GeoPoint(0.0,-0.8));
+ points.add(new GeoPoint(0.1,-0.7));
+ points.add(new GeoPoint(0.01,-0.6));
+ points.add(new GeoPoint(0.1,-0.5));
+ points.add(new GeoPoint(0.0,-0.4));
+
+ /*
+ System.out.println("Points: ");
+ for (GeoPoint p : points) {
+ System.out.println(" "+p);
+ }
+ */
+
+ c = GeoPolygonFactory.makeGeoPolygon(points,0);
+ // Sample some points within
+ gp = new GeoPoint(0.0,-0.5);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(0.0,-0.55);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(0.0,-0.45);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(-0.05,-0.5);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(0.05,-0.5);
+ assertTrue(c.isWithin(gp));
+ gp = new GeoPoint(0.0,-0.7);
+ assertTrue(c.isWithin(gp));
+ // Sample some nearby points outside
+ gp = new GeoPoint(0.0,-0.35);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(-0.15,-0.5);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(0.15,-0.5);
+ assertFalse(c.isWithin(gp));
+ // Random points outside
+ gp = new GeoPoint(0.0,0.0);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(Math.PI * 0.5,0.0);
+ assertFalse(c.isWithin(gp));
+ gp = new GeoPoint(0.0,Math.PI);
+ assertFalse(c.isWithin(gp));
+
+ }
+
+ @Test
+ public void testPolygonBounds() {
+ GeoMembershipShape c;
+ Bounds b;
+ List<GeoPoint> points;
+
+ points = new ArrayList<GeoPoint>();
+ points.add(new GeoPoint(-0.1,-0.5));
+ points.add(new GeoPoint(0.0,-0.6));
+ points.add(new GeoPoint(0.1,-0.5));
+ points.add(new GeoPoint(0.0,-0.4));
+
+ c = GeoPolygonFactory.makeGeoPolygon(points,0);
+
+ b = c.getBounds(null);
+ assertFalse(b.checkNoLongitudeBound());
+ assertFalse(b.checkNoTopLatitudeBound());
+ assertFalse(b.checkNoBottomLatitudeBound());
+ assertEquals(-0.6,b.getLeftLongitude(),0.000001);
+ assertEquals(-0.4,b.getRightLongitude(),0.000001);
+ assertEquals(-0.1,b.getMinLatitude(),0.000001);
+ assertEquals(0.1,b.getMaxLatitude(),0.000001);
+ }
+
+}