Point Outside of Area Which is Closest to Point Inside? - java

I have a program where an entity moves around in two-dimensional space. To move one step, the entity picks its next point, and then sets it as his current point.
Sometimes, however, the entity's next point lies in an Area (java.awt.geom.Area) that is forbidden (the "forbidden area" is actually a velocity obstacle).
How can the entity pick the point outside the Area which is closest to the entity's preferred point?
The Area is composed of different shapes (sometimes, the shapes are not touching).
My initial plan was to simply draw a line to the preferred point. Wherever the line intersected the Area first, this would be the next-best point. However, finding the intersection between a line and an Area turns out to be quite complex.
EDIT: This wouldn't necessarily find the closest point. This would just find the closet point on the same trajectory. I'm looking for the closest possible point.
Perhaps Area isn't the best class to use. All I require is something that can add multiple shapes, even when the shapes aren't touching.

I've solved the problem:
First, find all the line segments that constrain the Area. I've written code to do that on a different answer.
Then, it's just a matter of iterating through each line segment, and recording the point on the segment that's closest to the entity's desired point. Store these in the data structure of your choice (e.g., an ArrayList).
See: Shortest distance between a point and a line segment
Lastly, determine which of the points is closest to the desired point. VoilĂ !
Here's a demonstration:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
public class AreaTest extends JFrame{
private static final long serialVersionUID = -2221432546854106311L;
Area area = new Area();
ArrayList<Line2D.Double> areaSegments = new ArrayList<Line2D.Double>();
Point2D.Double insidePoint = new Point2D.Double(225, 225);
Point2D.Double closestPoint = new Point2D.Double(-1, -1);
Point2D.Double bestPoint = new Point2D.Double(-1, -1);
ArrayList<Point2D.Double> closestPointList = new ArrayList<Point2D.Double>();
AreaTest() {
Path2D.Double triangle = new Path2D.Double();
Random random = new Random();
// Draw three random triangles
for (int i = 0; i < 3; i++) {
triangle.moveTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.lineTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.lineTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.closePath();
area.add(new Area(triangle));
triangle.reset();
}
// Place a point inside the area
if (!area.contains(insidePoint)); {
while (!area.contains(insidePoint)) {
insidePoint.setLocation(random.nextInt(400) + 50, random.nextInt(400) + 50);
}
}
// Note: we're storing double[] and not Point2D.Double
ArrayList<double[]> areaPoints = new ArrayList<double[]>();
double[] coords = new double[6];
for (PathIterator pi = area.getPathIterator(null); !pi.isDone(); pi.next()) {
// Because the Area is composed of straight lines
int type = pi.currentSegment(coords);
// We record a double array of {segment type, x coord, y coord}
double[] pathIteratorCoords = {type, coords[0], coords[1]};
areaPoints.add(pathIteratorCoords);
}
double[] start = new double[3]; // To record where each polygon starts
for (int i = 0; i < areaPoints.size(); i++) {
// If we're not on the last point, return a line from this point to the next
double[] currentElement = areaPoints.get(i);
// We need a default value in case we've reached the end of the ArrayList
double[] nextElement = {-1, -1, -1};
if (i < areaPoints.size() - 1) {
nextElement = areaPoints.get(i + 1);
}
// Make the lines
if (currentElement[0] == PathIterator.SEG_MOVETO) {
start = currentElement; // Record where the polygon started to close it later
}
if (nextElement[0] == PathIterator.SEG_LINETO) {
areaSegments.add(
new Line2D.Double(
currentElement[1], currentElement[2],
nextElement[1], nextElement[2]
)
);
} else if (nextElement[0] == PathIterator.SEG_CLOSE) {
areaSegments.add(
new Line2D.Double(
currentElement[1], currentElement[2],
start[1], start[2]
)
);
}
}
// Calculate the nearest point on the edge
for (Line2D.Double line : areaSegments) {
// From: https://stackoverflow.com/questions/6176227
double u =
((insidePoint.getX() - line.x1) * (line.x2 - line.x1) + (insidePoint.getY() - line.y1) * (line.y2 - line.y1))
/ ((line.x2 - line.x1) * (line.x2 - line.x1) + (line.y2 - line.y1) * (line.y2 - line.y1));
double xu = line.x1 + u * (line.x2 - line.x1);
double yu = line.y1 + u * (line.y2 - line.y1);
if (u < 0) {
closestPoint.setLocation(line.getP1());
} else if (u > 1) {
closestPoint.setLocation(line.getP2());
} else {
closestPoint.setLocation(xu, yu);
}
closestPointList.add((Point2D.Double) closestPoint.clone());
if (closestPoint.distance(insidePoint) < bestPoint.distance(insidePoint)) {
bestPoint.setLocation(closestPoint);
}
}
setSize(new Dimension(500, 500));
setLocationRelativeTo(null); // To center the JFrame on screen
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public void paint(Graphics g) {
// Fill the area
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.lightGray);
g2d.fill(area);
// Draw the border line by line
g.setColor(Color.black);
for (Line2D.Double line : areaSegments) {
g2d.draw(line);
}
// Draw the inside point
g.setColor(Color.red);
g2d.fill(
new Ellipse2D.Double(
insidePoint.getX() - 3,
insidePoint.getY() - 3,
6,
6
)
);
// Draw the other close points
for (Point2D.Double point : closestPointList) {
g.setColor(Color.black);
g2d.fill(
new Ellipse2D.Double(
point.getX() - 3,
point.getY() - 3,
6,
6
)
);
}
// Draw the outside point
g.setColor(Color.green);
g2d.fill(
new Ellipse2D.Double(
bestPoint.getX() - 3,
bestPoint.getY() - 3,
6,
6
)
);
}
public static void main(String[] args) {
new AreaTest();
}
}
Here's the result:
And again:

View my answer on this post
You can get the closest point outside of a polygon with a simple and lightweight approach:
Simply find the closest line segment, and find the perpendicular angle to that segment that intercepts the input point.
Example Code:
Vector2 is 2 doubles, x and y (Like Unity)
public class PolyCollisions {
// Call this function...
public static Vector2 doCollisions (Vector2[] polygon, Vector2 point) {
if(!pointIsInPoly(polygon, point)) {
// The point is not colliding with the polygon, so it does not need to change location
return point;
}
// Get the closest point off the polygon
return closestPointOutsidePolygon(polygon, point);
}
// Check if the given point is within the given polygon (Vertexes)
//
// If so, call on collision if required, and move the point to the
// closest point outside of the polygon
public static boolean pointIsInPoly(Vector2[] verts, Vector2 p) {
int nvert = verts.length;
double[] vertx = new double[nvert];
double[] verty = new double[nvert];
for(int i = 0; i < nvert; i++) {
Vector2 vert = verts[i];
vertx[i] = vert.x;
verty[i] = vert.y;
}
double testx = p.x;
double testy = p.y;
int i, j;
boolean c = false;
for (i = 0, j = nvert-1; i < nvert; j = i++) {
if ( ((verty[i]>testy) != (verty[j]>testy)) &&
(testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
c = !c;
}
return c;
}
// Gets the closed point that isn't inside the polygon...
public static Vector2 closestPointOutsidePolygon (Vector2[] poly, Vector2 point) {
return getClosestPointInSegment(closestSegment(poly, point), point);
}
public static Vector2 getClosestPointInSegment (Vector2[] segment, Vector2 point) {
return newPointFromCollision(segment[0], segment[1], point);
}
public static Vector2 newPointFromCollision (Vector2 aLine, Vector2 bLine, Vector2 p) {
return nearestPointOnLine(aLine.x, aLine.y, bLine.x, bLine.y, p.x, p.y);
}
public static Vector2 nearestPointOnLine(double ax, double ay, double bx, double by, double px, double py) {
// https://stackoverflow.com/questions/1459368/snap-point-to-a-line-java
double apx = px - ax;
double apy = py - ay;
double abx = bx - ax;
double aby = by - ay;
double ab2 = abx * abx + aby * aby;
double ap_ab = apx * abx + apy * aby;
double t = ap_ab / ab2;
if (t < 0) {
t = 0;
} else if (t > 1) {
t = 1;
}
return new Vector2(ax + abx * t, ay + aby * t);
}
public static Vector2[] closestSegment (Vector2[] points, Vector2 point) {
Vector2[] returns = new Vector2[2];
int index = closestPointIndex(points, point);
returns[0] = points[index];
Vector2[] neighbors = new Vector2[] {
points[(index+1+points.length)%points.length],
points[(index-1+points.length)%points.length]
};
double[] neighborAngles = new double[] {
getAngle(new Vector2[] {point, returns[0], neighbors[0]}),
getAngle(new Vector2[] {point, returns[0], neighbors[1]})
};
if(neighborAngles[0] < neighborAngles[1]) {
returns[1] = neighbors[0];
} else {
returns[1] = neighbors[0];
}
return returns;
}
public static double getAngle (Vector2[] abc) {
// https://stackoverflow.com/questions/1211212/how-to-calculate-an-angle-from-three-points
// atan2(P2.y - P1.y, P2.x - P1.x) - atan2(P3.y - P1.y, P3.x - P1.x)
return Math.atan2(abc[2].y - abc[0].y, abc[2].x - abc[0].x) - Math.atan2(abc[1].y - abc[0].y, abc[1].x - abc[0].x);
}
//public static Vector2 lerp (Vector2 a, Vector2 b, double c) {
//
// return new Vector2(c*(a.x-b.x)+b.x, c*(a.y-b.y)+b.y);
//
//}
/*public static Vector2 closestPoint (Vector2[] points, Vector2 point) {
int leastDistanceIndex = 0;
double leastDistance = Double.MAX_VALUE;
for(int i = 0; i < points.length; i++) {
double dist = distance(points[i], point);
if(dist < leastDistance) {
leastDistanceIndex = i;
leastDistance = dist;
}
}
return points[leastDistanceIndex];
}*/
public static int closestPointIndex (Vector2[] points, Vector2 point) {
int leastDistanceIndex = 0;
double leastDistance = Double.MAX_VALUE;
for(int i = 0; i < points.length; i++) {
double dist = distance(points[i], point);
if(dist < leastDistance) {
leastDistanceIndex = i;
leastDistance = dist;
}
}
return leastDistanceIndex;
}
public static double distance (Vector2 a, Vector2 b) {
return Math.sqrt(Math.pow(Math.abs(a.x-b.x), 2)+Math.pow(Math.abs(a.y-b.y), 2));
}
}
Useful Links / Answers
Snap Point to Line
How to calculate an angle from 3 points

The most easy (and most inefficient) approach would be a brute force.
You have a preferred point inside an area. to find the closest point to it: hold two variables, one for minimal distance and one for current closest point. now simply step over every other point in your two dimensional space: if that point is not inside the forbidden area (or any forbidden area if there are many), then calculate the distance between it and the preferred point. If that distance is less than the current minimal distance, then make it become the current minimal distance and make the point become the current closest point.
when you finish, you will have the closest point outside the area and if none was found, you stay on your original point.
I am not specialist in geometry algorithms, but if the two dimensional space is very big and the calculation is not finishing fast enough, maybe you can try to improve it with the following: the Area class has a contains method that "tests if the interior of the Shape entirely contains the specified rectangular area". therefore, start creating rectangles(or squares) around the preferred point. you start with the minimal rectangle surrounding the point and on every loop you increase it by one point in each direction. for every rectangle that you create, check if it is contained in the area. you stop calculating rectangles when you hit the first rectangle that is not entirely contained in the area. then, you use the above algorithm (the brute force) but only on points contained in this rectangle and that are not inside the area.

The formula for distance between two points is (javascript):
var xDiff = ( point1x - point2x ),
yDiff = ( point1y - point2y ),
distance = Math.sqrt( ( xDiff * xDiff ) + ( yDiff * yDiff ) );
Loop around your "proposed new point", starting at one x-1, y-1 to x+1, y+1. At each point check to see that it's not a forbidden point, not the point you just came from, and not off the boundaries of the map. If it meets all those criteria, use the above formula to measure the distance and add it to an array. At the end of your "1-point out" loop, check if there are any distances in that array. If so, take the smallest one and you're done. If there aren't any, move onto x-2, y-2 to x+2, y+2 (2 points out).
This will be extremely fast for the small area you are referring to.
Demo: http://jsfiddle.net/ThinkingStiff/V7Bqm/
var X = 0,
Y = 1,
currentPoint = [5,5],
proposedPoint = [5,6],
forbiddenPoints = [[5,6],[6,6],[4,7],[5,7],[6,7],[4,8],[5,8]],
map = { left:1, top:1, right:10, bottom:10 };
function closestSafePoint( point ) {
var x = point[X], y = point[Y], safePoints = [];
for( var left = x - 1, top = y - 1, right = x + 1, bottom = y + 1;
left <= map.left || top <= map.top || right <= map.right || bottom <= map.bottom;
left--, top--, right++, bottom++) {
checkHorizontalPoints( safePoints, point, left, right, top );
checkHorizontalPoints( safePoints, point, left, right, bottom );
checkVerticalPoints( safePoints, point, top + 1, bottom - 1, left );
checkVerticalPoints( safePoints, point, top + 1, bottom - 1, right );
safePoints.sort( function( a, b ){ return a[1] - b[1] } );
return safePoints.length ? safePoints[0] : point;
};
};
function checkHorizontalPoints( points, fromPoint, startX, endX, y ) {
for( var x = startX; x <= endX ; x++ ) {
var toPoint = [x, y];
if( !isForbidden( toPoint ) && !isCurrent( toPoint) && onMap( toPoint ) ) {
points.push( [toPoint, distance( fromPoint, toPoint )] );
};
};
};
function checkVerticalPoints( points, fromPoint, startY, endY, x ) {
for( var y = startY; y <= endY ; y++ ) {
var toPoint = [x, y];
if( !isForbidden( toPoint ) && !isCurrent( toPoint) && onMap( toPoint ) ) {
points.push( [toPoint, distance( fromPoint, toPoint )] );
};
};
};
function isForbidden( point ) {
for( var index = 0; index < forbiddenPoints.length; index++ ) {
if( forbiddenPoints[index].toString() == point.toString() ) return true;
};
};
function isCurrent( point ) {
return currentPoint.toString() == point.toString() ? true : false;
};
function onMap( point ) {
var x = point[X], y = point[Y];
return x >= map.left && y >= map.top && x <= map.right && y <= map.bottom;
};
function distance( pointA, pointB ) {
var xDiff = ( pointA[X] - pointB[X] ),
yDiff = ( pointA[Y] - pointB[Y] );
return Math.sqrt( ( xDiff * xDiff ) + ( yDiff * yDiff ) );
};
console.log(
'current: ' + currentPoint + ', '
+ 'proposed: ' + proposedPoint + ', '
+ 'closest: ' + closestSafePoint( proposedPoint )[0]
);
One optimization you could make to this, if you're fairly sure most of your safe spots will be one or two points away is to break out as soon as you get to a point thats distance is the same as the level you're on. So if you're on loop one, and you get a point that is distance = 1, stop, since you'll never get closer than that.
UPDATE: I noticed you added "same trajectory" to your question. But in one of the comments, you also say it can't jump over the forbidden area. Those statements seem to conflict.
Same trajectory is a little more tricky and requires some trig. Check out my demo of circular divs at http://jsfiddle.net/ThinkingStiff/uLu7v/. There is a "point on ray" function halfway down at:
$this.siblings( ".circle" ).each( function()
This calculates the distance to move the surrounding circles on a ray away from the selected circle. This could be used to calculate a point on your trajectory. But, I think my original function is actually what you're looking for and you didn't mean same trajectory.

Related

Determine the polygon side with given inner angle

I made the following picture to help visualize the problem:
You can control the monkey, by rotating it. You can step to the neigbour fields, but here I have a problem calculating which is the field to step.
The monkey has an angle, which goes from 0 to 360 degress, 0 is when its head is up. I would like to calculate the neigbour field from this angle. (Basically this field is where the orangutan "looks").
I store the neigbours, and also the vertices for every polygon.
I tried with the following idea:
Start a half line from the orangutan, then calculate the intersection with each side of the polygon. If we have an intersection, then we know the two endpoints. Then search through the neigbour fields, if one of them has both points in its vertices, then this is the good one.
Here the code I wrote:
public Field getNeighbourByAngle(double angle) {
// Field center
Point2D c = center;
// New point initial coordinates
double x = c.getX(); double y = c.getY()+1;
// Rotate the point by the angle
Point2D rotatedPoint = new Point2D(
-(x*Math.cos(Math.toRadians(angle)) - y*Math.sin(Math.toRadians(angle))),
y*Math.cos(Math.toRadians(angle)) + x*Math.sin(Math.toRadians(angle)) );
// Get the vector from the center to the roteted point
Point2D v = rotatedPoint.subtract(c);
// Iterate over the vertex arraylist
for (int i = 0; i<verts.size(); i++) {
// Get the two endpoints
Point2D p1 = verts.get(i);
Point2D p2;
if (i == verts.size() - 1) {
p2 = verts.get(0);
} else { p2 = verts.get(i+1);}
// Calculate the intersection
// Using the formula:
// x = c.x + v.x * t
// x = p1.x * (1-t) + p2.x * t
// These two are equals, get t from the equation:
double t = ( p1.getX() - c.getX( )) / (v.getX() + p1.getX() - p2.getX() );
// t has to be between [0, 1] because p1 <-> p2 is just a line segment
if (0 <= t && t<= 1) {
// Iterate over the neigbours
for (int j = 0; j<neighbours.size(); j++) {
// If the neigbour has both p1 and p2 in its vertices list, then we found the correct neigbour.
if (neighbours.get(j).getVerts().contains(p1) &&
neighbours.get(j).getVerts().contains(p2)) {
return neighbours.get(j);
}
}
}
}
return null;
}
But I not get the correct results, I don't know where is the problem.

How to use AffineTransform with very little coordinates?

I have a set of two dimensions points. Their X and Y are greater than -2 and lesser than 2. Such point could be : (-0.00012 ; 1.2334 ).
I would want to display these points on a graph, using rectangles (a rectangle illustrates a point, and has its coordinates set to its point's ones - moreover, it has a size of 10*10).
Rectangles like (... ; Y) should be displayed above any rectangles like (... ; Y-1) (positive Y direction is up). Thus, I must set the graph's origin not at the top-left hand-corner, but somewhere else.
I'm trying to use Graphics2D's AffineTransform to do that.
I get the minimal value for all the X coordinates
I get the minimal value for all the Y coordinates
I get the maximal value for all the X coordinates
I get the maximal value for all the Y coordinates
I get the distance xmax-xmin and ymax-ymin
Then, I wrote the code I give you below.
Screenshots
Some days ago, using my own method to scale, I had this graph:
(so as I explained, Y are inverted and that's not a good thing)
For the moment, i.e., with the code I give you below, I have only one point that takes all the graph's place! Not good at all.
I would want to have:
(without lines, and without graph's axis. The important here is that points are correctly displayed, according to their coordinates).
Code
To get min and max coordinates value:
x_min = Double.parseDouble((String) list_all_points.get(0).get(0));
x_max = Double.parseDouble((String) list_all_points.get(0).get(0));
y_min = Double.parseDouble((String) list_all_points.get(0).get(1));
y_max = Double.parseDouble((String) list_all_points.get(0).get(1));
for(StorableData s : list_all_points) {
if(Double.parseDouble((String) s.get(0)) < x_min) {
x_min = Double.parseDouble((String) s.get(0));
}
if(Double.parseDouble((String) s.get(0)) > x_max) {
x_max = Double.parseDouble((String) s.get(0));
}
if(Double.parseDouble((String) s.get(1)) < y_min) {
y_min = Double.parseDouble((String) s.get(1));
}
if(Double.parseDouble((String) s.get(1)) > y_max) {
y_max = Double.parseDouble((String) s.get(1));
}
}
To draw a point:
int x, y;
private void drawPoint(Cupple storable_data) {
//x = (int) (storable_data.getNumber(0) * scaling_coef + move_x);
//y = (int) (storable_data.getNumber(1) * scaling_coef + move_y);
x = storable_data.getNumber(0).intValue();
y = storable_data.getNumber(1).intValue();
graphics.fillRect(x, y, 10, 10);
graphics.drawString(storable_data.toString(), x - 5, y - 5);
}
To paint the graph:
#Override
public void paint(Graphics graphics) {
this.graphics = graphics;
Graphics2D graphics_2d = ((Graphics2D) this.graphics);
AffineTransform affine_transform = graphics_2d.getTransform();
affine_transform.scale(getWidth()/(x_max - x_min), getHeight()/(y_max - y_min));
affine_transform.translate(x_min, y_min);
graphics_2d.transform(affine_transform);
for(StorableData storable_data : list_all_points) {
graphics_2d.setColor(Color.WHITE);
this.drawPoint((Cupple) storable_data);
}
I suggest you map each data point to a point on the screen, thus avoiding the following coordinate system pitfalls. Take your list of points and create from them a list of points to draw. Take into account that:
The drawing is pixel-based, so you will want to scale your points (or you would have rectangles 1 to 4 pixels wide...).
You will need to translate all your points because negative values will be outside the boundaries of the component on which you draw.
The direction of the y axis is reversed in the drawing coordinates.
Once that is done, use the new list of points for the drawing and the initial one for calculations. Here is an example:
public class Graph extends JPanel {
private static int gridSize = 6;
private static int scale = 100;
private static int size = gridSize * scale;
private static int translate = size / 2;
private static int pointSize = 10;
List<Point> dataPoints, scaledPoints;
Graph() {
setBackground(Color.WHITE);
// points taken from your example
Point p1 = new Point(-1, -2);
Point p2 = new Point(-1, 0);
Point p3 = new Point(1, 0);
Point p4 = new Point(1, -2);
dataPoints = Arrays.asList(p1, p2, p3, p4);
scaledPoints = dataPoints.stream()
.map(p -> new Point(p.x * scale + translate, -p.y * scale + translate))
.collect(Collectors.toList());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(size, size);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// draw a grid
for (int i = 0; i < gridSize; i++) {
g2d.drawLine(i * scale, 0, i * scale, size);
g2d.drawLine(0, i * scale, size, i * scale);
}
// draw the rectangle
g2d.setPaint(Color.RED);
g2d.drawPolygon(scaledPoints.stream().mapToInt(p -> p.x).toArray(),
scaledPoints.stream().mapToInt(p -> p.y).toArray(),
scaledPoints.size());
// draw the points
g2d.setPaint(Color.BLUE);
// origin
g2d.fillRect(translate, translate, pointSize, pointSize);
g2d.drawString("(0, 0)", translate, translate);
// data
for (int i = 0; i < dataPoints.size(); i++) {
Point sp = scaledPoints.get(i);
Point dp = dataPoints.get(i);
g2d.fillRect(sp.x, sp.y, pointSize, pointSize);
g2d.drawString("(" + dp.x + ", " + dp.y + ")", sp.x, sp.y);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setContentPane(new Graph());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
And another:
You might want to have the points aligned on the grid intersections and not below and to the right of them. I trust you will figure this one out.
Also, I ordered the points so that drawPolygon will paint the lines in the correct order. If your points are arbitrarily arranged, look for ways to find the outline. If you want lines between all points like in your example, iterate over all combinations of them with drawLine.

Algorithm to verify if a shape is inside another - javafx

I have a rectangular and circle. I need to verify whether a rectangle is inside that circle.
I tried to Shape.intersects but intersects is checked the number 1.
Does anyone know this kind of algorithm in javafx?
Just to exemplifly, in the figure only rectangles 1, 2, 3, and 4 are inside the circle.
thanks for your help.
Solution
The basic idea behind this solution is that any polygon is contained within any convex (see comments) shape iff every point within the polygon is within the shape. The intersects() method that you're attempting to use returns true if at least one point of the polygon is within the shape. You've already figured out that it'll work, but it'll also offer false positives for any partially-intersected shapes. To fix it, we define our own intersection test which looks at all points.
This can be generalized to scan any given polygon for "total intersection" with any given shape:
public boolean totalIntersects(Polygon poly, Shape testShape) {
List<Point> points = flatDoublesToPoints(poly.getPoints());
boolean inside = true; // If this is false after testing all points, the poly has at least one point outside of the shape.
for(Point point : points) {
if(!testShape.intersects(point.x, point.y, 1, 1)) { // The 3rd and 4th parameters here are "width" and "height". 1 for a point.
inside = false;
}
}
return inside;
}
where flatDoublesToPoints() and Point are defined as:
private List<Point> flatDoublesToPoints(List<Double> flatDoubles) {
List<Point> points = new ArrayList<>();
for(int i = 0; i < flatDoubles.size(); i += 2) {
points.add(new Point(flatDoubles.get(i), flatDoubles.get(i + 1)));
}
return points;
}
class Point {
public double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
flatDoublesToPoints() is needed to split the "flat" {x1, y1, x2, y2, x3, y3...} polygon lists into a more easy-to-understand data structure. If you're doing tons of comparisons, it may be helpful to skip this step, however, and operate on the "flat list" directly for memory reasons.
Application
The following applies the other methods to a situation extremely similar to yours. (Not exact, because I didn't have your code.)
public class Main extends Application {
public static final int SIZE = 600;
#Override
public void start(Stage primaryStage) throws Exception {
Pane rootPane = new Pane();
List<Rectangle> rects = new ArrayList<>();
for (int j = 0; j < 2; j++) {
for(int i = 0; i < 5; i++) {
Rectangle r = new Rectangle(i * 100, j == 0 ? 0 : 300, 100, 200);
r.setFill(Color.BEIGE);
r.setStroke(Color.BLACK);
rects.add(r);
}
}
rootPane.getChildren().addAll(rects);
Circle circle = new Circle(350, 100, 200);
circle.setStroke(Color.BLACK);
circle.setFill(null);
rootPane.getChildren().add(circle);
List<Polygon> polys = new ArrayList<>();
for(Rectangle rect : rects) {
polys.add(rectangleToPolygon(rect));
}
List<Polygon> intersects = getTotalIntersections(polys, circle);
System.out.println(intersects);
primaryStage.setScene(new Scene(rootPane, SIZE, SIZE));
primaryStage.show();
}
public List<Polygon> getTotalIntersections(List<Polygon> polys, Shape testShape) {
List<Polygon> intersections = new ArrayList<>();
for(Polygon poly : polys) {
if(totalIntersects(poly, testShape)) {
intersections.add(poly);
}
}
return intersections;
}
public static Polygon rectangleToPolygon(Rectangle rect) {
double[] points = {rect.getX(), rect.getY(),
rect.getX() + rect.getWidth(), rect.getY(),
rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight(),
rect.getX(), rect.getY() + rect.getHeight()};
return new Polygon(points);
}
public static void main(String[] args) {
Main.launch(args);
}
}
This code will print the following:
[Polygon[points=[200.0, 0.0, 300.0, 0.0, 300.0, 200.0, 200.0, 200.0], fill=0x000000ff], Polygon[points=[300.0, 0.0, 400.0, 0.0, 400.0, 200.0, 300.0, 200.0], fill=0x000000ff], Polygon[points=[400.0, 0.0, 500.0, 0.0, 500.0, 200.0, 400.0, 200.0], fill=0x000000ff]]
Which is your three polygons labeled 2, 3, and 4.
I don't think that JavaFX will have some special methods for this case.
To draw that circle you need coordinates (X_c, Y_c) of center and radius (R).
To draw rectangles you need to have coordinates ((X_1, Y_1), (X_2, Y_2) etc.) of angle points.
Then all you need is to check if all points of the rectangle is inside of the circle:
(X_1 - X_c)^2 + (Y_1 - Y_c)^2 < R^2
(X_2 - X_c)^2 + (Y_2 - Y_c)^2 < R^2
...
Try this :
import javafx.geometry.Point2D;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
/*
Check if a rectangle is contained with in a circle by checking
all rectangle corners.
For the rectangle to be contained in a circle, all its corners should be
in a distance smaller or equal to the circle's radius, from the circle's center.
Note:
Requires some more testing. I tested only a few test cases.
I am not familiar with javafx. This solution does not take into
calculation rectangle's arc or other attributes I may not be aware of.
*/
public class Test{
//apply
public static void main(String[] args){
Circle circle = new Circle(0 ,0, 100);
Rectangle rec = new Rectangle(0, 0, 50 , 50);
System.out.println("Is rectungle inside the circle ? "
+ isContained(circle,rec));
}
//check if rectangle is contained within a circle
private static boolean isContained(Circle circle,Rectangle rec) {
boolean isInside = true;
//get circle center & radius
Point2D center = new Point2D(circle.getCenterX(), circle.getCenterY());
double radius= circle.getRadius();
Point2D[] corners = getRectangleCorners(rec);
for(Point2D corner : corners) {
//if any corner falls outside the circle
//the rectangle is not contained in the circle
if(distanceBetween2Points(corner, center) > radius) {
return false;
}
}
return isInside;
}
//calculate distance between two points
//(updated a per fabian's suggestion)
private static double distanceBetween2Points
(Point2D corner, Point2D center) {
return corner.distance(center);
}
private static Point2D[] getRectangleCorners(Rectangle rec) {
Point2D[] corners = new Point2D[4];
corners[0] = new Point2D(rec.getX(), rec.getY());
corners[1] = new Point2D(rec.getX()+ rec.getWidth() , rec.getY());
corners[2] = new Point2D(rec.getX()+ rec.getWidth(), rec.getY()+ rec.getHeight());
corners[3] = new Point2D(rec.getX(), rec.getY()+ rec.getHeight());
return corners;
}
}
There is a working simple solution here : https://stackoverflow.com/a/8721483/1529139
Copy-paste here:
class Boundary {
private final Point[] points; // Points making up the boundary
...
/**
* Return true if the given point is contained inside the boundary.
* See: http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
* #param test The point to check
* #return true if the point is inside the boundary, false otherwise
*
*/
public boolean contains(Point test) {
int i;
int j;
boolean result = false;
for (i = 0, j = points.length - 1; i < points.length; j = i++) {
if ((points[i].y > test.y) != (points[j].y > test.y) &&
(test.x < (points[j].x - points[i].x) * (test.y - points[i].y) / (points[j].y-points[i].y) + points[i].x)) {
result = !result;
}
}
return result;
}
}

Test of Point inside polygon in Android

The other day I did a class in Java to calculate if a point(X,Y) is inside a polygon. (X and Y are double, because will be geo-coordinates).
I know that Java has the class Polygon, but I had to use Path2D and Point2D, because Polygon don't allow double's, just integers :(
Once I have the polygon done in Path2D, I used the method contains (Path2D had it), and my problem was solved.
But now, I want to import to Android, and the problem is here, because Path2D needs to import:
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
and in Android don't exist awt, so I can't use.
So, is there any class similar to Path2D that had contains method? or I have to calculate by myself?
Here is how I did in Java using Path2D:
private void ConstructPolygon(Vector<Point2D> coodinates)
{
this.polygon.moveTo(coodinates.get(0).getX(), coodinates.get(0).getY());
//System.out.println(coodinates.get(0).getX() + " " + coodinates.get(0).getY());
//System.out.println("asda");
for(int i = 1; i < this.num_points; i++)
{
//System.out.println(coodinates.get(i).getX() + " " + coodinates.get(i).getY());
this.polygon.lineTo(coodinates.get(i).getX(), coodinates.get(i).getY());
}
this.polygon.closePath();
}
public boolean InsideCity(Point2D punto)
{
return this.polygon.contains(punto);
}
You can use my simple library exactly for this: https://github.com/snatik/polygon-contains-point.
Prepare polygon:
Polygon polygon = Polygon.Builder()
.addVertex(new Point(1, 3))
.addVertex(new Point(2, 8))
.addVertex(new Point(5, 4))
.addVertex(new Point(5, 9))
.addVertex(new Point(7, 5))
.addVertex(new Point(6, 1))
.addVertex(new Point(3, 1))
.build();
And check whereas the point is inside the polygon:
Point point = new Point(4.5f, 7);
boolean contains = polygon.contains(point);
It works with float types and with polygons that contain holes :)
You can use Google Maps PolyUtil:
import com.google.maps.android.PolyUtil;
boolean inside = PolyUtil.containsLocation(new LatLng(...), poly, true);
Here is how I did it in Android.
It is based on this java program (ray casting algorithm) :
https://gis.stackexchange.com/questions/42879/check-if-lat-long-point-is-within-a-set-of-polygons-using-google-maps/46720#46720
public boolean pointInPolygon(LatLng point, Polygon polygon) {
// ray casting alogrithm http://rosettacode.org/wiki/Ray-casting_algorithm
int crossings = 0;
List<LatLng> path = polygon.getPoints();
path.remove(path.size()-1); //remove the last point that is added automatically by getPoints()
// for each edge
for (int i=0; i < path.size(); i++) {
LatLng a = path.get(i);
int j = i + 1;
//to close the last edge, you have to take the first point of your polygon
if (j >= path.size()) {
j = 0;
}
LatLng b = path.get(j);
if (rayCrossesSegment(point, a, b)) {
crossings++;
}
}
// odd number of crossings?
return (crossings % 2 == 1);
}
public boolean rayCrossesSegment(LatLng point, LatLng a,LatLng b) {
// Ray Casting algorithm checks, for each segment, if the point is 1) to the left of the segment and 2) not above nor below the segment. If these two conditions are met, it returns true
double px = point.longitude,
py = point.latitude,
ax = a.longitude,
ay = a.latitude,
bx = b.longitude,
by = b.latitude;
if (ay > by) {
ax = b.longitude;
ay = b.latitude;
bx = a.longitude;
by = a.latitude;
}
// alter longitude to cater for 180 degree crossings
if (px < 0 || ax <0 || bx <0) { px += 360; ax+=360; bx+=360; }
// if the point has the same latitude as a or b, increase slightly py
if (py == ay || py == by) py += 0.00000001;
// if the point is above, below or to the right of the segment, it returns false
if ((py > by || py < ay) || (px > Math.max(ax, bx))){
return false;
}
// if the point is not above, below or to the right and is to the left, return true
else if (px < Math.min(ax, bx)){
return true;
}
// if the two above conditions are not met, you have to compare the slope of segment [a,b] (the red one here) and segment [a,p] (the blue one here) to see if your point is to the left of segment [a,b] or not
else {
double red = (ax != bx) ? ((by - ay) / (bx - ax)) : Double.POSITIVE_INFINITY;
double blue = (ax != px) ? ((py - ay) / (px - ax)) : Double.POSITIVE_INFINITY;
return (blue >= red);
}
}
Sorry #sromku I asked my self (I never used this type of things)
That's how I solved if anyone have the same question
Builder poly2 = new Polygon.Builder();
for(int i = 0; i< xpoints.length;i++){
poly2.addVertex(new Point(xpoints[i],ypoints[i]));
}
Polygon polygon2 = poly2.build();

How to check if VERTEX ARRAY is clockwise?

Solved, used this code:
if ( !isClockwise(TempVectArray) ) { Collections.reverse(TempVectArray); }
...
private boolean isClockwise(ArrayList<Vec2> arl){
Iterator<Vec2> it = arl.iterator();
Vec2 pt1 = (Vec2)it.next();
Vec2 firstPt = pt1;
Vec2 lastPt = null;
double area = 0.0;
while(it.hasNext()){
Vec2 pt2 = (Vec2) it.next();
area += (((pt2.x - pt1.x) * (pt2.y + pt1.y)) / 2);
pt1 = pt2;
lastPt = pt1;
}
area += (((firstPt.x - lastPt.x) * (firstPt.y + lastPt.y)) / 2);
return area < 0;
}
Suppose I get a vertex array from the user tapping on the screen, but need it to be clockwise.
Maybe you know of some standard methods to check if it is clockwise and if it's not, then make it clockwise?
Thanks!
One way to do it is to first calculate the average point, and then sort everything around it by angle. Should be something like this:
public static void sortPointsClockwise(ArrayList<PointF> points) {
float averageX = 0;
float averageY = 0;
for (PointF point : points) {
averageX += point.x;
averageY += point.y;
}
final float finalAverageX = averageX / points.size();
final float finalAverageY = averageY / points.size();
Comparator<PointF> comparator = new Comparator<PointF>() {
public int compare(PointF lhs, PointF rhs) {
double lhsAngle = Math.atan2(lhs.y - finalAverageY, lhs.x - finalAverageX);
double rhsAngle = Math.atan2(rhs.y - finalAverageY, rhs.x - finalAverageX);
// Depending on the coordinate system, you might need to reverse these two conditions
if (lhsAngle < rhsAngle) return -1;
if (lhsAngle > rhsAngle) return 1;
return 0;
}
};
Collections.sort(points, comparator);
}
public static void sortPointsCounterClockwise(ArrayList<PointF> points) {
sortPointsClockwise(points);
Collections.reverse(points);
}
You have the sequence numbers and positions of the nodes. Get the movements which hold x and y changes in the move. All left to do is define a control structure such as:
if(movement_before is "up")
movement should-be "up" or "up-right"
if(movement_before is "up-left")
movement should-be "up" or "up-left" or "up-right"
etc..

Categories

Resources