简体   繁体   中英

Texture coordinates in OpenGL

Sorry for a really noob-level question...

I want to apply a specific piece of the texture (not the entire texture) to a quad. The texture is a 256x64 image and I'd like to be able to specify the relevant piece by stating the pixel coordinates of its upper-left and bottom-right corners ( [0,0] being the upper left corner of the whole image and [256,64] being the bottom right).

Any ideas on how to do that?

Thanks.

The fractional answer is correct, but if you want to use integer texture coordinates (for example in a VBO) you can use the GL_TEXTURE matrix to change your texture coordinate system:

        glMatrixMode(GL_TEXTURE)
        glLoadIdentity()
        glScalef(1f/256f, 1f/64f, 1f)

After that your texture coordinate units would be pixels. Another scaling strategy would be to scale so each tile is 1x1 in the final units.

imagine you want to use the 20x20 texel starting at 10,10, you'd use the following coordinates:

[10.f/256.f,10.f/64.f]
[30.f/256.f,10.f/64.f]
[30.f/256.f,30.f/64.f]
[10.f/256.f,30.f/64.f]

You use float-based texture coordinates, where they range from (0.0f, 0.0f) to (1.0f, 1.0f). In your case, you take your pixel values and divide them by either 256-1 or 64-1, depending on which dimension you are dealing with. (This assumes you really meant to say that your image goes to [255,63] and not [256,64], meaning that your coordinates are 0-based and not 1-based.)

Let's look at the following, simplified example of 1D texture of 8 pixels width (the pixel centers are at the digits):

 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |

The corresponding texture coordinates are:

 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
0/8 1/8 2/8 3/8 4/8 5/8 6/8 7/8 8/8

Now if you want the subtexture from texels 3 to 7 the texture coordinates to use are 2/8 to 7/8.

You should also take note about something else: Integer texture coordinates don't address texel centers, but the exact mid between them; this may cause a blurred appearance in certain situations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM