triangleSphereIntersect method

OctreeData? triangleSphereIntersect(
  1. Sphere sphere,
  2. Triangle triangle
)

Implementation

OctreeData? triangleSphereIntersect(Sphere sphere, Triangle triangle ) {
  triangle.getPlane( _plane );
  if(!sphere.intersectsPlane( _plane )) return null;
  double depth = _plane.distanceToSphere( sphere ).abs();
  double r2 = sphere.radius * sphere.radius - depth * depth;

  _plane.projectPoint( sphere.center, _v1 );

  if ( triangle.containsPoint( sphere.center ) ) {
    print('here2');
    return OctreeData(
      normal: _plane.normal.clone(),
      point: _v1.clone(),
      depth: _plane.distanceToSphere(sphere).abs()
    );
  }

  List<List<vmath.Vector3>> lines = [
    [ triangle.a, triangle.b ],
    [ triangle.b, triangle.c ],
    [ triangle.c, triangle.a ]
  ];

  for (int i = 0; i < lines.length; i ++ ) {
    _line1.set( lines[ i ][ 0 ], lines[ i ][ 1 ] );
    _line1.closestPointToPoint( _v1, true, _v2 );

    double d = _v2.distanceToSquared( sphere.center );
    vmath.Vector3 n = sphere.center.clone()..sub( _v2 )..normalize();
    if ( d < r2 ) {
      return OctreeData(
        normal: n,
        point: sphere.position.clone()..addScaled(n, sphere.radius),
        depth: sphere.radius - math.sqrt(d)
      );
    }
  }

  return null;
}