title: Omnidirectional shadow mapping with depth cubemap
body: <p>I'm working with omnidirectional point lights. I already implemented shadow mapping using a cubemap texture as color attachement of 6 framebuffers, and encoding the light-to-fragment distance in each pixel of it.</p>
  
  <p>Now I would like, if this is possible, to change my implementation this way:</p>
  
  <ul>
  <li>1) attach a depth cubemap texture to the depth buffer of my framebuffers, instead of colors.</li>
  <li>2) render depth only, do not write color in this pass</li>
  <li>3) in the main pass, read the depth from the cubemap texture, convert it to a distance, and check whether the current fragment is occluded by the light or not.</li>
  </ul>
  
  <p>My problem comes when converting back a depth value from the cubemap into a distance. I use the light-to-fragment vector (in world space) to fetch my depth value in the cubemap. At this point, I don't know which of the six faces is being used, nor what 2D texture coordinates match the depth value I'm reading. Then how can I convert that depth value to a distance?</p>
  
  <p>Here are snippets of my code to illustrate:</p>
  
  <p>Depth texture:</p>
  
  <pre><code>glGenTextures(1, &amp;TextureHandle);
  glBindTexture(GL_TEXTURE_CUBE_MAP, TextureHandle);
  for (int i = 0; i &lt; 6; ++i)
      glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT,
                Width, Height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
  
  glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  
  glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  </code></pre>
  
  <p>Framebuffers construction:</p>
  
  <pre><code>for (int i = 0; i &lt; 6; ++i)
  {
      glGenFramebuffers(1, &amp;FBO-&gt;FrameBufferID);
      glBindFramebuffer(GL_FRAMEBUFFER, FBO-&gt;FrameBufferID);
      glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
              GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, TextureHandle, 0);
      glDrawBuffer(GL_NONE);
  }
  </code></pre>
  
  <p>The piece of fragment shader I'm trying to write to achieve my code:</p>
  
  <pre><code>float ComputeShadowFactor(samplerCubeShadow ShadowCubeMap, vec3 VertToLightWS)
  {   
      float ShadowVec = texture(ShadowCubeMap, vec4(VertToLightWS, 1.0));
      ShadowVec = DepthValueToDistance(ShadowVec);
      if (ShadowVec * ShadowVec &gt; dot(VertToLightWS, VertToLightWS))
          return 1.0;
  
      return 0.0;
  }
  </code></pre>
  
  <p>The DepthValueToDistance function being my actual problem.</p>