texture_from_tga.cpp 2.2 KB

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