texture_from_tga.cpp 2.2 KB

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