title: Render the depth buffer into a texture using a frame buffer
body: <p>I am using JOGL, but this question applies to OpenGL in general. There seem to be similar questions lying around, but they are either directed at GLSL code, have to do with copying the contents of a frame buffer, or are a general advice - use frame buffer objects instead of <code>glCopyTexSubImage2D</code>.</p>
  
  <h2>Question</h2>
  
  <p>I am doing some shadow mapping. How do I render the depth channel directly to a texture using a frame buffer object?</p>
  
  <p>Can you please post a block of code that initializes the texture and the frame buffer object, as well as the code that initializes everything before rendering the scene?</p>
  
  <p>Currently, I use <code>glCopyTexSubImage2D</code>. I initialize the texture like this:</p>
  
  <pre><code>glGenTextures(1, &amp;textureNo)
  glBindTexture(GL_TEXTURE_2D, textureNo)
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE)
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL)
  glTexParameterf(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY)
  glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 2048, 2048, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, null)
  </code></pre>
  
  <p>and then I render like this:</p>
  
  <pre><code>glBindTexture(GL_TEXTURE_2D, textureNo)
  glClear(GL_DEPTH_BUFFER_BIT)
  drawScene()
  glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, 2048, 2048)
  </code></pre>
  
  <p>and this works fine, the texture ends up holding the depth channel of the scene - this means my projection and view matrices are set correctly to view the scene from the light point of view. I'd like to use frame buffer objects instead.</p>
  
  <p>What do I need to change above to render directly to the texture instead using a frame buffer object?</p>
  
  <p>EDIT:</p>
  
  <p>Here is what I tried. I first initialized the frame buffer object:</p>
  
  <pre><code>glGenFramebuffers(1, &amp;fbo)
  </code></pre>
  
  <p>I then rendered like this:</p>
  
  <pre><code>glBindFramebuffer(GL_FRAMEBUFFER, fbo)
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, textureNo, 0)
  glBindTexture(GL_TEXTURE_2D, textureNo)
  drawScene()
  </code></pre>
  
  <p>I have confirmed that the above works for textures of type <code>GL_RGB</code> and <code>GL_COLOR_ATTACHMENT0</code>, but it does not seem to work for <code>GL_DEPTH_COMPONENT</code> type textures and <code>GL_DEPTH_ATTACHMENT</code> - the depth channel does not get rendered into the texture <code>textureNo</code> above.</p>