I’ve got a task to check if one polyline is self-crossing at any time. This check must be very fast because my polyline is long (have about 50 points) and I’ve got a timeout. Here is what I wrote:
public bool IsSelfCrossing()
{
if (size <= 5)
return false;
Point first = body.Points.ElementAt(size - 1);
Point second = body.Points.ElementAt(size - 2);
for (int i = 0; i < size - 3; i++)
{
if (Intersect(first, second, body.Points.ElementAt(i),
body.Points.ElementAt(i + 1)))
{
return true;
}
}
return false;
}
private double Orientation(Point p1, Point p2, Point p3)
{
double dx1 = p2.X - p1.X;
double dy1 = p2.Y - p1.Y;
double dx2 = p3.X - p1.X;
double dy2 = p3.Y - p1.Y;
return dx1 * dy2 - dy1 * dx2;
}
bool Intersect(Point p1, Point p2, Point p3, Point p4)
{
return
Orientation(p1, p3, p4) * Orientation(p2, p3, p4) < 0 &&
Orientation(p3, p1, p2) * Orientation(p4, p1, p2) < 0;
}
The problem of these methods is that sometimes it fails (the methods are telling me that the polyline is self-crossing but it’s not).
Can you help me with better solution, please?
Here is a better implementation of your “Orientation” function, avoiding problems with rounding errors. Perhaps this helps in your case. It returns 0 if p0 is on a straight line between p1 and p2.
And here is my “Intersect” function: