Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/orxonox/branches/images/importer/material.cc @ 3133

Last change on this file since 3133 was 3133, checked in by bensch, 19 years ago

orxonox/branches/images: now PathTexture-stuff also works for the non-sdl-image-compiling

File size: 29.9 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Benjamin Grauer
13   co-programmer: ...
14
15   TGA-code: borrowed from nehe-Tutorials
16
17   ToDo:
18   - free SDL-surface when deleting Material.
19   - delete imgNameWithPath after use creation.
20*/
21
22#include "material.h"
23
24// headers only for PathList
25#include <unistd.h>
26#include <sys/types.h>
27#include <sys/stat.h>
28#include <stdlib.h>
29#include <fstream>
30
31using namespace std;
32
33
34PathList::PathList()
35{
36  pathName = NULL;
37  next = NULL;
38}
39PathList::PathList(char* pName)
40{
41  pathName = new char [strlen(pName)+1];
42  strcpy (pathName, pName);
43  next = NULL;
44}
45
46PathList::~PathList()
47{
48  if (pathName)
49    delete []pathName;
50  if (next)
51    delete next;
52}
53
54void PathList::addPath (char* pName)
55{
56  if (pName[0] == '\0')
57    {
58      if (verbose >=3)
59        printf("not Adding empty Path to the List.\n");
60      return;
61    }
62  char* tmpPName = new char[strlen(pName)];
63  strncpy(tmpPName, pName, strlen(pName)-1);
64  tmpPName[strlen(pName)-1] = '\0';
65  printf ("%s\n",tmpPName);
66  if (access (tmpPName, F_OK) == 0)
67    {
68      struct stat status;
69      stat(tmpPName, &status);
70      if (status.st_mode & S_IFDIR)
71        {
72          if (verbose >=2)
73            printf ("Adding Path %s to the PathList.\n", pName);
74          PathList* tmpPathList = this;
75          while (tmpPathList->next)
76            tmpPathList = tmpPathList->next;
77          tmpPathList->next = new PathList(pName);
78        }
79      else
80        if (verbose >=1)
81          printf ("You tried to add non-folder %s to a PathList.\n", tmpPName);
82    }
83  else
84    if (verbose >=1)
85      printf ("You tried to add non-existing folder %s to a PathList.\n", tmpPName);
86  delete []tmpPName;
87}
88
89/**
90   \brief creates a default Material with no Name
91   normally you call this to create a material List (for an obj-file) and then append with addMaterial()
92*/
93Material::Material()
94{
95  init();
96 
97  setName ("");
98}
99
100/**
101   \brief creates a Material.
102   \param mtlName Name of the Material to be added to the Material List
103*/
104Material::Material (char* mtlName)
105{
106  init();
107 
108  setName (mtlName);
109}
110
111/**
112    \brief deletes a Material
113*/
114Material::~Material()
115{
116  if (verbose >= 2)
117    printf ("delete Material %s.\n", name);
118  if (name)
119    delete []name;
120  if (diffuseTextureSet)
121    glDeleteTextures (1, &diffuseTexture);
122  if (nextMat)
123    delete nextMat;
124}
125
126/**
127   \brief adds a new Material to the List.
128   this Function will append a new Material to the end of a Material List.
129   \param mtlName The name of the Material to be added.
130*/
131Material* Material::addMaterial(char* mtlName)
132{
133  if (verbose >=2)
134    printf ("adding Material %s.\n", mtlName);
135   Material* tmpMat = this;
136  while (tmpMat->nextMat != NULL)
137    {
138      tmpMat = tmpMat->nextMat;
139    }
140  tmpMat->nextMat = new Material(mtlName);
141  return tmpMat->nextMat;
142 
143}
144
145/**
146   \brief initializes a new Material with its default Values
147*/
148void Material::init(void)
149{
150  if (verbose >= 3)
151    printf ("initializing new Material.\n");
152  nextMat = NULL;
153  name ="";
154  setIllum(1);
155  setDiffuse(0,0,0);
156  setAmbient(0,0,0);
157  setSpecular(.5,.5,.5);
158  setShininess(2.0);
159  setTransparency(0.0);
160
161  if (!pathList)
162    pathList = new PathList("");
163
164
165  diffuseTextureSet = false;
166  ambientTextureSet = false;
167  specularTextureSet = false;
168
169 
170}
171
172PathList *Material::pathList = NULL;
173
174/**
175   \brief Search for a Material called mtlName
176   \param mtlName the Name of the Material to search for
177   \returns Material named mtlName if it is found. NULL otherwise.
178*/
179Material* Material::search (char* mtlName)
180{
181  if (verbose >=3)
182    printf ("Searching for material %s", mtlName);
183  Material* searcher = this;
184  while (searcher != NULL)
185    {
186      if (verbose >= 3)
187        printf (".");
188      if (!strcmp (searcher->getName(), mtlName))
189        {
190          if (verbose >= 3)
191            printf ("found.\n");
192          return searcher;
193        }
194      searcher = searcher->nextMat;
195    }
196  if (verbose >=3)
197    printf ("not found\n");
198  return NULL;
199}
200
201/**
202   \brief sets the material with which the following Faces will be painted
203*/
204bool Material::select (void)
205{
206  // setting diffuse color
207  //  glColor3f (diffuse[0], diffuse[1], diffuse[2]);
208  glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse);
209
210  // setting ambient color
211  glMaterialfv(GL_FRONT, GL_AMBIENT, ambient);
212
213  // setting up Sprecular
214  glMaterialfv(GL_FRONT, GL_SPECULAR, specular);
215
216  // setting up Shininess
217  glMaterialf(GL_FRONT, GL_SHININESS, shininess);
218 
219  // setting illumination Model
220  if (illumModel == 1)
221    glShadeModel(GL_FLAT);
222  else if (illumModel >= 2)
223    glShadeModel(GL_SMOOTH);
224
225  if (diffuseTextureSet)
226    glBindTexture(GL_TEXTURE_2D, diffuseTexture);
227  else
228    glBindTexture(GL_TEXTURE_2D, 0);
229 
230}
231
232
233/**
234   \brief Set the Name of the Material. (Important for searching)
235   \param mtlName the Name of the Material to be set.
236*/ 
237void Material::setName (char* mtlName)
238{
239  name = new char [strlen(mtlName)+1];
240  strcpy(name, mtlName);
241  if (verbose >= 3)
242    printf("setting Material Name to %s.\n", name);
243
244  //  printf ("adding new Material: %s, %p\n", this->getName(), this);
245
246}
247/**
248   \returns The Name of The Material
249*/
250char* Material::getName (void)
251{
252  return name;
253}
254
255/**
256   \brief Sets the Material Illumination Model.
257   \brief illu illumination Model in int form
258*/
259void Material::setIllum (int illum)
260{
261  if (verbose >= 3)
262    printf("setting illumModel of Material %s to %i\n", name, illum);
263  illumModel = illum;
264  //  printf ("setting illumModel to: %i\n", illumModel);
265}
266/**
267   \brief Sets the Material Illumination Model.
268   \brief illu illumination Model in char* form
269*/void Material::setIllum (char* illum)
270{
271  setIllum (atoi(illum));
272}
273
274/**
275   \brief Sets the Material Diffuse Color.
276   \param r Red Color Channel.
277   \param g Green Color Channel.
278   \param b Blue Color Channel.
279*/
280void Material::setDiffuse (float r, float g, float b)
281{
282  if (verbose >= 3)
283    printf ("setting Diffuse Color of Material %s to r=%f g=%f b=%f.\n", name, r, g, b);
284  diffuse[0] = r;
285  diffuse[1] = g;
286  diffuse[2] = b; 
287  diffuse[3] = 1.0;
288
289}
290/**
291   \brief Sets the Material Diffuse Color.
292   \param rgb The red, green, blue channel in char format (with spaces between them)
293*/
294void Material::setDiffuse (char* rgb)
295{
296  float r,g,b;
297  sscanf (rgb, "%f %f %f", &r, &g, &b);
298  setDiffuse (r, g, b);
299}
300
301/**
302   \brief Sets the Material Ambient Color.
303   \param r Red Color Channel.
304   \param g Green Color Channel.
305   \param b Blue Color Channel.
306*/
307void Material::setAmbient (float r, float g, float b)
308{
309  if (verbose >=3)
310    printf ("setting Ambient Color of Material %s to r=%f g=%f b=%f.\n", name, r, g, b);
311  ambient[0] = r;
312  ambient[1] = g;
313  ambient[2] = b;
314  ambient[3] = 1.0;
315}
316/**
317   \brief Sets the Material Ambient Color.
318   \param rgb The red, green, blue channel in char format (with spaces between them)
319*/
320void Material::setAmbient (char* rgb)
321{
322  float r,g,b;
323  sscanf (rgb, "%f %f %f", &r, &g, &b);
324  setAmbient (r, g, b);
325}
326
327/**
328   \brief Sets the Material Specular Color.
329   \param r Red Color Channel.
330   \param g Green Color Channel.
331   \param b Blue Color Channel.
332*/
333void Material::setSpecular (float r, float g, float b)
334{
335  if (verbose >= 3)
336    printf ("setting Specular Color of Material %s to r=%f g=%f b=%f.\n", name, r, g, b);
337  specular[0] = r;
338  specular[1] = g;
339  specular[2] = b;
340  specular[3] = 1.0;
341 }
342/**
343   \brief Sets the Material Specular Color.
344   \param rgb The red, green, blue channel in char format (with spaces between them)
345*/
346void Material::setSpecular (char* rgb)
347{
348  float r,g,b;
349  sscanf (rgb, "%f %f %f", &r, &g, &b);
350  setSpecular (r, g, b);
351}
352
353/**
354   \brief Sets the Material Shininess.
355   \param shini stes the Shininess from float.
356*/
357void Material::setShininess (float shini)
358{
359  shininess = shini;
360}
361/**
362   \brief Sets the Material Shininess.
363   \param shini stes the Shininess from char*.
364*/
365void Material::setShininess (char* shini)
366{
367  setShininess (atof(shini));
368}
369
370/**
371   \brief Sets the Material Transparency.
372   \param trans stes the Transparency from int.
373*/
374void Material::setTransparency (float trans)
375{
376  if (verbose >= 3)
377    printf ("setting Transparency of Material %s to %f.\n", name, trans);
378  transparency = trans;
379}
380/**
381   \brief Sets the Material Transparency.
382   \param trans stes the Transparency from char*.
383*/
384void Material::setTransparency (char* trans)
385{
386  setTransparency (atof(trans));
387}
388
389void Material::addTexturePath(char* pathName)
390{
391  pathList->addPath (pathName);
392}
393char* Material::searchTextureInPaths(char* texName) const
394{
395  char* tmpName = NULL;
396  PathList* pList = pathList;
397  while (pList)
398    {
399      if (pList->pathName)
400        {
401          tmpName = new char [strlen(pList->pathName)+strlen(texName)+1];
402          strcpy(tmpName, pList->pathName);
403        }
404      else
405        {
406          tmpName = new char [strlen(texName)+1];
407          tmpName[0]='\0';
408        }
409      strcat(tmpName, texName);
410      printf("%s\n", tmpName);
411      if (access (tmpName, F_OK) == 0)
412        return tmpName;
413     
414      if (tmpName)
415        delete []tmpName;
416      tmpName = NULL;
417      pList = pList->next;
418    }
419  return NULL;
420}
421
422
423// MAPPING //
424
425/**
426   \brief Sets the Materials Diffuse Map
427   \param dMap the Name of the Image to Use
428*/
429void Material::setDiffuseMap(char* dMap)
430{
431  if (verbose>=2)
432    printf ("setting Diffuse Map %s\n", dMap);
433
434  //  diffuseTextureSet = loadBMP(dMap, &diffuseTexture);
435  diffuseTextureSet = loadImage(dMap, &diffuseTexture);
436
437}
438
439/**
440   \brief Sets the Materials Ambient Map
441   \param aMap the Name of the Image to Use
442*/
443void Material::setAmbientMap(char* aMap)
444{
445  SDL_Surface* ambientMap;
446
447}
448
449/**
450   \brief Sets the Materials Specular Map
451   \param sMap the Name of the Image to Use
452*/
453void Material::setSpecularMap(char* sMap)
454{
455  SDL_Surface* specularMap;
456
457}
458
459/**
460   \brief Sets the Materials Bumpiness
461   \param bump the Name of the Image to Use
462*/
463void Material::setBump(char* bump)
464{
465
466}
467
468bool Material::loadTexToGL (Image* pImage, GLuint* texture)
469{
470  if (verbose >=3)
471    printf ("Loading texture to OpenGL-Environment.\n");
472  glGenTextures(1, texture);
473  glBindTexture(GL_TEXTURE_2D, *texture);
474  /* not Working, and not needed.
475  glTexImage2D( GL_TEXTURE_2D, 0, 3, width,
476                height, 0, GL_BGR,
477                GL_UNSIGNED_BYTE, map->pixels );
478  */ 
479  gluBuild2DMipmaps(GL_TEXTURE_2D, 3, pImage->width, pImage->height, GL_RGB, GL_UNSIGNED_BYTE, pImage->data);
480 
481  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
482  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR); 
483}
484
485
486#ifdef HAVE_SDL_SDL_IMAGE_H
487bool Material::loadImage(char* imageName, GLuint* texture)
488{
489  char* imgNameWithPath = searchTextureInPaths(imageName);
490  if (imgNameWithPath)
491    {
492      SDL_Surface* map;
493      Image* pImage = new Image;
494      map=IMG_Load(imgNameWithPath);
495      if(!map)
496        {
497          printf("IMG_Load: %s\n", IMG_GetError());
498          return false;
499        }
500      pImage->height = map->h;
501      pImage->width  = map->w;
502      pImage->data   = (GLubyte*)map->pixels;
503      if( !IMG_isPNG(SDL_RWFromFile(imgNameWithPath, "rb")) && !IMG_isJPG(SDL_RWFromFile(imgNameWithPath, "rb")))
504        for (int i=0;i<map->h * map->w *3;i+=3)
505          { 
506            GLuint temp = pImage->data[i];
507            pImage->data[i] = pImage->data[i+2];
508            pImage->data[i+2] = temp;
509          }
510      loadTexToGL (pImage, texture);
511    }
512  else
513    {
514      if (verbose >=1)
515        printf ("Image not Found: %s\n", imgNameWithPath);
516      return false;
517    }
518}
519
520
521#else /* HAVE_SDL_SDL_IMAGE_H */
522/**
523   \brief Makes the Programm ready to Read-in a texture-File
524   1. Checks what type of Image should be imported
525   2. ToDO: Checks where to find the Image
526*/
527bool Material::loadImage(char* imageName, GLuint* texture)
528{
529  char* imgNameWithPath = searchTextureInPaths(imageName);
530  if (imgNameWithPath)
531    {
532      if (!strncmp(imgNameWithPath+strlen(imgNameWithPath)-4, ".bmp", 4))
533        {
534          if (verbose >=2)
535            printf ("Requested bmp-image. Trying to Import.\n");
536          return loadBMP(imgNameWithPath, texture);
537        }
538     
539      else if (!strncmp(imgNameWithPath+strlen(imgNameWithPath)-4, ".jpg", 4) || !strncmp(imgNameWithPath+strlen(imgNameWithPath)-5, ".jpg", 5))
540        {
541          if (verbose >=2)
542            printf ("Requested jpeg-image. Trying to Import\n");
543          return loadJPG(imgNameWithPath, texture);
544        }
545      else if (!strncmp(imgNameWithPath+strlen(imgNameWithPath)-4, ".tga", 4))
546        {
547          if (verbose >=2)
548            printf ("Requested tga-image. Trying to Import\n");
549          return loadTGA(imgNameWithPath, texture);
550        }
551      else if (!strncmp(imgNameWithPath+strlen(imgNameWithPath)-4, ".png", 4))
552        {
553          if (verbose >=2)
554            printf ("Requested png-image. Trying to Import\n");
555          return loadPNG(imgNameWithPath, texture);
556        }
557      else
558        {
559          if (verbose >=1)
560            printf ("Requested Image was not recognized in its type. (Maybe a type-Cast-error.)\n FileName: %s", imgNameWithPath);
561          return false;
562        }
563    }
564  else
565    {
566      if (verbose >=1)
567        printf ("Image not Found: %s\n", imgNameWithPath);
568      return false;
569    }
570}
571
572/**
573   \brief reads in a Windows BMP-file, and imports it to openGL.
574   \param bmpName The name of the Image to load.
575   \param texture A pointer to the Texture which should be read to.
576*/
577bool Material::loadBMP (char* bmpName, GLuint* texture)
578{
579  Image* pImage = new Image;
580  FILE *file;
581  unsigned long size;                 // size of the image in bytes.
582  unsigned long i;                    // standard counter.
583  unsigned short int planes;          // number of planes in image (must be 1)
584  unsigned short int bpp;             // number of bits per pixel (must be 24)
585  GLuint temp;                          // temporary color storage for bgr-rgb conversion.
586
587  // make sure the file is there.
588  if ((file = fopen(bmpName, "rb"))==NULL)
589    {
590      if (verbose >=1)
591        printf("File Not Found : %s\n",bmpName);
592      return false;
593    }
594  // seek through the bmp header, up to the width/height:
595  fseek(file, 18, SEEK_CUR);
596 
597  // read the width
598  if ((i = fread(&pImage->width, 4, 1, file)) != 1) 
599    {
600      if (verbose >=1)
601        printf("Error reading width from %s.\n", bmpName);
602      return false;
603    }
604  // read the height
605  if ((i = fread(&pImage->height, 4, 1, file)) != 1) 
606    {
607      if (verbose>=1)
608        printf("Error reading height from %s.\n", bmpName);
609      return false;
610    }
611 
612  // calculate the size (assuming 24 bits or 3 bytes per pixel).
613  size = pImage->width * pImage->height * 3;
614 
615  // read the planes
616  if ((fread(&planes, 2, 1, file)) != 1) 
617    {
618      if (verbose>=1)
619        printf("Error reading planes from %s.\n", bmpName);
620      return false;
621    }
622  if (planes != 1) 
623    {
624      if (verbose>=1)
625        printf("Planes from %s is not 1: %u\n", bmpName, planes);
626      return false;
627    }
628 
629  // read the bpp
630  if ((i = fread(&bpp, 2, 1, file)) != 1) 
631    {
632      if (verbose>=1)
633        printf("Error reading bpp from %s.\n", bmpName);
634      return false;
635    }
636  if (bpp != 24) 
637    {
638      if (verbose>=1)
639        printf("Bpp from %s is not 24: %u\n", bmpName, bpp);
640      return false;
641    }
642 
643  // seek past the rest of the bitmap header.
644  fseek(file, 24, SEEK_CUR);
645 
646  // read the data.
647  pImage->data = (GLubyte *) malloc(size);
648  if (pImage->data == NULL) 
649    {
650      if (verbose>=1)
651        printf("Error allocating memory for color-corrected image data");
652      return false;     
653    }
654 
655  if ((i = fread(pImage->data, size, 1, file)) != 1) 
656    {
657      if (verbose>=1)
658        printf("Error reading image data from %s.\n", bmpName);
659      return false;
660    }
661  fclose(file);
662
663  // reverse all of the colors. (bgr -> rgb)
664  for (i=0;i<size;i+=3) 
665    { 
666      temp = pImage->data[i];
667      pImage->data[i] = pImage->data[i+2];
668      pImage->data[i+2] = temp;
669    }
670  loadTexToGL (pImage, texture);
671 
672  return true;
673
674  if (pImage)
675    {
676      if (pImage->data)
677        {
678          free(pImage->data);
679        }
680     
681      free(pImage);
682    }
683
684}
685
686/**
687   \brief reads in a jpg-file
688   \param jpgName the Name of the Image to load
689   \param texture a reference to the Texture to write the image to
690*/
691bool Material::loadJPG (char* jpgName, GLuint* texture)
692{
693#ifdef HAVE_JPEGLIB_H
694  struct jpeg_decompress_struct cinfo;
695  Image *pImage = NULL;
696  FILE *pFile;
697 
698  // Open a file pointer to the jpeg file and check if it was found and opened
699  if((pFile = fopen(jpgName, "rb")) == NULL) 
700    {
701      // Display an error message saying the file was not found, then return NULL
702      printf("Unable to load JPG File %s.\n", jpgName);
703      return false;
704    }
705 
706  // Create an error handler
707  jpeg_error_mgr jerr;
708 
709  // Have our compression info object point to the error handler address
710  cinfo.err = jpeg_std_error(&jerr);
711 
712  // Initialize the decompression object
713  jpeg_create_decompress(&cinfo);
714 
715  // Specify the data source (Our file pointer)
716  jpeg_stdio_src(&cinfo, pFile);
717 
718  // Allocate the structure that will hold our eventual jpeg data (must free it!)
719  pImage = (Image*)malloc(sizeof(Image));
720 
721  // DECOFING
722  // Read in the header of the jpeg file
723  jpeg_read_header(&cinfo, TRUE);
724 
725  // Start to decompress the jpeg file with our compression info
726  jpeg_start_decompress(&cinfo);
727 
728  // Get the image dimensions and row span to read in the pixel data
729  pImage->rowSpan = cinfo.image_width * cinfo.num_components;
730  pImage->width   = cinfo.image_width;
731  pImage->height   = cinfo.image_height;
732 
733  // Allocate memory for the pixel buffer
734  pImage->data = new unsigned char[pImage->rowSpan * pImage->height];
735 
736  // Here we use the library's state variable cinfo.output_scanline as the
737  // loop counter, so that we don't have to keep track ourselves.
738 
739  // Create an array of row pointers
740  unsigned char** rowPtr = new unsigned char*[pImage->height];
741  for (int i = 0; i < pImage->height; i++)
742    rowPtr[i] = &(pImage->data[i*pImage->rowSpan]);
743 
744  // Now comes the juice of our work, here we extract all the pixel data
745  int rowsRead = 0;
746  while (cinfo.output_scanline < cinfo.output_height) 
747    {
748      // Read in the current row of pixels and increase the rowsRead count
749      rowsRead += jpeg_read_scanlines(&cinfo, &rowPtr[rowsRead], cinfo.output_height - rowsRead);
750    }
751 
752  // Delete the temporary row pointers
753  delete [] rowPtr;
754 
755  // Finish decompressing the data
756  jpeg_finish_decompress(&cinfo);//  decodeJPG(&cinfo, pImage);
757 
758  // This releases all the stored memory for reading and decoding the jpeg
759  jpeg_destroy_decompress(&cinfo);
760 
761  // Close the file pointer that opened the file
762  fclose(pFile);
763 
764
765  if(pImage == NULL)
766    exit(0);
767 
768  loadTexToGL (pImage, texture);
769  if (pImage)
770    {
771      if (pImage->data)
772        {
773          free(pImage->data);
774        }
775     
776      free(pImage);
777    }
778  return true;
779#else /* HAVE_JPEGLIB_H */
780  if (verbose >=1)
781    printf ("sorry, but you did not compile with jpeg-support.\nEither install SDL_image or jpeglib, and recompile to see the image\n");
782  return false;
783#endif /* HAVE_JPEGLIB_H */
784
785}
786
787/**
788   \brief reads in a tga-file
789   \param tgaName the Name of the Image to load
790   \param texture a reference to the Texture to write the image to
791*/
792bool Material::loadTGA(const char * tgaName, GLuint* texture)
793{
794  typedef struct
795  {
796    GLubyte Header[12];
797  } TGAHeader;
798  TGAHeader tgaHeader;                 
799 
800  GLubyte uTGAcompare[12] = {0,0,2, 0,0,0,0,0,0,0,0,0}; // Uncompressed TGA Header
801  GLubyte cTGAcompare[12] = {0,0,10,0,0,0,0,0,0,0,0,0}; // Compressed TGA Header
802  FILE * fTGA;
803  fTGA = fopen(tgaName, "rb");
804
805  if(fTGA == NULL)
806    {
807      printf("Error could not open texture file: %s\n", tgaName);
808      return false;
809    }
810 
811  if(fread(&tgaHeader, sizeof(TGAHeader), 1, fTGA) == 0)
812    {
813      printf("Error could not read file header of %s\n", tgaName);
814      if(fTGA != NULL)
815        {
816          fclose(fTGA);
817        }
818      return false;
819    }
820 
821  if(memcmp(uTGAcompare, &tgaHeader, sizeof(TGAHeader)) == 0)
822    {
823      loadUncompressedTGA(tgaName, fTGA, texture);
824      if (fTGA)
825        fclose (fTGA);
826    }
827  else if(memcmp(cTGAcompare, &tgaHeader, sizeof(TGAHeader)) == 0)
828    {
829      loadCompressedTGA(tgaName, fTGA, texture);
830        if (fTGA)
831          fclose (fTGA);
832    }
833  else
834    {
835      printf("Error TGA file be type 2 or type 10\n");
836      if (fTGA)
837        fclose(fTGA);
838      return false;
839    }
840  return true;
841}
842
843/**
844   \brief reads in an uncompressed tga-file
845   \param filename the Name of the Image to load
846   \param fTGA a Pointer to a File, that should be read
847   \param texture a reference to the Texture to write the image to
848*/
849bool Material::loadUncompressedTGA(const char * filename, FILE * fTGA, GLuint* texture)
850{
851  GLubyte header[6];      // First 6 Useful Bytes From The Header
852  GLuint  bytesPerPixel;  // Holds Number Of Bytes Per Pixel Used In The TGA File
853  GLuint  imageSize;      // Used To Store The Image Size When Setting Aside Ram
854  GLuint  temp;           // Temporary Variable
855  GLuint  type;
856  GLuint  Height;         // Height of Image
857  GLuint  Width;          // Width of Image
858  GLuint  Bpp;            // Bits Per Pixel
859
860  Image* pImage = new Image;
861  GLuint cswap;
862  if(fread(header, sizeof(header), 1, fTGA) == 0)
863    {
864      printf("Error could not read info header\n");
865      return false;
866    }
867 
868  Width = pImage->width  = header[1] * 256 + header[0];
869  Height =  pImage->height = header[3] * 256 + header[2];
870  Bpp = pImage->bpp = header[4];
871  // Make sure all information is valid
872  if((pImage->width <= 0) || (pImage->height <= 0) || ((pImage->bpp != 24) && (pImage->bpp !=32)))
873    {
874      printf("Error invalid texture information\n");
875      return false;
876    }
877 
878  if(pImage->bpp == 24) 
879    {
880      pImage->type = GL_RGB;
881    }
882  else
883    {
884      pImage->type = GL_RGBA;
885    }
886 
887  bytesPerPixel = (Bpp / 8);
888  imageSize = (bytesPerPixel * Width * Height);
889  pImage->data = (GLubyte*) malloc(imageSize);
890 
891  if(pImage->data == NULL)
892    {
893      printf("Error could not allocate memory for image\n");
894      return false;
895    }
896 
897  if(fread(pImage->data, 1, imageSize, fTGA) != imageSize)
898    {
899      printf("Error could not read image data\n");
900      if(pImage->data != NULL)
901        {
902          free(pImage->data);
903        }
904      return false;
905    }
906 
907  for(cswap = 0; cswap < (int)imageSize; cswap += bytesPerPixel)
908    {
909      pImage->data[cswap] ^= pImage->data[cswap+2] ^=
910        pImage->data[cswap] ^= pImage->data[cswap+2];
911    }
912 
913  loadTexToGL (pImage, texture);
914
915  return true;
916}
917
918/**
919   \brief reads in a compressed tga-file
920   \param filename the Name of the Image to load
921   \param fTGA a Pointer to a File, that should be read
922   \param texture a reference to the Texture to write the image to
923*/
924bool Material::loadCompressedTGA(const char * filename, FILE * fTGA, GLuint* texture)
925{
926  GLubyte header[6];      // First 6 Useful Bytes From The Header
927  GLuint  bytesPerPixel;  // Holds Number Of Bytes Per Pixel Used In The TGA File
928  GLuint  imageSize;      // Used To Store The Image Size When Setting Aside Ram
929  GLuint  temp;           // Temporary Variable
930  GLuint  type;
931  GLuint  Height;         // Height of Image
932  GLuint  Width;          // Width of Image
933  GLuint  Bpp;            // Bits Per Pixel
934
935  Image* pImage = new Image;
936
937 
938  if(fread(header, sizeof(header), 1, fTGA) == 0)
939    {
940      printf("Error could not read info header\n");
941      return false;
942    }
943 
944  Width = pImage->width  = header[1] * 256 + header[0];
945  Height = pImage->height = header[3] * 256 + header[2];
946  Bpp = pImage->bpp     = header[4];
947
948  GLuint pixelcount     = Height * Width;
949  GLuint currentpixel   = 0;
950  GLuint currentbyte    = 0;
951  GLubyte * colorbuffer = (GLubyte *)malloc(bytesPerPixel);
952
953  //Make sure all pImage info is ok
954  if((pImage->width <= 0) || (pImage->height <= 0) || ((pImage->bpp != 24) && (pImage->bpp !=32)))
955    {
956      printf("Error Invalid pImage information\n");
957      return false;
958    }
959 
960  bytesPerPixel = (Bpp / 8);
961  imageSize             = (bytesPerPixel * Width * Height);
962  pImage->data  = (GLubyte*) malloc(imageSize);
963 
964  if(pImage->data == NULL)
965    {
966      printf("Error could not allocate memory for image\n");
967      return false;
968    }
969 
970  do
971    {
972      GLubyte chunkheader = 0;
973     
974      if(fread(&chunkheader, sizeof(GLubyte), 1, fTGA) == 0)
975        {
976          printf("Error could not read RLE header\n");
977          if(pImage->data != NULL)
978            {
979              free(pImage->data);
980            }
981          return false;
982        }
983      // If the ehader is < 128, it means the that is the number of RAW color packets minus 1
984      if(chunkheader < 128)
985        {
986          short counter;
987          chunkheader++;
988          // Read RAW color values
989          for(counter = 0; counter < chunkheader; counter++)
990            { 
991              // Try to read 1 pixel
992              if(fread(colorbuffer, 1, bytesPerPixel, fTGA) != bytesPerPixel)
993                {
994                  printf("Error could not read image data\n");
995                  if(colorbuffer != NULL)
996                    {
997                      free(colorbuffer);
998                    }
999                 
1000                  if(pImage->data != NULL)
1001                    {
1002                      free(pImage->data);
1003                    }
1004                 
1005                  return false; 
1006                }
1007              // write to memory
1008              // Flip R and B vcolor values around in the process
1009              pImage->data[currentbyte    ] = colorbuffer[2];                               
1010              pImage->data[currentbyte + 1] = colorbuffer[1];
1011              pImage->data[currentbyte + 2] = colorbuffer[0];
1012             
1013              if(bytesPerPixel == 4) // if its a 32 bpp image
1014                {
1015                  pImage->data[currentbyte + 3] = colorbuffer[3];// copy the 4th byte
1016                }
1017             
1018              currentbyte += bytesPerPixel;
1019              currentpixel++;
1020
1021              // Make sure we haven't read too many pixels
1022              if(currentpixel > pixelcount)     
1023                {
1024                  printf("Error too many pixels read\n");
1025                  if(colorbuffer != NULL)
1026                    {
1027                      free(colorbuffer);
1028                    }
1029                 
1030                  if(pImage->data != NULL)
1031                    {
1032                      free(pImage->data);
1033                    }
1034                 
1035                  return false;
1036                }
1037            }
1038        }
1039      // chunkheader > 128 RLE data, next color  reapeated chunkheader - 127 times
1040      else
1041        {
1042          short counter;
1043          chunkheader -= 127;   // Subteact 127 to get rid of the ID bit
1044          if(fread(colorbuffer, 1, bytesPerPixel, fTGA) != bytesPerPixel) // Attempt to read following color values
1045            {
1046              printf("Error could not read from file");
1047              if(colorbuffer != NULL)
1048                {
1049                  free(colorbuffer);
1050                }
1051             
1052              if(pImage->data != NULL)
1053                {
1054                  free(pImage->data);
1055                }
1056             
1057              return false;
1058            }
1059         
1060          for(counter = 0; counter < chunkheader; counter++) //copy the color into the image data as many times as dictated
1061            {                                                   
1062              // switch R and B bytes areound while copying
1063              pImage->data[currentbyte    ] = colorbuffer[2];
1064              pImage->data[currentbyte + 1] = colorbuffer[1];
1065              pImage->data[currentbyte + 2] = colorbuffer[0];
1066             
1067              if(bytesPerPixel == 4)
1068                {
1069                  pImage->data[currentbyte + 3] = colorbuffer[3];
1070                }
1071             
1072              currentbyte += bytesPerPixel;
1073              currentpixel++;
1074             
1075              if(currentpixel > pixelcount)
1076                {
1077                  printf("Error too many pixels read\n");
1078                  if(colorbuffer != NULL)
1079                    {
1080                      free(colorbuffer);
1081                    }
1082                 
1083                  if(pImage->data != NULL)
1084                    {
1085                      free(pImage->data);
1086                    }
1087                 
1088                  return false;
1089                }
1090            }
1091        }
1092    }
1093 
1094  while(currentpixel < pixelcount);     // Loop while there are still pixels left
1095
1096  loadTexToGL (pImage, texture);
1097
1098  return true;
1099}
1100
1101
1102/*
1103static int ST_is_power_of_two(unsigned int number)
1104{
1105  return (number & (number - 1)) == 0;
1106}
1107*/
1108
1109/**
1110   \brief reads in a png-file
1111   \param pngName the Name of the Image to load
1112   \param texture a reference to the Texture to write the image to
1113*/
1114bool Material::loadPNG(const char* pngName, GLuint* texture)
1115{
1116#ifdef HAVE_PNG_H
1117  Image* pImage = new Image;
1118
1119  FILE *PNG_file = fopen(pngName, "rb");
1120  if (PNG_file == NULL)
1121    {
1122      return 0;
1123    }
1124 
1125  GLubyte PNG_header[8];
1126 
1127  fread(PNG_header, 1, 8, PNG_file);
1128  if (png_sig_cmp(PNG_header, 0, 8) != 0)
1129    {
1130      if (verbose >=2)
1131        printf ("Not Recognized as a pngFile\n");
1132      fclose (PNG_file);
1133      return 0;
1134    }
1135 
1136  png_structp PNG_reader = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1137  if (PNG_reader == NULL)
1138    {
1139      fclose(PNG_file);
1140      return 0;
1141    }
1142 
1143  png_infop PNG_info = png_create_info_struct(PNG_reader);
1144  if (PNG_info == NULL)
1145    {
1146      png_destroy_read_struct(&PNG_reader, NULL, NULL);
1147      fclose(PNG_file);
1148      return 0;
1149    }
1150 
1151  png_infop PNG_end_info = png_create_info_struct(PNG_reader);
1152  if (PNG_end_info == NULL)
1153    {
1154      png_destroy_read_struct(&PNG_reader, &PNG_info, NULL);
1155      fclose(PNG_file);
1156      return 0;
1157    }
1158 
1159  if (setjmp(png_jmpbuf(PNG_reader)))
1160    {
1161      png_destroy_read_struct(&PNG_reader, &PNG_info, &PNG_end_info);
1162      fclose(PNG_file);
1163      return (0);
1164    }
1165 
1166  png_init_io(PNG_reader, PNG_file);
1167  png_set_sig_bytes(PNG_reader, 8);
1168 
1169  png_read_info(PNG_reader, PNG_info);
1170 
1171  pImage->width = png_get_image_width(PNG_reader, PNG_info);
1172  pImage->height = png_get_image_height(PNG_reader, PNG_info);
1173 
1174  png_uint_32 bit_depth, color_type;
1175  bit_depth = png_get_bit_depth(PNG_reader, PNG_info);
1176  color_type = png_get_color_type(PNG_reader, PNG_info);
1177 
1178  if (color_type == PNG_COLOR_TYPE_PALETTE)
1179    {
1180      png_set_palette_to_rgb(PNG_reader);
1181    }
1182 
1183  if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
1184    {
1185      png_set_gray_1_2_4_to_8(PNG_reader);
1186    }
1187 
1188  if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
1189    {
1190      png_set_gray_to_rgb(PNG_reader);
1191    }
1192 
1193  if (png_get_valid(PNG_reader, PNG_info, PNG_INFO_tRNS))
1194    {
1195      png_set_tRNS_to_alpha(PNG_reader);
1196    }
1197  else
1198    {
1199      png_set_filler(PNG_reader, 0xff, PNG_FILLER_AFTER);
1200    }
1201 
1202  if (bit_depth == 16)
1203    {
1204      png_set_strip_16(PNG_reader);
1205    }
1206 
1207  png_read_update_info(PNG_reader, PNG_info);
1208 
1209  pImage->data = (png_byte*)malloc(4 * pImage->width * pImage->height);
1210  png_byte** PNG_rows = (png_byte**)malloc(pImage->height * sizeof(png_byte*));
1211 
1212  unsigned int row;
1213  for (row = 0; row < pImage->height; ++row)
1214    {
1215      PNG_rows[pImage->height - 1 - row] = pImage->data + (row * 4 * pImage->width);
1216    }
1217 
1218  png_read_image(PNG_reader, PNG_rows);
1219 
1220  free(PNG_rows);
1221 
1222  png_destroy_read_struct(&PNG_reader, &PNG_info, &PNG_end_info);
1223  fclose(PNG_file);
1224 
1225  /*  if (!ST_is_power_of_two(pImage->width) || !ST_is_power_of_two(pImage->height))
1226    {
1227      free(pImage->data);
1228      return 0;
1229    }
1230  */
1231  loadTexToGL (pImage, texture); 
1232 
1233  free(pImage->data);
1234 
1235  return true;
1236#else /* HAVE_PNG_H */
1237  if (verbose >=1)
1238    printf ("sorry, but you did not compile with png-support.\nEither install SDL_image or libpng, and recompile to see the image\n");
1239  return false;
1240#endif /* HAVE_PNG_H */
1241
1242}
1243
1244#endif /* HAVE_SDL_SDL_IMAGE_H */
Note: See TracBrowser for help on using the repository browser.