
// THIS CODE IS BASED ON THE PSEUDO-CODE FROM 
// "Real Pixels", Greg Ward, Graphics Gems II, p80-83, published by Arvo, Academic Press. 

#include <math.h>
#include "CompressedColor.h"


CompressedColor::CompressedColor()
{ r=g=b=e=0; }


CompressedColor::CompressedColor(const COLOR& col)
{
  setColor(col);
}


void CompressedColor::setColor(const COLOR& col)
{
  int   ex;
  float v;
  RGB   rgb;

  ColorToRGB(col, &rgb);
  
  v = RGBMAXCOMPONENT(rgb);
  if (v<1e-32)
    {
      r=0;
      g=0;
      b=0;
      e=0;
    }
  else
    {
      v = frexp(v,&ex)*256.0/v;
      r = (unsigned char)(rgb.r*v);
      g = (unsigned char)(rgb.g*v);
      b = (unsigned char)(rgb.b*v);
      e = (unsigned char)(ex+128);
    }      
}


void CompressedColor::getColor(COLOR& col)
{
  float v;
  RGB   rgb;

  if (e==0)
    {
      COLORSETMONOCHROME(col,0.0f);
    }
  else
    {
      v = ldexp(1.0/256.0,e-128);
      rgb.r = ((float)r + 0.5f)*v;
      rgb.g = ((float)g + 0.5f)*v;
      rgb.b = ((float)b + 0.5f)*v;
      RGBToColor(rgb, &col); 
    }  
}


int CompressedColor::getSize()
{ return 4;}


void CompressedColor::write(FILE *ff)
{
  fwrite((void*)(&r),sizeof(unsigned char),1,ff);
  fwrite((void*)(&g),sizeof(unsigned char),1,ff);
  fwrite((void*)(&b),sizeof(unsigned char),1,ff);
  fwrite((void*)(&e),sizeof(unsigned char),1,ff);
}

void CompressedColor::read(FILE *ff)
{
  fread((void*)(&r),sizeof(unsigned char),1,ff);
  fread((void*)(&g),sizeof(unsigned char),1,ff);
  fread((void*)(&b),sizeof(unsigned char),1,ff);
  fread((void*)(&e),sizeof(unsigned char),1,ff);
}




