[SOLVED] How to invert MeshDepthMaterial to be black-nearest?

Hi all,

my question is rather simple but I cannot seem to find an answer - maybe too obvious.

How do I make my depth plane black-nearest?

function plane(){
  var material_plane =  new THREE.MeshDepthMaterial();
  var geometry_plane =  new THREE.PlaneGeometry(10000,10000);
  var mesh_plane = new THREE.Mesh(geometry_plane, material_plane);
  mesh_plane.rotation.x = -90 * Math.PI/180;
  mesh_plane.position.y = -50;
  scene.add(mesh_plane)
}

Thanks!

I believe you have to change depthMaterial fragment shader
here is the original fragment shader code:

You can change parts of it with material.onBeforeCompile() method
here is an example of that method:
https://threejs.org/examples/?q=material#webgl_materials_modified

Thanks for your reply. I was hoping for a simpler solution, will give it a shot though.

Try this code:

material_plane.onBeforeCompile = function ( shader ) {
  shader.fragmentShader = shader.fragmentShader.replace(
     'vec4 diffuseColor = vec4( 1.0 );',
     'vec4 diffuseColor = vec4( 0.0 );'
  );
};

if that didn’t work you can also try this code:

material_plane.onBeforeCompile = function (shader) {
  shader.fragmentShader = shader.fragmentShader.replace(
    'gl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );',
    'gl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );'
  ).replace(
    'gl_FragColor = packDepthToRGBA( gl_FragCoord.z );',
    'gl_FragColor = packDepthToRGBA( 1.0 - gl_FragCoord.z );'
  );
};
2 Likes

Fantastic, the second example works! Thanks!