Getting pixel position in fragment shader

I’ve been trying to write a custom Cg shader that writes the model’s associated texture directly to the screen without applying any distortion or foreshortening (e.g. this tvtropes.org/pmwiki/pmwiki.php/M … ovingPlaid).

I can access the texture alright, but I can’t for the life of me find out how to get the position of the pixel currently being shaded by the fragment shader. Does anyone know how to do this?

It seems like it should be extremely straightforward, considering the code already knows where the pixel is, but the fragment shader doesn’t appear to.

Welcome to the forums!

The fragment position is calculated in the vertex shader (which is what you write to the output that is bound to the HPOS or POSITION semantic). You have to pass it separately (using a second variable, since POSITION is not a valid input semantic in the fragment shader), and finally do a perspective divide on it in your fragment shader (l_fragpos /= l_fragpos.w).

Now, l_fragpos.xy will contain the X and Y position of the fragment (in apiclip space, I think that this is either from -1 to 1 or from 0 to 1), and l_fragpos.z will contain the fragment depth.

If this is unclear, let me know, and I’ll write some example code.

Thanks. Got it working instantly after I read your post. I was calculating the fragment position in the vertex shader instead of the fragment shader, and that doesn’t seem to work (i presume something to do with it interpolating the fragment values wrongly).

I believe you have to wait with the perspective divide until after the values have been interpolated, so you can’t do it in the vertex shader.