render_to_tga.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 "render_to_tga.h"
  9. #include "tga.h"
  10. #include "OpenGL_convenience.h"
  11. #include <cstdlib>
  12. IGL_INLINE bool igl::opengl::render_to_tga(
  13. const std::string tga_file,
  14. const int width,
  15. const int height,
  16. const bool alpha)
  17. {
  18. size_t components = 3;
  19. GLenum format = GL_BGR;
  20. if(alpha)
  21. {
  22. format = GL_BGRA;
  23. components = 4;
  24. }
  25. GLubyte * cmap = NULL;
  26. // OpenGL by default tries to read data in multiples of 4, if our data is
  27. // only RGB or BGR and the width is not divible by 4 then we need to alert
  28. // opengl
  29. if((width % 4) != 0 &&
  30. (format == GL_RGB ||
  31. format == GL_BGR))
  32. {
  33. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  34. }
  35. GLubyte *pixels;
  36. pixels = (unsigned char *) malloc (width * height * components);
  37. glReadPixels(
  38. 0,
  39. 0,
  40. width,
  41. height,
  42. format,
  43. GL_UNSIGNED_BYTE,
  44. pixels);
  45. // set up generic image struct
  46. gliGenericImage * genericImage;
  47. genericImage = (gliGenericImage*) malloc(sizeof(gliGenericImage));
  48. genericImage->width = width;
  49. genericImage->height = height;
  50. genericImage->format = format;
  51. genericImage->components = components;
  52. genericImage->pixels = pixels;
  53. // CMAP is not supported, but we need to put something here
  54. genericImage->cmapEntries = 0;
  55. genericImage->cmapFormat = GL_BGR_EXT; // XXX fix me
  56. genericImage->cmap = cmap;
  57. // write pixels to tga file
  58. FILE * imgFile;
  59. // "-" as output file name is code for write to stdout
  60. if(tga_file.compare("-") == 0)
  61. {
  62. imgFile = stdout;
  63. }else{
  64. imgFile = fopen(tga_file.c_str(),"w");
  65. if(NULL==imgFile)
  66. {
  67. printf("IOError: %s could not be opened...\n",tga_file.c_str());
  68. return false;
  69. }
  70. }
  71. writeTGA(genericImage,imgFile);
  72. free(genericImage);
  73. return fclose(imgFile) == 0;
  74. }
  75. #ifdef IGL_STATIC_LIBRARY
  76. // Explicit template specialization
  77. #endif