GLProgramming.com

home :: about :: development guides :: irc :: forums :: search :: paste :: links :: contribute :: code dump

-> Click here to learn how to get live help <-



 
 

Development Guide Library


Pixel-based Texture co-ordinate range by Dranith

Motive

When I started with OpenGL one of the things I found most confusing was how texture coordinates had to be 0-1 no matter what. I asked around and always got that same answer. What I wanted is to be able to input texture coordinates in pixels. Well now that I know more, here is the code to set that up =).

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
void gldTexCoordRange(GLfloat max, GLfloat min = 0)
{
   // *NOTE* This assumes GL_TEXTURE is the current matrix
   GLdouble m[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};   

   // Set up the scale
   M(0, 0) = (GLdouble)(1/(max - min));
   M(1, 1) = (GLdouble)(1/(max - min));

   // Not needed as 3D textures aren't implemented yet
   M(2, 2) = (GLdouble)(1/(max - min));

   // Set up the translate
   M(0, 3) = min;
   M(1, 3) = min;
   M(2, 3) = min;                     // Again, not really needed

   // Fix the rest
   M(3, 3) = 1;

   // Add to current matrix
   glMultMatrixd(m);
}

Notes

If you are careful with matrix pushes and pops, this will only have to be called once, so I didn't bother with any optimisations at all. Wanted it to be straightforward and easy to read. Usage is as follows. If you want to set it up so you can input coordinates in 1-128 instead of 0-1:

glMatrixMode(GL_TEXTURE);
gldTexCoordRange(128 , 1);

Then, for example, the coordinate for the upper left corner of the texture would be:

glTexCoord2f(1, 128);

gldTexCoordRange assumes that the texture matrix is the current, if its not you may get some interesting side effects on your view.

--Dranith

 
Comments by GLProgramming users
 
Comment by felix_h05 17:40:23 13/Apr/2009