/* colors.c
 *
 * By Byron C. Darrah,
 * 4/28/94, Thursday
 * Initialize some colors for drawings to use.
 * For now, this simply makes a color table for 27 colors -- a fixed set of
 * combinations of the three primary colors, R, G & B.  In the future, color
 * should be enhanced to allow more efficient use of the colormap.   Eg:
 * allocate only colors that are needed, and thereby be able allocate a range
 * of colors for objects to make use of shading.  Another enhancement
 * could be to take over the colormap of the display entirely, so that
 * a color table is not needed for lookup of which pixel value has which
 * desired color.
 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <X11/Xlib.h>

#include "colors.h"

/*---------------------------------------------------------------------------*/

typedef struct
{
   unsigned short red, green, blue;
} d_color_t;

d_color_t d_colortab[16] =
{
   {    0,     0,     0},   /* Black        */
   {32768,     0,     0},   /* Dark red     */
   {    0, 32768,     0},   /* Dark green   */
   {    0,     0, 32768},   /* Dark blue    */
   {16384, 16384,     0},   /* Dark brown  */
   {32768,     0, 32768},   /* Dark magenta */
   {    0, 32768, 32768},   /* Dark cyan    */
   {21845, 21845, 21845},   /* Dark grey    */
   {43690, 43690, 43690},   /* Light grey   */
   {65535,     0,     0},   /* Red          */
   {    0, 65525,     0},   /* Green        */
   {    0,     0, 65535},   /* Blue         */
   {32768, 32768,     0},   /* Brown        */
   {65535,     0, 65535},   /* Magenta      */
   {    0, 65535, 65535},   /* Cyan         */
   {65535, 65535, 65535}    /* White        */
};

/*---------------------------------------------------------------------------*/

/* Allocate colors and build a lookup table for them, so that each time
 * this program is run, it may get different pixel values for the requested
 * colors, but the index to these colors in the color table will be the
 * same.
 */

int init_colors(Display *disp, unsigned long color_table[], int color)
{
   Colormap cmap;
   XColor   request_color = {0, 0, 0, 0, 0, 0};
   int i;

   cmap = DefaultColormap(disp, DefaultScreen(disp));
   for(i = 0; i < NUMCOLORS; i++)
   {
      if(color)
      {
         request_color.red   = d_colortab[i].red;
         request_color.green = d_colortab[i].green;
         request_color.blue  = d_colortab[i].blue;
         if(!XAllocColor(disp, cmap, &request_color))
            fprintf(stderr, "colors: Bad color allocated.\n");
         color_table[i] = request_color.pixel;
      }
      else
      {
         color_table[i] = (
             (d_colortab[i].red || d_colortab[i].green || d_colortab[i].blue)
             ? XWhitePixel(disp, DefaultScreen(disp))
             : XBlackPixel(disp, DefaultScreen(disp)));
      }
   }

   return(0);
}

/*---------------------------------------------------------------------------*/
