From d2bebff7368bba6fab4f5238a39c47dcb47e6bfc Mon Sep 17 00:00:00 2001 From: Tim Conkling Date: Fri, 16 Dec 2011 12:35:25 -0800 Subject: [PATCH] Functions for computing the distance between a Point and a Rectangle --- src/main/java/pythagoras/f/Rectangles.java | 35 +++++++++++++++++++ src/test/java/pythagoras/f/RectangleTest.java | 22 ++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/test/java/pythagoras/f/RectangleTest.java diff --git a/src/main/java/pythagoras/f/Rectangles.java b/src/main/java/pythagoras/f/Rectangles.java index 982ed5d..c1e54c0 100644 --- a/src/main/java/pythagoras/f/Rectangles.java +++ b/src/main/java/pythagoras/f/Rectangles.java @@ -30,4 +30,39 @@ public class Rectangles float y2 = Math.max(src1.maxY(), src2.maxY()); dst.setBounds(x1, y1, x2 - x1, y2 - y1); } + + /** + * Computes the Point on the rectangle that's closest to the given point, writing + the result int {@code out} + */ + public static Point closestInteriorPoint (IRectangle r, IPoint p, Point out) + { + out.set(MathUtil.clamp(p.x(), r.minX(), r.maxX()), + MathUtil.clamp(p.y(), r.minY(), r.maxY())); + return out; + } + + /** + * Computes the Point on the rectangle that's closest to the given point + */ + public static Point closestInteriorPoint (IRectangle r, IPoint p) { + return closestInteriorPoint(r, p, new Point()); + } + + /** + * Returns the squared Euclidean distance between the given point and the nearest point on the + * given rectangle. + */ + public static float pointRectDistanceSq (IRectangle r, IPoint p) { + Point p2 = closestInteriorPoint(r, p); + return Points.distanceSq(p.x(), p.y(), p2.x, p2.y); + } + + /** + * Returns the Euclidean distance between the given point and the nearest point on the + * given rectangle. + */ + public static float pointRectDistance (IRectangle r, IPoint p) { + return FloatMath.sqrt(pointRectDistanceSq(r, p)); + } } diff --git a/src/test/java/pythagoras/f/RectangleTest.java b/src/test/java/pythagoras/f/RectangleTest.java new file mode 100644 index 0000000..9051351 --- /dev/null +++ b/src/test/java/pythagoras/f/RectangleTest.java @@ -0,0 +1,22 @@ +// +// Pythagoras - a collection of geometry classes +// http://github.com/samskivert/pythagoras + +package pythagoras.f; + +import org.junit.*; +import static org.junit.Assert.*; + +public class RectangleTest +{ + @Test public void testPointRectDistance () { + testPointRectDistance(0, new Rectangle(0, 0, 10, 10), new Point(0, 0)); // edge + testPointRectDistance(0, new Rectangle(0, 0, 10, 10), new Point(5, 5)); // interior + testPointRectDistance(5, new Rectangle(0, 0, 10, 10), new Point(5, 15)); // exterior + } + + protected void testPointRectDistance (float expected, IRectangle r, Point p) { + assertEquals(expected, Rectangles.pointRectDistance(r, p), MathUtil.EPSILON); + } + +}