private void LineLineIntersection(
double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4, ref double[] p)
{
// x1,y1 P1 coordinates (point of line 1)
// x2,y2 P2 coordinates (point of line 1)
// x3,y3 P3 coordinates (point of line 2)
// x4,y4 P4 coordinates (point of line 2)
// p[1],p[2] intersection coordinates
//
// This function returns a pointer array which first index indicates
// weather they intersect on one point or not, followed by coordinate pairs.
double u_a, u_b, denom;
// calculate denominator first
denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
u_a = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);
u_b = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3);
// if denominator and numerator equal to zero, lines are coincident
if (Math.Abs(denom - 0.0) < EPS && (Math.Abs(u_b - 0.0) < EPS && Math.Abs(u_a - 0.0) < EPS))
{
p[0] = 0.0;
}
// if denominator equals to zero, lines are parallel
else if (Math.Abs(denom - 0.0) < EPS)
{
p[0] = 0.0;
}
else
{
p[0] = 1.0;
u_a = u_a / denom;
u_b = u_b / denom;
p[1] = x1 + u_a * (x2 - x1); // not the intersection point
p[2] = y1 + u_a * (y2 - y1);
}
}