I am writing an open-source game engine for Android (here), and I am having a bit of trouble rendering textured triangles. OpenGL doesn’t report any errors, but nothing renders. I can render vertex-colored triangles just fine, so I know my VBO- and shader-loading functions work. I have a feeling that I’m just missing some little detail. Here’s the relevant code:
// loaded is a boolean field
if(!loaded ){
int[] tex = { 0 };
GLES20.glGenTextures(1, tex, 0);
int handle = tex[0];
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, handle);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S,
GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T,
GLES20.GL_CLAMP_TO_EDGE);
if (useMipmaps) {
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MIN_FILTER,
GLES20.GL_LINEAR_MIPMAP_NEAREST);
} else {
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
}
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
// bmp is an android.graphics.Bitmap object
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bmp, 0);
if (useMipmaps)
GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
loaded = true;
}
GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + glTexture);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, handle);
GLES20.glUniform1i(GLES20.glGetUniformLocation(programHandle,
"s_baseMap"), glTexture);
GLES20.glDrawElements(GLES20.GL_TRIANGLES,
indexCount, GLES20.GL_UNSIGNED_SHORT, 0);
The vertex shader:
precision mediump float;
uniform mat4 u_viewProj;
uniform vec3 u_lightColor;
attribute mat4 a_model;
attribute vec4 a_pos;
attribute vec2 a_mtl; // Stores UV coords
varying vec2 v_tc;
void main() {
gl_Position = (u_viewProj * a_model) * a_pos;
v_tc = a_mtl;
}
And the fragment shader:
precision mediump float;
varying vec2 v_tc;
uniform sampler2D s_baseMap;
void main() {
vec4 black = vec4(0.0, 0.0, 0.0, 1.0);
gl_FragColor = black + texture2D(s_baseMap, v_tc);
}
I solved it. The problem was not in the texturing or frag shader at all. It was in the way the model matrix attribute was loaded to the vertex shader. My matrix loading code was this:
Yup, this was part of the “unnecessary” code that I removed in my second edit. *facepalm*
Turns out,
a_modelis the location of the first row of the model matrix. Because I was only loading data to the first row, the last three rows of the matrix were empty, so the vertex positions were messed up and the triangles were made degenerate. I fixed this by adding 1 toa_modelfor each successive row, like so:Now it works perfectly!