init_render_to_texture.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2015 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 "init_render_to_texture.h"
  9. #include "gl.h"
  10. #include <cassert>
  11. IGL_INLINE void igl::opengl::init_render_to_texture(
  12. const size_t width,
  13. const size_t height,
  14. GLuint & tex_id,
  15. GLuint & fbo_id,
  16. GLuint & dfbo_id)
  17. {
  18. using namespace std;
  19. // Delete if already exists
  20. glDeleteTextures(1,&tex_id);
  21. glDeleteFramebuffers(1,&fbo_id);
  22. glDeleteFramebuffers(1,&dfbo_id);
  23. // http://www.opengl.org/wiki/Framebuffer_Object_Examples#Quick_example.2C_render_to_texture_.282D.29
  24. glGenTextures(1, &tex_id);
  25. glBindTexture(GL_TEXTURE_2D, tex_id);
  26. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  27. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  28. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  29. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  30. //NULL means reserve texture memory, but texels are undefined
  31. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_BGRA, GL_FLOAT, NULL);
  32. glBindTexture(GL_TEXTURE_2D, 0);
  33. glGenFramebuffers(1, &fbo_id);
  34. glBindFramebuffer(GL_FRAMEBUFFER, fbo_id);
  35. //Attach 2D texture to this FBO
  36. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_id, 0);
  37. glGenRenderbuffers(1, &dfbo_id);
  38. glBindRenderbuffer(GL_RENDERBUFFER, dfbo_id);
  39. glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);
  40. //Attach depth buffer to FBO (for this example it's not really needed, but if
  41. //drawing a 3D scene it would be necessary to attach something)
  42. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, dfbo_id);
  43. //Does the GPU support current FBO configuration?
  44. GLenum status;
  45. status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  46. assert(status == GL_FRAMEBUFFER_COMPLETE);
  47. // Unbind to clean up
  48. glBindRenderbuffer(GL_RENDERBUFFER, 0);
  49. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  50. }