Search code examples
iosopengl-esmetal

GLSL gl_FragDepth equivalent in Metal shaders


I'm looking to adjust a fragments depth in a Metal shader. Previously I was achieving this via GLSL's built-in output variable gl_FragDepth. Is there an equivalent approach using Apple's Metal shaders on iOS?


Solution

  • Yes, you specify this with the depth attribute on a member of the struct you return from your fragment shader. For example, you'd create a type such as:

    struct FragmentOut {
        half4 color [[color(0)]];
        float depth [[depth(any)]];
    };
    

    Then, in your fragment function, create an instance of this struct, populate, and return it:

    fragment FragmentOut my_frag_function(...) {
        FragmentOut out;
        out.color = // compute fragment color (for first color attachment)
        out.depth = // compute fragment depth
        return out;
    }
    

    Note that rather than any, you can specify one of greater or less as the depth attribute argument, which indicates that the fragment depth you provide will be, respectively, greater than or less than the interpolated fragment depth. The semantics of these specifiers match those of the same name in OpenGL, and you should use them when possible for optimization purposes.