
/**
 * Readtexture does just what the name suggests. This file is mostly
 * a stolen and dumbed down version of the "textiff" demo from the GLUT
 * toolkit. I'll probably change this file to use PNG files when the
 * libpng matures a little more. Or at least gets out of beta. 
 *                               /August
 *
 * (Homage, obviously, to Mark Kilgard, who wrote GLUT.)
 * Original license follows:
 **/

/* Copyright (c) Mark J. Kilgard, 1997. */

/* This program is freely distributable without licensing fees  and is
   provided without guarantee or warrantee expressed or  implied. This
   program is -not- in the public domain. */

#include "xt.h"

texture *readTexture(char *tiffname)
{
  TIFFRGBAImage img;
  tsize_t npixels;
  TIFF *tif;
  char emsg[1024];
  texture *tex;

  tif = TIFFOpen(tiffname, "r");
  if (tif == NULL) 
    {
      fprintf(stderr, "Couldn't load texture file %s\n", tiffname);
      exit(0);
  }

  tex = (texture *)malloc(sizeof(texture));
  if(!tex)
  {
      g_print("Couldn't allocate memory for texture struct!\n");
      return NULL;
  }

  tex->depth = 4;

  if (TIFFRGBAImageBegin(&img, tif, 0, emsg)) 
    {
      npixels = (tsize_t) (img.width * img.height);
      tex->bits = (uint32 *) _TIFFmalloc(npixels * (tsize_t) sizeof(uint32));
      if (tex->bits != NULL)
	{
	  if (TIFFRGBAImageGet(&img, tex->bits, img.width, img.height) == 0)
	    {
	      TIFFError(tiffname, emsg);
	      exit(1);
	    }
	}
      TIFFRGBAImageEnd(&img);
    } 
  else 
    {
      TIFFError(tiffname, emsg);
      exit(1);
    }

/*
  if (!glutExtensionSupported("GL_EXT_abgr"))
  {
      // ABGR -> RGBA 

      int i;
      printf("Byteswapping texture...\n");
      for (i = 0; i < npixels; i++) 
      {
	  register unsigned char *cp = (unsigned char *) &(tex->bits[i]);
	  int t;
	  
	  t = cp[3];
	  cp[3] = cp[0];
	  cp[0] = t;
	  t = cp[2];
	  cp[2] = cp[1];
	  cp[1] = t;
      }
  }
*/
  tex->width = img.width;
  tex->height = img.height;

  return tex;
}

