// This sourcefile is created by Peter Jodda / peter@jodda.de
// It is under the Peter Jodda license:
// Everyboy may use it on his own risk. This header must stay in the file!
// If you expand this file, please contact me, that I can integrate the
// enhancemants in the original file.
//
// buffer2d 
// einfacher 2d buffer

#include <stdio.h>

#include "buffer2d.h"

#define PIXEL_ROT_MASKE   0x000000ff
#define PIXEL_GRUEN_MASKE 0x0000ff00
#define PIXEL_BLAU_MASKE  0x00ff0000

#define PIXEL_ROT_SHIFT   0
#define PIXEL_GRUEN_SHIFT 8
#define PIXEL_BLAU_SHIFT  16

#define PIXEL_ROT(x)   ((x&PIXEL_ROT_MASKE  )>>PIXEL_ROT_SHIFT  ) 
#define PIXEL_GRUEN(x) ((x&PIXEL_GRUEN_MASKE)>>PIXEL_GRUEN_SHIFT) 
#define PIXEL_BLAU(x)  ((x&PIXEL_BLAU_MASKE )>>PIXEL_BLAU_SHIFT ) 

#define PIXEL_MAKE(r,g,b) ((((int)r) << PIXEL_ROT_SHIFT)   | \
			      (((int)g) << PIXEL_GRUEN_SHIFT) | \
                              (((int)b) << PIXEL_BLAU_SHIFT)   )


buffer2d::buffer2d(int breite,int hoehe)
{
   bufferbreite = breite;
   bufferhoehe  = hoehe;
   
   buffer = new int[breite*hoehe];
}

buffer2d::~buffer2d()
{
   if(buffer != NULL)
      delete buffer;
   buffer = NULL;
}

int buffer2d::breite()
{
   return bufferbreite;
}

int buffer2d::hoehe()
{
   return bufferhoehe;
}


void buffer2d::set(int x,int y,int wert)
{
   if(   x < 0 || x>= bufferbreite
      || y <0  || y>= bufferhoehe
      || buffer ==NULL)
   {
      return;
   }
   buffer[x+(y*bufferbreite)] = wert;
}

void buffer2d::set(int x,int y,unsigned char r,unsigned char g,unsigned char b)
{
   if(   x < 0 || x>= bufferbreite
      || y <0  || y>= bufferhoehe
      || buffer ==NULL)
   {
      return;
   }
   buffer[x+(y*bufferbreite)] = PIXEL_MAKE(r,g,b);
}

int buffer2d::get(int x,int y)
{
   if(   x < 0 || x>= bufferbreite
      || y <0  || y>= bufferhoehe
      || buffer ==NULL)
   {
      return 0;
   }
   return buffer[x+(y*bufferbreite)] ;
}

void buffer2d::get(int x,int y,unsigned char *r,unsigned char *g,unsigned char *b)
{
   int wert;

   if(   x < 0 || x>= bufferbreite
      || y <0  || y>= bufferhoehe
      || buffer ==NULL)
   {
      return ;
   }

   wert =  buffer[x+(y*bufferbreite)] ;
   * r = (unsigned char) PIXEL_ROT(wert);
   * g = (unsigned char) PIXEL_GRUEN(wert);
   * b = (unsigned char) PIXEL_BLAU(wert);
}
