Search code examples
androidopengl-esfragment-shaderglsles

Is it possible to get the winding order in the fragment shader?


I am currently working with OpenGL ES 2.0 on Android and I find it a pretty expensive solution (in my case) to store a normal vector for each vertex or even for each fragment. I would like to determine the facing direction of the triangle in the fragment shader, having only position attributes of the vertices (and UV coordinates if that would help). Is there a way to implement this? As far as I know OpenGL knows the winding order of the triangles and takes advantage of it when rendering, however, I didn't find any solution to receive this information.


Solution

  • Yes, there is a built-in variable for this. It is named gl_FrontFacing, and is of type bool.

    For example, if you wanted to color the front facing triangles yellow, and the back facing triangles cyan, you would use the following in your fragment shader:

    if (gl_FrontFacing) {
        gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);
    } else {
        gl_FragColor = vec4(0.0, 1.0, 1.0, 1.0);
    }