| 882 | //----------------------------------------------------------------------------- |
| 883 | |
| 884 | bool mLineTriangleCollide( const Point3F &p1, const Point3F &p2, |
| 885 | const Point3F &t1, const Point3F &t2, const Point3F &t3, |
| 886 | Point3F *outUVW, F32 *outT ) |
| 887 | { |
| 888 | VectorF ab = t2 - t1; |
| 889 | VectorF ac = t3 - t1; |
| 890 | VectorF qp = p1 - p2; |
| 891 | |
| 892 | // Compute triangle normal. Can be precalculated or cached if |
| 893 | // intersecting multiple segments against the same triangle |
| 894 | VectorF n = mCross( ab, ac ); |
| 895 | |
| 896 | // Compute denominator d. If d <= 0, segment is parallel to or points |
| 897 | // away from triangle, so exit early |
| 898 | F32 d = mDot( qp, n ); |
| 899 | if ( d <= 0.0f ) |
| 900 | return false; |
| 901 | |
| 902 | // Compute intersection t value of pq with plane of triangle. A ray |
| 903 | // intersects if 0 <= t. Segment intersects iff 0 <= t <= 1. Delay |
| 904 | // dividing by d until intersection has been found to pierce triangle |
| 905 | VectorF ap = p1 - t1; |
| 906 | F32 t = mDot( ap, n ); |
| 907 | if ( t < 0.0f ) |
| 908 | return false; |
| 909 | if ( t > d ) |
| 910 | return false; // For segment; exclude this code line for a ray test |
| 911 | |
| 912 | // Compute barycentric coordinate components and test if within bounds |
| 913 | VectorF e = mCross( qp, ap ); |
| 914 | F32 v = mDot( ac, e ); |
| 915 | if ( v < 0.0f || v > d ) |
| 916 | return false; |
| 917 | F32 w = -mDot( ab, e ); |
| 918 | if ( w < 0.0f || v + w > d ) |
| 919 | return false; |
| 920 | |
| 921 | // Segment/ray intersects triangle. Perform delayed division and |
| 922 | // compute the last barycentric coordinate component |
| 923 | const F32 ood = 1.0f / d; |
| 924 | |
| 925 | if ( outT ) |
| 926 | *outT = t * ood; |
| 927 | |
| 928 | if ( outUVW ) |
| 929 | { |
| 930 | v *= ood; |
| 931 | w *= ood; |
| 932 | outUVW->set( 1.0f - v - w, v, w ); |
| 933 | } |
| 934 | |
| 935 | return true; |
| 936 | } |
| 937 | |
| 938 | //----------------------------------------------------------------------------- |
| 939 | |