lineLineMinimumPoints method

List<Vector3> lineLineMinimumPoints(
  1. dynamic line1,
  2. dynamic line2
)

Implementation

List<Vector3> lineLineMinimumPoints( line1, line2 ){
  Vector3 r = _v1.copy( line1.end ).sub( line1.start );
  Vector3 s = _v2.copy( line2.end ).sub( line2.start );
  Vector3 w = _v3.copy( line2.start ).sub( line1.start );

  num a = r.dot( s ),
    b = r.dot( r ),
    c = s.dot( s ),
    d = s.dot( w ),
    e = r.dot( w );

  double t1;
  double t2;
  num divisor = b * c - a * a;

  if ( Math.abs( divisor ) < EPS ) {
    double d1 = - d / c;
    double d2 = ( a - d ) / c;

    if ( Math.abs( d1 - 0.5 ) < Math.abs( d2 - 0.5 ) ) {
      t1 = 0;
      t2 = d1;
    }
    else {
      t1 = 1;
      t2 = d2;
    }
  }
  else {
    t1 = ( d * a + e * c ) / divisor;
    t2 = ( t1 * a - d ) / c;
  }

  t2 = Math.max( 0, Math.min( 1, t2 ) );
  t1 = Math.max( 0, Math.min( 1, t1 ) );

  Vector3 point1 = r.multiplyScalar( t1 ).add( line1.start );
  Vector3 point2 = s.multiplyScalar( t2 ).add( line2.start );

  return [point1, point2];
}