texture_from_tga.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include "texture_from_tga.h"
  2. #include "tga.h"
  3. IGL_INLINE bool igl::texture_from_tga(const std::string tga_file, GLuint & id)
  4. {
  5. using namespace std;
  6. using namespace igl;
  7. // read pixels to tga file
  8. FILE * imgFile;
  9. // "-" as input file name is code for read from stdin
  10. imgFile = fopen(tga_file.c_str(),"r");
  11. if(NULL==imgFile)
  12. {
  13. printf("IOError: %s could not be opened...",tga_file.c_str());
  14. return false;
  15. }
  16. // gliReadTGA annoyingly uses char * instead of const char *
  17. size_t len = tga_file.length();
  18. char* tga_file_char = new char [ len + 1 ];
  19. strcpy( tga_file_char, tga_file.c_str() );
  20. // read image
  21. gliGenericImage* img = gliReadTGA(imgFile, tga_file_char, 0, 0);
  22. // clean up filename buffer
  23. delete[] tga_file_char;
  24. fclose( imgFile );
  25. // set up texture mapping parameters and generate texture id
  26. glGenTextures(1,&id);
  27. glBindTexture(GL_TEXTURE_2D, id);
  28. // Texture parameters
  29. float empty[] = {1.0f,1.0f,1.0f,0.0f};
  30. glTexParameterfv(GL_TEXTURE_2D,GL_TEXTURE_BORDER_COLOR,empty);
  31. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
  32. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
  33. //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
  34. // GL_LINEAR_MIPMAP_NEAREST);
  35. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
  36. GL_LINEAR);
  37. // OpenGL by default tries to read data in multiples of 4, if our data is
  38. // only RGB or BGR and the width is not divible by 4 then we need to alert
  39. // opengl
  40. if((img->width % 4) != 0 &&
  41. (img->format == GL_RGB ||
  42. img->format == GL_BGR))
  43. {
  44. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  45. }
  46. // Load texture
  47. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img->width,
  48. img->height, 0, img->format, GL_UNSIGNED_BYTE,
  49. img->pixels);
  50. return id;
  51. }