2D texture is the most common texture type in OpenGLES. It is essentially a 2D image that adds details to the surface of an object. Texture coordinates range from 0 to 1. The figure below shows the texture coordinates and vertex coordinates in OpenGLES.
If we want to render a texture image, we can set the vertices and texture coordinates to be:
1 2 3 4 5 6 7 8 9 10 11 12 13
GLfloat vertices[] = { -1.0f, 0.5f, 0.0f, // Top left -1.0f, -0.5f, 0.0f, // Bottom left 1.0f, -0.5f, 0.0f, // Bottom right 1.0f, 0.5f, 0.0f, // Top right };
GLfloat textureCoords[] = { 0.0f, 0.0f, // top left 0.0f, 1.0f, // bottom left 1.0f, 1.0f, // bottom right 1.0f, 0.0f// top right };
OpenGL uses the winding order of the vertices to determine the “front” and “back” faces of a triangle. The default winding order is counter-clockwise (CCW) for front faces. So, when drawing a rectangle using two triangles, we can specify the order to be:
1
GLushort indices[] = { 0, 1, 2, 0, 2, 3 };
Generate 2D texture in OpenGL
1 2 3 4 5 6 7 8 9 10
// generate a texture glGenTextures(1, &mTextureID); // set the texture object as the current activate texture object glBindTexture(GL_TEXTURE_2D, mTextureID); // set texture wrapping glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, GL_NONE);
Load an RGBA image as texture.
On Kotlin side, we will load an jpeg as a bitmap, convert it to byteArray, and pass it down to native C++.
1 2 3 4 5 6 7 8 9 10 11 12
privatefunloadBitmap(resId: Int): Bitmap? { val fileStream = this.resources.openRawResource(resId) val bitmap: Bitmap? = BitmapFactory.decodeStream(fileStream) if (bitmap != null) { val buf = ByteBuffer.allocate(bitmap.byteCount) bitmap.copyPixelsToBuffer(buf) val byteArray = buf.array() mGLRender.setImageData(IMAGE_FORMAT_RGBA, bitmap.width, bitmap.height, byteArray) Log.d(TAG, "image width: ${bitmap.width}, image height: ${bitmap.height}") } return bitmap }