init_render_to_texture.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include "init_render_to_texture.h"
  2. #include <cassert>
  3. IGL_INLINE void igl::init_render_to_texture(
  4. const size_t width,
  5. const size_t height,
  6. GLuint & tex_id,
  7. GLuint & fbo_id,
  8. GLuint & dfbo_id)
  9. {
  10. using namespace std;
  11. // Delete if already exists
  12. glDeleteTextures(1,&tex_id);
  13. glDeleteFramebuffersEXT(1,&fbo_id);
  14. glDeleteFramebuffersEXT(1,&dfbo_id);
  15. // http://www.opengl.org/wiki/Framebuffer_Object_Examples#Quick_example.2C_render_to_texture_.282D.29
  16. glGenTextures(1, &tex_id);
  17. glBindTexture(GL_TEXTURE_2D, tex_id);
  18. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  19. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  20. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  21. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  22. //NULL means reserve texture memory, but texels are undefined
  23. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, width, height, 0, GL_BGRA, GL_FLOAT, NULL);
  24. glBindTexture(GL_TEXTURE_2D, 0);
  25. glGenFramebuffersEXT(1, &fbo_id);
  26. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_id);
  27. //Attach 2D texture to this FBO
  28. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, tex_id, 0);
  29. glGenRenderbuffersEXT(1, &dfbo_id);
  30. glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, dfbo_id);
  31. glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, width, height);
  32. //Attach depth buffer to FBO (for this example it's not really needed, but if
  33. //drawing a 3D scene it would be necessary to attach something)
  34. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, dfbo_id);
  35. //Does the GPU support current FBO configuration?
  36. GLenum status;
  37. status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
  38. assert(status == GL_FRAMEBUFFER_COMPLETE_EXT);
  39. // Unbind to clean up
  40. glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
  41. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  42. }