home *** CD-ROM | disk | FTP | other *** search
/ Tricks of the Windows Gam…ming Gurus (2nd Edition) / Disc2.iso / msdn_vcb / samples / vc98 / sdk / graphics / video / palmap / dibmap.c next >
Encoding:
C/C++ Source or Header  |  1997-10-05  |  22.0 KB  |  1,083 lines

  1. /**************************************************************************
  2.  *
  3.  *  THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
  4.  *  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  5.  *  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
  6.  *  PURPOSE.
  7.  *
  8.  *  Copyright (C) 1992 - 1997 Microsoft Corporation.  All Rights Reserved.
  9.  *
  10.  **************************************************************************/
  11.  
  12. #include <windows.h>
  13. #include <windowsx.h>
  14. #include "dibmap.h"
  15.  
  16. extern NEAR PASCAL MemCopy(LPVOID,LPVOID,DWORD);
  17. extern NEAR PASCAL MemFill(LPVOID,DWORD,BYTE);
  18.  
  19. void Histogram24(BYTE *pb, int dx, int dy, WORD WidthBytes, LPHISTOGRAM lpHistogram);
  20. void Histogram16(BYTE *pb, int dx, int dy, WORD WidthBytes, LPHISTOGRAM lpHistogram);
  21. void Histogram8(BYTE *pb, int dx, int dy, WORD WidthBytes, LPHISTOGRAM lpHistogram, LPWORD lpColors);
  22. void Histogram4(BYTE *pb, int dx, int dy, WORD WidthBytes, LPHISTOGRAM lpHistogram, LPWORD lpColors);
  23. void Histogram1(BYTE *pb, int dx, int dy, WORD WidthBytes, LPHISTOGRAM lpHistogram, LPWORD lpColors);
  24.  
  25. void Reduce24(BYTE *pbIn, int dx, int dy, WORD cbIn, BYTE *pbOut, WORD cbOut, LPBYTE lp16to8);
  26. void Reduce16(BYTE *pbIn, int dx, int dy, WORD cbIn, BYTE *pbOut, WORD cbOut, LPBYTE lp16to8);
  27. void Reduce8(BYTE *pbIn, int dx, int dy, WORD cbIn, BYTE *pbOut, WORD cbOut, LPBYTE lp8to8);
  28. void Reduce4(BYTE *pbIn, int dx, int dy, WORD cbIn, BYTE *pbOut, WORD cbOut, LPBYTE lp8to8);
  29. void Reduce1(BYTE *pbIn, int dx, int dy, WORD cbIn, BYTE *pbOut, WORD cbOut, LPBYTE lp8to8);
  30.  
  31. LPHISTOGRAM lpHistogram;
  32.  
  33. //
  34. // InitHistogram
  35. //
  36. // create a zero'ed histogram table, or initialize a existing table
  37. // to all zeros.
  38. //
  39. LPHISTOGRAM InitHistogram(
  40.     LPHISTOGRAM lpHistogram)
  41. {
  42.     if (lpHistogram == NULL)
  43.         lpHistogram = (LPVOID)GlobalAllocPtr(GHND, 32768L * sizeof(DWORD));
  44.  
  45.     return lpHistogram;
  46. }
  47.  
  48. //
  49. // FreeHistogram
  50. //
  51. // free a histogram table
  52. //
  53. void FreeHistogram(
  54.     LPHISTOGRAM lpHistogram)
  55. {
  56.     GlobalFreePtr(lpHistogram);
  57. }
  58.  
  59. //
  60. // DibHistogram
  61. //
  62. // take all colors in a dib and increment its entry in the Histogram table
  63. //
  64. // supports the following DIB formats: 1,4,8,16,24
  65. //
  66. BOOL DibHistogram(
  67.     LPBITMAPINFOHEADER lpbi,
  68.     LPBYTE lpBits,
  69.     int x,
  70.     int y,
  71.     int dx,
  72.     int dy,
  73.     LPHISTOGRAM lpHistogram)
  74. {
  75.     int        i;
  76.     WORD        WidthBytes;
  77.     RGBQUAD FAR *    prgbq;
  78.     WORD        argb16[256];
  79.  
  80.     if (lpbi == NULL || lpHistogram == NULL)
  81.         return FALSE;
  82.  
  83.     if (lpbi->biClrUsed == 0 && lpbi->biBitCount <= 8)
  84.         lpbi->biClrUsed = (1 << (int)lpbi->biBitCount);
  85.  
  86.     if (lpBits == NULL)
  87.         lpBits = (LPBYTE)lpbi + (int)lpbi->biSize
  88.             + (int)lpbi->biClrUsed*sizeof(RGBQUAD);
  89.  
  90.     WidthBytes = (WORD)(((LONG)lpbi->biBitCount * lpbi->biWidth + 7) / 8 + 3) & ~3;
  91.  
  92.     ((BYTE *)lpBits) += (DWORD)y*WidthBytes + ((x*(int)lpbi->biBitCount)/8);
  93.  
  94.     if (dx < 0 || dx > (int)lpbi->biWidth)
  95.         dx = (int)lpbi->biWidth;
  96.  
  97.     if (dy < 0 || dy > (int)lpbi->biHeight)
  98.         dy = (int)lpbi->biHeight;
  99.  
  100.     if ((int)lpbi->biBitCount <= 8)
  101.     {
  102.         prgbq = (LPVOID)((LPBYTE)lpbi + lpbi->biSize);
  103.  
  104.         for (i=0; i<(int)lpbi->biClrUsed; i++)
  105.         {
  106.             argb16[i] = (WORD) RGB16(prgbq[i].rgbRed,prgbq[i].rgbGreen,prgbq[i].rgbBlue);
  107.         }
  108.  
  109.         for (i=(int)lpbi->biClrUsed; i<256; i++)
  110.         {
  111.             argb16[i] = 0x0000;    // just in case!
  112.         }
  113.     }
  114.  
  115.     switch ((int)lpbi->biBitCount)
  116.     {
  117.         case 24:
  118.             Histogram24(lpBits, dx, dy, WidthBytes, lpHistogram);
  119.             break;
  120.  
  121.         case 16:
  122.             Histogram16(lpBits, dx, dy, WidthBytes, lpHistogram);
  123.             break;
  124.  
  125.         case 8:
  126.             Histogram8(lpBits, dx, dy, WidthBytes, lpHistogram, argb16);
  127.             break;
  128.  
  129.         case 4:
  130.             Histogram4(lpBits, dx, dy, WidthBytes, lpHistogram, argb16);
  131.             break;
  132.  
  133.         case 1:
  134.             Histogram1(lpBits, dx, dy, WidthBytes, lpHistogram, argb16);
  135.             break;
  136.     }
  137. }
  138.  
  139. //
  140. // will convert the given DIB to a 8bit DIB with the specifed palette
  141. //
  142. LPBITMAPINFOHEADER DibReduce(
  143.     LPBITMAPINFOHEADER lpbiIn,
  144.     LPBYTE pbIn,
  145.     HPALETTE hpal,
  146.     LPBYTE lp16to8)
  147. {
  148.     LPBITMAPINFOHEADER    lpdib;
  149.     WORD            nPalColors;  // NOTE win32 GetObject ONLY returns
  150.                                              // 2 bytes for HPALs
  151.     int            nDibColors;
  152.     WORD            cbOut;
  153.     WORD            cbIn;
  154.     BYTE            xlat[256];
  155.     BYTE *        pbOut;
  156.     RGBQUAD FAR *        prgb;
  157.     DWORD            dwSize;
  158.     int            i;
  159.     int            dx;
  160.     int            dy;
  161.     PALETTEENTRY        pe;
  162.  
  163.     dx    = (int)lpbiIn->biWidth;
  164.     dy    = (int)lpbiIn->biHeight;
  165.     cbIn    = (WORD)((((UINT)lpbiIn->biBitCount*dx+7)/8+3)&~3);
  166.     cbOut    = (WORD)((dx+3)&~3);
  167.  
  168.     GetObject(hpal, sizeof(WORD), (LPVOID)&nPalColors);
  169.     nDibColors = (int)lpbiIn->biClrUsed;
  170.  
  171.     if (nDibColors == 0 && lpbiIn->biBitCount <= 8)
  172.         nDibColors = (1 << (int)lpbiIn->biBitCount);
  173.  
  174.     if (pbIn == NULL)
  175.         pbIn = (LPBYTE)lpbiIn + (int)lpbiIn->biSize + nDibColors*sizeof(RGBQUAD);
  176.  
  177.     dwSize = (DWORD)cbOut * dy;
  178.  
  179.     lpdib = GlobalAllocPtr(GMEM_MOVEABLE,sizeof(BITMAPINFOHEADER)
  180.         + nPalColors*sizeof(RGBQUAD) + dwSize);
  181.  
  182.     if (!lpdib)
  183.         return NULL;
  184.  
  185.     lpdib->biSize        = sizeof(BITMAPINFOHEADER);
  186.     lpdib->biWidth        = lpbiIn->biWidth;
  187.     lpdib->biHeight        = lpbiIn->biHeight;
  188.     lpdib->biPlanes        = 1;
  189.     lpdib->biBitCount    = 8;
  190.     lpdib->biCompression    = BI_RGB;
  191.     lpdib->biSizeImage    = dwSize;
  192.     lpdib->biXPelsPerMeter    = 0;
  193.     lpdib->biYPelsPerMeter    = 0;
  194.     lpdib->biClrUsed    = (DWORD)nPalColors;
  195.     lpdib->biClrImportant    = 0;
  196.  
  197.     pbOut    = (LPBYTE)lpdib + (int)lpdib->biSize + nPalColors*sizeof(RGBQUAD);
  198.     prgb    = (LPVOID)((LPBYTE)lpdib + (int)lpdib->biSize);
  199.  
  200.     for (i=0; i<(int)nPalColors; i++)
  201.     {
  202.         GetPaletteEntries(hpal, i, 1, &pe);
  203.  
  204.         prgb[i].rgbRed        = pe.peRed;
  205.         prgb[i].rgbGreen    = pe.peGreen;
  206.         prgb[i].rgbBlue        = pe.peBlue;
  207.         prgb[i].rgbReserved    = 0;
  208.     }
  209.  
  210.     if ((int)lpbiIn->biBitCount <= 8)
  211.     {
  212.         prgb = (LPVOID)((LPBYTE)lpbiIn + lpbiIn->biSize);
  213.  
  214.         for (i=0; i<nDibColors; i++)
  215.             xlat[i] = lp16to8[RGB16(prgb[i].rgbRed,prgb[i].rgbGreen,prgb[i].rgbBlue)];
  216.  
  217.         for (; i<256; i++)
  218.             xlat[i] = 0;
  219.     }
  220.  
  221.     switch ((int)lpbiIn->biBitCount)
  222.     {
  223.         case 24:
  224.             Reduce24(pbIn, dx, dy, cbIn, pbOut, cbOut, lp16to8);
  225.             break;
  226.  
  227.         case 16:
  228.             Reduce16(pbIn, dx, dy, cbIn, pbOut, cbOut, lp16to8);
  229.             break;
  230.  
  231.         case 8:
  232.             Reduce8(pbIn, dx, dy, cbIn, pbOut, cbOut, xlat);
  233.             break;
  234.  
  235.         case 4:
  236.             Reduce4(pbIn, dx, dy, cbIn, pbOut, cbOut, xlat);
  237.             break;
  238.  
  239.         case 1:
  240.             Reduce1(pbIn, dx, dy, cbIn, pbOut, cbOut, xlat);
  241.             break;
  242.     }
  243.  
  244.     return lpdib;
  245. }
  246.  
  247. ///////////////////////////////////////////////////////////////////////////////
  248. // cluster.c
  249. ///////////////////////////////////////////////////////////////////////////////
  250.  
  251. #define IN_DEPTH    5        // # bits/component kept from input
  252. #define IN_SIZE        (1 << IN_DEPTH)    // max value of a color component
  253.  
  254. typedef enum { red, green, blue } color;
  255.  
  256. typedef struct tagCut
  257. {
  258.     long lvariance;        // for int version
  259.     int cutpoint;
  260.     unsigned long rem;    // for experimental fixed point
  261.     color cutaxis;
  262.     long w1, w2;
  263.     double variance;
  264. } Cut;
  265.  
  266. typedef struct tagColorBox    // from cluster.c
  267. {
  268.     struct tagColorBox *next;        /* pointer to next box */
  269.     int rmin, rmax, gmin, gmax, bmin, bmax;    /* bounding box */
  270.     long variance, wt;            /* weighted variance */
  271.     long sum[3];                /* sum of values */
  272. } ColorBox;
  273.  
  274. static int InitBoxes(int nBoxes);
  275. static void DeleteBoxes(void);
  276. static int SplitBoxAxis(ColorBox *box, Cut cutaxis);
  277. static void ShrinkBox(ColorBox *box);
  278. static int ComputePalette(LPHISTOGRAM lpHistogram, LPBYTE lp16to8, LPPALETTEENTRY palette);
  279. static COLORREF DetermineRepresentative(ColorBox *box, int palIndex);
  280. static Cut FindSplitAxis(ColorBox *box);
  281. static void SplitBox(ColorBox *box);
  282. static void SortBoxes(void);
  283.  
  284. HANDLE hBoxes;
  285. ColorBox    *UsedBoxes;
  286. ColorBox    *FreeBoxes;
  287. LPBYTE        glp16to8;
  288.  
  289. //#define hist(r,g,b) ((DWORD *)glpHistogram)[(WORD)(b) | ((WORD)(g)<<IN_DEPTH) | ((WORD)(r)<<(IN_DEPTH*2))]
  290. #define hist(r,g,b) GetHistogram((BYTE)(r),(BYTE)(g),(BYTE)(b))
  291.  
  292. #pragma optimize ("", off)
  293. //
  294. // set FS == lpHistogram.sel, so we can get at it quickly!
  295. //
  296. void NEAR PASCAL UseHistogram(
  297.     LPHISTOGRAM lpHistogramToSet)
  298. {
  299.         lpHistogram = lpHistogramToSet;
  300. }
  301.  
  302. //
  303. // get the DOWRD histogram count of a RGB
  304. //
  305. DWORD near _fastcall GetHistogram(
  306.     BYTE r,
  307.     BYTE g,
  308.     BYTE b)
  309. {
  310.         return lpHistogram[((UINT)r << 10 ) + ((UINT)g << 5) + (UINT)b];
  311. }
  312.  
  313. //
  314. // increment the histogram count of a RGB16
  315. //
  316. //
  317. // #define IncHistogram(w) if (lpHistogram[(WORD)(w)] < 0xFFFFFFFF)
  318. //                lpHistogram[(WORD)(w)]++;
  319. //
  320. void near _fastcall IncHistogram(WORD rgb16)
  321. {
  322.     if (lpHistogram[rgb16] != (DWORD)-1)
  323.         lpHistogram[rgb16]++;
  324. }
  325.  
  326. #pragma optimize ("", on)
  327.  
  328. // !!! C8 generates a Jump into the middle of a 2 byte instruction
  329. // !!! Stupid C8!
  330. #pragma optimize ("", off)
  331.  
  332. //
  333. // HistogramPalette
  334. //
  335. // given a histogram, will reduce it to 'nColors' number of colors.
  336. // returns a optimal palette.  if specifed lp16to8 will contain the
  337. // translate table from RGB16 to the palette index.
  338. //
  339. // you can specify lpHistogram as lp16to8
  340. //
  341. HPALETTE HistogramPalette(
  342.     LPHISTOGRAM lpHistogram,
  343.     LPBYTE lp16to8,
  344.     int nColors)
  345. {
  346.     struct {
  347.         WORD    palVersion;
  348.         WORD    palNumEntries;
  349.         PALETTEENTRY palPalEntry[256];
  350.     } pal;
  351.  
  352.     WORD        w;
  353.     DWORD        dwMax;
  354.     COLORREF    rgb;
  355.     ColorBox    *box;
  356.     int        i;
  357.  
  358.     //
  359.     // the 'C' code cant handle >64k histogram counts.
  360.     // !!!fix this
  361.     //
  362.     for (dwMax=0,w=0; w<0x8000; w++)
  363.         dwMax = max(dwMax,lpHistogram[w]);
  364.  
  365.     while (dwMax > 0xFFFFl)
  366.     {
  367.         for (w=0; w<0x8000; w++)
  368.             lpHistogram[w] /= 2;
  369.  
  370.         dwMax /= 2;
  371.     }
  372.  
  373.     if (!InitBoxes(min(nColors, 236)))
  374.         return NULL;
  375.  
  376.     UseHistogram(lpHistogram);
  377.     glp16to8 = lp16to8;
  378.  
  379.     /* while there are free boxes left, split the largest */
  380.  
  381.     i = 0;
  382.  
  383.     do {
  384.         i++;
  385.         SplitBox(UsedBoxes);
  386.     }
  387.     while (FreeBoxes && UsedBoxes->variance);
  388.  
  389.     SortBoxes();
  390.  
  391.     i=0;
  392.  
  393.     //
  394.     // add some standard colors to the histogram
  395.     //
  396.     if (nColors > 236)
  397.     {
  398.         HDC hdc;
  399.  
  400.         hdc = GetDC(NULL);
  401.  
  402.         if (GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE)
  403.         {
  404.             GetSystemPaletteEntries(hdc, 0,    
  405.                 10, &pal.palPalEntry[0]);
  406.             GetSystemPaletteEntries(hdc, 246,
  407.                 10, &pal.palPalEntry[246]);
  408.  
  409.             i = 10;
  410.         }
  411.  
  412.         ReleaseDC(NULL, hdc);
  413.     }
  414.  
  415.     /* Generate the representitives and the associated Palette mapping */
  416.     /* NOTE:  Might loop less than nColors times.                      */
  417.     for (box = UsedBoxes; box; box = box->next, i++)
  418.     {
  419.         rgb = DetermineRepresentative(box, i);
  420.         pal.palPalEntry[i].peRed    = GetRValue(rgb);
  421.         pal.palPalEntry[i].peGreen    = GetGValue(rgb);
  422.         pal.palPalEntry[i].peBlue    = GetBValue(rgb);
  423.         pal.palPalEntry[i].peFlags    = 0;
  424.     }
  425.  
  426.     DeleteBoxes();
  427.  
  428.     if (nColors > 236)
  429.     {
  430.         for (; i<246; i++)
  431.         {
  432.             pal.palPalEntry[i].peRed    = 0;
  433.             pal.palPalEntry[i].peGreen    = 0;
  434.             pal.palPalEntry[i].peBlue    = 0;
  435.             pal.palPalEntry[i].peFlags    = 0;
  436.         }
  437.  
  438.         i = 256;
  439.     }
  440.  
  441.     glp16to8 = NULL;
  442.  
  443.     pal.palVersion        = 0x300;
  444.     pal.palNumEntries    = (WORD)i;
  445.     return CreatePalette((LPLOGPALETTE)&pal);
  446. }
  447.  
  448. #pragma optimize ("", on)
  449.  
  450. static void SortBoxes(void)
  451. {
  452.     ColorBox *box;
  453.     ColorBox *newList;
  454.     ColorBox *insBox;
  455.     ColorBox *nextBox;
  456.  
  457.     newList = UsedBoxes;
  458.     nextBox = newList->next;
  459.     newList->next = NULL;
  460.  
  461.     for (box = nextBox; box; box = nextBox) { // just an insertion sort...
  462.             nextBox = box->next;
  463.             if (box->wt > newList->wt) {
  464.                     box->next = newList;
  465.                     newList = box;
  466.             } else {
  467.                     for (insBox = newList;
  468.                             insBox->next && (box->wt < insBox->next->wt);
  469.                             insBox = insBox->next) ;
  470.                     box->next = insBox->next;
  471.                     insBox->next = box;
  472.             }
  473.     }
  474.  
  475.     UsedBoxes = newList;
  476. }
  477.  
  478.  
  479. /*
  480.     allocate space for nBoxes boxes, set up links.  On exit UsedBoxes
  481.     points to one box, FreeBoxes points to remaining (nBoxes-1) boxes.
  482.     return 0 if successful.
  483. */
  484.  
  485. static BOOL InitBoxes(
  486.     int nBoxes)
  487. {
  488.     int i;
  489.  
  490.     hBoxes = LocalAlloc(LHND, nBoxes*sizeof(ColorBox));
  491.     if (!hBoxes)
  492.         return FALSE;
  493.  
  494.     UsedBoxes = (ColorBox*)LocalLock(hBoxes);
  495.     FreeBoxes = UsedBoxes + 1;
  496.     UsedBoxes->next = NULL;
  497.  
  498.     for (i = 0; i < nBoxes - 1; ++i)
  499.     {
  500.         FreeBoxes[i].next = FreeBoxes + i + 1;
  501.     }
  502.     FreeBoxes[nBoxes-2].next = NULL;
  503.  
  504.     /* save the bounding box */
  505.     UsedBoxes->rmin = UsedBoxes->gmin = UsedBoxes->bmin = 0;
  506.     UsedBoxes->rmax = UsedBoxes->gmax = UsedBoxes->bmax = IN_SIZE - 1;
  507.     UsedBoxes->variance = 9999999;    /* arbitrary large # */
  508.  
  509.     return TRUE;
  510. }
  511.  
  512. static void DeleteBoxes(void)
  513. {
  514.     LocalUnlock(hBoxes);
  515.     LocalFree(hBoxes);
  516.     hBoxes = NULL;
  517. }
  518.  
  519. static void SplitBox(
  520.     ColorBox *box)
  521. {
  522.     /*
  523.     split box into two roughly equal halves and update the data structures
  524.     appropriately.
  525.     */
  526.     Cut cutaxis;
  527.     ColorBox *temp, *temp2, *prev;
  528.  
  529.     cutaxis = FindSplitAxis(box);
  530.  
  531.     /* split the box along that axis.  If rc != 0 then the box contains
  532.     one color, and should not be split
  533.     */
  534.     if (SplitBoxAxis(box, cutaxis))
  535.         return;
  536.  
  537.     /* shrink each of the boxes to fit the points they enclose */
  538.     ShrinkBox(box);
  539.     ShrinkBox(FreeBoxes);
  540.  
  541.     /* move old box down in list, if necessary */
  542.     if (box->next && box->variance < box->next->variance)
  543.     {
  544.         UsedBoxes = box->next;
  545.         temp = box;
  546.         do {
  547.             prev = temp;
  548.             temp = temp->next;
  549.         } while (temp && temp->variance > box->variance);
  550.         box->next = temp;
  551.         prev->next = box;
  552.     }
  553.  
  554.     /* insert the new box in sorted order (descending), removing it
  555.     from the free list.
  556.     */
  557.     if (FreeBoxes->variance >= UsedBoxes->variance)
  558.     {
  559.         temp = FreeBoxes;
  560.         FreeBoxes = FreeBoxes->next;
  561.         temp->next = UsedBoxes;
  562.         UsedBoxes = temp;
  563.     }
  564.     else
  565.     {
  566.         temp = UsedBoxes;
  567.         do {
  568.             prev = temp;
  569.             temp = temp->next;
  570.         } while (temp && temp->variance > FreeBoxes->variance);
  571.         temp2 = FreeBoxes->next;
  572.         FreeBoxes->next = temp;
  573.         prev->next = FreeBoxes;
  574.         FreeBoxes = temp2;
  575.     }
  576. }
  577.  
  578. static Cut FindSplitAxis(
  579.     ColorBox *box)
  580. {
  581.     unsigned long    proj_r[IN_SIZE],proj_g[IN_SIZE],proj_b[IN_SIZE];
  582.     unsigned long    f;
  583.     double        currentMax,mean;
  584.     unsigned long    w,w1,m,m1;
  585.     int        r,g,b;
  586.     int        bestCut;
  587.     color        bestAxis;
  588.     Cut        cutRet;
  589.     double        temp1,temp2;
  590.     
  591.     for (r = 0; r < IN_SIZE; r++) {
  592.         proj_r[r] = proj_g[r] = proj_b[r] = 0;
  593.     }
  594.     
  595.     w = 0;
  596.     
  597.     // Project contents of box down onto axes
  598.     for (r = box->rmin; r <= box->rmax; r++) {
  599.         for (g = box->gmin; g <= box->gmax; ++g) {
  600.             for (b = box->bmin; b <= box->bmax; ++b) {
  601.                 f = hist(r,g,b);
  602.                 proj_r[r] += f;
  603.                 proj_g[g] += f;
  604.                 proj_b[b] += f;
  605.             }
  606.         }
  607.         w += proj_r[r];
  608.     }
  609.  
  610.     currentMax = 0.0f;
  611.  
  612. #define Check_Axis(l,color)                    \
  613.     m = 0;                            \
  614.     for (l = box->l##min; l <= box->l##max; (l)++) {    \
  615.         m += l * proj_##l[l];                \
  616.     }                            \
  617.     mean = ((double) m) / ((double) w);            \
  618.                                 \
  619.     w1 = 0;                            \
  620.     m1 = 0;                            \
  621.     for (l = box->l##min; l <= box->l##max; l++) {        \
  622.         w1 += proj_##l[l];                \
  623.         if (w1 == 0)                    \
  624.             continue;                \
  625.         if (w1 == w)                    \
  626.             break;                    \
  627.         m1 += l * proj_##l[l];                \
  628.         temp1 = mean - (((double) m1) / ((double) w1));    \
  629.         temp2 = (((double) w1) / ((double) (w-w1))) * temp1 * temp1; \
  630.         if (temp2 > currentMax) {            \
  631.             bestCut = l;                \
  632.             bestAxis = color;            \
  633.             currentMax = temp2;            \
  634.         }                        \
  635.     }
  636.     
  637.     Check_Axis(r,red);
  638.     Check_Axis(g,green);
  639.     Check_Axis(b,blue);
  640.     
  641.     cutRet.cutaxis = bestAxis;
  642.     cutRet.cutpoint = bestCut;
  643.     
  644.     return cutRet;
  645. }
  646.  
  647. static int SplitBoxAxis(
  648.     ColorBox *box,
  649.     Cut cutaxis)
  650. {
  651.     /*
  652.     Split box along splitaxis into two boxes, one of which is placed
  653.     back in box, the other going in the first free box (FreeBoxes)
  654.     If the box only contains one color, return non-zero, else return 0.
  655.     */
  656.     ColorBox *next;
  657.  
  658.     if ( box->variance == 0)
  659.         return 1;
  660.  
  661.     /* copy all non-link information to new box */
  662.     next = FreeBoxes->next;
  663.     *FreeBoxes = *box;
  664.     FreeBoxes->next = next;
  665.  
  666.     switch (cutaxis.cutaxis)
  667.     {
  668.         case red:
  669.             box->rmax = cutaxis.cutpoint;
  670.             FreeBoxes->rmin = cutaxis.cutpoint+1;
  671.             break;
  672.         case green:
  673.             box->gmax = cutaxis.cutpoint;
  674.             FreeBoxes->gmin = cutaxis.cutpoint+1;
  675.             break;
  676.         case blue:
  677.             box->bmax = cutaxis.cutpoint;
  678.             FreeBoxes->bmin = cutaxis.cutpoint+1;
  679.             break;
  680.     }
  681.  
  682.     return 0;
  683. }
  684.  
  685. static void ShrinkBox(
  686.     ColorBox *box)
  687. {
  688.     unsigned long n, sxx, sx2, var, quotient, remainder;
  689.     int r,g,b;
  690.     unsigned long f;
  691.     unsigned long    proj_r[IN_SIZE],proj_g[IN_SIZE],proj_b[IN_SIZE];
  692.  
  693.     n = 0;
  694.     
  695.     for (r = 0; r < IN_SIZE; r++) {
  696.         proj_r[r] = proj_g[r] = proj_b[r] = 0;
  697.     }
  698.     
  699.     // Project contents of box down onto axes
  700.     for (r = box->rmin; r <= box->rmax; r++) {
  701.         for (g = box->gmin; g <= box->gmax; ++g) {
  702.             for (b = box->bmin; b <= box->bmax; ++b) {
  703.                 f = hist(r,g,b);
  704.                 proj_r[r] += f;
  705.                 proj_g[g] += f;
  706.                 proj_b[b] += f;
  707.             }
  708.         }
  709.         n += proj_r[r];
  710.     }
  711.     
  712.     box->wt = n;
  713.     var = 0;
  714.     
  715. #define AddAxisVariance(c)                        \
  716.     sxx = 0; sx2 = 0;                        \
  717.     for (c = box->c##min; c <= box->c##max; c++) {            \
  718.         sxx += proj_##c[c] * c * c;                \
  719.         sx2 += proj_##c[c] * c;                    \
  720.     }                                \
  721.     quotient = sx2 / n; /* This stuff avoids overflow */        \
  722.     remainder = sx2 % n;                        \
  723.     var += sxx - quotient * sx2 - ((remainder * sx2)/n);
  724.     
  725.     AddAxisVariance(r);
  726.     AddAxisVariance(g);
  727.     AddAxisVariance(b);
  728.  
  729.     box->variance = var;
  730. }
  731.  
  732. static COLORREF DetermineRepresentative(
  733.     ColorBox *box,
  734.     int palIndex)
  735. {
  736.     /*
  737.     determines the rgb value to represent the pixels contained in
  738.     box.  nbits is the # bits/component we're allowed to return.
  739.     */
  740.     
  741.     long f;
  742.     long Rval, Gval, Bval;
  743.     unsigned long total;
  744.     int r, g, b;
  745.     int i;
  746.  
  747.     /* compute the weighted sum of the elements in the box */
  748.     Rval = Gval = Bval = total = 0;
  749.     for (r = box->rmin; r <= box->rmax; ++r)
  750.     {
  751.         for (g = box->gmin; g <= box->gmax; ++g)
  752.         {
  753.             for (b = box->bmin; b <= box->bmax; ++b)
  754.             {
  755.                 if (glp16to8)
  756.                 {
  757.                     i = (b) | (g << IN_DEPTH)
  758.                         | (r << (IN_DEPTH*2));
  759.                     glp16to8[i] = (BYTE)palIndex;
  760.                 }
  761.     
  762.                 f = hist(r,g,b);
  763.                 if (f == 0L)
  764.                     continue;
  765.  
  766.                 Rval += f * (long) r;
  767.                 Gval += f * (long) g;
  768.                 Bval += f * (long) b;
  769.  
  770.                 total += f;
  771.             }
  772.         }
  773.     }
  774.  
  775.     /* Bias the sum so that we round up at .5 */
  776.     Rval += total / 2;
  777.     Gval += total / 2;
  778.     Bval += total / 2;
  779.  
  780.     return RGB(Rval*255/total/IN_SIZE, Gval*255/total/IN_SIZE, Bval*255/total/IN_SIZE);
  781. }
  782.  
  783. ///////////////////////////////////////////////////////////////////////////////
  784. //
  785. ///////////////////////////////////////////////////////////////////////////////
  786.  
  787.  
  788. ///////////////////////////////////////////////////////////////////////////////
  789. //
  790. //  write this stuff in ASM!
  791. //
  792. ///////////////////////////////////////////////////////////////////////////////
  793.  
  794. void Histogram24(
  795.     BYTE *pb,
  796.     int dx,
  797.     int dy,
  798.     WORD WidthBytes,
  799.     LPHISTOGRAM lpHistogram)
  800. {
  801.     int x,y;
  802.     BYTE r,g,b;
  803.     WORD w;
  804.  
  805.     UseHistogram(lpHistogram);
  806.  
  807.     WidthBytes -= (WORD) (dx*3);
  808.     for (y=0; y<dy; y++)
  809.     {
  810.         for (x=0; x<dx; x++)
  811.         {
  812.             b = *pb++;
  813.             g = *pb++;
  814.             r = *pb++;
  815.             w = (WORD) RGB16(r,g,b);
  816.             IncHistogram(w);
  817.         }
  818.         pb += WidthBytes;
  819.     }
  820. }
  821.  
  822. void Histogram16(
  823.     BYTE *pb,
  824.     int dx,
  825.     int dy,
  826.     WORD WidthBytes,
  827.     LPHISTOGRAM lpHistogram)
  828. {
  829.     int x,y;
  830.     WORD w;
  831.  
  832.     UseHistogram(lpHistogram);
  833.  
  834.     WidthBytes -= (WORD)(dx*2);
  835.  
  836.     for (y=0; y<dy; y++)
  837.     {
  838.         for (x=0; x<dx; x++)
  839.         {
  840.             w = *((WORD *)pb)++;
  841.             w &= 0x7FFF;
  842.             IncHistogram(w);
  843.         }
  844.         pb += WidthBytes;
  845.     }
  846. }
  847.  
  848. void Histogram8(
  849.     BYTE *pb,
  850.     int dx,
  851.     int dy,
  852.     WORD WidthBytes,
  853.     LPHISTOGRAM lpHistogram,
  854.     LPWORD lpColors)
  855. {
  856.     int x,y;
  857.     WORD w;
  858.  
  859.     UseHistogram(lpHistogram);
  860.  
  861.     WidthBytes -= (WORD)dx;
  862.  
  863.     for (y=0; y<dy; y++)
  864.     {
  865.         for (x=0; x<dx; x++)
  866.         {
  867.             w = lpColors[*pb++];
  868.             IncHistogram(w);
  869.         }
  870.         pb += WidthBytes;
  871.     }
  872. }
  873.  
  874. void Histogram4(
  875.     BYTE *pb,
  876.     int dx,
  877.     int dy,
  878.     WORD WidthBytes,
  879.     LPHISTOGRAM lpHistogram,
  880.     LPWORD lpColors)
  881. {
  882.     int x,y;
  883.     BYTE b;
  884.     WORD w;
  885.  
  886.     UseHistogram(lpHistogram);
  887.  
  888.     WidthBytes -= (WORD)((dx+1)/2);
  889.  
  890.     for (y=0; y<dy; y++)
  891.     {
  892.         for (x=0; x<(dx+1)/2; x++)
  893.         {
  894.             b = *pb++;
  895.  
  896.             w = lpColors[b>>4];
  897.             IncHistogram(w);
  898.  
  899.             w = lpColors[b&0x0F];
  900.             IncHistogram(w);
  901.         }
  902.         pb += WidthBytes;
  903.     }
  904. }
  905.  
  906. void Histogram1(
  907.     BYTE *pb,
  908.     int dx,
  909.     int dy,
  910.     WORD WidthBytes,
  911.     LPHISTOGRAM lpHistogram,
  912.     LPWORD lpColors)
  913. {
  914.     int x,y,i;
  915.     BYTE b;
  916.     WORD w;
  917.  
  918.     UseHistogram(lpHistogram);
  919.  
  920.     WidthBytes -= (WORD)((dx+7)/8);
  921.  
  922.     for (y=0; y<dy; y++)
  923.     {
  924.         for (x=0; x<(dx+7)/8; x++)
  925.         {
  926.             b = *pb++;
  927.  
  928.             for (i=0; i<8; i++)
  929.             {
  930.                 w = lpColors[b>>7];
  931.                 IncHistogram(w);
  932.                 b<<=1;
  933.             }
  934.         }
  935.         pb += WidthBytes;
  936.     }
  937. }
  938.  
  939. ///////////////////////////////////////////////////////////////////////////////
  940. //
  941. //  write this stuff in ASM! too
  942. //
  943. ///////////////////////////////////////////////////////////////////////////////
  944.  
  945. void Reduce24(
  946.     BYTE *pbIn,
  947.     int dx,
  948.     int dy,
  949.     WORD cbIn,
  950.     BYTE *pbOut,
  951.     WORD cbOut,
  952.     LPBYTE lp16to8)
  953. {
  954.     int x,y;
  955.     BYTE r,g,b;
  956.  
  957.     cbOut    -= (WORD)dx;
  958.     cbIn    -= (WORD)(dx*3);
  959.  
  960.     for (y=0; y<dy; y++)
  961.     {
  962.         for (x=0; x<dx; x++)
  963.         {
  964.             b = *pbIn++;
  965.             g = *pbIn++;
  966.             r = *pbIn++;
  967.             *pbOut++ = lp16to8[RGB16(r,g,b)];
  968.         }
  969.         pbIn += cbIn;
  970.         pbOut+= cbOut;
  971.     }
  972. }
  973.  
  974. void Reduce16(
  975.     BYTE *pbIn,
  976.     int dx,
  977.     int dy,
  978.     WORD cbIn,
  979.     BYTE *pbOut,
  980.     WORD cbOut,
  981.     LPBYTE lp16to8)
  982. {
  983.     int x,y;
  984.     WORD w;
  985.  
  986.     cbOut    -= (WORD)dx;
  987.     cbIn    -= (WORD)(dx*2);
  988.  
  989.     for (y=0; y<dy; y++)
  990.     {
  991.         for (x=0; x<dx; x++)
  992.         {
  993.             w = *((WORD *)pbIn)++;
  994.             *pbOut++ = lp16to8[w&0x7FFF];
  995.         }
  996.         pbIn += cbIn;
  997.         pbOut+= cbOut;
  998.     }
  999. }
  1000.  
  1001. void Reduce8(
  1002.     BYTE *pbIn,
  1003.     int dx,
  1004.     int dy,
  1005.     WORD cbIn,
  1006.     BYTE *pbOut,
  1007.     WORD cbOut,
  1008.     LPBYTE lp8to8)
  1009. {
  1010.     int x,y;
  1011.  
  1012.     cbIn    -= (WORD)dx;
  1013.     cbOut    -= (WORD)dx;
  1014.  
  1015.     for (y=0; y<dy; y++)
  1016.     {
  1017.         for (x=0; x<dx; x++)
  1018.         {
  1019.             *pbOut++ = lp8to8[*pbIn++];
  1020.         }
  1021.         pbIn    += cbIn;
  1022.         pbOut    += cbOut;
  1023.     }
  1024. }
  1025.  
  1026. void Reduce4(
  1027.     BYTE *pbIn,
  1028.     int dx,
  1029.     int dy,
  1030.     WORD cbIn,
  1031.     BYTE *pbOut,
  1032.     WORD cbOut,
  1033.     LPBYTE lp8to8)
  1034. {
  1035.     int x,y;
  1036.     BYTE b;
  1037.  
  1038.     cbIn    -= (WORD)((dx+1)/2);
  1039.     cbOut    -= (WORD)((dx+1)&~1);
  1040.  
  1041.     for (y=0; y<dy; y++)
  1042.     {
  1043.         for (x=0; x<(dx+1)/2; x++)
  1044.         {
  1045.             b = *pbIn++;
  1046.             *pbOut++ = lp8to8[b>>4];
  1047.             *pbOut++ = lp8to8[b&0x0F];
  1048.         }
  1049.         pbIn    += cbIn;
  1050.         pbOut    += cbOut;
  1051.     }
  1052. }
  1053.  
  1054. void Reduce1(
  1055.     BYTE *pbIn,
  1056.     int dx,
  1057.     int dy,
  1058.     WORD cbIn,
  1059.     BYTE *pbOut,
  1060.     WORD cbOut,
  1061.     LPBYTE lp8to8)
  1062. {
  1063.     int x,y;
  1064.     BYTE b;
  1065.  
  1066.     cbIn    -= (WORD)((dx+7)/8);
  1067.     cbOut    -= (WORD)dx;
  1068.  
  1069.     for (y=0; y<dy; y++)
  1070.     {
  1071.         for (x=0; x<dx; x++)
  1072.         {
  1073.             if (x%8 == 0)
  1074.                 b = *pbIn++;
  1075.  
  1076.             *pbOut++ = lp8to8[b>>7];
  1077.             b<<=1;
  1078.         }
  1079.         pbIn    += cbIn;
  1080.         pbOut    += cbOut;
  1081.     }
  1082. }
  1083.