public static boolean intersect ( LineParametric3D_F64 line , Sphere3D_F64 sphere , Point3D_F64 a , Point3D_F64 b ) { // this equation was found by solving for l: // ||(P + V*l) - X0|| == r double r2 = sphere . radius * sphere . radius ; double PP = GeometryMath_F64 . dot ( line . p , line . p ) ; double PV = GeometryMath_F64 . dot ( line . p , line . slope ) ; double PX = GeometryMath_F64 . dot ( line . p , sphere . center ) ; double VV = GeometryMath_F64 . dot ( line . slope , line . slope ) ; double VX = GeometryMath_F64 . dot ( line . slope , sphere . center ) ; double XX = GeometryMath_F64 . dot ( sphere . center , sphere . center ) ; // Coefficients in the quadratic equation double A = VV ; double B = 2.0 * ( PV - VX ) ; double C = PP + XX - 2.0 * PX - r2 ; // solve for the quadratic equation double inner = B * B - 4.0 * A * C ; if ( inner < 0 ) return false ; double sqrt = Math . sqrt ( inner ) ; double t0 = ( - B + sqrt ) / ( 2.0 * A ) ; double t1 = ( - B - sqrt ) / ( 2.0 * A ) ; line . setPointOnLine ( t0 , a ) ; line . setPointOnLine ( t1 , b ) ; return true ; }
Finds the intersection of a line and sphere . There can be 0 1 or 2 intersections . If there is 1 intersection the same point is returned twice .