<p><strong>SOLUTION</strong></p>

<p>After a couple of days I realized that <strong>I was computing my projection matrix using a FOV angle in degrees and It should be in radians</strong>. I made the conversion and now everything works great. The interpolation among faces of my depth framebuffer's cubemap is now perfect. For this reason, It is important to handle every single trigonometric function's angle in radians.</p>

<p>Moreover, I realized that you can compute your view matrix either as I said in the question and in this way:</p>

<pre><code>view.lookAt(position, target.add(position.clone()), up);
</code></pre>

<p>This approach means that your point of view is placed in pointlight's center and you just render in each direction of your cubemap, but which are these directions? well, <strong>these directions are computed adding each target that I've in the switch block (according to each cubemap's face) with your pointlight's position</strong>.</p>

<p>Furthermore, <strong>It is not necessary to flip Y-Coordinate of the projection matrix</strong>, In this case, It is ok dispatch pointlight's perspective projection matrix to your GLSL shader without scaling It by (1, -1, 1) because <strong>I'm working with textures that don't have a flipped Y-Coordinate</strong>, I think you should flip Y-Coordinate of your pointlight's projection matrix <strong>only if you are working with a flipped texture's Y-Coordinate</strong>, this in order to have a correct omnidirectional shadow mapping effect.</p>

<p>Finally, I'll leave here the final version of my Omnidirectional Shadow Mapping algorithm on CPU/GPU side. On CPU side I'll explain every step that you have to do in order to compute a correct shadow map for each cubemap's face. On the other hand in GPU side, I'll explain my depth program's vertex/fragment shader and omnidirectional shadow mapping function in my main fragment shader, this in order to help somebody who could be learning this technique, or solve future doubts about this algorithm:</p>

<p><strong>CPU</strong></p>

<pre><code>  // Disable blending and enable front face culling.

  this.state.disable(gl.BLEND);

  this.state.enable(gl.CULL_FACE);
  this.state.cullFace(gl.FRONT);

  // Binds depth program

  program.bind(gl);

  // For each pointlight source do

  for (i = 0; i &lt; lights.length; i++) {
    light = lights[i];

    // Get each pointlight's world position

    position = light.worldPosition();

    // Binds pointlight's depth framebuffer. Besides, in this function,
    // viewport's dimensions are set according to depth framebuffer's dimension.

    light.depthFramebuffer.bind(gl, this.state);

    // Updates point light's framebuffer in order to create it 
    // or if it's resolution have changed, it'll be created again.

    light.depthFramebuffer.update(gl);

    // Check in which cubemap's face we are ...

    for (j = 0; j &lt; 6; j++) {
      switch (j) {
        case Cubemap.POSITIVE_X:
          target.set(1, 0, 0);
          up.set(0, -1, 0);
          break;
        case Cubemap.NEGATIVE_X:
          target.set(-1, 0, 0);
          up.set(0, -1, 0);
          break;
        case Cubemap.POSITIVE_Y:
          target.set(0, 1, 0);
          up.set(0, 0, 1);
          break;
        case Cubemap.NEGATIVE_Y:
          target.set(0, -1, 0);
          up.set(0, 0, -1);
          break;
        case Cubemap.POSITIVE_Z:
          target.set(0, 0, 1);
          up.set(0, -1, 0);
          break;
        case Cubemap.NEGATIVE_Z:
          target.set(0, 0, -1);
          up.set(0, -1, 0);
          break;
      }

      // Creates a view matrix using target and up vectors 
      // according to each face of pointlight's cubemap.

      view.lookAt(position, target.add(position.clone()), up);

      // Attaches cubemap's face to current framebuffer 
      // in order to record depth values in that direction.

      light.depthFramebuffer.texture.attach(gl, j);

      // Clears color &amp; depth buffers of your current framebuffer

      this.clear();

      // Render each shadow caster mesh using your depth program

      for (k = 0; k &lt; meshes.length; k++)
        this._renderMeshDepth(program, meshes[k], view, light.projection);
    }
  }
</code></pre>

<p>On renderMeshDepth function I've:</p>

<pre><code>  // Computes pointlight's model-view matrix 

  modelView.mul(view, mesh.world);

  // Dispatch each matrix to the GLSL depth program

  program.loadUniformMatrix(gl, 'uModelView', modelView);
  program.loadUniformMatrix(gl, 'uProjection', projection);

  // Renders a mesh using vertex buffer objects (VBO)

  mesh.render(gl, program.attributes, this.state, this.extensions);
</code></pre>

<p><strong>GPU</strong></p>

<p>Depth Program Vertex Shader:</p>

<pre><code>precision highp float;

attribute vec3 position;

uniform mat4 uModelView;
uniform mat4 uProjection;

void main() {
  gl_Position = uProjection * uModelView * vec4(position, 1.0);
}
</code></pre>

<p>Depth Program Fragment Shader:</p>

<pre><code>precision highp float;

// The pack function distributes fragment's depth precision storing 
// it throughout (R,G,B,A) color channels and not just R color channel 
// as usual in shadow mapping algorithms. This is because I'm working
// with 8-bit textures and one color channel hasn't enough precision 
// to store a depth value.

vec4 pack(const in float depth) {
  const vec4 bitShift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);
  const vec4 bitMask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);

  vec4 res = fract(depth * bitShift);
  res -= res.xxyz * bitMask;

  return res;
}

void main() {
  // Packs normalized fragment's Z-Coordinate which is in [0,1] interval.

  gl_FragColor = pack(gl_FragCoord.z);
}
</code></pre>

<p>Omnidirectional Shadow Mapping function in my main fragment shader:</p>

<pre><code>// Unpacks fragment's Z-Coordinate which was packed 
// on the depth program's fragment shader.

float unpack(in vec4 color) {
   const vec4 bitShift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
   return dot(color, bitShift);
}

// Computes Omnidirectional Shadow Mapping technique using a samplerCube
// vec3 lightPosition is your pointlight's position in world coordinates.
// vec3 vPosition is your vertex's position in world coordinates, in code
// I mean this -&gt; vPosition = vec3(uModel * vec4(position, 1.0));
// where uModel is your World/Model matrix.

float omnidirectionalShadow(in vec3 lightPosition, in float bias, in float darkness, in samplerCube sampler) {
    vec3 direction = vPosition - lightPosition;
    float vertexDepth = clamp(length(direction), 0.0, 1.0);
    float shadowMapDepth = unpack(textureCube(sampler, direction)) + bias;

    return (vertexDepth &gt; shadowMapDepth) ? darkness : 1.0;
}
</code></pre>

<p>Here you have a final render of the algorithm</p>

<p><a href="https://i.sstatic.net/AvMHa.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AvMHa.jpg" alt="enter image description here"></a></p>

<p>Have fun coding beautiful graphics, good luck :) </p>

<p>C.Z.</p>

CC BY-SA 4.0
2024-12-30T18:20:25.990Z
Any suggestion https://computergraphics.stackexchange.com/questions/14321/webgl-shadows-implementation-framebuffer
Nikola Lukic
CC BY-SA 3.0
2015-12-15T00:12:41.023Z
2015-12-21T15:05:18.920Z
2015-12-21T15:05:18.920Z
czapata91
<p>First of all, I want to say that I've read a lot of post about shadow mapping using depth maps and cubemaps and I understand how they work and also, I have working experience with them using OpenGL, but, I have an issue implementing Omnidirectional Shadow Mapping technique using a single point light source in my 3D graphics engine named "EZ3". My engine uses WebGL as a 3D graphics API and JavaScript as programming language, this is for my bachelor's thesis in Computer Science. </p>

<p>Basically this is how I've implemented my shadow mapping algorithm, but I'll only focus on point lights case because with them I can archive omnidirectional shadow mapping.</p>

<p>First, I active front-face culling like this:</p>

<pre><code>if (this.state.faceCulling !== Material.FRONT) {
    if (this.state.faceCulling === Material.NONE)
      gl.enable(gl.CULL_FACE);

    gl.cullFace(gl.FRONT);
    this.state.faceCulling = Material.FRONT;
  }
</code></pre>

<p>Second, I create a depth program in order to record depth values for each cubemap face, this is my depth program code in GLSL 1.0:</p>

<p>Vertex Shader:</p>

<pre><code>precision highp float;

attribute vec3 position;

uniform mat4 uModelView;
uniform mat4 uProjection;

void main() {
  gl_Position = uProjection * uModelView * vec4(position, 1.0);
}
</code></pre>

<p>Fragment Shader:</p>

<pre><code>precision highp float;

vec4 packDepth(const in float depth) {
  const vec4 bitShift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);
  const vec4 bitMask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);
  vec4 res = mod(depth * bitShift * vec4(255), vec4(256)) / vec4(255);
  res -= res.xxyz * bitMask;
  return res;
}

void main() {
  gl_FragData[0] = packDepth(gl_FragCoord.z);
}
</code></pre>

<p>Third, this is my JavaScript function's body that "archives" omnidirectional shadow mapping</p>

<pre><code>program.bind(gl);

  for (i = 0; i &lt; lights.length; i++) {
    light = lights[i];

    // Updates pointlight's projection matrix

    light.updateProjection();

    // Binds point light's depth framebuffer

    light.depthFramebuffer.bind(gl);

    // Updates point light's framebuffer in order to create it 
    // or if it's resolution changes, it'll be created again.

    light.depthFramebuffer.update(gl);

    // Sets viewport dimensions with depth framebuffer's dimensions

    this.viewport(new Vector2(), light.depthFramebuffer.size);

    if (light instanceof PointLight) {

      up = new Vector3();
      view = new Matrix4();
      origin = new Vector3();
      target = new Vector3();

      for (j = 0; j &lt; 6; j++) {

    // Check in which cubemap's face we are ...

        switch (j) {
          case Cubemap.POSITIVE_X:
            target.set(1, 0, 0);
            up.set(0, -1, 0);
            break;
          case Cubemap.NEGATIVE_X:
            target.set(-1, 0, 0);
            up.set(0, -1, 0);
            break;
          case Cubemap.POSITIVE_Y:
            target.set(0, 1, 0);
            up.set(0, 0, 1);
            break;
          case Cubemap.NEGATIVE_Y:
            target.set(0, -1, 0);
            up.set(0, 0, -1);
            break;
          case Cubemap.POSITIVE_Z:
            target.set(0, 0, 1);
            up.set(0, -1, 0);
            break;
          case Cubemap.NEGATIVE_Z:
            target.set(0, 0, -1);
            up.set(0, -1, 0);
            break;
        }

    // Creates a view matrix using target and up vectors according to each face of pointlight's
    // cubemap. Furthermore, I translate it in minus light position in order to place
    // the point light in the world's origin and render each cubemap's face at this 
    // point of view

        view.lookAt(origin, target, up);
        view.mul(new EZ3.Matrix4().translate(light.position.clone().negate()));

    // Flips the Y-coordinate of each cubemap face
    // scaling the projection matrix by (1, -1, 1).

    // This is a perspective projection matrix which has:
    // 90 degress of FOV.
    // 1.0 of aspect ratio.
    // Near clipping plane at 0.01.
    // Far clipping plane at 2000.0.

        projection = light.projection.clone();
        projection.scale(new EZ3.Vector3(1, -1, 1));

    // Attaches a cubemap face to current framebuffer in order to record depth values for the face with this line
    // gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + j, id, 0);

        light.depthFramebuffer.texture.attach(gl, j);

    // Clears current framebuffer's color with these lines:
    // gl.clearColor(1.0,1.0,1.0,1.0);
    // gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

        this.clear(color);

    // Renders shadow caster meshes using the depth program

        for (k = 0; k &lt; shadowCasters.length; k++)
          this._renderShadowCaster(shadowCasters[k], program, view, projection);
      }
    } else {
       // Directional light &amp; Spotlight case ...
    }
  }
</code></pre>

<p>Fourth, this is how I compute Omnidirectional Shadow Mapping using my depth cubemap in my main Vertex Shader &amp; Fragment Shader:</p>

<p>Vertex Shader:</p>

<pre><code>precision highp float;

attribute vec3 position;

uniform mat4 uModel;
uniform mat4 uModelView;
uniform mat4 uProjection;

varying vec3 vPosition;

void main() {
  vPosition = vec3(uModel * vec4(position, 1.0));

  gl_Position = uProjection * uModelView * vec4(position, 1.0);
}
</code></pre>

<p>Fragment Shader:</p>

<pre><code>float unpackDepth(in vec4 color) {
    return dot(color, vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0 ));
}

float pointShadow(const in PointLight light, const in samplerCube shadowSampler) {
    vec3 direction = vPosition - light.position;
    float vertexDepth = clamp(length(direction), 0.0, 1.0);
    float shadowMapDepth = unpackDepth(textureCube(shadowSampler, direction));

    return (vertexDepth &gt; shadowMapDepth) ? light.shadowDarkness : 1.0;
}
</code></pre>

<p>Finally, this is the result that I'm getting , my scene has a plane, a cube and a sphere. Besides, the red bright sphere is the point light source:</p>

<p><a href="https://i.sstatic.net/YM04V.jpg" rel="noreferrer"><img src="https://i.sstatic.net/YM04V.jpg" alt="Omnidirectional Shadow Mapping Issue"></a></p>

<p>As you can see, I seems like point light depth framebuffer's cubemap it is not doing a good interpolation among their faces.</p>

<p>Until now, I've no idea how to solve this.</p>

CC BY-SA 3.0
2015-12-13T14:11:21.907Z
This seemed a good question - did you delete it because you found the solution? If so you could undelete it and post an answer with your solution. Answering your own question is encouraged and you gain reputation for both the question and the answer. Plus it may help someone else who has a similar problem in future...
trichoplax is on Codidact now
CC BY-SA 3.0
2015-12-14T21:56:19.720Z
Hello @trichoplax actually I found the solution, I'll share the answer with everyone answering my own question. Honestly I deleted my question because I thought none cares about this issue.
czapata91
CC BY-SA 3.0
2015-12-15T00:38:57.447Z
Hey! @NathanReed  I'll change the title, thanks about that :)
czapata91
<glsl><webgl><shadow-mapping>
WebGL Omnidirectional Shadow Mapping Issue
czapata91
# WebGL Omnidirectional Shadow Mapping Issue

(Asked by: username_0 on 2015-12-08)

First of all, I want to say that I've read a lot of post about shadow mapping using depth maps and cubemaps and I understand how they work and also, I have working experience with them using OpenGL, but, I have an issue implementing Omnidirectional Shadow Mapping technique using a single point light source in my 3D graphics engine named "EZ3". My engine uses WebGL as a 3D graphics API and JavaScript as programming language, this is for my bachelor's thesis in Computer Science.

Basically this is how I've implemented my shadow mapping algorithm, but I'll only focus on point lights case because with them I can archive omnidirectional shadow mapping.

First, I active front-face culling like this:

```
if (this.state.faceCulling !== Material.FRONT) {
    if (this.state.faceCulling === Material.NONE)
      gl.enable(gl.CULL_FACE);

    gl.cullFace(gl.FRONT);
    this.state.faceCulling = Material.FRONT;
  }

```

Second, I create a depth program in order to record depth values for each cubemap face, this is my depth program code in GLSL 1.0:

Vertex Shader:

```
precision highp float;

attribute vec3 position;

uniform mat4 uModelView;
uniform mat4 uProjection;

void main() {
  gl_Position = uProjection * uModelView * vec4(position, 1.0);
}

```

Fragment Shader:

```
precision highp float;

vec4 packDepth(const in float depth) {
  const vec4 bitShift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);
  const vec4 bitMask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);
  vec4 res = mod(depth * bitShift * vec4(255), vec4(256)) / vec4(255);
  res -= res.xxyz * bitMask;
  return res;
}

void main() {
  gl_FragData[0] = packDepth(gl_FragCoord.z);
}

```

Third, this is my JavaScript function's body that "archives" omnidirectional shadow mapping

```
program.bind(gl);

  for (i = 0; i < lights.length; i++) {
    light = lights[i];

    // Updates pointlight's projection matrix

    light.updateProjection();

    // Binds point light's depth framebuffer

    light.depthFramebuffer.bind(gl);

    // Updates point light's framebuffer in order to create it 
    // or if it's resolution changes, it'll be created again.

    light.depthFramebuffer.update(gl);

    // Sets viewport dimensions with depth framebuffer's dimensions

    this.viewport(new Vector2(), light.depthFramebuffer.size);

    if (light instanceof PointLight) {

      up = new Vector3();
      view = new Matrix4();
      origin = new Vector3();
      target = new Vector3();

      for (j = 0; j < 6; j++) {

    // Check in which cubemap's face we are ...

        switch (j) {
          case Cubemap.POSITIVE_X:
            target.set(1, 0, 0);
            up.set(0, -1, 0);
            break;
          case Cubemap.NEGATIVE_X:
            target.set(-1, 0, 0);
            up.set(0, -1, 0);
            break;
          case Cubemap.POSITIVE_Y:
            target.set(0, 1, 0);
            up.set(0, 0, 1);
            break;
          case Cubemap.NEGATIVE_Y:
            target.set(0, -1, 0);
            up.set(0, 0, -1);
            break;
          case Cubemap.POSITIVE_Z:
            target.set(0, 0, 1);
            up.set(0, -1, 0);
            break;
          case Cubemap.NEGATIVE_Z:
            target.set(0, 0, -1);
            up.set(0, -1, 0);
            break;
        }

    // Creates a view matrix using target and up vectors according to each face of pointlight's
    // cubemap. Furthermore, I translate it in minus light position in order to place
    // the point light in the world's origin and render each cubemap's face at this 
    // point of view

        view.lookAt(origin, target, up);
        view.mul(new EZ3.Matrix4().translate(light.position.clone().negate()));

    // Flips the Y-coordinate of each cubemap face
    // scaling the projection matrix by (1, -1, 1).

    // This is a perspective projection matrix which has:
    // 90 degress of FOV.
    // 1.0 of aspect ratio.
    // Near clipping plane at 0.01.
    // Far clipping plane at 2000.0.

        projection = light.projection.clone();
        projection.scale(new EZ3.Vector3(1, -1, 1));

    // Attaches a cubemap face to current framebuffer in order to record depth values for the face with this line
    // gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + j, id, 0);

        light.depthFramebuffer.texture.attach(gl, j);

    // Clears current framebuffer's color with these lines:
    // gl.clearColor(1.0,1.0,1.0,1.0);
    // gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

        this.clear(color);

    // Renders shadow caster meshes using the depth program

        for (k = 0; k < shadowCasters.length; k++)
          this._renderShadowCaster(shadowCasters[k], program, view, projection);
      }
    } else {
       // Directional light & Spotlight case ...
    }
  }

```

Fourth, this is how I compute Omnidirectional Shadow Mapping using my depth cubemap in my main Vertex Shader & Fragment Shader:

Vertex Shader:

```
precision highp float;

attribute vec3 position;

uniform mat4 uModel;
uniform mat4 uModelView;
uniform mat4 uProjection;

varying vec3 vPosition;

void main() {
  vPosition = vec3(uModel * vec4(position, 1.0));

  gl_Position = uProjection * uModelView * vec4(position, 1.0);
}

```

Fragment Shader:

```
float unpackDepth(in vec4 color) {
    return dot(color, vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0 ));
}

float pointShadow(const in PointLight light, const in samplerCube shadowSampler) {
    vec3 direction = vPosition - light.position;
    float vertexDepth = clamp(length(direction), 0.0, 1.0);
    float shadowMapDepth = unpackDepth(textureCube(shadowSampler, direction));

    return (vertexDepth > shadowMapDepth) ? light.shadowDarkness : 1.0;
}

```

Finally, this is the result that I'm getting , my scene has a plane, a cube and a sphere. Besides, the red bright sphere is the point light source:

[![Omnidirectional Shadow Mapping Issue](https://i.sstatic.net/YM04V.jpg)](https://i.sstatic.net/YM04V.jpg)

As you can see, I seems like point light depth framebuffer's cubemap it is not doing a good interpolation among their faces.

Until now, I've no idea how to solve this.

**Tags:** glsl, webgl, shadow-mapping

> **Comments:**
> **username_1**: This seemed a good question - did you delete it because you found the solution? If so you could undelete it and post an answer with your solution. Answering your own question is encouraged and you gain reputation for both the question and the answer. Plus it may help someone else who has a similar problem in future...  
> **username_0**: Hello @username_1 actually I found the solution, I'll share the answer with everyone answering my own question. Honestly I deleted my question because I thought none cares about this issue.  
> **username_0**: Hey! @NathanReed  I'll change the title, thanks about that :)  

---

## 1 answers

### Answer by username_0 on 2015-12-15. Score: 8 | Accepted answer

**SOLUTION**

After a couple of days I realized that **I was computing my projection matrix using a FOV angle in degrees and It should be in radians**. I made the conversion and now everything works great. The interpolation among faces of my depth framebuffer's cubemap is now perfect. For this reason, It is important to handle every single trigonometric function's angle in radians.

Moreover, I realized that you can compute your view matrix either as I said in the question and in this way:

```
view.lookAt(position, target.add(position.clone()), up);

```

This approach means that your point of view is placed in pointlight's center and you just render in each direction of your cubemap, but which are these directions? well, **these directions are computed adding each target that I've in the switch block (according to each cubemap's face) with your pointlight's position**.

Furthermore, **It is not necessary to flip Y-Coordinate of the projection matrix**, In this case, It is ok dispatch pointlight's perspective projection matrix to your GLSL shader without scaling It by (1, -1, 1) because **I'm working with textures that don't have a flipped Y-Coordinate**, I think you should flip Y-Coordinate of your pointlight's projection matrix **only if you are working with a flipped texture's Y-Coordinate**, this in order to have a correct omnidirectional shadow mapping effect.

Finally, I'll leave here the final version of my Omnidirectional Shadow Mapping algorithm on CPU/GPU side. On CPU side I'll explain every step that you have to do in order to compute a correct shadow map for each cubemap's face. On the other hand in GPU side, I'll explain my depth program's vertex/fragment shader and omnidirectional shadow mapping function in my main fragment shader, this in order to help somebody who could be learning this technique, or solve future doubts about this algorithm:

**CPU**

```
  // Disable blending and enable front face culling.

  this.state.disable(gl.BLEND);

  this.state.enable(gl.CULL_FACE);
  this.state.cullFace(gl.FRONT);

  // Binds depth program

  program.bind(gl);

  // For each pointlight source do

  for (i = 0; i < lights.length; i++) {
    light = lights[i];

    // Get each pointlight's world position

    position = light.worldPosition();

    // Binds pointlight's depth framebuffer. Besides, in this function,
    // viewport's dimensions are set according to depth framebuffer's dimension.

    light.depthFramebuffer.bind(gl, this.state);

    // Updates point light's framebuffer in order to create it 
    // or if it's resolution have changed, it'll be created again.

    light.depthFramebuffer.update(gl);

    // Check in which cubemap's face we are ...

    for (j = 0; j < 6; j++) {
      switch (j) {
        case Cubemap.POSITIVE_X:
          target.set(1, 0, 0);
          up.set(0, -1, 0);
          break;
        case Cubemap.NEGATIVE_X:
          target.set(-1, 0, 0);
          up.set(0, -1, 0);
          break;
        case Cubemap.POSITIVE_Y:
          target.set(0, 1, 0);
          up.set(0, 0, 1);
          break;
        case Cubemap.NEGATIVE_Y:
          target.set(0, -1, 0);
          up.set(0, 0, -1);
          break;
        case Cubemap.POSITIVE_Z:
          target.set(0, 0, 1);
          up.set(0, -1, 0);
          break;
        case Cubemap.NEGATIVE_Z:
          target.set(0, 0, -1);
          up.set(0, -1, 0);
          break;
      }

      // Creates a view matrix using target and up vectors 
      // according to each face of pointlight's cubemap.

      view.lookAt(position, target.add(position.clone()), up);

      // Attaches cubemap's face to current framebuffer 
      // in order to record depth values in that direction.

      light.depthFramebuffer.texture.attach(gl, j);

      // Clears color & depth buffers of your current framebuffer

      this.clear();

      // Render each shadow caster mesh using your depth program

      for (k = 0; k < meshes.length; k++)
        this._renderMeshDepth(program, meshes[k], view, light.projection);
    }
  }

```

On renderMeshDepth function I've:

```
  // Computes pointlight's model-view matrix 

  modelView.mul(view, mesh.world);

  // Dispatch each matrix to the GLSL depth program

  program.loadUniformMatrix(gl, 'uModelView', modelView);
  program.loadUniformMatrix(gl, 'uProjection', projection);

  // Renders a mesh using vertex buffer objects (VBO)

  mesh.render(gl, program.attributes, this.state, this.extensions);

```

**GPU**

Depth Program Vertex Shader:

```
precision highp float;

attribute vec3 position;

uniform mat4 uModelView;
uniform mat4 uProjection;

void main() {
  gl_Position = uProjection * uModelView * vec4(position, 1.0);
}

```

Depth Program Fragment Shader:

```
precision highp float;

// The pack function distributes fragment's depth precision storing 
// it throughout (R,G,B,A) color channels and not just R color channel 
// as usual in shadow mapping algorithms. This is because I'm working
// with 8-bit textures and one color channel hasn't enough precision 
// to store a depth value.

vec4 pack(const in float depth) {
  const vec4 bitShift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);
  const vec4 bitMask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);

  vec4 res = fract(depth * bitShift);
  res -= res.xxyz * bitMask;

  return res;
}

void main() {
  // Packs normalized fragment's Z-Coordinate which is in [0,1] interval.

  gl_FragColor = pack(gl_FragCoord.z);
}

```

Omnidirectional Shadow Mapping function in my main fragment shader:

```
// Unpacks fragment's Z-Coordinate which was packed 
// on the depth program's fragment shader.

float unpack(in vec4 color) {
   const vec4 bitShift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
   return dot(color, bitShift);
}

// Computes Omnidirectional Shadow Mapping technique using a samplerCube
// vec3 lightPosition is your pointlight's position in world coordinates.
// vec3 vPosition is your vertex's position in world coordinates, in code
// I mean this -> vPosition = vec3(uModel * vec4(position, 1.0));
// where uModel is your World/Model matrix.

float omnidirectionalShadow(in vec3 lightPosition, in float bias, in float darkness, in samplerCube sampler) {
    vec3 direction = vPosition - lightPosition;
    float vertexDepth = clamp(length(direction), 0.0, 1.0);
    float shadowMapDepth = unpack(textureCube(sampler, direction)) + bias;

    return (vertexDepth > shadowMapDepth) ? darkness : 1.0;
}

```

Here you have a final render of the algorithm

[![enter image description here](https://i.sstatic.net/AvMHa.jpg)](https://i.sstatic.net/AvMHa.jpg)

Have fun coding beautiful graphics, good luck :)

C.Z.

> **Comments:**
> **username_2**: Any suggestion https://computergraphics.stackexchange.com/questions/14321/webgl-shadows-implementation-framebuffer  

---

