PDA

View Full Version : Computing screen coordinates oddities



NeXEkho
12-25-2010, 05:29 AM
I would like to have access to the fragment's screen position from inside the fragment shader. I assumed I'd be able to take the clip space X/Y in the vertex shader and divide by the W to get a nice clean X/Y from -1 to 1. But this, err, doesn't seem to work. It's all distorted, clearly clinging to the shapes somewhat. But for some reason it works if I do the W divide in the fragment. I don't fancy wasting a lot of cycles (this is multiple additive passes) doing what could be interpolated if I can help it, any ideas why this works the way it does.

(Fragment version)

vec4 v4TransformMe = m4Transform * vec4( ( v3VertexIn * fFalloff ) + v3Position, 1.0 );

v3TexCoordOut = vec3( v4TransformMe.xy, v4TransformMe.w );

gl_Position = v4TransformMe;

v3TexCoordOut.xy / v3TexCoordOut.z

(Vertex interpolated version)

vec4 v4TransformMe = m4Transform * vec4( ( v3VertexIn * fFalloff ) + v3Position, 1.0 );

v3TexCoordOut = v4TransformMe.xy / v4TransformMe.w;

gl_Position = v4TransformMe;

(the nasty scale and position in the vertex shader is being replaced with a properly built matrix as soon as this is sorted, I swear ;])

I realise that depth is nonlinear, but I assumed that even so it's done on a vertex level and interpolated via fragment... is this not the case?

Dark Photon
12-26-2010, 08:19 AM
I would like to have access to the fragment's screen position from inside the fragment shader. I assumed I'd be able to take the clip space X/Y in the vertex shader and divide by the W to get a nice clean X/Y from -1 to 1. But this, err, doesn't seem to work. It's all distorted, clearly clinging to the shapes somewhat. But for some reason it works if I do the W divide in the fragment.

Check this out. They all say the same thing in different ways.

* http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.3.211&rep=rep1&type=pdf
* http://en.wikipedia.org/wiki/Texture_mapping#Perspective_correctness
* http://www.lysator.liu.se/~mikaelk/doc/perspectivetexture/
* http://www.gamedev.net/reference/articles/article331.asp

NeXEkho
12-26-2010, 06:10 PM
I see, thanks! I do recall that graphical artifact occurring on a number of Playstation games.

kRogue
01-02-2011, 12:02 AM
gl_FragCoord is a built in GLSL read only variable to get the position of the fragment from within a fragment shader, been there since atleast GLSL 1.1, i.e. OpenGL 2.0. Also available in GLSL of OpenGL ES2.