Search code examples
shaderfragment-shaderwebgl2

WebGL2: write fragment depth to depth texture


I have a simple fragment shader used in WebGL2 that outputs different colors into two different texture targets. How to assign writing of gl_fragDepth values to third (depth) texture target (location = 2)?

#version 300 es
precision mediump float;

layout(location = 0) out vec4 fragColor1;
layout(location = 1) out vec4 fragColor2;

void main(void) {
   fragColor1 = vec4(1.0, 0.0, 0.0, 1.0); // printf of WebGL :)
   fragColor2 = vec4(1.0, 0.0, 0.0, 1.0);
}

Solution

  • You can only output one true depth value per fragment, but it sounds like you aren't doing so yet, so all you need to do is attach a DEPTH_ATTACHMENT to the framebuffer and write to gl_FragDepth in your fragment shader.