Calculating screen texture coordinates in CG/HLSL

纵然是瞬间 提交于 2019-12-12 09:13:24

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/14204364/calculating-screen-texture-coordinates-in-cg-hlsl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!