Ejemplo n.º 1
0
int intersect3D_RayTriangle( Ray R, Triangle T, Point &I )
{
   // Vector    u, v, n;              // triangle vectors
    //Vector    dir, w0, w;           // ray vectors
    float     r, a, b;              // params to calc ray-plane intersect

    // get triangle edge vectors and plane normal
    Vector u(T.V0(), T.V1());
    Vector v(T.V0(), T.V2());
    Vector n(u,v);              // cross product
    if (n.vecteurNull())             // triangle is degenerate
        return -1;                  // do not deal with this case

    Vector dir(R.P1(), R.P0());              // ray direction vector
    Vector w0(R.P0(),T.V0());
    a = - n.dot(w0);
    b = n.dot(dir);
    if (fabs(b) < SMALL_NUM) {     // ray is  parallel to triangle plane
        if (a == 0)                 // ray lies in triangle plane
            return 2;
        else return 0;              // ray disjoint from plane
    }

    // get intersect point of ray with triangle plane
    r = a / b;
    if (r < 0.0)                    // ray goes away from triangle
        return 0;                   // => no intersect
    // for a segment, also test if (r > 1.0) => no intersect

    I.setCoordonne(R.P0().x() + r * dir.x(), R.P0().y() + r * dir.y(),R.P0().z() + r * dir.z()); // intersect point of ray and plane

    // is I inside T?
    float    uu, uv, vv, wu, wv, D;
    uu = u.dot(u);
    uv = u.dot(v);
    vv = v.dot(v);
    Vector w(I,T.V0());
    wu = w.dot(u);
    wv = w.dot(v);
    D = uv * uv - uu * vv;

    // get and test parametric coords
    float s, t;
    s = (uv * wv - vv * wu) / D;
    if (s < 0.0 || s > 1.0)         // I is outside T
        return 0;
    t = (uv * wu - uu * wv) / D;
    if (t < 0.0 || (s + t) > 1.0)  // I is outside T
        return 0;

    return 1;                       // I is in T
}