Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

The problem you have is that gl_ModelViewProjectionMatrix * gl_Vertex computed in a shader is not always what the fixed function pipeline yields. To get identical results, do fake_frag_coord = ftransform().

Edit:

And then scale it with your screen dimensions.

I wish I had more rep so I could nitpick too. Here's what I know. OpenGL performs the Divide-By-W automatically for you, so by the time a position arrives in a fragment shader, it's already in NDC coordinates, and by then W will be 1.0, the only time you need to divide by W is if you want to do the same math on the CPU side, and get the same results, OR, if you for some odd reason, wanted to get NDC coordinates within your vertex shader.

varying vec2 fake_frag_coord;
//in vertex shader:

fake_frag_coord=(gl_ModelViewMatrix * gl_Vertex).xy
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top