In a fragment shader I get the UV coordinates of the current pixel in the range of [0.0,1.0]. However, I don't render the whole texture (thus in UV from 0.0 to 1.0), but only a sub rectangle of it. So the UV coordinates I get in this shader are only a sub range of [0.0,1.0], as the other parts are outside the rectangle that I render.
In my shader I do want to work with UV coordinates in the range of [0.0,1.0], but mapped to the sub rectangle of the texture that I render.
So my question is: given the total size of the texture and the sub rectangle of that texture that I render, how can I convert the given UV coordinates for the overall texture to the "inner" UV coordinates of my sub rectangle, but again also in the range [0.0,1.0]?
In the following I will use GLSL and the GLSL type vec2
which corresponds to the HLSL type float2
.
Suppose you have a texture with a size (vec2 tSize
) and a rectangular area in the texture from vec2 tMin;
to vec2 tMax
. You want to map the texture coordinate (vec2 uv
) in the range [0.0, 1.0] to the rectangular area in the texture. Either do the mapping with an expression using the formula val * (max - min) + min:
vec2 uvMapped = (uv * (tMax - tMin) + tMin) / tSize;
Or use the GLSL function mix
(GLSL mix
, corresponds to HLSL lerp
):
vec2 uvMapped = mix(tMin, tMax, uv) / tSize;