// The TextureLandscape Class - Ingrid Brandt

class TextureLandscape
{
#define PictureCoords(x,y) (((y) * xsize + (x)) * 3)
   
 protected:
   int x_size;
   int y_size;
   
   GLubyte * colours;
   
   GLuint textureId;
   
 public:
   TextureLandscape ()
   {
      x_size = 0;
      y_size = 0;
   }
   
   ~TextureLandscape ()
   {
      glDeleteTextures (1, &textureId);
      delete [] colours;
   }
   TextureLandscape (char * filename)
   {
      std::cout << "Loading texture: " << filename << "\n";
      
      FILE * file;
      if (strstr (filename, "ppm") == NULL)
      {
         char line [MAXSTRING];
         sprintf (line, "giftopnm %s | pnmflip -tb >tmptexture.pnm",
                  filename);
         system (line);
         
         file = fopen ("tmptexture.pnm", "r");
      }
      else
        file = fopen (filename, "r");
      
      if (file == NULL)
      {
         std::cerr << "Could not open pnm file " << filename << "\n";
         exit (1);
      }
      
	  int c;
      if (fscanf (file, "P6\n%d %d\n%d\n", &x_size, &y_size, &c) != 3)
      {
	 std::cerr << "Unable to read file header of converted " << filename << "\n";
         exit (1);
      }
      
      colours = new GLubyte [x_size * y_size * 3];
      fread (colours, x_size * 3, y_size, file);  
      fclose (file);
      
      // set up OpenGL texturing.
      glGenTextures (1, &textureId);
      glBindTexture (GL_TEXTURE_2D, textureId);
      
      glTexImage2D (GL_TEXTURE_2D, 0, 3, x_size, y_size, 0, GL_RGB,
                    GL_UNSIGNED_BYTE, colours);
      glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
      glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
      glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
      glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
   }
   // make this texture active.
   void activate ()
   {
      glBindTexture (GL_TEXTURE_2D, textureId);
   }
   int textureID ()
   {
      return textureId;
   }
};  


