/* ImageTexture.C: ImageTexture nodes (public source) */

#include "ImageTexture.H"
#include "renderer.H"
#include "file.H"

namespace xrml {

void ImageTexture::load(void)
{
  if (Map || cantload) return;  // don't load it twice
  
  // load image texture into buffer   /* TODO: only partial PPM support for now */
  if (url.size == 0) Error(NULL, "opengl_renderer::load_imageTexture: no url given");

  class file* f = world->openFileFromURLs(url);
  if (!f) {
    Error(NULL, "couldn't open texture image file");
    cantload = true;
    return;
  }
  Info(NULL, "reading image texture from file '%s' ... ", f->url);

  // read header
  int colorsize=0;
  int width=0, height=0;
  int r = fscanf(f->fp, "P6\n%d %d\n%d", &width, &height, &colorsize);
  fgetc(f->fp); // skip the newline character
  if (r != 3) {
    Error(NULL, "image texture file '%s' is a bad raw PPM file", f->url);
    f->close();
    cantload = true;
    return;
  }

  // calc amount of memory needed and allocate it
  Width = width;
  Height = height;
  Channels = 3; // load it as a RGB texture
  Map = new unsigned char [Width * Height * 3];

  // read image
  for (int j=0; j<Height; j++) {
    unsigned char *pix =
      Map + (Height-j -1) * Width * 3;
    for (int i=0; i < Width; i++, pix += 3) {
      pix[0] = (unsigned char)(fgetc(f->fp) * 256 / (colorsize+1));
      pix[1] = (unsigned char)(fgetc(f->fp) * 256 / (colorsize+1));
      pix[2] = (unsigned char)(fgetc(f->fp) * 256 / (colorsize+1));
      //      pix[3] = 255;
    }
  }
  if (ferror(f->fp)) {
    Error(NULL, "error reading image texture file '%s'", f->url);
    f->close();
    cantload = true;
    return;
  }

  // close file
  f->close();

  cantload = false;
  return;
}

void ImageTexture::render(void)
{
  // does nothing
}

void ImageTexture::begin_render(void)
{
  //  if (!Texture::Map && !cantload) load();
  //  cerr << __FILE__ << ":" << __LINE__ << ": " << Texture::Width << "x" << Texture::Height << "x" << Texture::Channels << " texture. Map = " << Texture::Map << "\n";
  world->renderer->begin_ImageTexture(this);
}

void ImageTexture::end_render(void)
{
  world->renderer->end_ImageTexture(this);
}

}  // namespace xrml
