GBuffer.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // ----------------------------------------------------------------
  2. // From Game Programming in C++ by Sanjay Madhav
  3. // Copyright (C) 2017 Sanjay Madhav. All rights reserved.
  4. //
  5. // Released under the BSD License
  6. // See LICENSE in root directory for full details.
  7. // ----------------------------------------------------------------
  8. #include "GBuffer.h"
  9. #include <GL/glew.h>
  10. #include "Texture.h"
  11. GBuffer::GBuffer()
  12. :mBufferID(0)
  13. {
  14. }
  15. GBuffer::~GBuffer()
  16. {
  17. }
  18. bool GBuffer::Create(int width, int height)
  19. {
  20. // Create the framebuffer object
  21. glGenFramebuffers(1, &mBufferID);
  22. glBindFramebuffer(GL_FRAMEBUFFER, mBufferID);
  23. // Add a depth buffer to this target
  24. GLuint depthBuffer;
  25. glGenRenderbuffers(1, &depthBuffer);
  26. glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer);
  27. glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT,
  28. width, height);
  29. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
  30. GL_RENDERBUFFER, depthBuffer);
  31. // Create textures for each output in the G-buffer
  32. for (int i = 0; i < NUM_GBUFFER_TEXTURES; i++)
  33. {
  34. Texture* tex = new Texture();
  35. // We want three 32-bit float components for each texture
  36. tex->CreateForRendering(width, height, GL_RGB32F);
  37. mTextures.emplace_back(tex);
  38. // Attach this texture to a color output
  39. glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i,
  40. tex->GetTextureID(), 0);
  41. }
  42. // Create a vector of the color attachments
  43. std::vector<GLenum> attachments;
  44. for (int i = 0; i < NUM_GBUFFER_TEXTURES; i++)
  45. {
  46. attachments.emplace_back(GL_COLOR_ATTACHMENT0 + i);
  47. }
  48. // Set the list of buffers to draw to
  49. glDrawBuffers(static_cast<GLsizei>(attachments.size()),
  50. attachments.data());
  51. // Make sure everything worked
  52. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  53. {
  54. Destroy();
  55. return false;
  56. }
  57. return true;
  58. }
  59. void GBuffer::Destroy()
  60. {
  61. glDeleteFramebuffers(1, &mBufferID);
  62. for (Texture* t : mTextures)
  63. {
  64. t->Unload();
  65. delete t;
  66. }
  67. }
  68. Texture* GBuffer::GetTexture(Type type)
  69. {
  70. if (mTextures.size() > 0)
  71. {
  72. return mTextures[type];
  73. }
  74. else
  75. {
  76. return nullptr;
  77. }
  78. }
  79. void GBuffer::SetTexturesActive()
  80. {
  81. for (int i = 0; i < NUM_GBUFFER_TEXTURES; i++)
  82. {
  83. mTextures[i]->SetActive(i);
  84. }
  85. }