How to calculate gl_FragCoord in glsl

DaedalusFall picture DaedalusFall · Aug 17, 2009 · Viewed 23k times · Source

Ok, in my GLSL fragment shader I want to be able to calculate the distance of the fragment from a particular line in space.

The result of this is that I am first trying to use a varying vec2 set in my vertex shader to mirror what ends up in gl_FragCoord:

varying vec2 fake_frag_coord;
//in vertex shader:
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
fake_frag_coord=(gl_ModelViewProjectionMatrix * gl_Vertex).xy;

Now in the fragment shader I expect:

gl_FragCoord.xy==fake_frag_coord

But it does not. What operation does the pipeline do on gl_Position to turn it into gl_FragCoord that I am neglecting to do on fake_frag_coord?

Answer

Jay Kominek picture Jay Kominek · Aug 17, 2009

gl_FragCoord is screen coordinates, so you'd need to have information about the screen size and such to produce it based on the Position. The fake_frag_coord you've produced will correspond to a point in the screen in normalized device coordinates I think (-1 to 1). So if you were to multiply by half the screen's size in a particular dimension, and then add that size, you'd get actual screen pixels.