Skip to content

Instantly share code, notes, and snippets.

@ThePhD
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThePhD/03a6eb2ba462fac1d67a to your computer and use it in GitHub Desktop.
Save ThePhD/03a6eb2ba462fac1d67a to your computer and use it in GitHub Desktop.
template <typename T>
optional<THit3<T>> intersect( const TRay3<T>& ray, const RTriangle3<T>& target, bool singlesided = false ) {
THit3<T> hit;
RVector3<T> edgeb = target.b - target.a;
RVector3<T> edgec = target.c - target.a;
RVector3<T> nperpendicular = cross( edgec, ray.direction );
T determinant = dot( edgeb, nperpendicular );
if ( determinant == static_cast<T>( 0 ) || ( singlesided && ( determinant > static_cast<T>( 0 ) ) ) )
return nullopt;
RVector3<T> atoorigin = ray.origin - target.a;
T u = dot( atoorigin, nperpendicular ) / determinant;
if ( u < static_cast<T>( 0 ) || u > static_cast<T>( 1 ) )
return nullopt;
RVector3<T> originedgecross = cross( atoorigin, edgeb );
T v = dot( ray.direction, originedgecross ) / determinant;
if ( v < static_cast<T>( 0 ) || v > static_cast<T>( 1 ) )
return nullopt;
hit.distance0 = hit.distance1 = dot( edgec, originedgecross ) / determinant;
if ( !( hit.distance0 > static_cast<T>( 0 ) ) )
return nullopt;
hit.contact = ray.at( hit.distance0 );
hit.stu.s = u;
hit.stu.t = v;
hit.inside = false;
return std::move( hit );
}
void testhit( Ray3 ray, Triangle3 triangle ) {
auto hit = intersect( ray, triangle );
std::cout << ( hit ? "Hit!" : "Sad." ) << std::endl;
}
int main( ) {
Triangle3 triangle(
Vector3{ 0, 0, 0 },
Vector3{ 0, 4, 0 },
Vector3{ 4, 0, 0 } );
Vector3 dir0( 0, 0, 1 );
testhit( { Vector3( 4, 4, -30 ), dir0 }, triangle );
testhit( { Vector3( 1, 1, -30 ), dir0 }, triangle );
testhit( { Vector3( 0, 0, -30 ), dir0 }, triangle );
testhit( { Vector3( -1, 0, -30 ), dir0 }, triangle );
testhit( { Vector3( 0, -1, -30 ), dir0 }, triangle );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment