home *** CD-ROM | disk | FTP | other *** search
/ RISC DISC 3 / RISC_DISC_3.iso / resources / etexts / gems / gemsv / ch4_8 / qbezier.c
Encoding:
C/C++ Source or Header  |  1995-04-04  |  2.2 KB  |  80 lines

  1. /* Quick and Simple Bezier Curve Drawing --- Robert D. Miller
  2.  * This 2-D planar Bezier curve drawing software is 3-D compliant ---
  3.  * redefine Point and change the commented lines as indicated.
  4.  */
  5.  
  6. #include <stdio.h>
  7. #define MaxCtlPoints  12
  8.  
  9. typedef struct {float x; float y;} Point;       /* for 2-D curves */
  10.                                                 /* for 3-D space curves */
  11. /* typedef struct {float x; float y; float z;} Point; */
  12. typedef Point PtArray[99];
  13. typedef Point BezArray[MaxCtlPoints];
  14.  
  15. void BezierForm(int NumCtlPoints, PtArray p, BezArray c)
  16. /*   Setup Bezier coefficient array once for each control polygon. */
  17. {
  18.     int k; long n, choose;
  19.     n= NumCtlPoints -1;
  20.     for(k = 0; k <= n; k++) {
  21.         if (k == 0) choose = 1;
  22.         else if (k == 1) choose = n;
  23.         else choose = choose *(n-k+1)/k;
  24.         c[k].x = p[k].x *choose;
  25.         c[k].y = p[k].y *choose;
  26.      /* c[k].z = p[k].z *choose; */   /* use for 3-D curves */
  27.         };
  28. }
  29.  
  30. void BezierCurve(int NumCtlPoints, BezArray c, Point *pt, float t)
  31. /*  Return Point pt(t), t <= 0 <= 1 from C, given the number
  32.     of Points in control polygon. BezierForm must be called
  33.     once for any given control polygon. */
  34. {   int k, n;
  35.     float t1, tt, u;
  36.     BezArray b;
  37.  
  38.     n = NumCtlPoints -1;  u =t;
  39.     b[0].x = c[0].x;
  40.     b[0].y = c[0].y;
  41.  /* b[0].z = c[0].z; */      /* for 3-D curves */
  42.     for(k =1; k <=n; k++) {
  43.         b[k].x = c[k].x *u;
  44.         b[k].y = c[k].y *u;
  45.         /* b[k].z = c[k].z *u   /* for 3-D curves */
  46.         u =u*t;
  47.         };
  48.  
  49.      (*pt).x = b[n].x;  (*pt).y = b[n].y;
  50.      t1 = 1-t;          tt = t1;
  51.      for(k =n-1; k >=0; k--) {
  52.          (*pt).x += b[k].x *tt;
  53.          (*pt).y += b[k].y *tt;
  54.       /* (*pt).z += b[k].z *tt;  */   /* Again, 3-D */
  55.          tt =tt*t1;
  56.          }
  57. }
  58.  
  59. float u;
  60. int   k;
  61. PtArray pn;
  62. BezArray bc;
  63. Point pt;
  64. void main ()
  65. {
  66.     pn[0].x = 100;  pn[0].y = 20;
  67.     pn[1].x = 120;  pn[1].y = 40;
  68.     pn[2].x = 140;  pn[2].y = 25;
  69.     pn[3].x = 160;  pn[3].y = 20;
  70.     BezierForm(4, pn, bc);
  71.  
  72.     for(k =0; k <=10; k++) {
  73.         BezierCurve(4, bc, &pt, (float)k/10.0);
  74.         printf("%3d  %8.4f  %8.4f\n",k, pt.x, pt.y);
  75.      /* draw curve  */
  76.      /* if (k = 0) MoveTo(pt.x, pt.y);
  77.         else LineTo(pt.x, pt.y);  */
  78.         }
  79. }
  80.