Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/orxonox/branches/parenting/src/importer/texture.cc @ 3346

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

orxonox/branches/parenting: SLD_Surface now gets deleted in loadImage(SLD_image)

File size: 24.0 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(3)("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(2)("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   \param texture The Texture to apply it to.
193*/
194bool Texture::loadTexToGL (Image* pImage)
195{
196  PRINTF(2)("Loading texture to OpenGL-Environment.\n");
197  glGenTextures(1, &this->texture);
198  glBindTexture(GL_TEXTURE_2D, this->texture);
199  /* not Working, and not needed.
200  glTexImage2D( GL_TEXTURE_2D, 0, 3, width,
201                height, 0, GL_BGR,
202                GL_UNSIGNED_BYTE, map->pixels );
203  */ 
204  gluBuild2DMipmaps(GL_TEXTURE_2D, 3, pImage->width, pImage->height, GL_RGB, GL_UNSIGNED_BYTE, pImage->data);
205 
206  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
207  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR); 
208}
209
210
211#ifdef HAVE_SDL_SDL_IMAGE_H
212bool Texture::loadImage(char* imageName)
213{
214  char* imgNameWithPath = searchTextureInPaths(imageName);
215  if (imgNameWithPath)
216    {
217      this->map=IMG_Load(imgNameWithPath);
218      if(!map)
219        {
220          PRINTF(1)("IMG_Load: %s\n", IMG_GetError());
221          return false;
222        }
223      pImage->height = map->h;
224      pImage->width  = map->w;
225      pImage->data   = (GLubyte*)map->pixels;
226      pImage->bpp    = 3;//map->BytesPerPixel;
227      if( !IMG_isPNG(SDL_RWFromFile(imgNameWithPath, "rb")) && !IMG_isJPG(SDL_RWFromFile(imgNameWithPath, "rb")))
228        for (int i=0;i<map->h * map->w *3;i+=3)
229          { 
230            GLuint temp = pImage->data[i];
231            pImage->data[i] = pImage->data[i+2];
232            pImage->data[i+2] = temp;
233          }
234      /* this is the real swapping algorithm */
235      for( int i = 0 ; i < (pImage->height / 2) ; ++i )
236        for( int j = 0 ; j < pImage->width * pImage->bpp; j += pImage->bpp )
237          for(int k = 0; k < pImage->bpp; ++k)
238            swap( pImage->data[ (i * pImage->width * pImage->bpp) + j + k], pImage->data[ ( (pImage->height - i - 1) * pImage->width * pImage->bpp ) + j + k]);
239 
240      this->loadTexToGL (this->pImage);
241      SDL_FreeSurface(map);
242      this->pImage->data = NULL;
243    }
244  else
245    {
246      PRINTF(1)("Image not Found: %s\n", imgNameWithPath);
247      return false;
248    }
249}
250
251
252#else /* HAVE_SDL_SDL_IMAGE_H */
253/**
254   \brief Makes the Programm ready to Read-in a texture-File
255   1. Checks what type of Image should be imported
256   2. ToDO: Checks where to find the Image
257*/
258bool Texture::loadImage(char* imageName)
259{
260  char* imgNameWithPath = searchTextureInPaths(imageName);
261  if (imgNameWithPath)
262    {
263      if (!strncmp(imgNameWithPath+strlen(imgNameWithPath)-4, ".bmp", 4))
264        {
265          PRINTF(3)("Requested bmp-image. Trying to Import.\n");
266          return this->loadBMP(imgNameWithPath);
267        }
268     
269      else if (!strncmp(imgNameWithPath+strlen(imgNameWithPath)-4, ".jpg", 4) || !strncmp(imgNameWithPath+strlen(imgNameWithPath)-5, ".jpg", 5))
270        {
271          PRINTF(3)("Requested jpeg-image. Trying to Import\n");
272          return this->loadJPG(imgNameWithPath);
273        }
274      else if (!strncmp(imgNameWithPath+strlen(imgNameWithPath)-4, ".tga", 4))
275        {
276          PRINTF(3)("Requested tga-image. Trying to Import\n");
277          return this->loadTGA(imgNameWithPath);
278        }
279      else if (!strncmp(imgNameWithPath+strlen(imgNameWithPath)-4, ".png", 4))
280        {
281          PRINTF(3)("Requested png-image. Trying to Import\n");
282          return this->loadPNG(imgNameWithPath);
283        }
284      else
285        {
286          PRINTF(1)("Requested Image was not recognized in its type. (Maybe a type-Cast-error.)\n FileName: %s", imgNameWithPath);
287          return false;
288        }
289    }
290  else
291    {
292      PRINTF(1)("Image not Found: %s\n", imgNameWithPath);
293      return false;
294    }
295}
296
297/**
298   \brief reads in a Windows BMP-file, and imports it to openGL.
299   \param bmpName The name of the Image to load.
300   \param texture A pointer to the Texture which should be read to.
301*/
302bool Texture::loadBMP (char* bmpName)
303{
304  FILE *file;
305  unsigned long size;                 // size of the image in bytes.
306  unsigned long i;                    // standard counter.
307  unsigned short int planes;          // number of planes in image (must be 1)
308  unsigned short int bpp;             // number of bits per pixel (must be 24)
309  GLuint temp;                          // temporary color storage for bgr-rgb conversion.
310
311  // make sure the file is there.
312  if ((file = fopen(bmpName, "rb"))==NULL)
313    {
314      PRINTF(1)("File Not Found : %s\n",bmpName);
315      return false;
316    }
317  // seek through the bmp header, up to the width/height:
318  fseek(file, 18, SEEK_CUR);
319 
320  // read the width
321  if ((i = fread(&pImage->width, 4, 1, file)) != 1) 
322    {
323      PRINTF(1)("Error reading width from %s.\n", bmpName);
324      return false;
325    }
326  // read the height
327  if ((i = fread(&pImage->height, 4, 1, file)) != 1) 
328    {
329      PRINTF(1)("Error reading height from %s.\n", bmpName);
330      return false;
331    }
332 
333  // calculate the size (assuming 24 bits or 3 bytes per pixel).
334  size = pImage->width * pImage->height * 3;
335 
336  // read the planes
337  if ((fread(&planes, 2, 1, file)) != 1) 
338    {
339      PRINTF(1)("Error reading planes from %s.\n", bmpName);
340      return false;
341    }
342  if (planes != 1) 
343    {
344      PRINTF(1)("Planes from %s is not 1: %u\n", bmpName, planes);
345      return false;
346    }
347 
348  // read the bpp
349  if ((i = fread(&bpp, 2, 1, file)) != 1) 
350    {
351      PRINTF(1)("Error reading bpp from %s.\n", bmpName);
352      return false;
353    }
354  if (bpp != 24) 
355    {
356      PRINTF(1)("Bpp from %s is not 24: %u\n", bmpName, bpp);
357      return false;
358    }
359 
360  // seek past the rest of the bitmap header.
361  fseek(file, 24, SEEK_CUR);
362 
363  // read the data.
364  pImage->data = (GLubyte *) malloc(size);
365  if (pImage->data == NULL) 
366    {
367      PRINTF(1)("Error allocating memory for color-corrected image data");
368      return false;     
369    }
370 
371  if ((i = fread(pImage->data, size, 1, file)) != 1) 
372    {
373      PRINTF(1)("Error reading image data from %s.\n", bmpName);
374      return false;
375    }
376  fclose(file);
377
378  // reverse all of the colors. (bgr -> rgb)
379  for (i=0;i<size;i+=3) 
380    { 
381      temp = pImage->data[i];
382      pImage->data[i] = pImage->data[i+2];
383      pImage->data[i+2] = temp;
384    }
385  this->loadTexToGL (pImage);
386 
387
388  if (pImage)
389    {
390      if (pImage->data)
391        {
392          free(pImage->data);
393        }
394     
395      free(pImage);
396    }
397  return true;
398
399}
400
401/**
402   \brief reads in a jpg-file
403   \param jpgName the Name of the Image to load
404   \param texture a reference to the Texture to write the image to
405*/
406bool Texture::loadJPG (char* jpgName)
407{
408#ifdef HAVE_JPEGLIB_H
409  struct jpeg_decompress_struct cinfo;
410  Image *pImage = NULL;
411  FILE *pFile;
412 
413  // Open a file pointer to the jpeg file and check if it was found and opened
414  if((pFile = fopen(jpgName, "rb")) == NULL) 
415    {
416      // Display an error message saying the file was not found, then return NULL
417      PRINTF(1)("Unable to load JPG File %s.\n", jpgName);
418      return false;
419    }
420 
421  // Create an error handler
422  jpeg_error_mgr jerr;
423 
424  // Have our compression info object point to the error handler address
425  cinfo.err = jpeg_std_error(&jerr);
426 
427  // Initialize the decompression object
428  jpeg_create_decompress(&cinfo);
429 
430  // Specify the data source (Our file pointer)
431  jpeg_stdio_src(&cinfo, pFile);
432 
433  // Allocate the structure that will hold our eventual jpeg data (must free it!)
434  pImage = (Image*)malloc(sizeof(Image));
435 
436  // DECOFING
437  // Read in the header of the jpeg file
438  jpeg_read_header(&cinfo, TRUE);
439 
440  // Start to decompress the jpeg file with our compression info
441  jpeg_start_decompress(&cinfo);
442 
443  // Get the image dimensions and row span to read in the pixel data
444  pImage->rowSpan = cinfo.image_width * cinfo.num_components;
445  pImage->width   = cinfo.image_width;
446  pImage->height   = cinfo.image_height;
447 
448  // Allocate memory for the pixel buffer
449  pImage->data = new unsigned char[pImage->rowSpan * pImage->height];
450 
451  // Here we use the library's state variable cinfo.output_scanline as the
452  // loop counter, so that we don't have to keep track ourselves.
453 
454  // Create an array of row pointers
455  unsigned char** rowPtr = new unsigned char*[pImage->height];
456  for (int i = 0; i < pImage->height; i++)
457    rowPtr[i] = &(pImage->data[i*pImage->rowSpan]);
458 
459  // Now comes the juice of our work, here we extract all the pixel data
460  int rowsRead = 0;
461  while (cinfo.output_scanline < cinfo.output_height) 
462    {
463      // Read in the current row of pixels and increase the rowsRead count
464      rowsRead += jpeg_read_scanlines(&cinfo, &rowPtr[rowsRead], cinfo.output_height - rowsRead);
465    }
466 
467  // Delete the temporary row pointers
468  delete [] rowPtr;
469 
470  // Finish decompressing the data
471  jpeg_finish_decompress(&cinfo);//  decodeJPG(&cinfo, pImage);
472 
473  // This releases all the stored memory for reading and decoding the jpeg
474  jpeg_destroy_decompress(&cinfo);
475 
476  // Close the file pointer that opened the file
477  fclose(pFile);
478 
479
480  if(pImage == NULL)
481    exit(0);
482 
483  this->loadTexToGL (pImage);
484  if (pImage)
485    {
486      if (pImage->data)
487        {
488          free(pImage->data);
489        }
490     
491      free(pImage);
492    }
493  return true;
494#else /* HAVE_JPEGLIB_H */
495  PRINTF(1)("sorry, but you did not compile with jpeg-support.\nEither install SDL_image or jpeglib, and recompile to see the image\n");
496  return false;
497#endif /* HAVE_JPEGLIB_H */
498
499}
500
501/**
502   \brief reads in a tga-file
503   \param tgaName the Name of the Image to load
504   \param texture a reference to the Texture to write the image to
505*/
506bool Texture::loadTGA(const char * tgaName)
507{
508  typedef struct
509  {
510    GLubyte Header[12];
511  } TGAHeader;
512  TGAHeader tgaHeader;                 
513 
514  GLubyte uTGAcompare[12] = {0,0,2, 0,0,0,0,0,0,0,0,0}; // Uncompressed TGA Header
515  GLubyte cTGAcompare[12] = {0,0,10,0,0,0,0,0,0,0,0,0}; // Compressed TGA Header
516  FILE * fTGA;
517  fTGA = fopen(tgaName, "rb");
518
519  if(fTGA == NULL)
520    {
521      PRINTF(1)("Error could not open texture file: %s\n", tgaName);
522      return false;
523    }
524 
525  if(fread(&tgaHeader, sizeof(TGAHeader), 1, fTGA) == 0)
526    {
527      PRINTF(1)("Error could not read file header of %s\n", tgaName);
528      if(fTGA != NULL)
529        {
530          fclose(fTGA);
531        }
532      return false;
533    }
534 
535  if(memcmp(uTGAcompare, &tgaHeader, sizeof(TGAHeader)) == 0)
536    {
537      loadUncompressedTGA(tgaName, fTGA);
538      if (fTGA)
539        fclose (fTGA);
540    }
541  else if(memcmp(cTGAcompare, &tgaHeader, sizeof(TGAHeader)) == 0)
542    {
543      loadCompressedTGA(tgaName, fTGA);
544        if (fTGA)
545          fclose (fTGA);
546    }
547  else
548    {
549      PRINTF(1)("Error TGA file be type 2 or type 10\n");
550      if (fTGA)
551        fclose(fTGA);
552      return false;
553    }
554  return true;
555}
556
557/**
558   \brief reads in an uncompressed tga-file
559   \param filename the Name of the Image to load
560   \param fTGA a Pointer to a File, that should be read
561   \param texture a reference to the Texture to write the image to
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(1)("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(1)("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(1)("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(1)("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   \param texture a reference to the Texture to write the image to
636*/
637bool Texture::loadCompressedTGA(const char * filename, FILE * fTGA)
638{
639  GLubyte header[6];      // First 6 Useful Bytes From The Header
640  GLuint  bytesPerPixel;  // Holds Number Of Bytes Per Pixel Used In The TGA File
641  GLuint  imageSize;      // Used To Store The Image Size When Setting Aside Ram
642  GLuint  temp;           // Temporary Variable
643  GLuint  type;
644  GLuint  Height;         // Height of Image
645  GLuint  Width;          // Width of Image
646  GLuint  Bpp;            // Bits Per Pixel
647
648  if(fread(header, sizeof(header), 1, fTGA) == 0)
649    {
650      PRINTF(1)("Error could not read info header\n");
651      return false;
652    }
653 
654  Width = pImage->width  = header[1] * 256 + header[0];
655  Height = pImage->height = header[3] * 256 + header[2];
656  Bpp = pImage->bpp     = header[4];
657
658  GLuint pixelcount     = Height * Width;
659  GLuint currentpixel   = 0;
660  GLuint currentbyte    = 0;
661  GLubyte * colorbuffer = (GLubyte *)malloc(bytesPerPixel);
662
663  //Make sure all pImage info is ok
664  if((pImage->width <= 0) || (pImage->height <= 0) || ((pImage->bpp != 24) && (pImage->bpp !=32)))
665    {
666      PRINTF(1)("Error Invalid pImage information\n");
667      return false;
668    }
669 
670  bytesPerPixel = (Bpp / 8);
671  imageSize             = (bytesPerPixel * Width * Height);
672  pImage->data  = (GLubyte*) malloc(imageSize);
673 
674  if(pImage->data == NULL)
675    {
676      PRINTF(1)("Error could not allocate memory for image\n");
677      return false;
678    }
679 
680  do
681    {
682      GLubyte chunkheader = 0;
683     
684      if(fread(&chunkheader, sizeof(GLubyte), 1, fTGA) == 0)
685        {
686          PRINTF(1)("Error could not read RLE header\n");
687          if(pImage->data != NULL)
688            {
689              free(pImage->data);
690            }
691          return false;
692        }
693      // If the ehader is < 128, it means the that is the number of RAW color packets minus 1
694      if(chunkheader < 128)
695        {
696          short counter;
697          chunkheader++;
698          // Read RAW color values
699          for(counter = 0; counter < chunkheader; counter++)
700            { 
701              // Try to read 1 pixel
702              if(fread(colorbuffer, 1, bytesPerPixel, fTGA) != bytesPerPixel)
703                {
704                  PRINTF(1)("Error could not read image data\n");
705                  if(colorbuffer != NULL)
706                    {
707                      free(colorbuffer);
708                    }
709                 
710                  if(pImage->data != NULL)
711                    {
712                      free(pImage->data);
713                    }
714                 
715                  return false; 
716                }
717              // write to memory
718              // Flip R and B vcolor values around in the process
719              pImage->data[currentbyte    ] = colorbuffer[2];                               
720              pImage->data[currentbyte + 1] = colorbuffer[1];
721              pImage->data[currentbyte + 2] = colorbuffer[0];
722             
723              if(bytesPerPixel == 4) // if its a 32 bpp image
724                {
725                  pImage->data[currentbyte + 3] = colorbuffer[3];// copy the 4th byte
726                }
727             
728              currentbyte += bytesPerPixel;
729              currentpixel++;
730
731              // Make sure we haven't read too many pixels
732              if(currentpixel > pixelcount)     
733                {
734                  PRINTF(1)("Error too many pixels read\n");
735                  if(colorbuffer != NULL)
736                    {
737                      free(colorbuffer);
738                    }
739                 
740                  if(pImage->data != NULL)
741                    {
742                      free(pImage->data);
743                    }
744                 
745                  return false;
746                }
747            }
748        }
749      // chunkheader > 128 RLE data, next color  reapeated chunkheader - 127 times
750      else
751        {
752          short counter;
753          chunkheader -= 127;   // Subteact 127 to get rid of the ID bit
754          if(fread(colorbuffer, 1, bytesPerPixel, fTGA) != bytesPerPixel) // Attempt to read following color values
755            {
756              PRINTF(1)("Error could not read from file");
757              if(colorbuffer != NULL)
758                {
759                  free(colorbuffer);
760                }
761             
762              if(pImage->data != NULL)
763                {
764                  free(pImage->data);
765                }
766             
767              return false;
768            }
769         
770          for(counter = 0; counter < chunkheader; counter++) //copy the color into the image data as many times as dictated
771            {                                                   
772              // switch R and B bytes areound while copying
773              pImage->data[currentbyte    ] = colorbuffer[2];
774              pImage->data[currentbyte + 1] = colorbuffer[1];
775              pImage->data[currentbyte + 2] = colorbuffer[0];
776             
777              if(bytesPerPixel == 4)
778                {
779                  pImage->data[currentbyte + 3] = colorbuffer[3];
780                }
781             
782              currentbyte += bytesPerPixel;
783              currentpixel++;
784             
785              if(currentpixel > pixelcount)
786                {
787                  PRINTF(1)("Error too many pixels read\n");
788                  if(colorbuffer != NULL)
789                    {
790                      free(colorbuffer);
791                    }
792                 
793                  if(pImage->data != NULL)
794                    {
795                      free(pImage->data);
796                    }
797                 
798                  return false;
799                }
800            }
801        }
802    }
803 
804  while(currentpixel < pixelcount);     // Loop while there are still pixels left
805
806  this->loadTexToGL (pImage);
807
808  return true;
809}
810
811
812/*
813static int ST_is_power_of_two(unsigned int number)
814{
815  return (number & (number - 1)) == 0;
816}
817*/
818
819/**
820   \brief reads in a png-file
821   \param pngName the Name of the Image to load
822   \param texture a reference to the Texture to write the image to
823*/
824bool Texture::loadPNG(const char* pngName)
825{
826#ifdef HAVE_PNG_H
827
828  FILE *PNG_file = fopen(pngName, "rb");
829  if (PNG_file == NULL)
830    {
831      return 0;
832    }
833 
834  GLubyte PNG_header[8];
835 
836  fread(PNG_header, 1, 8, PNG_file);
837  if (png_sig_cmp(PNG_header, 0, 8) != 0)
838    {
839      PRINTF(2)("Not Recognized as a pngFile\n");
840      fclose (PNG_file);
841      return 0;
842    }
843 
844  png_structp PNG_reader = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
845  if (PNG_reader == NULL)
846    {
847      fclose(PNG_file);
848      return 0;
849    }
850 
851  png_infop PNG_info = png_create_info_struct(PNG_reader);
852  if (PNG_info == NULL)
853    {
854      png_destroy_read_struct(&PNG_reader, NULL, NULL);
855      fclose(PNG_file);
856      return 0;
857    }
858 
859  png_infop PNG_end_info = png_create_info_struct(PNG_reader);
860  if (PNG_end_info == NULL)
861    {
862      png_destroy_read_struct(&PNG_reader, &PNG_info, NULL);
863      fclose(PNG_file);
864      return 0;
865    }
866 
867  if (setjmp(png_jmpbuf(PNG_reader)))
868    {
869      png_destroy_read_struct(&PNG_reader, &PNG_info, &PNG_end_info);
870      fclose(PNG_file);
871      return (0);
872    }
873 
874  png_init_io(PNG_reader, PNG_file);
875  png_set_sig_bytes(PNG_reader, 8);
876 
877  png_read_info(PNG_reader, PNG_info);
878 
879  pImage->width = png_get_image_width(PNG_reader, PNG_info);
880  pImage->height = png_get_image_height(PNG_reader, PNG_info);
881 
882  png_uint_32 bit_depth, color_type;
883  bit_depth = png_get_bit_depth(PNG_reader, PNG_info);
884  color_type = png_get_color_type(PNG_reader, PNG_info);
885 
886  if (color_type == PNG_COLOR_TYPE_PALETTE)
887    {
888      png_set_palette_to_rgb(PNG_reader);
889    }
890 
891  if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
892    {
893      png_set_gray_1_2_4_to_8(PNG_reader);
894    }
895 
896  if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
897    {
898      png_set_gray_to_rgb(PNG_reader);
899    }
900 
901  if (png_get_valid(PNG_reader, PNG_info, PNG_INFO_tRNS))
902    {
903      png_set_tRNS_to_alpha(PNG_reader);
904    }
905  else
906    {
907      png_set_filler(PNG_reader, 0xff, PNG_FILLER_AFTER);
908    }
909 
910  if (bit_depth == 16)
911    {
912      png_set_strip_16(PNG_reader);
913    }
914 
915  png_read_update_info(PNG_reader, PNG_info);
916 
917  pImage->data = (png_byte*)malloc(4 * pImage->width * pImage->height);
918  png_byte** PNG_rows = (png_byte**)malloc(pImage->height * sizeof(png_byte*));
919 
920  unsigned int row;
921  for (row = 0; row < pImage->height; ++row)
922    {
923      PNG_rows[pImage->height - 1 - row] = pImage->data + (row * 4 * pImage->width);
924    }
925 
926  png_read_image(PNG_reader, PNG_rows);
927 
928  free(PNG_rows);
929 
930  png_destroy_read_struct(&PNG_reader, &PNG_info, &PNG_end_info);
931  fclose(PNG_file);
932 
933  /*  if (!ST_is_power_of_two(pImage->width) || !ST_is_power_of_two(pImage->height))
934    {
935      free(pImage->data);
936      return 0;
937    }
938  */
939  this->loadTexToGL (pImage); 
940 
941  free(pImage->data);
942 
943  return true;
944#else /* HAVE_PNG_H */
945  PRINTF(1)("sorry, but you did not compile with png-support.\nEither install SDL_image or libpng, and recompile to see the image\n");
946  return false;
947#endif /* HAVE_PNG_H */
948
949}
950#endif /* HAVE_SDL_SDL_IMAGE_H */
Note: See TracBrowser for help on using the repository browser.