// file Line.java class DegenerateLine extends Exception {} class ParallelException extends Exception {} public class Line { // An unbounded line of the parameterized form { p + t*v | -infty < t < infty } // is implemented as the pair [p,v] where p is the point and v is the direction public double[] point; public double[] direction; // Constructor public Line (double[] p, double[] d) throws DegenerateLine { if (VecMagSquared(d) < epsilon*epsilon) throw new DegenerateLine(); point = p; direction = d; } public String toString() { return "L: [" + point[0] + ", " + point[1] + "] [" + direction [0] + ", " + direction [1] + "]"; } // Computes the intersection of Line this with Line l2. Returns a quadruple: // xi, yi, the coordinates of the intersection // and t1, t2, the associated parameters on each line. // That is, [x1,y1} = this.point + t1*this.direction = // l2.point + t2*this.direction // Throw an exception if the lines are parallel. public double[] intersect(Line l2) throws ParallelException { double det = direction[0]*l2.direction[1] - direction[1]*l2.direction[0]; if (- epsilon < det && det < epsilon) throw new ParallelException(); double[] ans = new double[4]; ans[2] = ((l2.point[0]-point[0])*l2.direction[1] - (l2.point[1]-point[1])*l2.direction[0]) / det; ans[3] = ((l2.point[0]-point[0])*direction[1] - (l2.point[1]-point[1])*direction[0]) / det; ans[0] = point[0] + ans[2] * direction[0]; ans[1] = point[1] + ans[2] * direction[1]; return ans; } // end intersect public static final double epsilon = 0.001; // Small distance // Magnitude of vector v squared. public static double SumSquared(double x, double y) { return x*x + y*y; } public static double VecMagSquared(double[] v) { return SumSquared(v[0],v[1]); } public static double DistSquared(double[] p1, double[] p2) { return SumSquared(p2[0]-p1[0], p2[1]-p1[1]); } } // end Line