Depth testing with transparency

I am mucking about a little bit with creating a custom material that extends RawShaderMaterial.

But I am having some issues with depth, that I could use some help with.

So here is my model (the pink parts). It is essentially the edge of a cylinder.

The dimmed part is the backside of the mesh that is wrapped around the cylinder.

So oddly enough, the backside is rendered on top of the frontside.

since the frontside is closer to the camera, I think this behavior is wrong.

In the constructor of my shader I have this

        super({
            uniforms,
            glslVersion: GLSL3,
            transparent: true,
            polygonOffset: true,
            polygonOffsetFactor: -0.1,
            depthTest: false,
            side: DoubleSide,
            vertexShader: vertex,
            fragmentShader: common.trim() + "\n" + fragment.trim()
        });

where super is the RawShaderMaterial.

I’ve tried fixing it by setting depthTest to true which almost works

the front face does indeed get rendered infront, but where the front is transparent it doesn’t fall back into the backside.

Is there something obvious I can do to fix it?
If I recall correctly, using a “normal” material doesn’t produce this issue. However I would prefer to fix my custom shader if possible.

I don’t know if it is relevant, but currently I am “setting” alpha like this in the shader

out vec4 fragColor;
...
void main() {
...
    fragColor = vec4(colour, alpha);
}

so it is nothing fancy.

1 Like

The polygons of geometry are rendered in the order they are in the buffer, distance to camera is not relevant here.

Alpha testing should do the trick:

void main() {
...
    if(alpha < 0.01) // adjust as needed
        discard;
    fragColor = vec4(colour, alpha);
    // fragColor = vec4(colour * alpha, alpha);
}

The edge might look bad; the commented line is for premultiplied alpha blending, which you should use here to get clean blending.

4 Likes

amazing!

first time seeing the discard keyword. Exactly what I needed and works like a charm :slight_smile: