home *** CD-ROM | disk | FTP | other *** search
/ RISC DISC 3 / RISC_DISC_3.iso / resources / etexts / gems / gemsv / ch7_2 / test.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-04-04  |  2.0 KB  |  70 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include "vec.h"
  5. #include "pcube.h"
  6.  
  7.  
  8. /*
  9.  *  Calculate a vector perpendicular to a planar polygon.
  10.  *  If the polygon is non-planar, a "best fit" plane will be used.
  11.  *  The polygon may be concave or even self-intersecting,
  12.  *  but it should have nonzero area or the result will be a zero vector
  13.  *  (e.g. the "bowtie" quad).
  14.  *  The length of vector will be twice the area of the polygon.
  15.  *  NOTE:  This algorithm gives the same answer as Newell's method
  16.  *  (see Graphics Gems III) but is slightly more efficient than Newell's
  17.  *  for triangles and quads (slightly less efficient for higher polygons).
  18.  */
  19. static real *
  20. get_polygon_normal(real normal[3],
  21.            int nverts, const real verts[/* nverts */][3])
  22. {
  23.     int i;
  24.     real tothis[3], toprev[3], cross[3];
  25.  
  26.     /*
  27.      * Triangulate the polygon and sum up the nverts-2 triangle normals.
  28.      */
  29.     ZEROVEC3(normal);
  30.     VMV3(toprev, verts[1], verts[0]);      /* 3 subtracts */
  31.     for (i = 2; i <= nverts-1; ++i) {   /* n-2 times... */
  32.     VMV3(tothis, verts[i], verts[0]);    /* 3 subtracts */
  33.     VXV3(cross, toprev, tothis);         /* 3 subtracts, 6 multiplies */
  34.     VPV3(normal, normal, cross);         /* 3 adds */
  35.     SET3(toprev, tothis);
  36.     }
  37.     return normal;
  38. }
  39.  
  40.  
  41. main(int argc, char *argv[])
  42. {
  43.     int i, j, k, ntris, ins=0;
  44.     real tri[3][3], normal[3];
  45.     long fast, full;
  46.  
  47.     if(argc != 2)
  48.         exit(printf("usage: %s <ntris>\n", argv[0]));
  49.     ntris = atoi(argv[1]);
  50.     for(i=0; i<ntris; i++) {
  51.         for(j=0; j<3; j++)
  52.             for(k=0; k<3; k++)
  53.                 tri[j][k] = (drand48() - .5) * 5.0;
  54.         get_polygon_normal(normal, 3, tri);
  55.         fast = fast_polygon_intersects_cube(3, tri, normal, 0, 0);
  56.         full = polygon_intersects_cube(3, tri, normal, 0, 0);
  57.         if(fast != full)
  58.         {
  59.             printf("fast = %d, full = %d\n", fast, full);
  60.             printf("\t(%f,%f,%f)\n\t,(%f,%f,%f)\n\t,(%f,%f,%f)\n",
  61.                 tri[0][0], tri[0][1], tri[0][2],
  62.                 tri[1][0], tri[1][1], tri[1][2],
  63.                 tri[2][0], tri[2][1], tri[2][2]);
  64.         }
  65.         if(fast)
  66.             ins++;
  67.     }
  68.     printf("%f percent intersected\n", (float)ins / ntris * 100);
  69. }
  70.