title: Rendering the Z-buffer to texture in WebGL
body: <p>When I create z-buffer texture like so:</p>
  
  <pre><code>gl.bindTexture(GL_TEXTURE_2D, texBuff);
  gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  gl.texImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, frameBuff.width, frameBuff.height,    0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, null);
  </code></pre>
  
  <p>I get a proper z-buffer which I can then use for shadows (and my shadows render fine). However, if I create a color texture, and color the texture with the z-value, my shadows have a lot of artifacts (even with a high bias). The color buffer is created like this:</p>
  
  <pre><code>gl.bindTexture(GL_TEXTURE_2D, colorBuff);
  gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  gl.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, frameBuff.width, frameBuff.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, null);
  </code></pre>
  
  <p>This is the fragment shader program that writes to the color buffer:</p>
  
  <pre><code>precision highp float;
  void main() {
      float z = gl_FragCoord.z;
      gl_FragColor = vec4(z, z, z, 1.0); 
  }
  </code></pre>
  
  <p>When I render the two textures to some surface, they look similar. </p>
  
  <p>So my question is, why is my color texture not working? Is gl_FragCoord.z not the correct z value that's written to the z-buffer? According to <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/gl_FragCoord.xml" rel="nofollow">http://www.opengl.org/sdk/docs/manglsl/xhtml/gl_FragCoord.xml</a> it is. Are the texture coordinated different when I bind a color buffer? Or is the z value incorrect?</p>