home *** CD-ROM | disk | FTP | other *** search
/ Photo CD Demo 1 / Demo.bin / gems / graphics / raypolyg.c < prev    next >
Text File  |  1992-04-09  |  2KB  |  52 lines

  1. /*
  2. An Efficient Ray/Polygon Intersection
  3. by Didier Badouel
  4. from "Graphics Gems", Academic Press, 1990
  5. */
  6.  
  7. /* the value of t is computed.
  8.  * i1 and i2 come from the polygon description.
  9.  * V is the vertex table for the polygon and N the
  10.  * associated normal vectors.
  11.  */
  12. P[0] = ray.O[0] + ray.D[0]*t;
  13. P[1] = ray.O[1] + ray.D[1]*t;
  14. P[2] = ray.O[2] + ray.D[2]*t;
  15. u0 = P[i1] - V[0][i1]; v0 = P[i2] - V[0][i2];
  16. inter = FALSE; i = 2;
  17. do {
  18.     /* The polygon is viewed as (n-2) triangles. */
  19.     u1 = V[i-1][i1] - V[0][i1]; v1 = V[i-1][i2] - V[0][i2];
  20.     u2 = V[i  ][i1] - V[0][i1]; v2 = V[i  ][i2] - V[0][i2];
  21.  
  22.     if (u1 == 0)    {
  23.         beta = u0/u2;
  24.         if ((beta >= 0.)&&(beta <= 1.)) {
  25.             alpha = (v0 - beta*v2)/v1;
  26.             inter = ((alpha >= 0.)&&(alpha+beta) <= 1.));
  27.         }
  28.     } else {
  29.         beta = (v0*u1 - u0*v1)/(v2*u1 - u2*v1);
  30.         if ((beta >= 0.)&&(beta <= 1.)) {
  31.             alpha = (u0 - beta*u2)/u1;
  32.             inter = ((alpha >= 0)&&((alpha+beta) <= 1.));
  33.         }
  34.     }
  35. } while ((!inter)&&(++i < poly.n));
  36.  
  37. if (inter) {
  38.     /* Storing the intersection point. */
  39.     ray.P[0] = P[0]; ray.P[1] = P[1]; ray.P[2] = P[2];
  40.     /* the normal vector can be interpolated now or later. */
  41.     if (poly.interpolate) {
  42.         gamma = 1 - (alpha+beta);
  43.         ray.normal[0] = gamma * N[0][0] + alpha * N[i-1][0] + 
  44.         beta * N[i][0];
  45.         ray.normal[1] = gamma * N[0][1] + alpha * N[i-1][1] +
  46.          beta * N[i][1];
  47.         ray.normal[2] = gamma * N[0][2] + alpha * N[i-1][2] +
  48.          beta * N[i][2];
  49.     }
  50. }
  51. return (inter);
  52.