Wednesday, January 28, 2015

That One Bit of Graphics Programming Advice You Can Never Find When You Need It

Exactly reading texel (X,Y) from an texure that's W by H texels, in an interpolated sampler without clamping:

Accessing that spot in an array would be 0 to (W-1) horizontally and 0 to (H-1) vertically.
In texels, the coordinate of the center of the first texel on a row would not be 0, it would be 0.5.  And the coordinate of the last texel on that row would not be W-1, it would be (W-1)-0.5.
In that case, you have a range of W-2, startng from 0.5 and ending at W-1.5.  The same goes for H, a range of H-2 starting from 0.5 and ending at H-1.5.
To turn that into normalized (0 to 1) UV coordinates, divide by W-1 and H-1.

So in UV terms, that is:
U = (0.5 + X*(W-2)) / (W-1)
V = (0.5 + Y*(H-2)) / (H-1)

Example:
If the image is 256x512, then the texel addresses if it were an array would be 0-255 and 0-511, so
U = ((0.5 + X*254) / 255
V = ((0.5 + Y*510) / 511

And now I can look this up when I forget it.

No comments:

Post a Comment