Reputation: 11506
In OpenGL , sometimes when doing multi-pass rendering and post-processing I need to apply texels to the primitive's assembly fragments which are part of full screen texture composition.That is usually the case when the current pass comes from FBO texture to which the screen quad had been rendered during previous pass.To achieve this I calculate objects UV coordinates in SCREEN SPACE .In GLSL I calculate it like this:
vec2 texelSize = 1.0 / vec2(textureSize(TEXTURE, 0));
vec2 screenTexCoords = gl_FragCoord.xy * texelSize;
Now I am experimenting with Unity3D which uses CG/HLSL.The docs for these languages are poor.How can I calculate screen uv coordinates in CG/HLSL?
Upvotes: 2
Views: 6863
Reputation: 48347
To calculate screen texcoords, you typically pass the screen resolution or reciprocal thereof (res
or rcpres
) to the shader, then use the texcoords from your fullscreen quad (assuming a range of [0,1]
) modified by those.
Edit: Note that in many cases, you want both res
and rcpres
available. res
is useful for calculating the current position (you wouldn't want to use rcpres
for that, since it would then require division), but rcpres
can be calculated once on the CPU and is useful for moving by a single texel ((res * uv) + rcpres)
is one more texel from origin).
Something like:
float2 res; // contains the screen res, ie {640, 480}
void postEffect(in float2 uv : TEXCOORD, ...)
{
float2 pos = uv * res; // pos now contains your current position
The logic being that the coords coming from the fs quad are 0,0
at texel 0,0
and 1,1
at texel maxX,maxY
, so knowing the dimensions, you can just multiply.
You have to provide the value of res
to each effect, however, which depends on your shader system (Unity3D may do it already).
Upvotes: 3