I want to upload a simple texture to overlay the square I have drawn on the screen. The code without the texture shows a red square in the centre of the screen. Im editing this code to overlay the texture over the top, however every time I try to apply the texture to the square it distorts the image and moves across the screen. EDIT: Whole code available here: http://codetidy.com/6291/
Before texture applied:
After texture applied:
Some sample code:
void init()
// Create an OpenGL 2D texture from the BOX resource.
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_SRC_COLOR);
glGenTextures(1, &TextureHandle);
glBindTexture(GL_TEXTURE_2D, TextureHandle);
// Set texture parameters.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
maOpenGLTexImage2D(TEXTURE);
EDIT: Whole draw() function
void draw()
GLfloat vVertices[] = { -1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f
};
GLfloat TexCoord[] = {0.0, 1.0,
0.0, 0.0,
1.0, 1.0,
1.0, 0.0};
// Set the viewport
glViewport(0, 0, mWidth, mHeight);
// Clear the color buffer
glClear(GL_COLOR_BUFFER_BIT);
// Use the program object
glUseProgram(mShader);
checkGLError("glUseProgram");
glBindTexture(GL_TEXTURE_2D, TextureHandle);
// Set uniform function
glUniformMatrix4fv(mMvpLoc, 1, false, MyMatrix);
checkGLError("glUniform4fv");
//glActiveTexture(GL_TEXTURE0);
glUniform1i(mTextureLoc, 0);
// Load the vertex data, i.e attributes and quads
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, TexCoord);
checkGLError("glVertexAttribPointer");
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
checkGLError("glEnableVertexAttribArray");
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
checkGLError("glDrawArrays");
Vertex and fragment shader:
char vertexShaderSource[] =
"attribute vec4 vPosition; \n"
"uniform mat4 uMvp; \n"
"attribute vec2 TexCoordIn; \n"
"varying vec2 TexCoordOut; \n"
"void main() \n"
"{ \n"
"gl_Position = uMvp * vPosition; \n"
"TexCoordOut = TexCoordIn.xy; \n"
"} \n";
char fragmentShaderSource[] =
"precision highp float;\n"
"varying vec2 TexCoordOut;\n"
"uniform sampler2D Texture;\n"
"void main()\n"
"{\n"
"gl_FragColor = texture2D(Texture, TexCoordOut);\n"
"}\n";
Draw()
code and the part where vertex/texture coordinates are generated – c.s.