Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/orxonox/trunk/src/lib/graphics/importer/texture.cc @ 3548

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

orxonox/trunk: debug information in importer set like they should be

File size: 23.6 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*/
18
19
20#include "texture.h"
21
22// headers only for PathList
23#include <unistd.h>
24#include <sys/types.h>
25#include <sys/stat.h>
26#include <stdlib.h>
27#include <fstream>
28
29/**
30   \brief creates a ned PathList.
31   
32   It is a good idea to use this as an initial List,
33   because if you give on a name the Path will not be checked for its existence.
34*/
35PathList::PathList()
36{
37  this->pathName = NULL;
38  this->next = NULL;
39}
40
41/**
42   \brief Creates a new PathList with a Name.
43   \param pName the Name of The Path.
44
45   This function just adds the Path without checking if it exists.
46*/
47PathList::PathList(char* pName)
48{
49  this->pathName = new char [strlen(pName)+1];
50  strcpy (this->pathName, pName);
51  this->next = NULL;
52}
53
54/**
55   \brief destroys a PathList
56
57   It does this by deleting the Name and then delete its preceding PathList.
58*/
59PathList::~PathList()
60{
61  if (this->pathName)
62    delete []this->pathName;
63  if (this->next)
64    delete this->next;
65}
66
67PathList* PathList::firstPath = NULL;
68
69/**
70   \returns A Pointer to the first Path of the Pathlist
71*/
72PathList* PathList::getInstance(void)
73{
74  if (firstPath)
75    return firstPath;
76  firstPath = new PathList();
77}
78/**
79   \brief Adds a new Pathlist Element.
80   \param pName
81   
82   Adding a Path automatically checks if the Path exists,
83   and if it does not it will not add it to the List.
84*/
85void PathList::addPath (char* pName)
86{
87  if (pName[0] == '\0')
88    {
89      PRINTF(2)("not Adding empty Path to the List.\n");
90      return;
91    }
92  char* tmpPName = new char[strlen(pName)];
93  strncpy(tmpPName, pName, strlen(pName)-1);
94  tmpPName[strlen(pName)-1] = '\0';
95  if (access (tmpPName, F_OK) == 0)
96    {
97      struct stat status;
98      stat(tmpPName, &status);
99      if (status.st_mode & S_IFDIR)
100        {
101          PRINTF(4)("Adding Path %s to the PathList.\n", pName);
102          PathList* tmpPathList = this;
103          while (tmpPathList->next)
104            tmpPathList = tmpPathList->next;
105          tmpPathList->next = new PathList(pName);
106        }
107      else
108        PRINTF(2)("You tried to add non-folder %s to a PathList.\n", tmpPName);
109    }
110  else
111      PRINTF(2)("You tried to add non-existing folder %s to a PathList.\n", tmpPName);
112  delete []tmpPName;
113}
114
115
116
117/**
118   \brief Constructor for a Texture
119*/
120Texture::Texture(void)
121{
122  this->pImage = new Image;
123  this->pImage->data = NULL;
124  this->map = NULL;
125  this->texture = 0;
126}
127
128/**
129   \brief Destructor of a Texture
130   
131   Frees Data, and deletes the textures from GL
132*/
133Texture::~Texture(void)
134{
135  if (this->pImage->data)
136    delete []this->pImage->data;
137  delete pImage;
138  if (this->texture)
139    glDeleteTextures(1, &this->texture);
140}
141
142/**
143   \brief Searches for a Texture inside one of the defined Paths
144   \param texName The name of the texture o search for.
145   \returns pathName+texName if texName was found in the pathList. NULL if the Texture is not found.
146*/
147char* Texture::searchTextureInPaths(char* texName) const
148{
149  char* tmpName = NULL;
150  PathList* pList = PathList::getInstance();
151  while (pList)
152    {
153      if (pList->pathName)
154        {
155          tmpName = new char [strlen(pList->pathName)+strlen(texName)+1];
156          strcpy(tmpName, pList->pathName);
157        }
158      else
159        {
160          tmpName = new char [strlen(texName)+1];
161          tmpName[0]='\0';
162        }
163      strcat(tmpName, texName);
164      if (access (tmpName, F_OK) == 0)
165        return tmpName;
166     
167      if (tmpName)
168        delete []tmpName;
169      tmpName = NULL;
170      pList = pList->next;
171    }
172  return NULL;
173}
174
175/**
176   \brief a Simple function that switches two char values
177   \param a The first value
178   \param b The second value
179*/
180inline void Texture::swap (unsigned char &a, unsigned char &b)
181{
182  unsigned char temp;
183  temp = a;
184  a    = b;
185  b    = temp;
186}
187
188
189/**
190   \brief Loads a Texture to the openGL-environment.
191   \param pImage The Image to load to openGL
192*/
193bool Texture::loadTexToGL (Image* pImage)
194{
195  PRINTF(4)("Loading texture to OpenGL-Environment.\n");
196  glGenTextures(1, &this->texture);
197  glBindTexture(GL_TEXTURE_2D, this->texture);
198  /* not Working, and not needed.
199  glTexImage2D( GL_TEXTURE_2D, 0, 3, width,
200                height, 0, GL_BGR,
201                GL_UNSIGNED_BYTE, map->pixels );
202  */ 
203  gluBuild2DMipmaps(GL_TEXTURE_2D, 3, pImage->width, pImage->height, pImage->format, GL_UNSIGNED_BYTE, pImage->data);
204 
205  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
206  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR); 
207}
208
209
210#ifdef HAVE_SDL_SDL_IMAGE_H
211bool Texture::loadImage(char* imageName)
212{
213  char* imgNameWithPath = searchTextureInPaths(imageName);
214  if (imgNameWithPath)
215    {
216      this->map=IMG_Load(imgNameWithPath);
217      if(!map)
218        {
219          PRINTF(1)("IMG_Load: %s\n", IMG_GetError());
220          return false;
221        }
222      pImage->height = map->h;
223      pImage->width  = map->w;
224      pImage->data   = (GLubyte*)map->pixels;
225      pImage->bpp    = map->format->BytesPerPixel;
226      if (pImage->bpp == 3)
227        pImage->format = GL_RGB;
228      else if (pImage->bpp == 4)
229        pImage->format = GL_RGBA;
230         
231      if( !IMG_isPNG(SDL_RWFromFile(imgNameWithPath, "rb")) && !IMG_isJPG(SDL_RWFromFile(imgNameWithPath, "rb")))
232        for (int i=0;i<map->h * map->w *3;i+=3)
233          { 
234            GLuint temp = pImage->data[i];
235            pImage->data[i] = pImage->data[i+2];
236            pImage->data[i+2] = temp;
237          }
238      /* this is the real swapping algorithm */
239      for( int i = 0 ; i < (pImage->height / 2) ; ++i )
240        for( int j = 0 ; j < pImage->width * pImage->bpp; j += pImage->bpp )
241          for(int k = 0; k < pImage->bpp; ++k)
242            swap( pImage->data[ (i * pImage->width * pImage->bpp) + j + k], pImage->data[ ( (pImage->height - i - 1) * pImage->width * pImage->bpp ) + j + k]);
243 
244      this->loadTexToGL (this->pImage);
245      SDL_FreeSurface(map);
246      this->pImage->data = NULL;
247    }
248  else
249    {
250      PRINTF(2)("Image not Found: %s\n", imgNameWithPath);
251      return false;
252    }
253}
254
255
256#else /* HAVE_SDL_SDL_IMAGE_H */
257/**
258   \brief Makes the Programm ready to Read-in a texture-File
259   1. Checks what type of Image should be imported
260   \todo Checks where to find the Image
261*/
262bool Texture::loadImage(char* imageName)
263{
264  char* imgNameWithPath = searchTextureInPaths(imageName);
265  if (imgNameWithPath)
266    {
267      if (!strncmp(imgNameWithPath+strlen(imgNameWithPath)-4, ".bmp", 4))
268        {
269          PRINTF(4)("Requested bmp-image. Trying to Import.\n");
270          return this->loadBMP(imgNameWithPath);
271        }
272     
273      else if (!strncmp(imgNameWithPath+strlen(imgNameWithPath)-4, ".jpg", 4) || !strncmp(imgNameWithPath+strlen(imgNameWithPath)-5, ".jpg", 5))
274        {
275          PRINTF(4)("Requested jpeg-image. Trying to Import\n");
276          return this->loadJPG(imgNameWithPath);
277        }
278      else if (!strncmp(imgNameWithPath+strlen(imgNameWithPath)-4, ".tga", 4))
279        {
280          PRINTF(4)("Requested tga-image. Trying to Import\n");
281          return this->loadTGA(imgNameWithPath);
282        }
283      else if (!strncmp(imgNameWithPath+strlen(imgNameWithPath)-4, ".png", 4))
284        {
285          PRINTF(4)("Requested png-image. Trying to Import\n");
286          return this->loadPNG(imgNameWithPath);
287        }
288      else
289        {
290          PRINTF(2)("Requested Image was not recognized in its type. (Maybe a type-Cast-error.)\n FileName: %s", imgNameWithPath);
291          return false;
292        }
293    }
294  else
295    {
296      PRINTF(2)("Image not Found: %s\n", imgNameWithPath);
297      return false;
298    }
299}
300
301/**
302   \brief reads in a Windows BMP-file, and imports it to openGL.
303   \param bmpName The name of the Image to load.
304*/
305bool Texture::loadBMP (char* bmpName)
306{
307  FILE *file;
308  unsigned long size;                 // size of the image in bytes.
309  unsigned long i;                    // standard counter.
310  unsigned short int planes;          // number of planes in image (must be 1)
311  unsigned short int bpp;             // number of bits per pixel (must be 24)
312  GLuint temp;                          // temporary color storage for bgr-rgb conversion.
313
314  // make sure the file is there.
315  if ((file = fopen(bmpName, "rb"))==NULL)
316    {
317      PRINTF(2)("File Not Found : %s\n",bmpName);
318      return false;
319    }
320  // seek through the bmp header, up to the width/height:
321  fseek(file, 18, SEEK_CUR);
322 
323  // read the width
324  if ((i = fread(&pImage->width, 4, 1, file)) != 1) 
325    {
326      PRINTF(2)("Error reading width from %s.\n", bmpName);
327      return false;
328    }
329  // read the height
330  if ((i = fread(&pImage->height, 4, 1, file)) != 1) 
331    {
332      PRINTF(2)("Error reading height from %s.\n", bmpName);
333      return false;
334    }
335 
336  // calculate the size (assuming 24 bits or 3 bytes per pixel).
337  size = pImage->width * pImage->height * 3;
338 
339  // read the planes
340  if ((fread(&planes, 2, 1, file)) != 1) 
341    {
342      PRINTF(2)("Error reading planes from %s.\n", bmpName);
343      return false;
344    }
345  if (planes != 1) 
346    {
347      PRINTF(1)("Planes from %s is not 1: %u\n", bmpName, planes);
348      return false;
349    }
350 
351  // read the bpp
352  if ((i = fread(&bpp, 2, 1, file)) != 1) 
353    {
354      PRINTF(2)("Error reading bpp from %s.\n", bmpName);
355      return false;
356    }
357  if (bpp != 24) 
358    {
359      PRINTF(2)("Bpp from %s is not 24: %u\n", bmpName, bpp);
360      return false;
361    }
362 
363  // seek past the rest of the bitmap header.
364  fseek(file, 24, SEEK_CUR);
365 
366  // read the data.
367  pImage->data = (GLubyte *) malloc(size);
368  if (pImage->data == NULL) 
369    {
370      PRINTF(2)("Error allocating memory for color-corrected image data");
371      return false;     
372    }
373 
374  if ((i = fread(pImage->data, size, 1, file)) != 1) 
375    {
376      PRINTF(2)("Error reading image data from %s.\n", bmpName);
377      return false;
378    }
379  fclose(file);
380
381  // reverse all of the colors. (bgr -> rgb)
382  for (i=0;i<size;i+=3) 
383    { 
384      temp = pImage->data[i];
385      pImage->data[i] = pImage->data[i+2];
386      pImage->data[i+2] = temp;
387    }
388  this->loadTexToGL (pImage);
389 
390
391  if (pImage)
392    {
393      if (pImage->data)
394        {
395          free(pImage->data);
396        }
397     
398      free(pImage);
399    }
400  return true;
401
402}
403
404/**
405   \brief reads in a jpg-file
406   \param jpgName the Name of the Image to load
407*/
408bool Texture::loadJPG (char* jpgName)
409{
410#ifdef HAVE_JPEGLIB_H
411  struct jpeg_decompress_struct cinfo;
412  Image *pImage = NULL;
413  FILE *pFile;
414 
415  // Open a file pointer to the jpeg file and check if it was found and opened
416  if((pFile = fopen(jpgName, "rb")) == NULL) 
417    {
418      // Display an error message saying the file was not found, then return NULL
419      PRINTF(2)("Unable to load JPG File %s.\n", jpgName);
420      return false;
421    }
422 
423  // Create an error handler
424  jpeg_error_mgr jerr;
425 
426  // Have our compression info object point to the error handler address
427  cinfo.err = jpeg_std_error(&jerr);
428 
429  // Initialize the decompression object
430  jpeg_create_decompress(&cinfo);
431 
432  // Specify the data source (Our file pointer)
433  jpeg_stdio_src(&cinfo, pFile);
434 
435  // Allocate the structure that will hold our eventual jpeg data (must free it!)
436  pImage = (Image*)malloc(sizeof(Image));
437 
438  // DECOFING
439  // Read in the header of the jpeg file
440  jpeg_read_header(&cinfo, TRUE);
441 
442  // Start to decompress the jpeg file with our compression info
443  jpeg_start_decompress(&cinfo);
444 
445  // Get the image dimensions and row span to read in the pixel data
446  pImage->rowSpan = cinfo.image_width * cinfo.num_components;
447  pImage->width   = cinfo.image_width;
448  pImage->height   = cinfo.image_height;
449 
450  // Allocate memory for the pixel buffer
451  pImage->data = new unsigned char[pImage->rowSpan * pImage->height];
452 
453  // Here we use the library's state variable cinfo.output_scanline as the
454  // loop counter, so that we don't have to keep track ourselves.
455 
456  // Create an array of row pointers
457  unsigned char** rowPtr = new unsigned char*[pImage->height];
458  for (int i = 0; i < pImage->height; i++)
459    rowPtr[i] = &(pImage->data[i*pImage->rowSpan]);
460 
461  // Now comes the juice of our work, here we extract all the pixel data
462  int rowsRead = 0;
463  while (cinfo.output_scanline < cinfo.output_height) 
464    {
465      // Read in the current row of pixels and increase the rowsRead count
466      rowsRead += jpeg_read_scanlines(&cinfo, &rowPtr[rowsRead], cinfo.output_height - rowsRead);
467    }
468 
469  // Delete the temporary row pointers
470  delete [] rowPtr;
471 
472  // Finish decompressing the data
473  jpeg_finish_decompress(&cinfo);//  decodeJPG(&cinfo, pImage);
474 
475  // This releases all the stored memory for reading and decoding the jpeg
476  jpeg_destroy_decompress(&cinfo);
477 
478  // Close the file pointer that opened the file
479  fclose(pFile);
480 
481
482  if(pImage == NULL)
483    exit(0);
484 
485  this->loadTexToGL (pImage);
486  if (pImage)
487    {
488      if (pImage->data)
489        {
490          free(pImage->data);
491        }
492     
493      free(pImage);
494    }
495  return true;
496#else /* HAVE_JPEGLIB_H */
497  PRINTF(1)("sorry, but you did not compile with jpeg-support.\nEither install SDL_image or jpeglib, and recompile to see the image\n");
498  return false;
499#endif /* HAVE_JPEGLIB_H */
500
501}
502
503/**
504   \brief reads in a tga-file
505   \param tgaName the Name of the Image to load
506*/
507bool Texture::loadTGA(const char * tgaName)
508{
509  typedef struct
510  {
511    GLubyte Header[12];
512  } TGAHeader;
513  TGAHeader tgaHeader;                 
514 
515  GLubyte uTGAcompare[12] = {0,0,2, 0,0,0,0,0,0,0,0,0}; // Uncompressed TGA Header
516  GLubyte cTGAcompare[12] = {0,0,10,0,0,0,0,0,0,0,0,0}; // Compressed TGA Header
517  FILE * fTGA;
518  fTGA = fopen(tgaName, "rb");
519
520  if(fTGA == NULL)
521    {
522      PRINTF(2)("Error could not open texture file: %s\n", tgaName);
523      return false;
524    }
525 
526  if(fread(&tgaHeader, sizeof(TGAHeader), 1, fTGA) == 0)
527    {
528      PRINTF(2)("Error could not read file header of %s\n", tgaName);
529      if(fTGA != NULL)
530        {
531          fclose(fTGA);
532        }
533      return false;
534    }
535 
536  if(memcmp(uTGAcompare, &tgaHeader, sizeof(TGAHeader)) == 0)
537    {
538      loadUncompressedTGA(tgaName, fTGA);
539      if (fTGA)
540        fclose (fTGA);
541    }
542  else if(memcmp(cTGAcompare, &tgaHeader, sizeof(TGAHeader)) == 0)
543    {
544      loadCompressedTGA(tgaName, fTGA);
545        if (fTGA)
546          fclose (fTGA);
547    }
548  else
549    {
550      PRINTF(2)("Error TGA file be type 2 or type 10\n");
551      if (fTGA)
552        fclose(fTGA);
553      return false;
554    }
555  return true;
556}
557
558/**
559   \brief reads in an uncompressed tga-file
560   \param filename the Name of the Image to load
561   \param fTGA a Pointer to a File, that should be read
562*/
563bool Texture::loadUncompressedTGA(const char * filename, FILE * fTGA)
564{
565  GLubyte header[6];      // First 6 Useful Bytes From The Header
566  GLuint  bytesPerPixel;  // Holds Number Of Bytes Per Pixel Used In The TGA File
567  GLuint  imageSize;      // Used To Store The Image Size When Setting Aside Ram
568  GLuint  temp;           // Temporary Variable
569  GLuint  type;
570  GLuint  Height;         // Height of Image
571  GLuint  Width;          // Width of Image
572  GLuint  Bpp;            // Bits Per Pixel
573
574  GLuint cswap;
575  if(fread(header, sizeof(header), 1, fTGA) == 0)
576    {
577      PRINTF(2)("Error could not read info header\n");
578      return false;
579    }
580 
581  Width = pImage->width  = header[1] * 256 + header[0];
582  Height =  pImage->height = header[3] * 256 + header[2];
583  Bpp = pImage->bpp = header[4];
584  // Make sure all information is valid
585  if((pImage->width <= 0) || (pImage->height <= 0) || ((pImage->bpp != 24) && (pImage->bpp !=32)))
586    {
587      PRINTF(2)("Error invalid texture information\n");
588      return false;
589    }
590 
591  if(pImage->bpp == 24) 
592    {
593      pImage->type = GL_RGB;
594    }
595  else
596    {
597      pImage->type = GL_RGBA;
598    }
599 
600  bytesPerPixel = (Bpp / 8);
601  imageSize = (bytesPerPixel * Width * Height);
602  pImage->data = (GLubyte*) malloc(imageSize);
603 
604  if(pImage->data == NULL)
605    {
606      PRINTF(2)("Error could not allocate memory for image\n");
607      return false;
608    }
609 
610  if(fread(pImage->data, 1, imageSize, fTGA) != imageSize)
611    {
612      PRINTF(2)("Error could not read image data\n");
613      if(pImage->data != NULL)
614        {
615          free(pImage->data);
616        }
617      return false;
618    }
619 
620  for(cswap = 0; cswap < (int)imageSize; cswap += bytesPerPixel)
621    {
622      pImage->data[cswap] ^= pImage->data[cswap+2] ^=
623        pImage->data[cswap] ^= pImage->data[cswap+2];
624    }
625 
626  this->loadTexToGL (pImage);
627
628  return true;
629}
630
631/**
632   \brief reads in a compressed tga-file
633   \param filename the Name of the Image to load
634   \param fTGA a Pointer to a File, that should be read
635*/
636bool Texture::loadCompressedTGA(const char * filename, FILE * fTGA)
637{
638  GLubyte header[6];      // First 6 Useful Bytes From The Header
639  GLuint  bytesPerPixel;  // Holds Number Of Bytes Per Pixel Used In The TGA File
640  GLuint  imageSize;      // Used To Store The Image Size When Setting Aside Ram
641  GLuint  temp;           // Temporary Variable
642  GLuint  type;
643  GLuint  Height;         // Height of Image
644  GLuint  Width;          // Width of Image
645  GLuint  Bpp;            // Bits Per Pixel
646
647  if(fread(header, sizeof(header), 1, fTGA) == 0)
648    {
649      PRINTF(2)("Error could not read info header\n");
650      return false;
651    }
652 
653  Width = pImage->width  = header[1] * 256 + header[0];
654  Height = pImage->height = header[3] * 256 + header[2];
655  Bpp = pImage->bpp     = header[4];
656
657  GLuint pixelcount     = Height * Width;
658  GLuint currentpixel   = 0;
659  GLuint currentbyte    = 0;
660  GLubyte * colorbuffer = (GLubyte *)malloc(bytesPerPixel);
661
662  //Make sure all pImage info is ok
663  if((pImage->width <= 0) || (pImage->height <= 0) || ((pImage->bpp != 24) && (pImage->bpp !=32)))
664    {
665      PRINTF(2)("Error Invalid pImage information\n");
666      return false;
667    }
668 
669  bytesPerPixel = (Bpp / 8);
670  imageSize             = (bytesPerPixel * Width * Height);
671  pImage->data  = (GLubyte*) malloc(imageSize);
672 
673  if(pImage->data == NULL)
674    {
675      PRINTF(2)("Error could not allocate memory for image\n");
676      return false;
677    }
678 
679  do
680    {
681      GLubyte chunkheader = 0;
682     
683      if(fread(&chunkheader, sizeof(GLubyte), 1, fTGA) == 0)
684        {
685          PRINTF(2)("Error could not read RLE header\n");
686          if(pImage->data != NULL)
687            {
688              free(pImage->data);
689            }
690          return false;
691        }
692      // If the ehader is < 128, it means the that is the number of RAW color packets minus 1
693      if(chunkheader < 128)
694        {
695          short counter;
696          chunkheader++;
697          // Read RAW color values
698          for(counter = 0; counter < chunkheader; counter++)
699            { 
700              // Try to read 1 pixel
701              if(fread(colorbuffer, 1, bytesPerPixel, fTGA) != bytesPerPixel)
702                {
703                  PRINTF(2)("Error could not read image data\n");
704                  if(colorbuffer != NULL)
705                    {
706                      free(colorbuffer);
707                    }
708                 
709                  if(pImage->data != NULL)
710                    {
711                      free(pImage->data);
712                    }
713                 
714                  return false; 
715                }
716              // write to memory
717              // Flip R and B vcolor values around in the process
718              pImage->data[currentbyte    ] = colorbuffer[2];                               
719              pImage->data[currentbyte + 1] = colorbuffer[1];
720              pImage->data[currentbyte + 2] = colorbuffer[0];
721             
722              if(bytesPerPixel == 4) // if its a 32 bpp image
723                {
724                  pImage->data[currentbyte + 3] = colorbuffer[3];// copy the 4th byte
725                }
726             
727              currentbyte += bytesPerPixel;
728              currentpixel++;
729
730              // Make sure we haven't read too many pixels
731              if(currentpixel > pixelcount)     
732                {
733                  PRINTF(2)("Error too many pixels read\n");
734                  if(colorbuffer != NULL)
735                    {
736                      free(colorbuffer);
737                    }
738                 
739                  if(pImage->data != NULL)
740                    {
741                      free(pImage->data);
742                    }
743                 
744                  return false;
745                }
746            }
747        }
748      // chunkheader > 128 RLE data, next color  reapeated chunkheader - 127 times
749      else
750        {
751          short counter;
752          chunkheader -= 127;   // Subteact 127 to get rid of the ID bit
753          if(fread(colorbuffer, 1, bytesPerPixel, fTGA) != bytesPerPixel) // Attempt to read following color values
754            {
755              PRINTF(2)("Error could not read from file");
756              if(colorbuffer != NULL)
757                {
758                  free(colorbuffer);
759                }
760             
761              if(pImage->data != NULL)
762                {
763                  free(pImage->data);
764                }
765             
766              return false;
767            }
768         
769          for(counter = 0; counter < chunkheader; counter++) //copy the color into the image data as many times as dictated
770            {                                                   
771              // switch R and B bytes areound while copying
772              pImage->data[currentbyte    ] = colorbuffer[2];
773              pImage->data[currentbyte + 1] = colorbuffer[1];
774              pImage->data[currentbyte + 2] = colorbuffer[0];
775             
776              if(bytesPerPixel == 4)
777                {
778                  pImage->data[currentbyte + 3] = colorbuffer[3];
779                }
780             
781              currentbyte += bytesPerPixel;
782              currentpixel++;
783             
784              if(currentpixel > pixelcount)
785                {
786                  PRINTF(2)("Error too many pixels read\n");
787                  if(colorbuffer != NULL)
788                    {
789                      free(colorbuffer);
790                    }
791                 
792                  if(pImage->data != NULL)
793                    {
794                      free(pImage->data);
795                    }
796                 
797                  return false;
798                }
799            }
800        }
801    }
802 
803  while(currentpixel < pixelcount);     // Loop while there are still pixels left
804
805  this->loadTexToGL (pImage);
806
807  return true;
808}
809
810
811/**
812   \brief reads in a png-file
813   \param pngName the Name of the Image to load
814*/
815bool Texture::loadPNG(const char* pngName)
816{
817#ifdef HAVE_PNG_H
818
819  FILE *PNG_file = fopen(pngName, "rb");
820  if (PNG_file == NULL)
821    {
822      return 0;
823    }
824 
825  GLubyte PNG_header[8];
826 
827  fread(PNG_header, 1, 8, PNG_file);
828  if (png_sig_cmp(PNG_header, 0, 8) != 0)
829    {
830      PRINTF(2)("Not Recognized as a pngFile\n");
831      fclose (PNG_file);
832      return 0;
833    }
834 
835  png_structp PNG_reader = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
836  if (PNG_reader == NULL)
837    {
838      fclose(PNG_file);
839      return 0;
840    }
841 
842  png_infop PNG_info = png_create_info_struct(PNG_reader);
843  if (PNG_info == NULL)
844    {
845      png_destroy_read_struct(&PNG_reader, NULL, NULL);
846      fclose(PNG_file);
847      return 0;
848    }
849 
850  png_infop PNG_end_info = png_create_info_struct(PNG_reader);
851  if (PNG_end_info == NULL)
852    {
853      png_destroy_read_struct(&PNG_reader, &PNG_info, NULL);
854      fclose(PNG_file);
855      return 0;
856    }
857 
858  if (setjmp(png_jmpbuf(PNG_reader)))
859    {
860      png_destroy_read_struct(&PNG_reader, &PNG_info, &PNG_end_info);
861      fclose(PNG_file);
862      return (0);
863    }
864 
865  png_init_io(PNG_reader, PNG_file);
866  png_set_sig_bytes(PNG_reader, 8);
867 
868  png_read_info(PNG_reader, PNG_info);
869 
870  pImage->width = png_get_image_width(PNG_reader, PNG_info);
871  pImage->height = png_get_image_height(PNG_reader, PNG_info);
872 
873  png_uint_32 bit_depth, color_type;
874  bit_depth = png_get_bit_depth(PNG_reader, PNG_info);
875  color_type = png_get_color_type(PNG_reader, PNG_info);
876 
877  if (color_type == PNG_COLOR_TYPE_PALETTE)
878    {
879      png_set_palette_to_rgb(PNG_reader);
880    }
881 
882  if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
883    {
884      png_set_gray_1_2_4_to_8(PNG_reader);
885    }
886 
887  if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
888    {
889      png_set_gray_to_rgb(PNG_reader);
890    }
891 
892  if (png_get_valid(PNG_reader, PNG_info, PNG_INFO_tRNS))
893    {
894      png_set_tRNS_to_alpha(PNG_reader);
895    }
896  else
897    {
898      png_set_filler(PNG_reader, 0xff, PNG_FILLER_AFTER);
899    }
900 
901  if (bit_depth == 16)
902    {
903      png_set_strip_16(PNG_reader);
904    }
905 
906  png_read_update_info(PNG_reader, PNG_info);
907 
908  pImage->data = (png_byte*)malloc(4 * pImage->width * pImage->height);
909  png_byte** PNG_rows = (png_byte**)malloc(pImage->height * sizeof(png_byte*));
910 
911  unsigned int row;
912  for (row = 0; row < pImage->height; ++row)
913    {
914      PNG_rows[pImage->height - 1 - row] = pImage->data + (row * 4 * pImage->width);
915    }
916 
917  png_read_image(PNG_reader, PNG_rows);
918 
919  free(PNG_rows);
920 
921  png_destroy_read_struct(&PNG_reader, &PNG_info, &PNG_end_info);
922  fclose(PNG_file);
923 
924  /*  if (!ST_is_power_of_two(pImage->width) || !ST_is_power_of_two(pImage->height))
925    {
926      free(pImage->data);
927      return 0;
928    }
929  */
930  this->loadTexToGL (pImage); 
931 
932  free(pImage->data);
933 
934  return true;
935#else /* HAVE_PNG_H */
936  PRINTF(1)("sorry, but you did not compile with png-support.\nEither install SDL_image or libpng, and recompile to see the image\n");
937  return false;
938#endif /* HAVE_PNG_H */
939
940}
941#endif /* HAVE_SDL_SDL_IMAGE_H */
Note: See TracBrowser for help on using the repository browser.