Sam - 1 year ago 113
Objective-C Question

# OpenGL Texture Coordinates in Pixel Space

I'm working on an iPhone app that uses OpenGL ES 2 for its drawing. I know that typically texture coordinates are defined in the 0-1 range, but ideally I'd like to map them from 0-1023 (the size of my TextureAtlas) for readability's sake. I've seen sample code that defines coordinates in this manner, but haven't been able to suss out what previous calls were made that allowed for this.

`glMatrixMode(GL_TEXTURE)`
seems like it might be involved, but I'm not quite sure how to implement it.

My end goal would be to accomplish something like this, where the texture I'd be using within the atlas is in the upper left 48px square:

``````GLshort texcoords[]={
48,48,
0,48,
48,0,
0,0,
};
glVertexAttribPointer(ATTRIB_TEXTUREPOSITON, 2, GL_SHORT, 0, 0, texcoords);
glEnableVertexAttribArray(ATTRIB_TEXTUREPOSITON);
``````

Turns out this is possible in OpenGl ES 2. Here's how I accomplished it:

``````precision mediump float;
varying vec2 v_texCoord;
uniform sampler2D textureSample;
uniform float texScale;
void main()
{
vec2 mult=(2.0*v_texCoord - 1.0)/(2.0*texScale);
gl_FragColor = texture2D(textureSample,mult);
}
``````

Obj-C:

``````GLshort texCoords[]={
512,512,
0,512,
512,0,
0,0,
};
GLfloat textureWidth = 512.0; //texture size, assumed square, power of 2
texCoordLoc = glGetAttribLocation ( program, "a_texCoord");
GLuint textureScale = glGetUniformLocation ( program, "texScale");
glUniform1f(textureScale, textureWidth);
glVertexAttribPointer ( texCoordLoc, 2, GL_SHORT, GL_FALSE, 0, texCoords);
``````

If anyone has comments on how this might work performance-wise, I would be interested.