texture_from_tga.cpp 1.8 KB

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