- Home /
Get target RenderTexture dimensions in fragment shader used for Graphics.Blit
I'm resizing (scaling up) a texture by doing something like:
Material testMaterial = new Material(Shader.Find("Unlit/MyTestFragmentShader"));
Graphics.Blit(_sourceTex, renderTex, testMaterial);
where _sourceTex is a Texture2D and renderTex is a RenderTexture that is larger than _sourceTex by some integer multiple. So if, say, _sourceTex is 10x10, renderTex might be 40x40 for e.g., with each pixel of _sourcePixel ending up as 4x4 pixels in renderTex. I'm doing this in the Editor.
This is doing what I want. However, as a further step I would like, in my fragment shader, to put 1 pixel 'gaps' between what were the original pixels from the source. So for example _sourceTex is 10x10, renderTex is 40x40 but every 4th pixel (in both dimensions) is transparent - effectively each original pixel ends up as a 3x3 'cell' with a 1 pixel transparent border in both x and y.
To do this, in the fragment shader, I need to know how big each 'cell' is in the destination texture, which will be destination.width / source.width
. I know source width from _MainTex_TexelSize.z
and this works as expected. I thought I could use _ScreenParams.x
to get the target width, but _ScreenParams actually has the value the dimensions of Editor game view width, not the target RenderTexture dimensions.
I can just pass in the target RenderTexture dimensions as a property to the shader, and that will solve my problem, but is there any way of getting the actual RenderTexture dimensions in a similar way to _ScreenParams from inside the shader?
In theory, if you really needed to find the dimensions of the destination RT without passing them in yourself, you could use partial derivatives, i.e.
//Where zw is the destination's dimensions, and xy are the distance between texels
float4 texelSize;
texelSize.xy = abs (float2 (ddx (i.uv.x), ddy (i.uv.y)));
texelSize.zw = 1.0 / texelSize.xy;
It won't be as precise as the original, and I don't see a reason why you shouldn't be able to just pass in the texture's dimensions, but it should work.
No, sorry. I'm doing things a bit differently now - basically I just create the target render texture at the size it needs to be, then pass in the 'cell' size and the 'gap' size to the shader as properties, so I don't really need to worry about the target texture width in the shader.
Your answer
