This is an automated email from the ASF dual-hosted git repository. asf-gitbox-commits pushed a commit to branch geoapi-4.0 in repository https://gitbox.apache.org/repos/asf/sis.git
commit 461ae178e40ff61acdfcf85979d7f2321783708c Author: jsorel <[email protected]> AuthorDate: Tue Dec 1 17:28:21 2026 +0100 feat(Geometry): add collision between solids --- .../main/org/apache/sis/geometries/Geometry.java | 24 + .../apache/sis/geometries/operation/Collision.java | 531 +++++++++++++++++++++ .../geometries/operation/GeometryProcessor.java | 26 + .../apache/sis/geometries/operation/Nearest.java | 115 ++++- .../sis/geometries/operation/CollisionTest.java | 222 +++++++++ 5 files changed, 902 insertions(+), 16 deletions(-) diff --git a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/Geometry.java b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/Geometry.java index 06b2c1ac3e..102ec45dd4 100644 --- a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/Geometry.java +++ b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/Geometry.java @@ -17,6 +17,7 @@ package org.apache.sis.geometries; import java.util.Map; +import java.util.Optional; import javax.measure.Quantity; import static org.opengis.annotation.Specification.ISO_19107; import org.opengis.annotation.UML; @@ -28,6 +29,7 @@ import org.apache.sis.geometries.adapter.WellKnownBinary; import org.apache.sis.geometries.adapter.WellKnownText; import org.apache.sis.geometries.internal.shared.AbstractGeometry; import org.apache.sis.geometries.mesh.MeshPrimitive; +import org.apache.sis.geometries.operation.Collision; import org.apache.sis.geometries.operation.GeometryProcessor; import org.apache.sis.geometries.operation.OperationException; import org.apache.sis.measure.Quantities; @@ -756,6 +758,28 @@ public sealed interface Geometry return new GeometryProcessor().signedDistance(this, other); } + /** + * Returns the contact between this geometry and the given geometry, as in collision detection: + * the contact point, the normal going from this geometry to the other one, and the depth of their overlap. + * Moving the other geometry by the depth along the normal separates the two geometries. + * + * <p>Constraints:</p> + * <ul> + * <li>A geometry enclosing a volume, such as a sphere, a capsule or a box, is seen as the solid it encloses, + * and a hyperplane as the half-space opposite to its normal.</li> + * <li>Empty if the geometries are apart or if either geometry is empty.</li> + * </ul> + * + * @param other the geometry to test for contact. + * @return contact between the two geometries, or an empty value if they are apart. + * @throws OperationException if the contact cannot be computed. + * + * @see GeometryProcessor#collide(org.apache.sis.geometries.Geometry, org.apache.sis.geometries.Geometry) + */ + default Optional<Collision.Contact> collide(Geometry other) throws OperationException { + return new GeometryProcessor().collide(this, other); + } + /** * Returns the set-theoretic intersection of this geometry and the given geometry. * diff --git a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/Collision.java b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/Collision.java new file mode 100644 index 0000000000..8e331a738e --- /dev/null +++ b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/Collision.java @@ -0,0 +1,531 @@ +/* + * 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. + */ +package org.apache.sis.geometries.operation; + +import java.util.List; +import java.util.Optional; +import java.util.function.DoubleUnaryOperator; +import java.util.function.ToDoubleFunction; +import org.apache.sis.geometries.Geometry; +import org.apache.sis.maths.DataType; +import org.apache.sis.maths.Vector; + + +/** + * Contacts between the solids enclosed by geometries, as in collision detection. + * + * <ul> + * <li>The geometries are seen as solids as in {@link Distance#nearestSolids(Geometry, Geometry)}.</li> + * <li>The deepest corners of a box, or the deepest part of a capsule axis lying on a box, are averaged when they + * are within a small ratio of the solid size from each other. This keeps a box or a capsule lying flat from + * being pushed on a single corner.</li> + * </ul> + * + * @author Johann Sorel (Geomatys) + * + * @see "Christer Ericson, Real-Time Collision Detection, chapters 4 and 5" + */ +public final class Collision { + /** + * Depth difference, relative to the solid size, below which several contact points are averaged. + */ + private static final double FLATNESS = 1E-3; + + /** + * Ratio by which the overlap along the cross product of two edges must be smaller than the overlap + * along a face normal to be selected, so that boxes resting on a face are pushed along its normal. + */ + private static final double EDGE_PREFERENCE = 0.95; + + /** + * Distances below this ratio of the solid sizes are considered zero. + */ + private static final double EPSILON = 1E-12; + + /** + * Squared sine of the angle below which two capsule axes are parallel. + */ + private static final double PARALLEL = 1E-6; + + /** + * Number of iterations of the bisections, enough to reach the precision of double values. + */ + private static final int BISECTION_ITERATIONS = 60; + + /** + * Contact between two solids. + * + * <ul> + * <li>The normal is a unit vector going from the first solid to the second: + * moving the second solid by the depth along the normal separates them.</li> + * <li>The depth is zero for solids touching without overlap, it is never negative.</li> + * <li>The point is halfway between the deepest points of the two solids.</li> + * </ul> + * + * @param point the contact point. + * @param normal unit direction from the first solid to the second. + * @param depth depth of the overlap, zero or positive. + */ + public record Contact(Vector<?> point, Vector<?> normal, double depth) { + /** + * Returns the same contact seen from the second solid. + * + * @return the contact with the normal reversed. + */ + public Contact reverse() { + return new Contact(point, normal.negate(), depth); + } + } + + private Collision() { + } + + /** + * Returns the contact between the solids enclosed by two geometries. + * + * <ul> + * <li>Each geometry may be a point, a sphere, a capsule, a box, a hyperplane or a plane, but not both planes. + * A hyperplane is the half-space on the side opposite to its normal. A plane is a sheet without side, + * which pushes the other solid toward the side where most of it is.</li> + * <li>Two solids without preferred direction, for example two spheres of the same center, + * are pushed apart along the last axis.</li> + * <li>The depth may be underestimated in the cases listed by {@link Distance#signedDistance(Geometry, Geometry)}.</li> + * </ul> + * + * @param first the first geometry. + * @param second the second geometry, in the reference system of the first one. + * @return the contact, or an empty value if the solids are apart. + * @throws OperationException if the geometries are not in the same reference system. + * @throws UnsupportedOperationException if a geometry type, or a pair of planes, is not supported. + */ + public static Optional<Contact> contact(final Geometry first, final Geometry second) { + ProcessorUtils.ensureSameCRS(first, second); + final Nearest a = Nearest.of(first); + final Nearest b = Nearest.of(second); + if (isPlane(a)) { + if (isPlane(b)) { + throw new UnsupportedOperationException("The contact between two planes is not supported."); + } + return withPlane(a, b); + } + if (isPlane(b)) { + return withPlane(b, a).map(Contact::reverse); + } + if (b instanceof Nearest.Balls balls) { + return withBalls(a, balls); + } + if (a instanceof Nearest.Balls balls) { + return withBalls(b, balls).map(Contact::reverse); + } + return withBox((Nearest.Box) a, (Nearest.Box) b); + } + + /** + * Returns whether the given solid is a half-space or a sheet. + */ + private static boolean isPlane(final Nearest solid) { + return solid instanceof Nearest.HalfSpace || solid instanceof Nearest.Sheet; + } + + /** + * Returns the contact between a half-space or a sheet and a solid which is not a plane. + * The solid reaches the farthest along any direction with the balls at the two ends of its axis, + * or with the corners of a box, which are tested as spheres of radius zero. + */ + private static Optional<Contact> withPlane(final Nearest plane, final Nearest solid) { + final List<Vector<?>> centers; + final double[] radii; + final double size; + switch (solid) { + case Nearest.Balls cdt -> { + centers = List.of(cdt.start(), cdt.end()); + radii = new double[] {cdt.startRadius(), cdt.endRadius()}; + size = Math.max(cdt.startRadius(), cdt.endRadius()) + cdt.start().distance(cdt.end()); + } + case Nearest.Box cdt -> { + centers = cdt.corners(); + radii = new double[centers.size()]; + size = Vector.of(cdt.halfSizes()).length(); + } + default -> throw new AssertionError(solid); + } + final Vector<?> boundaryNormal; + final ToDoubleFunction<Vector<?>> offset; + switch (plane) { + case Nearest.HalfSpace cdt -> { + boundaryNormal = cdt.plane().getNormal(); + offset = cdt::signedDistance; + } + case Nearest.Sheet cdt -> { + boundaryNormal = cdt.plane().getNormal(); + offset = cdt::offset; + } + default -> throw new AssertionError(plane); + } + double side = 1; + if (plane instanceof Nearest.Sheet) { + // Push the solid toward the side where most of it is, which is the shortest move. + double lowest = Double.POSITIVE_INFINITY; + double highest = Double.NEGATIVE_INFINITY; + for (int i = 0; i < radii.length; i++) { + final double distance = offset.applyAsDouble(centers.get(i)); + lowest = Math.min(lowest, distance - radii[i]); + highest = Math.max(highest, distance + radii[i]); + } + if (highest < -lowest) { + side = -1; + } + } + final Vector<?> normal = boundaryNormal.copy(DataType.DOUBLE).normalize().scale(side); + final double[] depths = new double[radii.length]; + double depth = Double.NEGATIVE_INFINITY; + for (int i = 0; i < depths.length; i++) { + depths[i] = radii[i] - side * offset.applyAsDouble(centers.get(i)); + depth = Math.max(depth, depths[i]); + } + if (depth < 0) { + return Optional.empty(); + } + final double threshold = depth - FLATNESS * size; + Vector<?> sum = null; + int count = 0; + for (int i = 0; i < depths.length; i++) { + if (depths[i] >= threshold) { + // Halfway between the deepest point of the sphere and the boundary of the plane. + final Vector<?> point = centers.get(i).copy(DataType.DOUBLE).combine(1, normal, depths[i] / 2 - radii[i]); + sum = (sum == null) ? point : sum.add(point); + count++; + } + } + return Optional.of(new Contact(sum.scale(1.0 / count), normal, depth)); + } + + /** + * Returns the contact between a solid, which is balls or a box, and balls interpolated along an axis. + * The depth is the one of the ball reaching the deepest into the solid. The contact is measured + * on the middle ball of the part of the axis lying flat on a box or facing a parallel capsule, + * otherwise on the ball nearest to the solid. + * + * @param solid the first solid, from which the normal goes. + * @param balls the second solid. + */ + private static Optional<Contact> withBalls(final Nearest solid, final Nearest.Balls balls) { + final double deepest = balls.deepest(solid::signedDistance); + final double distance = solid.signedDistance(balls.center(deepest)) - balls.radius(deepest); + if (distance > 0) { + return Optional.empty(); + } + final double t = (solid instanceof Nearest.Balls other) ? facing(other, balls, deepest) : flatMiddle(solid, balls, deepest, distance); + final Vector<?> center = balls.center(t); + final Vector<?> normal = outward(solid, center, balls); + final Vector<?> onSolid = center.combine(1, normal, -solid.signedDistance(center)); + final Vector<?> onBalls = center.combine(1, normal, -balls.radius(t)); + return Optional.of(new Contact(onSolid.lerp(onBalls, 0.5), normal, -distance)); + } + + /** + * Returns the middle of the part of the axis whose balls reach almost as deep into a box as the deepest one, + * which is the whole axis of a capsule lying flat on a face. + * + * @param box the box. + * @param balls the balls in contact with the box. + * @param deepest ratio of the ball reaching the deepest into the box. + * @param distance signed distance between that ball and the box. + * @return ratio of the ball in the middle of the flat part. + */ + private static double flatMiddle(final Nearest box, final Nearest.Balls balls, final double deepest, final double distance) { + if (balls.isBall()) { + return deepest; + } + final double size = Math.max(balls.startRadius(), balls.endRadius()) + balls.start().distance(balls.end()); + final double threshold = distance + FLATNESS * size; + final DoubleUnaryOperator function = (t) -> box.signedDistance(balls.center(t)) - balls.radius(t); + return (boundary(function, deepest, 0, threshold) + boundary(function, deepest, 1, threshold)) / 2; + } + + /** + * Searches by bisection the ratio where a convex function rises above a threshold. + * + * @param function the convex function. + * @param below a ratio where the function is below the threshold. + * @param above a ratio where the function may be above the threshold. + * @param threshold the threshold. + * @return the last ratio before the function rises above the threshold. + */ + private static double boundary(final DoubleUnaryOperator function, final double below, final double above, final double threshold) { + if (function.applyAsDouble(above) <= threshold) { + return above; + } + double in = below; + double out = above; + for (int i = 0; i < BISECTION_ITERATIONS; i++) { + final double middle = (in + out) / 2; + if (function.applyAsDouble(middle) <= threshold) { + in = middle; + } else { + out = middle; + } + } + return in; + } + + /** + * Returns the ratio on the axis of balls of their contact with other balls: the ball nearest to a sphere, + * the middle of the part facing a parallel capsule, or the point nearest to the axis of a capsule. + * Capsules of different end radii use the ball reaching the deepest. + * + * @param other the other balls. + * @param balls the balls on which to measure the contact. + * @param deepest ratio of the ball reaching the deepest into the other balls. + * @return ratio of the ball of the contact. + */ + private static double facing(final Nearest.Balls other, final Nearest.Balls balls, final double deepest) { + if (balls.isBall()) { + return 0; + } + if (other.isBall()) { + return balls.nearestRatio(other.start()); + } + if (balls.startRadius() != balls.endRadius() || other.startRadius() != other.endRadius()) { + return deepest; + } + final Vector<?> axis = balls.end().copy(DataType.DOUBLE).subtract(balls.start()); + final Vector<?> otherAxis = other.end().copy(DataType.DOUBLE).subtract(other.start()); + if (isParallel(axis, otherAxis)) { + // Ratios on the other axis of the projections of the two ends of the balls axis. + final double l2 = otherAxis.lengthSquare(); + final double s0 = balls.start().copy(DataType.DOUBLE).subtract(other.start()).dot(otherAxis) / l2; + final double s1 = balls.end() .copy(DataType.DOUBLE).subtract(other.start()).dot(otherAxis) / l2; + if (s1 != s0) { + final double t0 = -s0 / (s1 - s0); + final double t1 = (1 - s0) / (s1 - s0); + final double low = Math.max(0, Math.min(t0, t1)); + final double high = Math.min(1, Math.max(t0, t1)); + if (low <= high) { + return (low + high) / 2; + } + } + } + final int dimension = axis.getDimension(); + final double[] ratios = new double[2]; + Distance.distanceSquare(balls.start().toArrayDouble(), balls.end().toArrayDouble(), new double[dimension], + other.start().toArrayDouble(), other.end().toArrayDouble(), new double[dimension], + ratios, EPSILON); + return ratios[0]; + } + + /** + * Returns whether two directions are parallel, or one of them is zero. + */ + private static boolean isParallel(final Vector<?> a, final Vector<?> b) { + final double dot = a.dot(b); + return dot * dot >= (1 - PARALLEL) * a.lengthSquare() * b.lengthSquare(); + } + + /** + * Returns the unit direction in which a position moves away from a solid the fastest, + * which is the direction of the gradient of its signed distance. + * + * @param solid balls or a box. + * @param position the position, usually the center of a ball of the other solid. + * @param balls the other solid, used when the solid gives no direction. + * @return unit direction from the solid toward the position. + */ + private static Vector<?> outward(final Nearest solid, final Vector<?> position, final Nearest.Balls balls) { + switch (solid) { + case Nearest.Box box -> { + final Vector<?> away = position.copy(DataType.DOUBLE).subtract(box.nearest(position)); + final double length = away.length(); + if (length > EPSILON * Vector.of(box.halfSizes()).length()) { + return away.scale(1 / length); + } + // Inside the box: through the nearest face. + final double[] local = box.local(position); + int face = 0; + double gap = Double.POSITIVE_INFINITY; + for (int k = 0; k < local.length; k++) { + final double g = box.halfSizes()[k] - Math.abs(local[k]); + if (g < gap) { + gap = g; + face = k; + } + } + final Vector<?> axis = box.axes()[face].copy(DataType.DOUBLE); + return (local[face] < 0) ? axis.negate() : axis; + } + case Nearest.Balls other -> { + final Vector<?> away = position.copy(DataType.DOUBLE).subtract(other.center(other.nearestRatio(position))); + final double length = away.length(); + final double size = Math.max(other.startRadius(), other.endRadius()) + Math.max(balls.startRadius(), balls.endRadius()); + if (length > EPSILON * size) { + return away.scale(1 / length); + } + return crossing(other, balls); + } + default -> throw new AssertionError(solid); + } + } + + /** + * Returns a direction for balls whose axis meets the axis of other balls: the common perpendicular + * of the two axes, or a perpendicular to the axes if they are parallel, or the last axis for two spheres. + * + * @param other the first balls, from which the direction goes. + * @param balls the second balls. + * @return unit direction from the first balls toward the second. + */ + private static Vector<?> crossing(final Nearest.Balls other, final Nearest.Balls balls) { + final Vector<?> axis = balls.end().copy(DataType.DOUBLE).subtract(balls.start()); + final Vector<?> otherAxis = other.end().copy(DataType.DOUBLE).subtract(other.start()); + final int dimension = axis.getDimension(); + if (dimension == 3) { + if (!isParallel(otherAxis, axis)) { + final Vector<?> cross = otherAxis.cross(axis); + final Vector<?> between = balls.center(0.5).subtract(other.center(0.5)); + final double sign = (between.dot(cross) < 0) ? -1 : 1; + return cross.scale(sign / cross.length()); + } + final Vector<?> reference = (otherAxis.lengthSquare() != 0) ? otherAxis : axis; + if (reference.lengthSquare() != 0) { + return perpendicular(reference); + } + } + final double[] last = new double[dimension]; + last[dimension - 1] = 1; + return Vector.of(last); + } + + /** + * Returns a unit vector perpendicular to the given vector in 3 dimensions, made with the axis + * of the coordinate system the least aligned with the vector. + */ + private static Vector<?> perpendicular(final Vector<?> vector) { + final double x = Math.abs(vector.get(0)); + final double y = Math.abs(vector.get(1)); + final double z = Math.abs(vector.get(2)); + final Vector<?> reference = (x <= y && x <= z) ? Vector.of(1.0, 0.0, 0.0) + : (y <= z) ? Vector.of(0.0, 1.0, 0.0) + : Vector.of(0.0, 0.0, 1.0); + return vector.cross(reference).normalize(); + } + + /** + * Returns the contact between two boxes, along the separating axis of the smallest overlap. + * The face normals are preferred to the cross products of edges of nearly equal overlap. + */ + private static Optional<Contact> withBox(final Nearest.Box box, final Nearest.Box other) { + Nearest.Box.SeparatingAxis best = null; + double smallest = Double.POSITIVE_INFINITY; + for (final Nearest.Box.SeparatingAxis axis : box.separatingAxes(other)) { + final double overlap = box.overlap(other, axis); + if (overlap < 0) { + return Optional.empty(); + } + if (overlap < (axis.isEdges() ? smallest * EDGE_PREFERENCE : smallest)) { + smallest = overlap; + best = axis; + } + } + final Vector<?> between = other.center().copy(DataType.DOUBLE).subtract(box.center()); + Vector<?> normal = best.direction().copy(DataType.DOUBLE); + if (between.dot(normal) < 0) { + normal = normal.negate(); + } + final Vector<?> point; + if (best.isEdges()) { + point = edgeContact(box, other, best.axis(), best.otherAxis(), normal); + } else if (best.axis() >= 0) { + point = faceContact(box, other, best.axis(), normal); + } else { + point = faceContact(other, box, best.otherAxis(), normal.negate()); + } + return Optional.of(new Contact(point, normal, smallest)); + } + + /** + * Returns the contact point of a box sinking into a face of another box. + * The incident corners within the flatness tolerance of the deepest one are kept inside the face and averaged. + * + * @param reference the box of the face. + * @param incident the box sinking into the face. + * @param face index of the axis of the reference box normal to the face. + * @param normal outward unit normal of the face. + * @return the contact point. + */ + private static Vector<?> faceContact(final Nearest.Box reference, final Nearest.Box incident, final int face, final Vector<?> normal) { + final List<Vector<?>> corners = incident.corners(); + final double[] depths = new double[corners.size()]; + double deepest = Double.NEGATIVE_INFINITY; + for (int i = 0; i < depths.length; i++) { + depths[i] = reference.halfSizes()[face] - corners.get(i).copy(DataType.DOUBLE).subtract(reference.center()).dot(normal); + deepest = Math.max(deepest, depths[i]); + } + final double threshold = deepest - FLATNESS * Vector.of(incident.halfSizes()).length(); + Vector<?> sum = null; + int count = 0; + for (int i = 0; i < depths.length; i++) { + if (depths[i] >= threshold) { + final double[] local = reference.local(corners.get(i)); + for (int k = 0; k < local.length; k++) { + if (k != face) { + local[k] = Math.clamp(local[k], -reference.halfSizes()[k], reference.halfSizes()[k]); + } + } + final Vector<?> point = reference.world(local).combine(1, normal, depths[i] / 2); + sum = (sum == null) ? point : sum.add(point); + count++; + } + } + return sum.scale(1.0 / count); + } + + /** + * Returns the contact point of two crossing edges, which is the middle of their nearest points. + * + * @param box the first box. + * @param other the second box. + * @param edge index of the axis of the first box parallel to its edge. + * @param otherEdge index of the axis of the second box parallel to its edge. + * @param normal unit direction from the first box to the second box. + * @return the contact point. + */ + private static Vector<?> edgeContact(final Nearest.Box box, final Nearest.Box other, final int edge, final int otherEdge, + final Vector<?> normal) + { + final double[][] segment = supportEdge(box, edge, normal); + final double[][] otherSegment = supportEdge(other, otherEdge, normal.negate()); + final double[] nearest = new double[segment[0].length]; + final double[] otherNearest = new double[segment[0].length]; + Distance.distanceSquare(segment[0], segment[1], nearest, otherSegment[0], otherSegment[1], otherNearest, + new double[2], EPSILON); + return Vector.of(nearest).lerp(Vector.of(otherNearest), 0.5); + } + + /** + * Returns the two ends of the edge of a box which is parallel to the given axis and the farthest along a direction. + */ + private static double[][] supportEdge(final Nearest.Box box, final int edge, final Vector<?> direction) { + final double[] local = new double[box.axes().length]; + for (int k = 0; k < local.length; k++) { + local[k] = (box.axes()[k].dot(direction) < 0) ? -box.halfSizes()[k] : box.halfSizes()[k]; + } + local[edge] = -box.halfSizes()[edge]; + final double[] start = box.world(local).toArrayDouble(); + local[edge] = box.halfSizes()[edge]; + return new double[][] {start, box.world(local).toArrayDouble()}; + } +} diff --git a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/GeometryProcessor.java b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/GeometryProcessor.java index b97d623ff2..541a627c0f 100644 --- a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/GeometryProcessor.java +++ b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/GeometryProcessor.java @@ -23,6 +23,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.UnaryOperator; @@ -341,6 +342,31 @@ public final class GeometryProcessor { return Quantities.create(Distance.signedDistance(geom1, geom2), Geometries.getLinearUnit(geom1)); } + /** + * Returns the contact between two geometries, as in collision detection: the contact point, + * the normal going from the first geometry to the second, and the depth of their overlap. + * Moving the second geometry by the depth along the normal separates the two geometries. + * + * <ul> + * <li>A geometry enclosing a volume, such as a sphere, a capsule or a box, is seen as the solid it encloses, + * and a hyperplane as the half-space opposite to its normal.</li> + * <li>Empty if the geometries are apart or if either geometry is empty.</li> + * </ul> + * + * @param geom1 the first geometry. + * @param geom2 the second geometry, in the reference system of the first one. + * @return the contact, or an empty value if the geometries are apart. + * @throws OperationException if the contact cannot be computed. + * @throws UnsupportedOperationException if the computation is not yet implemented for the types of the geometries. + */ + public Optional<Collision.Contact> collide(Geometry geom1, Geometry geom2) throws OperationException { + if (geom1.isEmpty() || geom2.isEmpty()) { + // The empty set has no position in common with any geometry. + return Optional.empty(); + } + return Collision.contact(geom1, geom2); + } + /** * Returns a geometric object that represents the Point set intersection of this geometric object with anotherGeometry. */ diff --git a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/Nearest.java b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/Nearest.java index 270b56fc44..e12960ec70 100644 --- a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/Nearest.java +++ b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/Nearest.java @@ -137,6 +137,15 @@ sealed interface Nearest { return startRadius + (endRadius - startRadius) * t; } + /** + * Returns whether these balls are a single ball, as for a point or a sphere. + * + * @return whether the two ends have the same center and radius. + */ + boolean isBall() { + return startRadius == endRadius && start.distance(end) == 0; + } + @Override public double signedDistance(final Vector<?> position) { return switch (geometry) { @@ -225,7 +234,7 @@ sealed interface Nearest { * @return ratio from 0 at the start to 1 at the end. */ double deepest(final ToDoubleFunction<Vector<?>> signedDistance) { - if (startRadius == endRadius && start.distance(end) == 0) { + if (isBall()) { return 0; } final DoubleUnaryOperator distance = (t) -> signedDistance.applyAsDouble(center(t)) - radius(t); @@ -380,41 +389,115 @@ sealed interface Nearest { } /** - * Returns the largest gap between the projections of this box and another box on the separating axes, - * which are the face normals of the two boxes and, in 3 dimensions, the cross products of their edges. - * The boxes are apart if the result is positive. Otherwise the result is minus the depth of their overlap, - * which is the length of the shortest translation separating them. + * An axis which may separate two boxes. + * + * @param direction unit direction of the axis. + * @param axis index of the axis of the first box normal to its faces or parallel to its edges, or -1. + * @param otherAxis index of the axis of the other box normal to its faces or parallel to its edges, or -1. + */ + record SeparatingAxis(Vector<?> direction, int axis, int otherAxis) { + /** + * Returns whether this axis is the cross product of two edges, rather than the normal of the faces of a box. + * + * @return whether both axis indices are set. + */ + boolean isEdges() { + return axis >= 0 && otherAxis >= 0; + } + } + + /** + * Returns the axes which may separate this box and another box: the face normals of this box, + * then the face normals of the other box, then in 3 dimensions the cross products of their edges. * * <ul> * <li>The two boxes shall have the same dimension, at most 3.</li> * </ul> * * @param other the other box. - * @return largest gap between the projections of the boxes, negative if they overlap. + * @return the candidate separating axes. * * @see "Christer Ericson, Real-Time Collision Detection, section 4.4.1" */ - double separation(final Box other) { - final List<Vector<?>> candidates = new ArrayList<>(List.of(axes)); - candidates.addAll(List.of(other.axes)); + List<SeparatingAxis> separatingAxes(final Box other) { + final List<SeparatingAxis> candidates = new ArrayList<>(); + for (int i = 0; i < axes.length; i++) { + candidates.add(new SeparatingAxis(axes[i], i, -1)); + } + for (int j = 0; j < other.axes.length; j++) { + candidates.add(new SeparatingAxis(other.axes[j], -1, j)); + } if (axes.length == 3) { - for (final Vector<?> axis : axes) { - for (final Vector<?> otherAxis : other.axes) { - final Vector<?> cross = axis.cross(otherAxis); + for (int i = 0; i < axes.length; i++) { + for (int j = 0; j < other.axes.length; j++) { + final Vector<?> cross = axes[i].cross(other.axes[j]); final double length = cross.length(); if (length > PARALLEL) { - candidates.add(cross.scale(1 / length)); + candidates.add(new SeparatingAxis(cross.scale(1 / length), i, j)); } } } } - final Vector<?> between = other.center.copy(DataType.DOUBLE).subtract(center); + return candidates; + } + + /** + * Returns the overlap of the projections of this box and another box on an axis. + * + * @param other the other box. + * @param axis the axis on which to project the boxes. + * @return overlap of the projections, negative if the axis separates the boxes. + */ + double overlap(final Box other, final SeparatingAxis axis) { + final Vector<?> direction = axis.direction(); + final double between = other.center.copy(DataType.DOUBLE).subtract(center).dot(direction); + return projectedRadius(direction) + other.projectedRadius(direction) - Math.abs(between); + } + + /** + * Returns the largest gap between the projections of this box and another box on the separating axes. + * The boxes are apart if the result is positive. Otherwise the result is minus the depth of their overlap, + * which is the length of the shortest translation separating them. + * + * @param other the other box, of the same dimension, at most 3. + * @return largest gap between the projections of the boxes, negative if they overlap. + */ + double separation(final Box other) { double separation = Double.NEGATIVE_INFINITY; - for (final Vector<?> axis : candidates) { - separation = Math.max(separation, Math.abs(between.dot(axis)) - projectedRadius(axis) - other.projectedRadius(axis)); + for (final SeparatingAxis axis : separatingAxes(other)) { + separation = Math.max(separation, -overlap(other, axis)); } return separation; } + + /** + * Returns the coordinates of a position along the axes of this box, relative to its center. + * + * @param position the position. + * @return coordinates of the position along each axis. + */ + double[] local(final Vector<?> position) { + final Vector<?> offset = position.copy(DataType.DOUBLE).subtract(center); + final double[] local = new double[axes.length]; + for (int k = 0; k < axes.length; k++) { + local[k] = offset.dot(axes[k]); + } + return local; + } + + /** + * Returns the position of the given coordinates along the axes of this box, relative to its center. + * + * @param local coordinates along each axis. + * @return the position. + */ + Vector<?> world(final double[] local) { + Vector<?> position = center.copy(DataType.DOUBLE); + for (int k = 0; k < axes.length; k++) { + position = position.combine(1, axes[k], local[k]); + } + return position; + } } /** diff --git a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/CollisionTest.java b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/CollisionTest.java new file mode 100644 index 0000000000..5e8b2d7942 --- /dev/null +++ b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/CollisionTest.java @@ -0,0 +1,222 @@ +/* + * 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. + */ +package org.apache.sis.geometries.operation; + +import java.util.Optional; +import org.apache.sis.geometries.BBox; +import org.apache.sis.geometries.Geometry; +import org.apache.sis.geometries.GeometryFactory; +import org.apache.sis.geometries.HyperPlane; +import org.apache.sis.geometries.OBBox; +import org.apache.sis.geometries.Plane; +import org.apache.sis.geometries.surface.Capsule; +import org.apache.sis.geometries.surface.Sphere; +import org.apache.sis.maths.Vector; + +// Test dependencies +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + + +/** + * Tests {@link Collision}. The cases of spheres, capsules, boxes and half-spaces are those of the physics + * of the KHR glTF extensions, the first ones are the 3D cases of the un-lib {@code CollisionTest}. + * + * @author Johann Sorel (Geomatys) + */ +public class CollisionTest extends AbstractD9IMTest { + /** + * Cosine and sine of 45°. + */ + private static final double S = 0.7071067811865476; + + private static Sphere sphere(final double x, final double y, final double z, final double radius) { + return GeometryFactory.DEFAULT.createSphere(GeometryFactory.DEFAULT.createDataPoints(CRS_3D, x, y, z), radius); + } + + private static Capsule capsule(final double r1, final double r2, final double... axis) { + final Capsule capsule = GeometryFactory.DEFAULT.createCapsule(GeometryFactory.DEFAULT.createDataPoints(CRS_3D, axis)); + capsule.setRadiusBottom(r1); + capsule.setRadiusTop(r2); + return capsule; + } + + private static HyperPlane halfSpace(final double y, final double ny) { + return new HyperPlane(CRS_3D, Vector.of(0.0, y, 0.0), Vector.of(0.0, ny, 0.0)); + } + + private static BBox cube(final double x, final double y, final double z, final double half) { + return new BBox(CRS_3D, x - half, y - half, z - half, x + half, y + half, z + half); + } + + private static OBBox box(final Vector<?> center, final Vector<?> xAxis, final Vector<?> yAxis, final Vector<?> zAxis) { + final OBBox box = new OBBox(CRS_3D); + box.setCenter(center); + box.setXAxis(xAxis); + box.setYAxis(yAxis); + box.setZAxis(zAxis); + return box; + } + + /** + * Returns a cube turned by 45° around the third axis. + */ + private static OBBox diamond(final double x, final double y, final double z, final double half) { + return box(Vector.of(x, y, z), Vector.of(S * half, S * half, 0.0), Vector.of(-S * half, S * half, 0.0), Vector.of(0.0, 0.0, half)); + } + + /** + * Returns a cube turned by 45° around the second axis, which touches {@code diamond(0, 0, 0, 1)} + * by an edge when its center is at x = 2.7284271247461903 with an overlap of 0.1. + */ + private static OBBox tilted(final double x) { + return box(Vector.of(x, 0.0, 0.0), Vector.of(S, 0.0, -S), Vector.of(0.0, 1.0, 0.0), Vector.of(S, 0.0, S)); + } + + private static void assertContact(final double[] point, final double[] normal, final double depth, + final Geometry first, final Geometry second) + { + final Collision.Contact contact = Collision.contact(first, second).orElseThrow(); + assertArrayEquals(point, contact.point().toArrayDouble(), TOLERANCE, "point"); + assertArrayEquals(normal, contact.normal().toArrayDouble(), TOLERANCE, "normal"); + assertEquals(depth, contact.depth(), TOLERANCE, "depth"); + } + + /** + * A sphere center below a half-space boundary moves by its radius plus the center depth. + * The half-space may also face down, and be given as the second geometry. + */ + @Test + public void testHalfSpaceSphere() { + assertContact(new double[] {0, 4.5, 0}, new double[] {0, 1, 0}, 3, halfSpace(6, 1), sphere(0, 5, 0, 2)); + assertContact(new double[] {0, 6.5, 0}, new double[] {0, 1, 0}, 1, sphere(0, 5, 0, 2), halfSpace(6, -1)); + assertContact(new double[] {0, 6.5, 0}, new double[] {0, -1, 0}, 1, sphere(0, 9, 0, 3), halfSpace(7, 1)); + } + + /** + * Contacts between spheres and capsules, which are on the line between their nearest axis points. + */ + @Test + public void testSpheresAndCapsules() { + assertContact(new double[] {0, 11, 0}, new double[] {0, -1, 0}, 2, sphere(0, 20, 0, 10), sphere(0, 9, 0, 3)); + assertContact(new double[] {0, 13.05, 0}, new double[] {0, 1, 0}, 0.1, sphere(0, 12.1, 0, 1), sphere(0, 16, 0, 3)); + assertContact(new double[] {0, 7, 0}, new double[] {0, -1, 0}, 2, sphere(0, 9, 0, 3), capsule(3, 3, 0,-5,0, 0,5,0)); + assertContact(new double[] {0, 7, 0}, new double[] {0, 1, 0}, 2, capsule(3, 3, 0,-5,0, 0,5,0), sphere(0, 9, 0, 3)); + assertContact(new double[] {0, 6.5, 0}, new double[] {0, 1, 0}, 1, capsule(2, 2, 0,4,0, 0,5,0), capsule(2, 2, 0,8,0, 0,9,0)); + } + + /** + * Parallel capsules touch in the middle of the part where they face each other, + * crossing capsules are pushed apart along their common perpendicular. + */ + @Test + public void testParallelAndCrossingCapsules() { + assertContact(new double[] {3, 0.4, 0}, new double[] {0, 1, 0}, 0.2, + capsule(0.5, 0.5, 0,0,0, 4,0,0), capsule(0.5, 0.5, 2,0.8,0, 6,0.8,0)); + assertContact(new double[] {0, 0, 0}, new double[] {0, -1, 0}, 1, + capsule(0.5, 0.5, -1,0,0, 1,0,0), capsule(0.5, 0.5, 0,0,-1, 0,0,1)); + } + + /** + * Spheres against boxes: through the nearest face of a box containing the sphere center, + * and against the edge of a box turned by 45°. + */ + @Test + public void testSphereAndBox() { + assertContact(new double[] {0, 3.5, 0}, new double[] {0, -1, 0}, 1, sphere(0, 5, 0, 2), new BBox(CRS_3D, -2,1,-2, 2,4,2)); + assertContact(new double[] {0, 0.625, 0}, new double[] {0, 1, 0}, 0.75, new BBox(CRS_3D, -2,-1,-2, 2,1,2), sphere(0, 0.5, 0, 0.25)); + assertContact(new double[] {11.207106781186548, 0, 0}, new double[] {1, 0, 0}, 0.41421356237309515, + diamond(10, 0, 0, 1), sphere(12, 0, 0, 1)); + } + + /** + * A capsule lying flat on a box touches it in its middle. A tilted capsule touches it near its lowest end. + */ + @Test + public void testCapsuleOnBox() { + final BBox box = new BBox(CRS_3D, -2,-1,-2, 2,1,2); + assertContact(new double[] {0, 0.75, 0}, new double[] {0, -1, 0}, 0.5, capsule(1, 1, -1,1.5,0, 1,1.5,0), box); + final Collision.Contact contact = Collision.contact(box, capsule(1, 1, -1,1.5,0, 1,2.5,0)).orElseThrow(); + assertArrayEquals(new double[] {-1, 0.75, 0}, contact.point().toArrayDouble(), 0.01, "point"); + assertArrayEquals(new double[] {0, 1, 0}, contact.normal().toArrayDouble(), TOLERANCE, "normal"); + assertEquals(0.5, contact.depth(), TOLERANCE, "depth"); + } + + /** + * Boxes sinking into each other, by a face or by crossing edges. + */ + @Test + public void testBoxes() { + assertContact(new double[] {0, 0.875, 0}, new double[] {0, 1, 0}, 0.25, cube(0, 0, 0, 1), cube(0, 1.25, 0, 0.5)); + assertContact(new double[] {0, 0.875, 0}, new double[] {0, -1, 0}, 0.25, cube(0, 1.25, 0, 0.5), cube(0, 0, 0, 1)); + assertContact(new double[] {0, 0.8964466094067262, 0}, new double[] {0, 1, 0}, 0.20710678118654757, + cube(0, 0, 0, 1), diamond(0, 1.5, 0, 0.5)); + assertContact(new double[] {1.3642135623730951, 0, 0}, new double[] {1, 0, 0}, 0.1, + diamond(0, 0, 0, 1), tilted(2.7284271247461903)); + } + + /** + * Boxes and capsules sinking into half-spaces and sheets. Their deepest corners or ends are averaged + * when they lie flat, a sheet pushes them to the side where most of them is. + */ + @Test + public void testPlanes() { + assertContact(new double[] {0, -0.25, 0}, new double[] {0, 1, 0}, 0.5, halfSpace(0, 1), cube(0, 0.5, 0, 1)); + assertContact(new double[] {0, -0.20710678118654757, 0}, new double[] {0, -1, 0}, 0.41421356237309515, + diamond(0, 1, 0, 1), halfSpace(0, 1)); + assertContact(new double[] {0, 6.5, 0}, new double[] {0, 1, 0}, 1, capsule(2, 2, 0,4,0, 0,5,0), halfSpace(6, -1)); + final HyperPlane below = new HyperPlane(CRS_3D, Vector.of(0.0, 0.0, -1.0), Vector.of(0.0, 0.0, 1.0)); + assertContact(new double[] {0, 0, -1.5}, new double[] {0, 0, 1}, 1, below, capsule(2, 1, 0,0,0, 0,0,2)); + final Plane sheet = new Plane(CRS_3D, Vector.of(0.0, 0.0, 5.0), Vector.of(0.0, 0.0, 1.0)); + assertContact(new double[] {0, 0, 5.25}, new double[] {0, 0, -1}, 0.5, sheet, sphere(0, 0, 4.5, 1)); + } + + /** + * Two spheres at the same center have no preferred direction, they are pushed along the last axis. + */ + @Test + public void testConcentricSpheres() { + assertContact(new double[] {0, 0, -0.5}, new double[] {0, 0, 1}, 3, sphere(0, 0, 0, 1), sphere(0, 0, 0, 2)); + } + + /** + * Solids apart have no contact, including two boxes separated only along the cross product of their edges. + */ + @Test + public void testApart() { + assertTrue(Collision.contact(sphere(0, 0, 0, 1), sphere(3, 0, 0, 1)).isEmpty()); + assertTrue(Collision.contact(sphere(0, 2, 0, 1), halfSpace(0, 1)).isEmpty()); + assertTrue(Collision.contact(cube(0, 0, 0, 1), capsule(1, 1, -1,3,0, 1,3,0)).isEmpty()); + assertTrue(Collision.contact(diamond(0, 0, 0, 1), tilted(2.9284271247461903)).isEmpty()); + assertThrows(UnsupportedOperationException.class, () -> Collision.contact(halfSpace(0, 1), halfSpace(0, 1))); + } + + /** + * Tests {@code collide(Geometry, Geometry)} of the geometry processor. + */ + @Test + public void testProcessorCollide() { + final GeometryProcessor processor = new GeometryProcessor(); + final Optional<Collision.Contact> contact = processor.collide(sphere(0, 20, 0, 10), sphere(0, 9, 0, 3)); + assertEquals(2, contact.orElseThrow().depth(), TOLERANCE); + assertTrue(processor.collide(sphere(0, 0, 0, 1), sphere(3, 0, 0, 1)).isEmpty()); + assertEquals(2, sphere(0, 20, 0, 10).collide(sphere(0, 9, 0, 3)).orElseThrow().depth(), TOLERANCE, "Geometry method."); + } +}
