render_to_tga.cpp 2.1 KB

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