Sampling the depth texture always returns 0

I have looked at this example and tried to do the same: set up a separate render target with a depth texture, then pass this depth texture as a uniform to a shader. Problem is, when I try to sample its values, all I ever get is 0!

So I create a target:

let depthTarget = new THREE.WebGLRenderTarget(canvas.width, canvas.height, {depthBuffer: true, depthTexture: new THREE.DepthTexture(canvas.width, canvas.height)});

I render to this target (the scene is a view of a terrain btw, and this terrain is just a plane with some vertex shader transformations):

renderer.setRenderTarget(depthTarget);
renderer.render(this.scene, this.camera);

Then I pass depthTarget.depthTexture as a uniform to a shader for another object from another scene. There doesn’t seem to be any error with how I set up the uniforms, seeing as passing any other texture, like an external image, works just fine.

I sample the texture in the fragment shader:

vec2 screenPos = vec2((gl_FragCoord.x) / width, (gl_FragCoord.y) / height);
gl_FragColor = vec4(texture2D(depthTexture, screenPos).x, 0, 0, 1);

(actually I plan to use it in a different manner – I need to reconstruct world position from depth – but when I started to suspect there was something wrong with the depth texture, this was how I decided to check)

If I now render this (separate) scene with an object that uses this shader that samples the depth texture, and read pixels from the render target, then I find that the value is always 0, which it really shouldn’t be, seeing as I have the object (a plane with vertices transformed from height map data on its vertex shader) visible… depthWrite is enabled for the material used to render the plane. Am I missing something else?

Hello, have you solved this problem now. I have the same problem.