texture_from_tga.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "texture_from_tga.h"
  9. #ifndef IGL_NO_OPENGL
  10. #include "tga.h"
  11. #include "report_gl_error.h"
  12. #include <cstring>
  13. IGL_INLINE bool igl::texture_from_tga(const std::string tga_file, GLuint & id)
  14. {
  15. using namespace std;
  16. // read pixels to tga file
  17. FILE * imgFile;
  18. // "-" as input file name is code for read from stdin
  19. imgFile = fopen(tga_file.c_str(),"r");
  20. if(NULL==imgFile)
  21. {
  22. printf("IOError: %s could not be opened...",tga_file.c_str());
  23. return false;
  24. }
  25. // gliReadTGA annoyingly uses char * instead of const char *
  26. size_t len = tga_file.length();
  27. char* tga_file_char = new char [ len + 1 ];
  28. strcpy( tga_file_char, tga_file.c_str() );
  29. // read image
  30. gliGenericImage* img = gliReadTGA(imgFile, tga_file_char, 0, 0);
  31. // clean up filename buffer
  32. delete[] tga_file_char;
  33. fclose( imgFile );
  34. // set up texture mapping parameters and generate texture id
  35. glGenTextures(1,&id);
  36. glBindTexture(GL_TEXTURE_2D, id);
  37. // Texture parameters
  38. float empty[] = {1.0f,1.0f,1.0f,0.0f};
  39. glTexParameterfv(GL_TEXTURE_2D,GL_TEXTURE_BORDER_COLOR,empty);
  40. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
  41. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
  42. //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
  43. // GL_LINEAR_MIPMAP_NEAREST);
  44. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
  45. GL_LINEAR);
  46. // OpenGL by default tries to read data in multiples of 4, if our data is
  47. // only RGB or BGR and the width is not divible by 4 then we need to alert
  48. // opengl
  49. if((img->width % 4) != 0 &&
  50. (img->format == GL_RGB ||
  51. img->format == GL_BGR))
  52. {
  53. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  54. igl::report_gl_error();
  55. }
  56. // Load texture
  57. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img->width,
  58. img->height, 0, img->format, GL_UNSIGNED_BYTE,
  59. img->pixels);
  60. return id;
  61. }
  62. #endif