home *** CD-ROM | disk | FTP | other *** search
/ Web Designer 98 (Professional) / WebDesigner 1.0.iso / cgi2 / fly_tar.z / fly_tar / fly / gd1.2 / gd.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-01-02  |  58.7 KB  |  2,536 lines

  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include "gd.h"
  6. #include "mtables.c"
  7.  
  8. static void gdImageBrushApply(gdImagePtr im, int x, int y);
  9. static void gdImageTileApply(gdImagePtr im, int x, int y);
  10.  
  11. gdImagePtr gdImageCreate(int sx, int sy)
  12. {
  13.     int i;
  14.     gdImagePtr im;
  15.     im = (gdImage *) malloc(sizeof(gdImage));
  16.     im->pixels = (unsigned char **) malloc(sizeof(unsigned char *) * sx);
  17.     im->polyInts = 0;
  18.     im->polyAllocated = 0;
  19.     im->brush = 0;
  20.     im->tile = 0;
  21.     im->style = 0;
  22.     for (i=0; (i<sx); i++) {
  23.         im->pixels[i] = (unsigned char *) calloc(
  24.             sy, sizeof(unsigned char));
  25.     }    
  26.     im->sx = sx;
  27.     im->sy = sy;
  28.     im->colorsTotal = 0;
  29.     im->transparent = (-1);
  30.     im->interlace = 0;
  31.     return im;
  32. }
  33.  
  34. void gdImageDestroy(gdImagePtr im)
  35. {
  36.     int i;
  37.     for (i=0; (i<im->sx); i++) {
  38.         free(im->pixels[i]);
  39.     }    
  40.     free(im->pixels);
  41.     if (im->polyInts) {
  42.             free(im->polyInts);
  43.     }
  44.     if (im->style) {
  45.         free(im->style);
  46.     }
  47.     free(im);
  48. }
  49.  
  50. int gdImageColorClosest(gdImagePtr im, int r, int g, int b)
  51. {
  52.     int i;
  53.     long rd, gd, bd;
  54.     int ct = (-1);
  55.     long mindist = 0;
  56.     for (i=0; (i<(im->colorsTotal)); i++) {
  57.         long dist;
  58.         if (im->open[i]) {
  59.             continue;
  60.         }
  61.         rd = (im->red[i] - r);    
  62.         gd = (im->green[i] - g);
  63.         bd = (im->blue[i] - b);
  64.         dist = rd * rd + gd * gd + bd * bd;
  65.         if ((i == 0) || (dist < mindist)) {
  66.             mindist = dist;    
  67.             ct = i;
  68.         }
  69.     }
  70.     return ct;
  71. }
  72.  
  73. int gdImageColorExact(gdImagePtr im, int r, int g, int b)
  74. {
  75.     int i;
  76.     for (i=0; (i<(im->colorsTotal)); i++) {
  77.         if (im->open[i]) {
  78.             continue;
  79.         }
  80.         if ((im->red[i] == r) && 
  81.             (im->green[i] == g) &&
  82.             (im->blue[i] == b)) {
  83.             return i;
  84.         }
  85.     }
  86.     return -1;
  87. }
  88.  
  89. int gdImageColorAllocate(gdImagePtr im, int r, int g, int b)
  90. {
  91.     int i;
  92.     int ct = (-1);
  93.     for (i=0; (i<(im->colorsTotal)); i++) {
  94.         if (im->open[i]) {
  95.             ct = i;
  96.             break;
  97.         }
  98.     }    
  99.     if (ct == (-1)) {
  100.         ct = im->colorsTotal;
  101.         if (ct == gdMaxColors) {
  102.             return -1;
  103.         }
  104.         im->colorsTotal++;
  105.     }
  106.     im->red[ct] = r;
  107.     im->green[ct] = g;
  108.     im->blue[ct] = b;
  109.     im->open[ct] = 0;
  110.     return ct;
  111. }
  112.  
  113. void gdImageColorDeallocate(gdImagePtr im, int color)
  114. {
  115.     /* Mark it open. */
  116.     im->open[color] = 1;
  117. }
  118.  
  119. void gdImageColorTransparent(gdImagePtr im, int color)
  120. {
  121.     im->transparent = color;
  122. }
  123.  
  124. void gdImageSetPixel(gdImagePtr im, int x, int y, int color)
  125. {
  126.     int p;
  127.     switch(color) {
  128.         case gdStyled:
  129.         if (!im->style) {
  130.             /* Refuse to draw if no style is set. */
  131.             return;
  132.         } else {
  133.             p = im->style[im->stylePos++];
  134.         }
  135.         if (p != (gdTransparent)) {
  136.             gdImageSetPixel(im, x, y, p);
  137.         }
  138.         im->stylePos = im->stylePos %  im->styleLength;
  139.         break;
  140.         case gdStyledBrushed:
  141.         if (!im->style) {
  142.             /* Refuse to draw if no style is set. */
  143.             return;
  144.         }
  145.         p = im->style[im->stylePos++];
  146.         if ((p != gdTransparent) && (p != 0)) {
  147.             gdImageSetPixel(im, x, y, gdBrushed);
  148.         }
  149.         im->stylePos = im->stylePos %  im->styleLength;
  150.         break;
  151.         case gdBrushed:
  152.         gdImageBrushApply(im, x, y);
  153.         break;
  154.         case gdTiled:
  155.         gdImageTileApply(im, x, y);
  156.         break;
  157.         default:
  158.         if (gdImageBoundsSafe(im, x, y)) {
  159.              im->pixels[x][y] = color;
  160.         }
  161.         break;
  162.     }
  163. }
  164.  
  165. static void gdImageBrushApply(gdImagePtr im, int x, int y)
  166. {
  167.     int lx, ly;
  168.     int hy;
  169.     int hx;
  170.     int x1, y1, x2, y2;
  171.     int srcx, srcy;
  172.     if (!im->brush) {
  173.         return;
  174.     }
  175.     hy = gdImageSY(im->brush)/2;
  176.     y1 = y - hy;
  177.     y2 = y1 + gdImageSY(im->brush);    
  178.     hx = gdImageSX(im->brush)/2;
  179.     x1 = x - hx;
  180.     x2 = x1 + gdImageSX(im->brush);
  181.     srcy = 0;
  182.     for (ly = y1; (ly < y2); ly++) {
  183.         srcx = 0;
  184.         for (lx = x1; (lx < x2); lx++) {
  185.             int p;
  186.             p = gdImageGetPixel(im->brush, srcx, srcy);
  187.             /* Allow for non-square brushes! */
  188.             if (p != gdImageGetTransparent(im->brush)) {
  189.                 gdImageSetPixel(im, lx, ly,
  190.                     im->brushColorMap[p]);
  191.             }
  192.             srcx++;
  193.         }
  194.         srcy++;
  195.     }    
  196. }        
  197.  
  198. static void gdImageTileApply(gdImagePtr im, int x, int y)
  199. {
  200.     int srcx, srcy;
  201.     int p;
  202.     if (!im->tile) {
  203.         return;
  204.     }
  205.     srcx = x % gdImageSX(im->tile);
  206.     srcy = y % gdImageSY(im->tile);
  207.     p = gdImageGetPixel(im->tile, srcx, srcy);
  208.     /* Allow for transparency */
  209.     if (p != gdImageGetTransparent(im->tile)) {
  210.         gdImageSetPixel(im, x, y,
  211.             im->tileColorMap[p]);
  212.     }
  213. }        
  214.  
  215. int gdImageGetPixel(gdImagePtr im, int x, int y)
  216. {
  217.     if (gdImageBoundsSafe(im, x, y)) {
  218.         return im->pixels[x][y];
  219.     } else {
  220.         return 0;
  221.     }
  222. }
  223.  
  224. /* Bresenham as presented in Foley & Van Dam */
  225.  
  226. void gdImageLine(gdImagePtr im, int x1, int y1, int x2, int y2, int color)
  227. {
  228.     int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag;
  229.     dx = abs(x2-x1);
  230.     dy = abs(y2-y1);
  231.     if (dy <= dx) {
  232.         d = 2*dy - dx;
  233.         incr1 = 2*dy;
  234.         incr2 = 2 * (dy - dx);
  235.         if (x1 > x2) {
  236.             x = x2;
  237.             y = y2;
  238.             ydirflag = (-1);
  239.             xend = x1;
  240.         } else {
  241.             x = x1;
  242.             y = y1;
  243.             ydirflag = 1;
  244.             xend = x2;
  245.         }
  246.         gdImageSetPixel(im, x, y, color);
  247.         if (((y2 - y1) * ydirflag) > 0) {
  248.             while (x < xend) {
  249.                 x++;
  250.                 if (d <0) {
  251.                     d+=incr1;
  252.                 } else {
  253.                     y++;
  254.                     d+=incr2;
  255.                 }
  256.                 gdImageSetPixel(im, x, y, color);
  257.             }
  258.         } else {
  259.             while (x < xend) {
  260.                 x++;
  261.                 if (d <0) {
  262.                     d+=incr1;
  263.                 } else {
  264.                     y--;
  265.                     d+=incr2;
  266.                 }
  267.                 gdImageSetPixel(im, x, y, color);
  268.             }
  269.         }        
  270.     } else {
  271.         d = 2*dx - dy;
  272.         incr1 = 2*dx;
  273.         incr2 = 2 * (dx - dy);
  274.         if (y1 > y2) {
  275.             y = y2;
  276.             x = x2;
  277.             yend = y1;
  278.             xdirflag = (-1);
  279.         } else {
  280.             y = y1;
  281.             x = x1;
  282.             yend = y2;
  283.             xdirflag = 1;
  284.         }
  285.         gdImageSetPixel(im, x, y, color);
  286.         if (((x2 - x1) * xdirflag) > 0) {
  287.             while (y < yend) {
  288.                 y++;
  289.                 if (d <0) {
  290.                     d+=incr1;
  291.                 } else {
  292.                     x++;
  293.                     d+=incr2;
  294.                 }
  295.                 gdImageSetPixel(im, x, y, color);
  296.             }
  297.         } else {
  298.             while (y < yend) {
  299.                 y++;
  300.                 if (d <0) {
  301.                     d+=incr1;
  302.                 } else {
  303.                     x--;
  304.                     d+=incr2;
  305.                 }
  306.                 gdImageSetPixel(im, x, y, color);
  307.             }
  308.         }
  309.     }
  310. }
  311.  
  312. /* As above, plus dashing */
  313.  
  314. #define dashedSet \
  315.     { \
  316.         dashStep++; \
  317.         if (dashStep == gdDashSize) { \
  318.             dashStep = 0; \
  319.             on = !on; \
  320.         } \
  321.         if (on) { \
  322.             gdImageSetPixel(im, x, y, color); \
  323.         } \
  324.     }
  325.  
  326. void gdImageDashedLine(gdImagePtr im, int x1, int y1, int x2, int y2, int color)
  327. {
  328.     int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag;
  329.     int dashStep = 0;
  330.     int on = 1;
  331.     dx = abs(x2-x1);
  332.     dy = abs(y2-y1);
  333.     if (dy <= dx) {
  334.         d = 2*dy - dx;
  335.         incr1 = 2*dy;
  336.         incr2 = 2 * (dy - dx);
  337.         if (x1 > x2) {
  338.             x = x2;
  339.             y = y2;
  340.             ydirflag = (-1);
  341.             xend = x1;
  342.         } else {
  343.             x = x1;
  344.             y = y1;
  345.             ydirflag = 1;
  346.             xend = x2;
  347.         }
  348.         dashedSet;
  349.         if (((y2 - y1) * ydirflag) > 0) {
  350.             while (x < xend) {
  351.                 x++;
  352.                 if (d <0) {
  353.                     d+=incr1;
  354.                 } else {
  355.                     y++;
  356.                     d+=incr2;
  357.                 }
  358.                 dashedSet;
  359.             }
  360.         } else {
  361.             while (x < xend) {
  362.                 x++;
  363.                 if (d <0) {
  364.                     d+=incr1;
  365.                 } else {
  366.                     y--;
  367.                     d+=incr2;
  368.                 }
  369.                 dashedSet;
  370.             }
  371.         }        
  372.     } else {
  373.         d = 2*dx - dy;
  374.         incr1 = 2*dx;
  375.         incr2 = 2 * (dx - dy);
  376.         if (y1 > y2) {
  377.             y = y2;
  378.             x = x2;
  379.             yend = y1;
  380.             xdirflag = (-1);
  381.         } else {
  382.             y = y1;
  383.             x = x1;
  384.             yend = y2;
  385.             xdirflag = 1;
  386.         }
  387.         dashedSet;
  388.         if (((x2 - x1) * xdirflag) > 0) {
  389.             while (y < yend) {
  390.                 y++;
  391.                 if (d <0) {
  392.                     d+=incr1;
  393.                 } else {
  394.                     x++;
  395.                     d+=incr2;
  396.                 }
  397.                 dashedSet;
  398.             }
  399.         } else {
  400.             while (y < yend) {
  401.                 y++;
  402.                 if (d <0) {
  403.                     d+=incr1;
  404.                 } else {
  405.                     x--;
  406.                     d+=incr2;
  407.                 }
  408.                 dashedSet;
  409.             }
  410.         }
  411.     }
  412. }
  413.  
  414. int gdImageBoundsSafe(gdImagePtr im, int x, int y)
  415. {
  416.     return (!(((y < 0) || (y >= im->sy)) ||
  417.         ((x < 0) || (x >= im->sx))));
  418. }
  419.  
  420. void gdImageChar(gdImagePtr im, gdFontPtr f, int x, int y, int c, int color)
  421. {
  422.     int cx, cy;
  423.     int px, py;
  424.     int fline;
  425.     cx = 0;
  426.     cy = 0;
  427.     if ((c < f->offset) || (c >= (f->offset + f->nchars))) {
  428.         return;
  429.     }
  430.     fline = (c - f->offset) * f->h * f->w;
  431.     for (py = y; (py < (y + f->h)); py++) {
  432.         for (px = x; (px < (x + f->w)); px++) {
  433.             if (f->data[fline + cy * f->w + cx]) {
  434.                 gdImageSetPixel(im, px, py, color);    
  435.             }
  436.             cx++;
  437.         }
  438.         cx = 0;
  439.         cy++;
  440.     }
  441. }
  442.  
  443. void gdImageCharUp(gdImagePtr im, gdFontPtr f, int x, int y, char c, int color)
  444. {
  445.     int cx, cy;
  446.     int px, py;
  447.     int fline;
  448.     cx = 0;
  449.     cy = 0;
  450.     if ((c < f->offset) || (c >= (f->offset + f->nchars))) {
  451.         return;
  452.     }
  453.     fline = (c - f->offset) * f->h * f->w;
  454.     for (py = y; (py > (y - f->w)); py--) {
  455.         for (px = x; (px < (x + f->h)); px++) {
  456.             if (f->data[fline + cy * f->w + cx]) {
  457.                 gdImageSetPixel(im, px, py, color);    
  458.             }
  459.             cy++;
  460.         }
  461.         cy = 0;
  462.         cx++;
  463.     }
  464. }
  465.  
  466. void gdImageString(gdImagePtr im, gdFontPtr f, int x, int y, char *s, int color)
  467. {
  468.     int i;
  469.     int l;
  470.     l = strlen(s);
  471.     for (i=0; (i<l); i++) {
  472.         gdImageChar(im, f, x, y, s[i], color);
  473.         x += f->w;
  474.     }
  475. }
  476.  
  477. void gdImageStringUp(gdImagePtr im, gdFontPtr f, int x, int y, char *s, int color)
  478. {
  479.     int i;
  480.     int l;
  481.     l = strlen(s);
  482.     for (i=0; (i<l); i++) {
  483.         gdImageCharUp(im, f, x, y, s[i], color);
  484.         y -= f->w;
  485.     }
  486. }
  487.  
  488. /* s and e are integers modulo 360 (degrees), with 0 degrees
  489.   being the rightmost extreme and degrees changing clockwise.
  490.   cx and cy are the center in pixels; w and h are the horizontal 
  491.   and vertical diameter in pixels. Nice interface, but slow, since
  492.   I don't yet use Bresenham (I'm using an inefficient but
  493.   simple solution with too much work going on in it; generalizing
  494.   Bresenham to ellipses and partial arcs of ellipses is non-trivial,
  495.   at least for me) and there are other inefficiencies (small circles
  496.   do far too much work). */
  497.  
  498. void gdImageArc(gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color)
  499. {
  500.     int i;
  501.     int lx = 0, ly = 0;
  502.     int w2, h2;
  503.     w2 = w/2;
  504.     h2 = h/2;
  505.     while (e < s) {
  506.         e += 360;
  507.     }
  508.     for (i=s; (i <= e); i++) {
  509.         int x, y;
  510.         x = ((long)cost[i % 360] * (long)w2 / costScale) + cx; 
  511.         y = ((long)sint[i % 360] * (long)h2 / sintScale) + cy;
  512.         if (i != s) {
  513.             gdImageLine(im, lx, ly, x, y, color);    
  514.         }
  515.         lx = x;
  516.         ly = y;
  517.     }
  518. }
  519.  
  520.  
  521. #if 0
  522.     /* Bresenham octant code, which I should use eventually */
  523.     int x, y, d;
  524.     x = 0;
  525.     y = w;
  526.     d = 3-2*w;
  527.     while (x < y) {
  528.         gdImageSetPixel(im, cx+x, cy+y, color);
  529.         if (d < 0) {
  530.             d += 4 * x + 6;
  531.         } else {
  532.             d += 4 * (x - y) + 10;
  533.             y--;
  534.         }
  535.         x++;
  536.     }
  537.     if (x == y) {
  538.         gdImageSetPixel(im, cx+x, cy+y, color);
  539.     }
  540. #endif
  541.  
  542. void gdImageFillToBorder(gdImagePtr im, int x, int y, int border, int color)
  543. {
  544.     int lastBorder;
  545.     /* Seek left */
  546.     int leftLimit, rightLimit;
  547.     int i;
  548.     leftLimit = (-1);
  549.     if (border < 0) {
  550.         /* Refuse to fill to a non-solid border */
  551.         return;
  552.     }
  553.     for (i = x; (i >= 0); i--) {
  554.         if (gdImageGetPixel(im, i, y) == border) {
  555.             break;
  556.         }
  557.         gdImageSetPixel(im, i, y, color);
  558.         leftLimit = i;
  559.     }
  560.     if (leftLimit == (-1)) {
  561.         return;
  562.     }
  563.     /* Seek right */
  564.     rightLimit = x;
  565.     for (i = (x+1); (i < im->sx); i++) {    
  566.         if (gdImageGetPixel(im, i, y) == border) {
  567.             break;
  568.         }
  569.         gdImageSetPixel(im, i, y, color);
  570.         rightLimit = i;
  571.     }
  572.     /* Look at lines above and below and start paints */
  573.     /* Above */
  574.     if (y > 0) {
  575.         lastBorder = 1;
  576.         for (i = leftLimit; (i <= rightLimit); i++) {
  577.             int c;
  578.             c = gdImageGetPixel(im, i, y-1);
  579.             if (lastBorder) {
  580.                 if ((c != border) && (c != color)) {    
  581.                     gdImageFillToBorder(im, i, y-1, 
  582.                         border, color);        
  583.                     lastBorder = 0;
  584.                 }
  585.             } else if ((c == border) || (c == color)) {
  586.                 lastBorder = 1;
  587.             }
  588.         }
  589.     }
  590.     /* Below */
  591.     if (y < ((im->sy) - 1)) {
  592.         lastBorder = 1;
  593.         for (i = leftLimit; (i <= rightLimit); i++) {
  594.             int c;
  595.             c = gdImageGetPixel(im, i, y+1);
  596.             if (lastBorder) {
  597.                 if ((c != border) && (c != color)) {    
  598.                     gdImageFillToBorder(im, i, y+1, 
  599.                         border, color);        
  600.                     lastBorder = 0;
  601.                 }
  602.             } else if ((c == border) || (c == color)) {
  603.                 lastBorder = 1;
  604.             }
  605.         }
  606.     }
  607. }
  608.  
  609. void gdImageFill(gdImagePtr im, int x, int y, int color)
  610. {
  611.     int lastBorder;
  612.     int old;
  613.     int leftLimit, rightLimit;
  614.     int i;
  615.     old = gdImageGetPixel(im, x, y);
  616.     if (color == gdTiled) {
  617.         /* Tile fill -- got to watch out! */
  618.         int p, tileColor;    
  619.         int srcx, srcy;
  620.         if (!im->tile) {
  621.             return;
  622.         }
  623.         /* Refuse to flood-fill with a transparent pattern --
  624.             I can't do it without allocating another image */
  625.         if (gdImageGetTransparent(im->tile) != (-1)) {
  626.             return;
  627.         }    
  628.         srcx = x % gdImageSX(im->tile);
  629.         srcy = y % gdImageSY(im->tile);
  630.         p = gdImageGetPixel(im->tile, srcx, srcy);
  631.         tileColor = im->tileColorMap[p];
  632.         if (old == tileColor) {
  633.             /* Nothing to be done */
  634.             return;
  635.         }
  636.     } else {
  637.         if (old == color) {
  638.             /* Nothing to be done */
  639.             return;
  640.         }
  641.     }
  642.     /* Seek left */
  643.     leftLimit = (-1);
  644.     for (i = x; (i >= 0); i--) {
  645.         if (gdImageGetPixel(im, i, y) != old) {
  646.             break;
  647.         }
  648.         gdImageSetPixel(im, i, y, color);
  649.         leftLimit = i;
  650.     }
  651.     if (leftLimit == (-1)) {
  652.         return;
  653.     }
  654.     /* Seek right */
  655.     rightLimit = x;
  656.     for (i = (x+1); (i < im->sx); i++) {    
  657.         if (gdImageGetPixel(im, i, y) != old) {
  658.             break;
  659.         }
  660.         gdImageSetPixel(im, i, y, color);
  661.         rightLimit = i;
  662.     }
  663.     /* Look at lines above and below and start paints */
  664.     /* Above */
  665.     if (y > 0) {
  666.         lastBorder = 1;
  667.         for (i = leftLimit; (i <= rightLimit); i++) {
  668.             int c;
  669.             c = gdImageGetPixel(im, i, y-1);
  670.             if (lastBorder) {
  671.                 if (c == old) {    
  672.                     gdImageFill(im, i, y-1, color);        
  673.                     lastBorder = 0;
  674.                 }
  675.             } else if (c != old) {
  676.                 lastBorder = 1;
  677.             }
  678.         }
  679.     }
  680.     /* Below */
  681.     if (y < ((im->sy) - 1)) {
  682.         lastBorder = 1;
  683.         for (i = leftLimit; (i <= rightLimit); i++) {
  684.             int c;
  685.             c = gdImageGetPixel(im, i, y+1);
  686.             if (lastBorder) {
  687.                 if (c == old) {
  688.                     gdImageFill(im, i, y+1, color);        
  689.                     lastBorder = 0;
  690.                 }
  691.             } else if (c != old) {
  692.                 lastBorder = 1;
  693.             }
  694.         }
  695.     }
  696. }
  697.     
  698. #ifdef TEST_CODE
  699. void gdImageDump(gdImagePtr im)
  700. {
  701.     int i, j;
  702.     for (i=0; (i < im->sy); i++) {
  703.         for (j=0; (j < im->sx); j++) {
  704.             printf("%d", im->pixels[j][i]);
  705.         }
  706.         printf("\n");
  707.     }
  708. }
  709. #endif
  710.  
  711. /* Code drawn from ppmtogif.c, from the pbmplus package
  712. **
  713. ** Based on GIFENCOD by David Rowley <mgardi@watdscu.waterloo.edu>. A
  714. ** Lempel-Zim compression based on "compress".
  715. **
  716. ** Modified by Marcel Wijkstra <wijkstra@fwi.uva.nl>
  717. **
  718. ** Copyright (C) 1989 by Jef Poskanzer.
  719. **
  720. ** Permission to use, copy, modify, and distribute this software and its
  721. ** documentation for any purpose and without fee is hereby granted, provided
  722. ** that the above copyright notice appear in all copies and that both that
  723. ** copyright notice and this permission notice appear in supporting
  724. ** documentation.  This software is provided "as is" without express or
  725. ** implied warranty.
  726. **
  727. ** The Graphics Interchange Format(c) is the Copyright property of
  728. ** CompuServe Incorporated.  GIF(sm) is a Service Mark property of
  729. ** CompuServe Incorporated.
  730. */
  731.  
  732. /*
  733.  * a code_int must be able to hold 2**GIFBITS values of type int, and also -1
  734.  */
  735. typedef int             code_int;
  736.  
  737. #ifdef SIGNED_COMPARE_SLOW
  738. typedef unsigned long int count_int;
  739. typedef unsigned short int count_short;
  740. #else /*SIGNED_COMPARE_SLOW*/
  741. typedef long int          count_int;
  742. #endif /*SIGNED_COMPARE_SLOW*/
  743.  
  744. static int colorstobpp(int colors);
  745. static void BumpPixel (void);
  746. static int GIFNextPixel (gdImagePtr im);
  747. static void GIFEncode (FILE *fp, int GWidth, int GHeight, int GInterlace, int Background, int Transparent, int BitsPerPixel, int *Red, int *Green, int *Blue, gdImagePtr im);
  748. static void Putword (int w, FILE *fp);
  749. static void compress (int init_bits, FILE *outfile, gdImagePtr im);
  750. static void output (code_int code);
  751. static void cl_block (void);
  752. static void cl_hash (register count_int hsize);
  753. static void char_init (void);
  754. static void char_out (int c);
  755. static void flush_char (void);
  756. /* Allows for reuse */
  757. static void init_statics(void);
  758.  
  759. void gdImageGif(gdImagePtr im, FILE *out)
  760. {
  761.     int interlace, transparent, BitsPerPixel;
  762.     interlace = im->interlace;
  763.     transparent = im->transparent;
  764.  
  765.     BitsPerPixel = colorstobpp(im->colorsTotal);
  766.     /* Clear any old values in statics strewn through the GIF code */
  767.     init_statics();
  768.     /* All set, let's do it. */
  769.     GIFEncode(
  770.         out, im->sx, im->sy, interlace, 0, transparent, BitsPerPixel,
  771.         im->red, im->green, im->blue, im);
  772. }
  773.  
  774. static int
  775. colorstobpp(int colors)
  776. {
  777.     int bpp = 0;
  778.  
  779.     if ( colors <= 2 )
  780.         bpp = 1;
  781.     else if ( colors <= 4 )
  782.         bpp = 2;
  783.     else if ( colors <= 8 )
  784.         bpp = 3;
  785.     else if ( colors <= 16 )
  786.         bpp = 4;
  787.     else if ( colors <= 32 )
  788.         bpp = 5;
  789.     else if ( colors <= 64 )
  790.         bpp = 6;
  791.     else if ( colors <= 128 )
  792.         bpp = 7;
  793.     else if ( colors <= 256 )
  794.         bpp = 8;
  795.     return bpp;
  796.     }
  797.  
  798. /*****************************************************************************
  799.  *
  800.  * GIFENCODE.C    - GIF Image compression interface
  801.  *
  802.  * GIFEncode( FName, GHeight, GWidth, GInterlace, Background, Transparent,
  803.  *            BitsPerPixel, Red, Green, Blue, gdImagePtr )
  804.  *
  805.  *****************************************************************************/
  806.  
  807. #define TRUE 1
  808. #define FALSE 0
  809.  
  810. static int Width, Height;
  811. static int curx, cury;
  812. static long CountDown;
  813. static int Pass = 0;
  814. static int Interlace;
  815.  
  816. /*
  817.  * Bump the 'curx' and 'cury' to point to the next pixel
  818.  */
  819. static void
  820. BumpPixel(void)
  821. {
  822.         /*
  823.          * Bump the current X position
  824.          */
  825.         ++curx;
  826.  
  827.         /*
  828.          * If we are at the end of a scan line, set curx back to the beginning
  829.          * If we are interlaced, bump the cury to the appropriate spot,
  830.          * otherwise, just increment it.
  831.          */
  832.         if( curx == Width ) {
  833.                 curx = 0;
  834.  
  835.                 if( !Interlace )
  836.                         ++cury;
  837.                 else {
  838.                      switch( Pass ) {
  839.  
  840.                        case 0:
  841.                           cury += 8;
  842.                           if( cury >= Height ) {
  843.                                 ++Pass;
  844.                                 cury = 4;
  845.                           }
  846.                           break;
  847.  
  848.                        case 1:
  849.                           cury += 8;
  850.                           if( cury >= Height ) {
  851.                                 ++Pass;
  852.                                 cury = 2;
  853.                           }
  854.                           break;
  855.  
  856.                        case 2:
  857.                           cury += 4;
  858.                           if( cury >= Height ) {
  859.                              ++Pass;
  860.                              cury = 1;
  861.                           }
  862.                           break;
  863.  
  864.                        case 3:
  865.                           cury += 2;
  866.                           break;
  867.                         }
  868.                 }
  869.         }
  870. }
  871.  
  872. /*
  873.  * Return the next pixel from the image
  874.  */
  875. static int
  876. GIFNextPixel(gdImagePtr im)
  877. {
  878.         int r;
  879.  
  880.         if( CountDown == 0 )
  881.                 return EOF;
  882.  
  883.         --CountDown;
  884.  
  885.         r = gdImageGetPixel(im, curx, cury);
  886.  
  887.         BumpPixel();
  888.  
  889.         return r;
  890. }
  891.  
  892. /* public */
  893.  
  894. static void
  895. GIFEncode(FILE *fp, int GWidth, int GHeight, int GInterlace, int Background, int Transparent, int BitsPerPixel, int *Red, int *Green, int *Blue, gdImagePtr im)
  896. {
  897.         int B;
  898.         int RWidth, RHeight;
  899.         int LeftOfs, TopOfs;
  900.         int Resolution;
  901.         int ColorMapSize;
  902.         int InitCodeSize;
  903.         int i;
  904.  
  905.         Interlace = GInterlace;
  906.  
  907.         ColorMapSize = 1 << BitsPerPixel;
  908.  
  909.         RWidth = Width = GWidth;
  910.         RHeight = Height = GHeight;
  911.         LeftOfs = TopOfs = 0;
  912.  
  913.         Resolution = BitsPerPixel;
  914.  
  915.         /*
  916.          * Calculate number of bits we are expecting
  917.          */
  918.         CountDown = (long)Width * (long)Height;
  919.  
  920.         /*
  921.          * Indicate which pass we are on (if interlace)
  922.          */
  923.         Pass = 0;
  924.  
  925.         /*
  926.          * The initial code size
  927.          */
  928.         if( BitsPerPixel <= 1 )
  929.                 InitCodeSize = 2;
  930.         else
  931.                 InitCodeSize = BitsPerPixel;
  932.  
  933.         /*
  934.          * Set up the current x and y position
  935.          */
  936.         curx = cury = 0;
  937.  
  938.         /*
  939.          * Write the Magic header
  940.          */
  941.         fwrite( Transparent < 0 ? "GIF87a" : "GIF89a", 1, 6, fp );
  942.  
  943.         /*
  944.          * Write out the screen width and height
  945.          */
  946.         Putword( RWidth, fp );
  947.         Putword( RHeight, fp );
  948.  
  949.         /*
  950.          * Indicate that there is a global colour map
  951.          */
  952.         B = 0x80;       /* Yes, there is a color map */
  953.  
  954.         /*
  955.          * OR in the resolution
  956.          */
  957.         B |= (Resolution - 1) << 5;
  958.  
  959.         /*
  960.          * OR in the Bits per Pixel
  961.          */
  962.         B |= (BitsPerPixel - 1);
  963.  
  964.         /*
  965.          * Write it out
  966.          */
  967.         fputc( B, fp );
  968.  
  969.         /*
  970.          * Write out the Background colour
  971.          */
  972.         fputc( Background, fp );
  973.  
  974.         /*
  975.          * Byte of 0's (future expansion)
  976.          */
  977.         fputc( 0, fp );
  978.  
  979.         /*
  980.          * Write out the Global Colour Map
  981.          */
  982.         for( i=0; i<ColorMapSize; ++i ) {
  983.                 fputc( Red[i], fp );
  984.                 fputc( Green[i], fp );
  985.                 fputc( Blue[i], fp );
  986.         }
  987.  
  988.     /*
  989.      * Write out extension for transparent colour index, if necessary.
  990.      */
  991.     if ( Transparent >= 0 ) {
  992.         fputc( '!', fp );
  993.         fputc( 0xf9, fp );
  994.         fputc( 4, fp );
  995.         fputc( 1, fp );
  996.         fputc( 0, fp );
  997.         fputc( 0, fp );
  998.         fputc( (unsigned char) Transparent, fp );
  999.         fputc( 0, fp );
  1000.     }
  1001.  
  1002.         /*
  1003.          * Write an Image separator
  1004.          */
  1005.         fputc( ',', fp );
  1006.  
  1007.         /*
  1008.          * Write the Image header
  1009.          */
  1010.  
  1011.         Putword( LeftOfs, fp );
  1012.         Putword( TopOfs, fp );
  1013.         Putword( Width, fp );
  1014.         Putword( Height, fp );
  1015.  
  1016.         /*
  1017.          * Write out whether or not the image is interlaced
  1018.          */
  1019.         if( Interlace )
  1020.                 fputc( 0x40, fp );
  1021.         else
  1022.                 fputc( 0x00, fp );
  1023.  
  1024.         /*
  1025.          * Write out the initial code size
  1026.          */
  1027.         fputc( InitCodeSize, fp );
  1028.  
  1029.         /*
  1030.          * Go and actually compress the data
  1031.          */
  1032.         compress( InitCodeSize+1, fp, im );
  1033.  
  1034.         /*
  1035.          * Write out a Zero-length packet (to end the series)
  1036.          */
  1037.         fputc( 0, fp );
  1038.  
  1039.         /*
  1040.          * Write the GIF file terminator
  1041.          */
  1042.         fputc( ';', fp );
  1043. }
  1044.  
  1045. /*
  1046.  * Write out a word to the GIF file
  1047.  */
  1048. static void
  1049. Putword(int w, FILE *fp)
  1050. {
  1051.         fputc( w & 0xff, fp );
  1052.         fputc( (w / 256) & 0xff, fp );
  1053. }
  1054.  
  1055.  
  1056. /***************************************************************************
  1057.  *
  1058.  *  GIFCOMPR.C       - GIF Image compression routines
  1059.  *
  1060.  *  Lempel-Ziv compression based on 'compress'.  GIF modifications by
  1061.  *  David Rowley (mgardi@watdcsu.waterloo.edu)
  1062.  *
  1063.  ***************************************************************************/
  1064.  
  1065. /*
  1066.  * General DEFINEs
  1067.  */
  1068.  
  1069. #define GIFBITS    12
  1070.  
  1071. #define HSIZE  5003            /* 80% occupancy */
  1072.  
  1073. #ifdef NO_UCHAR
  1074.  typedef char   char_type;
  1075. #else /*NO_UCHAR*/
  1076.  typedef        unsigned char   char_type;
  1077. #endif /*NO_UCHAR*/
  1078.  
  1079. /*
  1080.  *
  1081.  * GIF Image compression - modified 'compress'
  1082.  *
  1083.  * Based on: compress.c - File compression ala IEEE Computer, June 1984.
  1084.  *
  1085.  * By Authors:  Spencer W. Thomas       (decvax!harpo!utah-cs!utah-gr!thomas)
  1086.  *              Jim McKie               (decvax!mcvax!jim)
  1087.  *              Steve Davies            (decvax!vax135!petsd!peora!srd)
  1088.  *              Ken Turkowski           (decvax!decwrl!turtlevax!ken)
  1089.  *              James A. Woods          (decvax!ihnp4!ames!jaw)
  1090.  *              Joe Orost               (decvax!vax135!petsd!joe)
  1091.  *
  1092.  */
  1093. #include <ctype.h>
  1094.  
  1095. #define ARGVAL() (*++(*argv) || (--argc && *++argv))
  1096.  
  1097. static int n_bits;                        /* number of bits/code */
  1098. static int maxbits = GIFBITS;                /* user settable max # bits/code */
  1099. static code_int maxcode;                  /* maximum code, given n_bits */
  1100. static code_int maxmaxcode = (code_int)1 << GIFBITS; /* should NEVER generate this code */
  1101. #ifdef COMPATIBLE               /* But wrong! */
  1102. # define MAXCODE(n_bits)        ((code_int) 1 << (n_bits) - 1)
  1103. #else /*COMPATIBLE*/
  1104. # define MAXCODE(n_bits)        (((code_int) 1 << (n_bits)) - 1)
  1105. #endif /*COMPATIBLE*/
  1106.  
  1107. static count_int htab [HSIZE];
  1108. static unsigned short codetab [HSIZE];
  1109. #define HashTabOf(i)       htab[i]
  1110. #define CodeTabOf(i)    codetab[i]
  1111.  
  1112. static code_int hsize = HSIZE;                 /* for dynamic table sizing */
  1113.  
  1114. /*
  1115.  * To save much memory, we overlay the table used by compress() with those
  1116.  * used by decompress().  The tab_prefix table is the same size and type
  1117.  * as the codetab.  The tab_suffix table needs 2**GIFBITS characters.  We
  1118.  * get this from the beginning of htab.  The output stack uses the rest
  1119.  * of htab, and contains characters.  There is plenty of room for any
  1120.  * possible stack (stack used to be 8000 characters).
  1121.  */
  1122.  
  1123. #define tab_prefixof(i) CodeTabOf(i)
  1124. #define tab_suffixof(i)        ((char_type*)(htab))[i]
  1125. #define de_stack               ((char_type*)&tab_suffixof((code_int)1<<GIFBITS))
  1126.  
  1127. static code_int free_ent = 0;                  /* first unused entry */
  1128.  
  1129. /*
  1130.  * block compression parameters -- after all codes are used up,
  1131.  * and compression rate changes, start over.
  1132.  */
  1133. static int clear_flg = 0;
  1134.  
  1135. static int offset;
  1136. static long int in_count = 1;            /* length of input */
  1137. static long int out_count = 0;           /* # of codes output (for debugging) */
  1138.  
  1139. /*
  1140.  * compress stdin to stdout
  1141.  *
  1142.  * Algorithm:  use open addressing double hashing (no chaining) on the
  1143.  * prefix code / next character combination.  We do a variant of Knuth's
  1144.  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  1145.  * secondary probe.  Here, the modular division first probe is gives way
  1146.  * to a faster exclusive-or manipulation.  Also do block compression with
  1147.  * an adaptive reset, whereby the code table is cleared when the compression
  1148.  * ratio decreases, but after the table fills.  The variable-length output
  1149.  * codes are re-sized at this point, and a special CLEAR code is generated
  1150.  * for the decompressor.  Late addition:  construct the table according to
  1151.  * file size for noticeable speed improvement on small files.  Please direct
  1152.  * questions about this implementation to ames!jaw.
  1153.  */
  1154.  
  1155. static int g_init_bits;
  1156. static FILE* g_outfile;
  1157.  
  1158. static int ClearCode;
  1159. static int EOFCode;
  1160.  
  1161. static void
  1162. compress(int init_bits, FILE *outfile, gdImagePtr im)
  1163. {
  1164.     register long fcode;
  1165.     register code_int i /* = 0 */;
  1166.     register int c;
  1167.     register code_int ent;
  1168.     register code_int disp;
  1169.     register code_int hsize_reg;
  1170.     register int hshift;
  1171.  
  1172.     /*
  1173.      * Set up the globals:  g_init_bits - initial number of bits
  1174.      *                      g_outfile   - pointer to output file
  1175.      */
  1176.     g_init_bits = init_bits;
  1177.     g_outfile = outfile;
  1178.  
  1179.     /*
  1180.      * Set up the necessary values
  1181.      */
  1182.     offset = 0;
  1183.     out_count = 0;
  1184.     clear_flg = 0;
  1185.     in_count = 1;
  1186.     maxcode = MAXCODE(n_bits = g_init_bits);
  1187.  
  1188.     ClearCode = (1 << (init_bits - 1));
  1189.     EOFCode = ClearCode + 1;
  1190.     free_ent = ClearCode + 2;
  1191.  
  1192.     char_init();
  1193.  
  1194.     ent = GIFNextPixel( im );
  1195.  
  1196.     hshift = 0;
  1197.     for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
  1198.         ++hshift;
  1199.     hshift = 8 - hshift;                /* set hash code range bound */
  1200.  
  1201.     hsize_reg = hsize;
  1202.     cl_hash( (count_int) hsize_reg);            /* clear hash table */
  1203.  
  1204.     output( (code_int)ClearCode );
  1205.  
  1206. #ifdef SIGNED_COMPARE_SLOW
  1207.     while ( (c = GIFNextPixel( im )) != (unsigned) EOF ) {
  1208. #else /*SIGNED_COMPARE_SLOW*/
  1209.     while ( (c = GIFNextPixel( im )) != EOF ) {  /* } */
  1210. #endif /*SIGNED_COMPARE_SLOW*/
  1211.  
  1212.         ++in_count;
  1213.  
  1214.         fcode = (long) (((long) c << maxbits) + ent);
  1215.         i = (((code_int)c << hshift) ^ ent);    /* xor hashing */
  1216.  
  1217.         if ( HashTabOf (i) == fcode ) {
  1218.             ent = CodeTabOf (i);
  1219.             continue;
  1220.         } else if ( (long)HashTabOf (i) < 0 )      /* empty slot */
  1221.             goto nomatch;
  1222.         disp = hsize_reg - i;           /* secondary hash (after G. Knott) */
  1223.         if ( i == 0 )
  1224.             disp = 1;
  1225. probe:
  1226.         if ( (i -= disp) < 0 )
  1227.             i += hsize_reg;
  1228.  
  1229.         if ( HashTabOf (i) == fcode ) {
  1230.             ent = CodeTabOf (i);
  1231.             continue;
  1232.         }
  1233.         if ( (long)HashTabOf (i) > 0 )
  1234.             goto probe;
  1235. nomatch:
  1236.         output ( (code_int) ent );
  1237.         ++out_count;
  1238.         ent = c;
  1239. #ifdef SIGNED_COMPARE_SLOW
  1240.         if ( (unsigned) free_ent < (unsigned) maxmaxcode) {
  1241. #else /*SIGNED_COMPARE_SLOW*/
  1242.         if ( free_ent < maxmaxcode ) {  /* } */
  1243. #endif /*SIGNED_COMPARE_SLOW*/
  1244.             CodeTabOf (i) = free_ent++; /* code -> hashtable */
  1245.             HashTabOf (i) = fcode;
  1246.         } else
  1247.                 cl_block();
  1248.     }
  1249.     /*
  1250.      * Put out the final code.
  1251.      */
  1252.     output( (code_int)ent );
  1253.     ++out_count;
  1254.     output( (code_int) EOFCode );
  1255. }
  1256.  
  1257. /*****************************************************************
  1258.  * TAG( output )
  1259.  *
  1260.  * Output the given code.
  1261.  * Inputs:
  1262.  *      code:   A n_bits-bit integer.  If == -1, then EOF.  This assumes
  1263.  *              that n_bits =< (long)wordsize - 1.
  1264.  * Outputs:
  1265.  *      Outputs code to the file.
  1266.  * Assumptions:
  1267.  *      Chars are 8 bits long.
  1268.  * Algorithm:
  1269.  *      Maintain a GIFBITS character long buffer (so that 8 codes will
  1270.  * fit in it exactly).  Use the VAX insv instruction to insert each
  1271.  * code in turn.  When the buffer fills up empty it and start over.
  1272.  */
  1273.  
  1274. static unsigned long cur_accum = 0;
  1275. static int cur_bits = 0;
  1276.  
  1277. static unsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,
  1278.                                   0x001F, 0x003F, 0x007F, 0x00FF,
  1279.                                   0x01FF, 0x03FF, 0x07FF, 0x0FFF,
  1280.                                   0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
  1281.  
  1282. static void
  1283. output(code_int code)
  1284. {
  1285.     cur_accum &= masks[ cur_bits ];
  1286.  
  1287.     if( cur_bits > 0 )
  1288.         cur_accum |= ((long)code << cur_bits);
  1289.     else
  1290.         cur_accum = code;
  1291.  
  1292.     cur_bits += n_bits;
  1293.  
  1294.     while( cur_bits >= 8 ) {
  1295.         char_out( (unsigned int)(cur_accum & 0xff) );
  1296.         cur_accum >>= 8;
  1297.         cur_bits -= 8;
  1298.     }
  1299.  
  1300.     /*
  1301.      * If the next entry is going to be too big for the code size,
  1302.      * then increase it, if possible.
  1303.      */
  1304.    if ( free_ent > maxcode || clear_flg ) {
  1305.  
  1306.             if( clear_flg ) {
  1307.  
  1308.                 maxcode = MAXCODE (n_bits = g_init_bits);
  1309.                 clear_flg = 0;
  1310.  
  1311.             } else {
  1312.  
  1313.                 ++n_bits;
  1314.                 if ( n_bits == maxbits )
  1315.                     maxcode = maxmaxcode;
  1316.                 else
  1317.                     maxcode = MAXCODE(n_bits);
  1318.             }
  1319.         }
  1320.  
  1321.     if( code == EOFCode ) {
  1322.         /*
  1323.          * At EOF, write the rest of the buffer.
  1324.          */
  1325.         while( cur_bits > 0 ) {
  1326.                 char_out( (unsigned int)(cur_accum & 0xff) );
  1327.                 cur_accum >>= 8;
  1328.                 cur_bits -= 8;
  1329.         }
  1330.  
  1331.         flush_char();
  1332.  
  1333.         fflush( g_outfile );
  1334.  
  1335.         if( ferror( g_outfile ) )
  1336.         return;
  1337.     }
  1338. }
  1339.  
  1340. /*
  1341.  * Clear out the hash table
  1342.  */
  1343. static void
  1344. cl_block (void)             /* table clear for block compress */
  1345. {
  1346.  
  1347.         cl_hash ( (count_int) hsize );
  1348.         free_ent = ClearCode + 2;
  1349.         clear_flg = 1;
  1350.  
  1351.         output( (code_int)ClearCode );
  1352. }
  1353.  
  1354. static void
  1355. cl_hash(register count_int hsize)          /* reset code table */
  1356.                          
  1357. {
  1358.  
  1359.         register count_int *htab_p = htab+hsize;
  1360.  
  1361.         register long i;
  1362.         register long m1 = -1;
  1363.  
  1364.         i = hsize - 16;
  1365.         do {                            /* might use Sys V memset(3) here */
  1366.                 *(htab_p-16) = m1;
  1367.                 *(htab_p-15) = m1;
  1368.                 *(htab_p-14) = m1;
  1369.                 *(htab_p-13) = m1;
  1370.                 *(htab_p-12) = m1;
  1371.                 *(htab_p-11) = m1;
  1372.                 *(htab_p-10) = m1;
  1373.                 *(htab_p-9) = m1;
  1374.                 *(htab_p-8) = m1;
  1375.                 *(htab_p-7) = m1;
  1376.                 *(htab_p-6) = m1;
  1377.                 *(htab_p-5) = m1;
  1378.                 *(htab_p-4) = m1;
  1379.                 *(htab_p-3) = m1;
  1380.                 *(htab_p-2) = m1;
  1381.                 *(htab_p-1) = m1;
  1382.                 htab_p -= 16;
  1383.         } while ((i -= 16) >= 0);
  1384.  
  1385.         for ( i += 16; i > 0; --i )
  1386.                 *--htab_p = m1;
  1387. }
  1388.  
  1389. /******************************************************************************
  1390.  *
  1391.  * GIF Specific routines
  1392.  *
  1393.  ******************************************************************************/
  1394.  
  1395. /*
  1396.  * Number of characters so far in this 'packet'
  1397.  */
  1398. static int a_count;
  1399.  
  1400. /*
  1401.  * Set up the 'byte output' routine
  1402.  */
  1403. static void
  1404. char_init(void)
  1405. {
  1406.         a_count = 0;
  1407. }
  1408.  
  1409. /*
  1410.  * Define the storage for the packet accumulator
  1411.  */
  1412. static char accum[ 256 ];
  1413.  
  1414. /*
  1415.  * Add a character to the end of the current packet, and if it is 254
  1416.  * characters, flush the packet to disk.
  1417.  */
  1418. static void
  1419. char_out(int c)
  1420. {
  1421.         accum[ a_count++ ] = c;
  1422.         if( a_count >= 254 )
  1423.                 flush_char();
  1424. }
  1425.  
  1426. /*
  1427.  * Flush the packet to disk, and reset the accumulator
  1428.  */
  1429. static void
  1430. flush_char(void)
  1431. {
  1432.         if( a_count > 0 ) {
  1433.                 fputc( a_count, g_outfile );
  1434.                 fwrite( accum, 1, a_count, g_outfile );
  1435.                 a_count = 0;
  1436.         }
  1437. }
  1438.  
  1439. static void init_statics(void) {
  1440.     /* Some of these are properly initialized later. What I'm doing
  1441.         here is making sure code that depends on C's initialization
  1442.         of statics doesn't break when the code gets called more
  1443.         than once. */
  1444.     Width = 0;
  1445.     Height = 0;
  1446.     curx = 0;
  1447.     cury = 0;
  1448.     CountDown = 0;
  1449.     Pass = 0;
  1450.     Interlace = 0;
  1451.     a_count = 0;
  1452.     cur_accum = 0;
  1453.     cur_bits = 0;
  1454.     g_init_bits = 0;
  1455.     g_outfile = 0;
  1456.     ClearCode = 0;
  1457.     EOFCode = 0;
  1458.     free_ent = 0;
  1459.     clear_flg = 0;
  1460.     offset = 0;
  1461.     in_count = 1;
  1462.     out_count = 0;    
  1463.     hsize = HSIZE;
  1464.     n_bits = 0;
  1465.     maxbits = GIFBITS;
  1466.     maxcode = 0;
  1467.     maxmaxcode = (code_int)1 << GIFBITS;
  1468. }
  1469.  
  1470.  
  1471. /* +-------------------------------------------------------------------+ */
  1472. /* | Copyright 1990, 1991, 1993, David Koblas.  (koblas@netcom.com)    | */
  1473. /* |   Permission to use, copy, modify, and distribute this software   | */
  1474. /* |   and its documentation for any purpose and without fee is hereby | */
  1475. /* |   granted, provided that the above copyright notice appear in all | */
  1476. /* |   copies and that both that copyright notice and this permission  | */
  1477. /* |   notice appear in supporting documentation.  This software is    | */
  1478. /* |   provided "as is" without express or implied warranty.           | */
  1479. /* +-------------------------------------------------------------------+ */
  1480.  
  1481.  
  1482. #define        MAXCOLORMAPSIZE         256
  1483.  
  1484. #define        TRUE    1
  1485. #define        FALSE   0
  1486.  
  1487. #define CM_RED         0
  1488. #define CM_GREEN       1
  1489. #define CM_BLUE                2
  1490.  
  1491. #define        MAX_LWZ_BITS            12
  1492.  
  1493. #define INTERLACE              0x40
  1494. #define LOCALCOLORMAP  0x80
  1495. #define BitSet(byte, bit)      (((byte) & (bit)) == (bit))
  1496.  
  1497. #define        ReadOK(file,buffer,len) (fread(buffer, len, 1, file) != 0)
  1498.  
  1499. #define LM_to_uint(a,b)                        (((b)<<8)|(a))
  1500.  
  1501. /* We may eventually want to use this information, but def it out for now */
  1502. #if 0
  1503. static struct {
  1504.        unsigned int    Width;
  1505.        unsigned int    Height;
  1506.        unsigned char   ColorMap[3][MAXCOLORMAPSIZE];
  1507.        unsigned int    BitPixel;
  1508.        unsigned int    ColorResolution;
  1509.        unsigned int    Background;
  1510.        unsigned int    AspectRatio;
  1511. } GifScreen;
  1512. #endif
  1513.  
  1514. static struct {
  1515.        int     transparent;
  1516.        int     delayTime;
  1517.        int     inputFlag;
  1518.        int     disposal;
  1519. } Gif89 = { -1, -1, -1, 0 };
  1520.  
  1521. static int ReadColorMap (FILE *fd, int number, unsigned char (*buffer)[256]);
  1522. static int DoExtension (FILE *fd, int label, int *Transparent);
  1523. static int GetDataBlock (FILE *fd, unsigned char *buf);
  1524. static int GetCode (FILE *fd, int code_size, int flag);
  1525. static int LWZReadByte (FILE *fd, int flag, int input_code_size);
  1526. static void ReadImage (gdImagePtr im, FILE *fd, int len, int height, unsigned char (*cmap)[256], int interlace, int ignore);
  1527.  
  1528. int ZeroDataBlock;
  1529.  
  1530. gdImagePtr
  1531. gdImageCreateFromGif(FILE *fd)
  1532. {
  1533.        int imageNumber;
  1534.        int BitPixel;
  1535.        int ColorResolution;
  1536.        int Background;
  1537.        int AspectRatio;
  1538.        int Transparent = (-1);
  1539.        unsigned char   buf[16];
  1540.        unsigned char   c;
  1541.        unsigned char   ColorMap[3][MAXCOLORMAPSIZE];
  1542.        unsigned char   localColorMap[3][MAXCOLORMAPSIZE];
  1543.        int             imw, imh;
  1544.        int             useGlobalColormap;
  1545.        int             bitPixel;
  1546.        int             imageCount = 0;
  1547.        char            version[4];
  1548.        gdImagePtr im = 0;
  1549.        ZeroDataBlock = FALSE;
  1550.  
  1551.        imageNumber = 1;
  1552.        if (! ReadOK(fd,buf,6)) {
  1553.         return 0;
  1554.     }
  1555.        if (strncmp((char *)buf,"GIF",3) != 0) {
  1556.         return 0;
  1557.     }
  1558.        strncpy(version, (char *)buf + 3, 3);
  1559.        version[3] = '\0';
  1560.  
  1561.        if ((strcmp(version, "87a") != 0) && (strcmp(version, "89a") != 0)) {
  1562.         return 0;
  1563.     }
  1564.        if (! ReadOK(fd,buf,7)) {
  1565.         return 0;
  1566.     }
  1567.        BitPixel        = 2<<(buf[4]&0x07);
  1568.        ColorResolution = (int) (((buf[4]&0x70)>>3)+1);
  1569.        Background      = buf[5];
  1570.        AspectRatio     = buf[6];
  1571.  
  1572.        if (BitSet(buf[4], LOCALCOLORMAP)) {    /* Global Colormap */
  1573.                if (ReadColorMap(fd, BitPixel, ColorMap)) {
  1574.             return 0;
  1575.         }
  1576.        }
  1577.        for (;;) {
  1578.                if (! ReadOK(fd,&c,1)) {
  1579.                        return 0;
  1580.                }
  1581.                if (c == ';') {         /* GIF terminator */
  1582.                        int i;
  1583.                        if (imageCount < imageNumber) {
  1584.                                return 0;
  1585.                        }
  1586.                        /* Terminator before any image was declared! */
  1587.                        if (!im) {
  1588.                               return 0;
  1589.                        }
  1590.                /* Check for open colors at the end, so
  1591.                           we can reduce colorsTotal and ultimately
  1592.                           BitsPerPixel */
  1593.                        for (i=((im->colorsTotal-1)); (i>=0); i--) {
  1594.                                if (im->open[i]) {
  1595.                                        im->colorsTotal--;
  1596.                                } else {
  1597.                                        break;
  1598.                                }
  1599.                        } 
  1600.                        return im;
  1601.                }
  1602.  
  1603.                if (c == '!') {         /* Extension */
  1604.                        if (! ReadOK(fd,&c,1)) {
  1605.                                return 0;
  1606.                        }
  1607.                        DoExtension(fd, c, &Transparent);
  1608.                        continue;
  1609.                }
  1610.  
  1611.                if (c != ',') {         /* Not a valid start character */
  1612.                        continue;
  1613.                }
  1614.  
  1615.                ++imageCount;
  1616.  
  1617.                if (! ReadOK(fd,buf,9)) {
  1618.                    return 0;
  1619.                }
  1620.  
  1621.                useGlobalColormap = ! BitSet(buf[8], LOCALCOLORMAP);
  1622.  
  1623.                bitPixel = 1<<((buf[8]&0x07)+1);
  1624.  
  1625.                imw = LM_to_uint(buf[4],buf[5]);
  1626.                imh = LM_to_uint(buf[6],buf[7]);
  1627.            if (!(im = gdImageCreate(imw, imh))) {
  1628.              return 0;
  1629.            }
  1630.                im->interlace = BitSet(buf[8], INTERLACE);
  1631.                if (! useGlobalColormap) {
  1632.                        if (ReadColorMap(fd, bitPixel, localColorMap)) { 
  1633.                                  return 0;
  1634.                        }
  1635.                        ReadImage(im, fd, imw, imh, localColorMap, 
  1636.                                  BitSet(buf[8], INTERLACE), 
  1637.                                  imageCount != imageNumber);
  1638.                } else {
  1639.                        ReadImage(im, fd, imw, imh,
  1640.                                  ColorMap, 
  1641.                                  BitSet(buf[8], INTERLACE), 
  1642.                                  imageCount != imageNumber);
  1643.                }
  1644.                if (Transparent != (-1)) {
  1645.                        gdImageColorTransparent(im, Transparent);
  1646.                }       
  1647.        }
  1648. }
  1649.  
  1650. static int
  1651. ReadColorMap(FILE *fd, int number, unsigned char (*buffer)[256])
  1652. {
  1653.        int             i;
  1654.        unsigned char   rgb[3];
  1655.  
  1656.  
  1657.        for (i = 0; i < number; ++i) {
  1658.                if (! ReadOK(fd, rgb, sizeof(rgb))) {
  1659.                        return TRUE;
  1660.                }
  1661.                buffer[CM_RED][i] = rgb[0] ;
  1662.                buffer[CM_GREEN][i] = rgb[1] ;
  1663.                buffer[CM_BLUE][i] = rgb[2] ;
  1664.        }
  1665.  
  1666.  
  1667.        return FALSE;
  1668. }
  1669.  
  1670. static int
  1671. DoExtension(FILE *fd, int label, int *Transparent)
  1672. {
  1673.        static unsigned char     buf[256];
  1674.  
  1675.        switch (label) {
  1676.        case 0xf9:              /* Graphic Control Extension */
  1677.                (void) GetDataBlock(fd, (unsigned char*) buf);
  1678.                Gif89.disposal    = (buf[0] >> 2) & 0x7;
  1679.                Gif89.inputFlag   = (buf[0] >> 1) & 0x1;
  1680.                Gif89.delayTime   = LM_to_uint(buf[1],buf[2]);
  1681.                if ((buf[0] & 0x1) != 0)
  1682.                        *Transparent = buf[3];
  1683.  
  1684.                while (GetDataBlock(fd, (unsigned char*) buf) != 0)
  1685.                        ;
  1686.                return FALSE;
  1687.        default:
  1688.                break;
  1689.        }
  1690.        while (GetDataBlock(fd, (unsigned char*) buf) != 0)
  1691.                ;
  1692.  
  1693.        return FALSE;
  1694. }
  1695.  
  1696. static int
  1697. GetDataBlock(FILE *fd, unsigned char *buf)
  1698. {
  1699.        unsigned char   count;
  1700.  
  1701.        if (! ReadOK(fd,&count,1)) {
  1702.                return -1;
  1703.        }
  1704.  
  1705.        ZeroDataBlock = count == 0;
  1706.  
  1707.        if ((count != 0) && (! ReadOK(fd, buf, count))) {
  1708.                return -1;
  1709.        }
  1710.  
  1711.        return count;
  1712. }
  1713.  
  1714. static int
  1715. GetCode(FILE *fd, int code_size, int flag)
  1716. {
  1717.        static unsigned char    buf[280];
  1718.        static int              curbit, lastbit, done, last_byte;
  1719.        int                     i, j, ret;
  1720.        unsigned char           count;
  1721.  
  1722.        if (flag) {
  1723.                curbit = 0;
  1724.                lastbit = 0;
  1725.                done = FALSE;
  1726.                return 0;
  1727.        }
  1728.  
  1729.        if ( (curbit+code_size) >= lastbit) {
  1730.                if (done) {
  1731.                        if (curbit >= lastbit) {
  1732.                                 /* Oh well */
  1733.                        }                        
  1734.                        return -1;
  1735.                }
  1736.                buf[0] = buf[last_byte-2];
  1737.                buf[1] = buf[last_byte-1];
  1738.  
  1739.                if ((count = GetDataBlock(fd, &buf[2])) == 0)
  1740.                        done = TRUE;
  1741.  
  1742.                last_byte = 2 + count;
  1743.                curbit = (curbit - lastbit) + 16;
  1744.                lastbit = (2+count)*8 ;
  1745.        }
  1746.  
  1747.        ret = 0;
  1748.        for (i = curbit, j = 0; j < code_size; ++i, ++j)
  1749.                ret |= ((buf[ i / 8 ] & (1 << (i % 8))) != 0) << j;
  1750.  
  1751.        curbit += code_size;
  1752.  
  1753.        return ret;
  1754. }
  1755.  
  1756. static int
  1757. LWZReadByte(FILE *fd, int flag, int input_code_size)
  1758. {
  1759.        static int      fresh = FALSE;
  1760.        int             code, incode;
  1761.        static int      code_size, set_code_size;
  1762.        static int      max_code, max_code_size;
  1763.        static int      firstcode, oldcode;
  1764.        static int      clear_code, end_code;
  1765.        static int      table[2][(1<< MAX_LWZ_BITS)];
  1766.        static int      stack[(1<<(MAX_LWZ_BITS))*2], *sp;
  1767.        register int    i;
  1768.  
  1769.        if (flag) {
  1770.                set_code_size = input_code_size;
  1771.                code_size = set_code_size+1;
  1772.                clear_code = 1 << set_code_size ;
  1773.                end_code = clear_code + 1;
  1774.                max_code_size = 2*clear_code;
  1775.                max_code = clear_code+2;
  1776.  
  1777.                GetCode(fd, 0, TRUE);
  1778.                
  1779.                fresh = TRUE;
  1780.  
  1781.                for (i = 0; i < clear_code; ++i) {
  1782.                        table[0][i] = 0;
  1783.                        table[1][i] = i;
  1784.                }
  1785.                for (; i < (1<<MAX_LWZ_BITS); ++i)
  1786.                        table[0][i] = table[1][0] = 0;
  1787.  
  1788.                sp = stack;
  1789.  
  1790.                return 0;
  1791.        } else if (fresh) {
  1792.                fresh = FALSE;
  1793.                do {
  1794.                        firstcode = oldcode =
  1795.                                GetCode(fd, code_size, FALSE);
  1796.                } while (firstcode == clear_code);
  1797.                return firstcode;
  1798.        }
  1799.  
  1800.        if (sp > stack)
  1801.                return *--sp;
  1802.  
  1803.        while ((code = GetCode(fd, code_size, FALSE)) >= 0) {
  1804.                if (code == clear_code) {
  1805.                        for (i = 0; i < clear_code; ++i) {
  1806.                                table[0][i] = 0;
  1807.                                table[1][i] = i;
  1808.                        }
  1809.                        for (; i < (1<<MAX_LWZ_BITS); ++i)
  1810.                                table[0][i] = table[1][i] = 0;
  1811.                        code_size = set_code_size+1;
  1812.                        max_code_size = 2*clear_code;
  1813.                        max_code = clear_code+2;
  1814.                        sp = stack;
  1815.                        firstcode = oldcode =
  1816.                                        GetCode(fd, code_size, FALSE);
  1817.                        return firstcode;
  1818.                } else if (code == end_code) {
  1819.                        int             count;
  1820.                        unsigned char   buf[260];
  1821.  
  1822.                        if (ZeroDataBlock)
  1823.                                return -2;
  1824.  
  1825.                        while ((count = GetDataBlock(fd, buf)) > 0)
  1826.                                ;
  1827.  
  1828.                        if (count != 0)
  1829.                        return -2;
  1830.                }
  1831.  
  1832.                incode = code;
  1833.  
  1834.                if (code >= max_code) {
  1835.                        *sp++ = firstcode;
  1836.                        code = oldcode;
  1837.                }
  1838.  
  1839.                while (code >= clear_code) {
  1840.                        *sp++ = table[1][code];
  1841.                        if (code == table[0][code]) {
  1842.                                /* Oh well */
  1843.                        }
  1844.                        code = table[0][code];
  1845.                }
  1846.  
  1847.                *sp++ = firstcode = table[1][code];
  1848.  
  1849.                if ((code = max_code) <(1<<MAX_LWZ_BITS)) {
  1850.                        table[0][code] = oldcode;
  1851.                        table[1][code] = firstcode;
  1852.                        ++max_code;
  1853.                        if ((max_code >= max_code_size) &&
  1854.                                (max_code_size < (1<<MAX_LWZ_BITS))) {
  1855.                                max_code_size *= 2;
  1856.                                ++code_size;
  1857.                        }
  1858.                }
  1859.  
  1860.                oldcode = incode;
  1861.  
  1862.                if (sp > stack)
  1863.                        return *--sp;
  1864.        }
  1865.        return code;
  1866. }
  1867.  
  1868. static void
  1869. ReadImage(gdImagePtr im, FILE *fd, int len, int height, unsigned char (*cmap)[256], int interlace, int ignore)
  1870. {
  1871.        unsigned char   c;      
  1872.        int             v;
  1873.        int             xpos = 0, ypos = 0, pass = 0;
  1874.        int i;
  1875.        /* Stash the color map into the image */
  1876.        for (i=0; (i<gdMaxColors); i++) {
  1877.                im->red[i] = cmap[CM_RED][i];    
  1878.                im->green[i] = cmap[CM_GREEN][i];    
  1879.                im->blue[i] = cmap[CM_BLUE][i];    
  1880.                im->open[i] = 1;
  1881.        }
  1882.        /* Many (perhaps most) of these colors will remain marked open. */
  1883.        im->colorsTotal = gdMaxColors;
  1884.        /*
  1885.        **  Initialize the Compression routines
  1886.        */
  1887.        if (! ReadOK(fd,&c,1)) {
  1888.                return; 
  1889.        }
  1890.        if (LWZReadByte(fd, TRUE, c) < 0) {
  1891.                return;
  1892.        }
  1893.  
  1894.        /*
  1895.        **  If this is an "uninteresting picture" ignore it.
  1896.        */
  1897.        if (ignore) {
  1898.                while (LWZReadByte(fd, FALSE, c) >= 0)
  1899.                        ;
  1900.                return;
  1901.        }
  1902.  
  1903.        while ((v = LWZReadByte(fd,FALSE,c)) >= 0 ) {
  1904.                /* This how we recognize which colors are actually used. */
  1905.                if (im->open[v]) {
  1906.                        im->open[v] = 0;
  1907.                }
  1908.                gdImageSetPixel(im, xpos, ypos, v);
  1909.                ++xpos;
  1910.                if (xpos == len) {
  1911.                        xpos = 0;
  1912.                        if (interlace) {
  1913.                                switch (pass) {
  1914.                                case 0:
  1915.                                case 1:
  1916.                                        ypos += 8; break;
  1917.                                case 2:
  1918.                                        ypos += 4; break;
  1919.                                case 3:
  1920.                                        ypos += 2; break;
  1921.                                }
  1922.  
  1923.                                if (ypos >= height) {
  1924.                                        ++pass;
  1925.                                        switch (pass) {
  1926.                                        case 1:
  1927.                                                ypos = 4; break;
  1928.                                        case 2:
  1929.                                                ypos = 2; break;
  1930.                                        case 3:
  1931.                                                ypos = 1; break;
  1932.                                        default:
  1933.                                                goto fini;
  1934.                                        }
  1935.                                }
  1936.                        } else {
  1937.                                ++ypos;
  1938.                        }
  1939.                }
  1940.                if (ypos >= height)
  1941.                        break;
  1942.        }
  1943.  
  1944. fini:
  1945.        if (LWZReadByte(fd,FALSE,c)>=0) {
  1946.                /* Ignore extra */
  1947.        }
  1948. }
  1949.  
  1950. void gdImageRectangle(gdImagePtr im, int x1, int y1, int x2, int y2, int color)
  1951. {
  1952.     gdImageLine(im, x1, y1, x2, y1, color);        
  1953.     gdImageLine(im, x1, y2, x2, y2, color);        
  1954.     gdImageLine(im, x1, y1, x1, y2, color);
  1955.     gdImageLine(im, x2, y1, x2, y2, color);
  1956. }
  1957.  
  1958. void gdImageFilledRectangle(gdImagePtr im, int x1, int y1, int x2, int y2, int color)
  1959. {
  1960.     int x, y;
  1961.     for (y=y1; (y<=y2); y++) {
  1962.         for (x=x1; (x<=x2); x++) {
  1963.             gdImageSetPixel(im, x, y, color);
  1964.         }
  1965.     }
  1966. }
  1967.  
  1968. void gdImageCopy(gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h)
  1969. {
  1970.     int c;
  1971.     int x, y;
  1972.     int tox, toy;
  1973.     int i;
  1974.     int colorMap[gdMaxColors];
  1975.     for (i=0; (i<gdMaxColors); i++) {
  1976.         colorMap[i] = (-1);
  1977.     }
  1978.     toy = dstY;
  1979.     for (y=srcY; (y < (srcY + h)); y++) {
  1980.         tox = dstX;
  1981.         for (x=srcX; (x < (srcX + w)); x++) {
  1982.             int nc;
  1983.             c = gdImageGetPixel(src, x, y);
  1984.             /* Added 7/24/95: support transparent copies */
  1985.             if (gdImageGetTransparent(src) == c) {
  1986.                 tox++;
  1987.                 continue;
  1988.             }
  1989.             /* Have we established a mapping for this color? */
  1990.             if (colorMap[c] == (-1)) {
  1991.                 /* If it's the same image, mapping is trivial */
  1992.                 if (dst == src) {
  1993.                     nc = c;
  1994.                 } else { 
  1995.                     /* First look for an exact match */
  1996.                     nc = gdImageColorExact(dst,
  1997.                         src->red[c], src->green[c],
  1998.                         src->blue[c]);
  1999.                 }    
  2000.                 if (nc == (-1)) {
  2001.                     /* No, so try to allocate it */
  2002.                     nc = gdImageColorAllocate(dst,
  2003.                         src->red[c], src->green[c],
  2004.                         src->blue[c]);
  2005.                     /* If we're out of colors, go for the
  2006.                         closest color */
  2007.                     if (nc == (-1)) {
  2008.                         nc = gdImageColorClosest(dst,
  2009.                             src->red[c], src->green[c],
  2010.                             src->blue[c]);
  2011.                     }
  2012.                 }
  2013.                 colorMap[c] = nc;
  2014.             }
  2015.             gdImageSetPixel(dst, tox, toy, colorMap[c]);
  2016.             tox++;
  2017.         }
  2018.         toy++;
  2019.     }
  2020. }            
  2021.  
  2022. void gdImageCopyResized(gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)
  2023. {
  2024.     int c;
  2025.     int x, y;
  2026.     int tox, toy;
  2027.     int ydest;
  2028.     int i;
  2029.     int colorMap[gdMaxColors];
  2030.     /* Stretch vectors */
  2031.     int *stx;
  2032.     int *sty;
  2033.     /* We only need to use floating point to determine the correct
  2034.         stretch vector for one line's worth. */
  2035.     double accum;
  2036.     stx = (int *) malloc(sizeof(int) * srcW);
  2037.     sty = (int *) malloc(sizeof(int) * srcH);
  2038.     accum = 0;
  2039.     for (i=0; (i < srcW); i++) {
  2040.         int got;
  2041.         accum += (double)dstW/(double)srcW;
  2042.         got = floor(accum);
  2043.         stx[i] = got;
  2044.         accum -= got;
  2045.     }
  2046.     accum = 0;
  2047.     for (i=0; (i < srcH); i++) {
  2048.         int got;
  2049.         accum += (double)dstH/(double)srcH;
  2050.         got = floor(accum);
  2051.         sty[i] = got;
  2052.         accum -= got;
  2053.     }
  2054.     for (i=0; (i<gdMaxColors); i++) {
  2055.         colorMap[i] = (-1);
  2056.     }
  2057.     toy = dstY;
  2058.     for (y=srcY; (y < (srcY + srcH)); y++) {
  2059.         for (ydest=0; (ydest < sty[y-srcY]); ydest++) {
  2060.             tox = dstX;
  2061.             for (x=srcX; (x < (srcX + srcW)); x++) {
  2062.                 int nc;
  2063.                 if (!stx[x - srcX]) {
  2064.                     continue;
  2065.                 }
  2066.                 c = gdImageGetPixel(src, x, y);
  2067.                 /* Added 7/24/95: support transparent copies */
  2068.                 if (gdImageGetTransparent(src) == c) {
  2069.                     tox += stx[x-srcX];
  2070.                     continue;
  2071.                 }
  2072.                 /* Have we established a mapping for this color? */
  2073.                 if (colorMap[c] == (-1)) {
  2074.                     /* If it's the same image, mapping is trivial */
  2075.                     if (dst == src) {
  2076.                         nc = c;
  2077.                     } else { 
  2078.                         /* First look for an exact match */
  2079.                         nc = gdImageColorExact(dst,
  2080.                             src->red[c], src->green[c],
  2081.                             src->blue[c]);
  2082.                     }    
  2083.                     if (nc == (-1)) {
  2084.                         /* No, so try to allocate it */
  2085.                         nc = gdImageColorAllocate(dst,
  2086.                             src->red[c], src->green[c],
  2087.                             src->blue[c]);
  2088.                         /* If we're out of colors, go for the
  2089.                             closest color */
  2090.                         if (nc == (-1)) {
  2091.                             nc = gdImageColorClosest(dst,
  2092.                                 src->red[c], src->green[c],
  2093.                                 src->blue[c]);
  2094.                         }
  2095.                     }
  2096.                     colorMap[c] = nc;
  2097.                 }
  2098.                 for (i=0; (i < stx[x - srcX]); i++) {
  2099.                     gdImageSetPixel(dst, tox, toy, colorMap[c]);
  2100.                     tox++;
  2101.                 }
  2102.             }
  2103.             toy++;
  2104.         }
  2105.     }
  2106.     free(stx);
  2107.     free(sty);
  2108. }
  2109.  
  2110. int gdGetWord(int *result, FILE *in)
  2111. {
  2112.     int r;
  2113.     r = getc(in);
  2114.     if (r == EOF) {
  2115.         return 0;
  2116.     }
  2117.     *result = r << 8;
  2118.     r = getc(in);    
  2119.     if (r == EOF) {
  2120.         return 0;
  2121.     }
  2122.     *result += r;
  2123.     return 1;
  2124. }
  2125.  
  2126. void gdPutWord(int w, FILE *out)
  2127. {
  2128.     putc((unsigned char)(w >> 8), out);
  2129.     putc((unsigned char)(w & 0xFF), out);
  2130. }
  2131.  
  2132. int gdGetByte(int *result, FILE *in)
  2133. {
  2134.     int r;
  2135.     r = getc(in);
  2136.     if (r == EOF) {
  2137.         return 0;
  2138.     }
  2139.     *result = r;
  2140.     return 1;
  2141. }
  2142.  
  2143. gdImagePtr gdImageCreateFromGd(FILE *in)
  2144. {
  2145.     int sx, sy;
  2146.     int x, y;
  2147.     int i;
  2148.     gdImagePtr im;
  2149.     if (!gdGetWord(&sx, in)) {
  2150.         goto fail1;
  2151.     }
  2152.     if (!gdGetWord(&sy, in)) {
  2153.         goto fail1;
  2154.     }
  2155.     im = gdImageCreate(sx, sy);
  2156.     if (!gdGetByte(&im->colorsTotal, in)) {
  2157.         goto fail2;
  2158.     }
  2159.     if (!gdGetWord(&im->transparent, in)) {
  2160.         goto fail2;
  2161.     }
  2162.     if (im->transparent == 257) {
  2163.         im->transparent = (-1);
  2164.     }
  2165.     for (i=0; (i<gdMaxColors); i++) {
  2166.         if (!gdGetByte(&im->red[i], in)) {
  2167.             goto fail2;
  2168.         }
  2169.         if (!gdGetByte(&im->green[i], in)) {
  2170.             goto fail2;
  2171.         }
  2172.         if (!gdGetByte(&im->blue[i], in)) {
  2173.             goto fail2;
  2174.         }
  2175.     }    
  2176.     for (y=0; (y<sy); y++) {
  2177.         for (x=0; (x<sx); x++) {    
  2178.             int ch;
  2179.             ch = getc(in);
  2180.             if (ch == EOF) {
  2181.                 gdImageDestroy(im);
  2182.                 return 0;
  2183.             }
  2184.             im->pixels[x][y] = ch;
  2185.         }
  2186.     }
  2187.     return im;
  2188. fail2:
  2189.     gdImageDestroy(im);
  2190. fail1:
  2191.     return 0;
  2192. }
  2193.     
  2194. void gdImageGd(gdImagePtr im, FILE *out)
  2195. {
  2196.     int x, y;
  2197.     int i;
  2198.     int trans;
  2199.     gdPutWord(im->sx, out);
  2200.     gdPutWord(im->sy, out);
  2201.     putc((unsigned char)im->colorsTotal, out);
  2202.     trans = im->transparent;
  2203.     if (trans == (-1)) {
  2204.         trans = 257;
  2205.     }    
  2206.     gdPutWord(trans, out);
  2207.     for (i=0; (i<gdMaxColors); i++) {
  2208.         putc((unsigned char)im->red[i], out);
  2209.         putc((unsigned char)im->green[i], out);    
  2210.         putc((unsigned char)im->blue[i], out);    
  2211.     }
  2212.     for (y=0; (y < im->sy); y++) {    
  2213.         for (x=0; (x < im->sx); x++) {    
  2214.             putc((unsigned char)im->pixels[x][y], out);
  2215.         }
  2216.     }
  2217. }
  2218.  
  2219. gdImagePtr
  2220. gdImageCreateFromXbm(FILE *fd)
  2221. {
  2222.     gdImagePtr im;    
  2223.     int bit;
  2224.     int w, h;
  2225.     int bytes;
  2226.     int ch;
  2227.     int i, x, y;
  2228.     char *sp;
  2229.     char s[161];
  2230.     if (!fgets(s, 160, fd)) {
  2231.         return 0;
  2232.     }
  2233.     sp = &s[0];
  2234.     /* Skip #define */
  2235.     sp = strchr(sp, ' ');
  2236.     if (!sp) {
  2237.         return 0;
  2238.     }
  2239.     /* Skip width label */
  2240.     sp++;
  2241.     sp = strchr(sp, ' ');
  2242.     if (!sp) {
  2243.         return 0;
  2244.     }
  2245.     /* Get width */
  2246.     w = atoi(sp + 1);
  2247.     if (!w) {
  2248.         return 0;
  2249.     }
  2250.     if (!fgets(s, 160, fd)) {
  2251.         return 0;
  2252.     }
  2253.     sp = s;
  2254.     /* Skip #define */
  2255.     sp = strchr(sp, ' ');
  2256.     if (!sp) {
  2257.         return 0;
  2258.     }
  2259.     /* Skip height label */
  2260.     sp++;
  2261.     sp = strchr(sp, ' ');
  2262.     if (!sp) {
  2263.         return 0;
  2264.     }
  2265.     /* Get height */
  2266.     h = atoi(sp + 1);
  2267.     if (!h) {
  2268.         return 0;
  2269.     }
  2270.     /* Skip declaration line */
  2271.     if (!fgets(s, 160, fd)) {
  2272.         return 0;
  2273.     }
  2274.     bytes = (w * h / 8) + 1;
  2275.     im = gdImageCreate(w, h);
  2276.     gdImageColorAllocate(im, 255, 255, 255);
  2277.     gdImageColorAllocate(im, 0, 0, 0);
  2278.     x = 0;
  2279.     y = 0;
  2280.     for (i=0; (i < bytes); i++) {
  2281.         char h[3];
  2282.         int b;
  2283.         /* Skip spaces, commas, CRs, 0x */
  2284.         while(1) {
  2285.             ch = getc(fd);
  2286.             if (ch == EOF) {
  2287.                 goto fail;
  2288.             }
  2289.             if (ch == 'x') {
  2290.                 break;
  2291.             }    
  2292.         }
  2293.         /* Get hex value */
  2294.         ch = getc(fd);
  2295.         if (ch == EOF) {
  2296.             goto fail;
  2297.         }
  2298.         h[0] = ch;
  2299.         ch = getc(fd);
  2300.         if (ch == EOF) {
  2301.             goto fail;
  2302.         }
  2303.         h[1] = ch;
  2304.         h[2] = '\0';
  2305.         sscanf(h, "%x", &b);        
  2306.         for (bit = 1; (bit <= 128); (bit = bit << 1)) {
  2307.             gdImageSetPixel(im, x++, y, (b & bit) ? 1 : 0);    
  2308.             if (x == im->sx) {
  2309.                 x = 0;
  2310.                 y++;
  2311.                 if (y == im->sy) {
  2312.                     return im;
  2313.                 }
  2314.                 /* Fix 8/8/95 */
  2315.                 break;
  2316.             }
  2317.         }
  2318.     }
  2319.     /* Shouldn't happen */
  2320.     fprintf(stderr, "Error: bug in gdImageCreateFromXbm!\n");
  2321.     return 0;
  2322. fail:
  2323.     gdImageDestroy(im);
  2324.     return 0;
  2325. }
  2326.  
  2327. void gdImagePolygon(gdImagePtr im, gdPointPtr p, int n, int c)
  2328. {
  2329.     int i;
  2330.     int lx, ly;
  2331.     if (!n) {
  2332.         return;
  2333.     }
  2334.     lx = p->x;
  2335.     ly = p->y;
  2336.     gdImageLine(im, lx, ly, p[n-1].x, p[n-1].y, c);
  2337.     for (i=1; (i < n); i++) {
  2338.         p++;
  2339.         gdImageLine(im, lx, ly, p->x, p->y, c);
  2340.         lx = p->x;
  2341.         ly = p->y;
  2342.     }
  2343. }    
  2344.     
  2345. int gdCompareInt(const void *a, const void *b);
  2346.     
  2347. void gdImageFilledPolygon(gdImagePtr im, gdPointPtr p, int n, int c)
  2348. {
  2349.     int i;
  2350.     int y;
  2351.     int y1, y2;
  2352.     int ints;
  2353.     if (!n) {
  2354.         return;
  2355.     }
  2356.     if (!im->polyAllocated) {
  2357.         im->polyInts = (int *) malloc(sizeof(int) * n);
  2358.         im->polyAllocated = n;
  2359.     }        
  2360.     if (im->polyAllocated < n) {
  2361.         while (im->polyAllocated < n) {
  2362.             im->polyAllocated *= 2;
  2363.         }    
  2364.         im->polyInts = (int *) realloc(im->polyInts,
  2365.             sizeof(int) * im->polyAllocated);
  2366.     }
  2367.     y1 = p[0].y;
  2368.     y2 = p[0].y;
  2369.     for (i=1; (i < n); i++) {
  2370.         if (p[i].y < y1) {
  2371.             y1 = p[i].y;
  2372.         }
  2373.         if (p[i].y > y2) {
  2374.             y2 = p[i].y;
  2375.         }
  2376.     }
  2377.     for (y=y1; (y <= y2); y++) {
  2378.         int interLast = 0;
  2379.         int dirLast = 0;
  2380.         int interFirst = 1;
  2381.         ints = 0;
  2382.         for (i=0; (i <= n); i++) {
  2383.             int x1, x2;
  2384.             int y1, y2;
  2385.             int dir;
  2386.             int ind1, ind2;
  2387.             int lastInd1 = 0;
  2388.             if ((i == n) || (!i)) {
  2389.                 ind1 = n-1;
  2390.                 ind2 = 0;
  2391.             } else {
  2392.                 ind1 = i-1;
  2393.                 ind2 = i;
  2394.             }
  2395.             y1 = p[ind1].y;
  2396.             y2 = p[ind2].y;
  2397.             if (y1 < y2) {
  2398.                 y1 = p[ind1].y;
  2399.                 y2 = p[ind2].y;
  2400.                 x1 = p[ind1].x;
  2401.                 x2 = p[ind2].x;
  2402.                 dir = -1;
  2403.             } else if (y1 > y2) {
  2404.                 y2 = p[ind1].y;
  2405.                 y1 = p[ind2].y;
  2406.                 x2 = p[ind1].x;
  2407.                 x1 = p[ind2].x;
  2408.                 dir = 1;
  2409.             } else {
  2410.                 /* Horizontal; just draw it */
  2411.                 gdImageLine(im, 
  2412.                     p[ind1].x, y1, 
  2413.                     p[ind2].x, y1,
  2414.                     c);
  2415.                 continue;
  2416.             }
  2417.             if ((y >= y1) && (y <= y2)) {
  2418.                 int inter = 
  2419.                     (y-y1) * (x2-x1) / (y2-y1) + x1;
  2420.                 /* Only count intersections once
  2421.                     except at maxima and minima. Also, 
  2422.                     if two consecutive intersections are
  2423.                     endpoints of the same horizontal line
  2424.                     that is not at a maxima or minima,    
  2425.                     discard the leftmost of the two. */
  2426.                 if (!interFirst) {
  2427.                     if ((p[ind1].y == p[lastInd1].y) &&
  2428.                         (p[ind1].x != p[lastInd1].x)) {
  2429.                         if (dir == dirLast) {
  2430.                             if (inter > interLast) {
  2431.                                 /* Replace the old one */
  2432.                                 im->polyInts[ints] = inter;
  2433.                             } else {
  2434.                                 /* Discard this one */
  2435.                             }    
  2436.                             continue;
  2437.                         }
  2438.                     }
  2439.                     if (inter == interLast) {
  2440.                         if (dir == dirLast) {
  2441.                             continue;
  2442.                         }
  2443.                     }
  2444.                 } 
  2445.                 if (i > 0) {
  2446.                     im->polyInts[ints++] = inter;
  2447.                 }
  2448.                 lastInd1 = i;
  2449.                 dirLast = dir;
  2450.                 interLast = inter;
  2451.                 interFirst = 0;
  2452.             }
  2453.         }
  2454.         qsort(im->polyInts, ints, sizeof(int), gdCompareInt);
  2455.         for (i=0; (i < (ints-1)); i+=2) {
  2456.             gdImageLine(im, im->polyInts[i], y,
  2457.                 im->polyInts[i+1], y, c);
  2458.         }
  2459.     }
  2460. }
  2461.     
  2462. int gdCompareInt(const void *a, const void *b)
  2463. {
  2464.     return (*(const int *)a) - (*(const int *)b);
  2465. }
  2466.  
  2467. void gdImageSetStyle(gdImagePtr im, int *style, int noOfPixels)
  2468. {
  2469.     if (im->style) {
  2470.         free(im->style);
  2471.     }
  2472.     im->style = (int *) 
  2473.         malloc(sizeof(int) * noOfPixels);
  2474.     memcpy(im->style, style, sizeof(int) * noOfPixels);
  2475.     im->styleLength = noOfPixels;
  2476.     im->stylePos = 0;
  2477. }
  2478.  
  2479. void gdImageSetBrush(gdImagePtr im, gdImagePtr brush)
  2480. {
  2481.     int i;
  2482.     im->brush = brush;
  2483.     for (i=0; (i < gdImageColorsTotal(brush)); i++) {
  2484.         int index;
  2485.         index = gdImageColorExact(im, 
  2486.             gdImageRed(brush, i),
  2487.             gdImageGreen(brush, i),
  2488.             gdImageBlue(brush, i));
  2489.         if (index == (-1)) {
  2490.             index = gdImageColorAllocate(im,
  2491.                 gdImageRed(brush, i),
  2492.                 gdImageGreen(brush, i),
  2493.                 gdImageBlue(brush, i));
  2494.             if (index == (-1)) {
  2495.                 index = gdImageColorClosest(im,
  2496.                     gdImageRed(brush, i),
  2497.                     gdImageGreen(brush, i),
  2498.                     gdImageBlue(brush, i));
  2499.             }
  2500.         }
  2501.         im->brushColorMap[i] = index;
  2502.     }
  2503. }
  2504.     
  2505. void gdImageSetTile(gdImagePtr im, gdImagePtr tile)
  2506. {
  2507.     int i;
  2508.     im->tile = tile;
  2509.     for (i=0; (i < gdImageColorsTotal(tile)); i++) {
  2510.         int index;
  2511.         index = gdImageColorExact(im, 
  2512.             gdImageRed(tile, i),
  2513.             gdImageGreen(tile, i),
  2514.             gdImageBlue(tile, i));
  2515.         if (index == (-1)) {
  2516.             index = gdImageColorAllocate(im,
  2517.                 gdImageRed(tile, i),
  2518.                 gdImageGreen(tile, i),
  2519.                 gdImageBlue(tile, i));
  2520.             if (index == (-1)) {
  2521.                 index = gdImageColorClosest(im,
  2522.                     gdImageRed(tile, i),
  2523.                     gdImageGreen(tile, i),
  2524.                     gdImageBlue(tile, i));
  2525.             }
  2526.         }
  2527.         im->tileColorMap[i] = index;
  2528.     }
  2529. }
  2530.  
  2531. void gdImageInterlace(gdImagePtr im, int interlaceArg)
  2532. {
  2533.     im->interlace = interlaceArg;
  2534. }
  2535.  
  2536.