Game Development Reference
In-Depth Information
Enabling Texturing
There's one more thing to complete before we can draw our triangle with the texture. We need
to bind the texture, and we need to tell OpenGL ES that it should actually apply the texture to
all triangles we render. Whether texture mapping is performed or not is another state of OpenGL
ES, which we can enable and disable with the following methods:
GL10.glEnable(GL10.GL_TEXTURE_2D);
GL10.glDisable(GL10.GL_TEXTURE_2D);
These look vaguely familiar. When we enabled/disabled vertex attributes in the previous
sections, we used
glEnableClientState()
/
glDisableClientState()
. As we noted earlier,
those are relics from the infancy of OpenGL itself. There's a reason why those are not
merged with
glEnable()
/
glDisable()
, but we won't go into that here. Just remember to use
glEnableClientState()
/
glDisableClientState()
to enable and disable vertex attributes, and
use
glEnable()
/
glDisable()
for any other states of OpenGL, such as texturing.
Putting It Together
With that out of our way, we can now write a small example that puts all of this together.
Listing 7-7 shows an excerpt of the
TexturedTriangleTest.java
source file, listing only the
relevant parts of the
TexturedTriangleScreen
class contained in it.
Listing 7-7. Excerpt from TexturedTriangleTest.java; Texturing a Triangle
class
TexturedTriangleScreen
extends
Screen {
final int
VERTEX_SIZE = (2 + 2) * 4;
GLGraphics glGraphics;
FloatBuffer vertices;
int
textureId;
public
TexturedTriangleScreen(Game game) {
super
(game);
glGraphics = ((GLGame) game).getGLGraphics();
ByteBuffer byteBuffer = ByteBuffer.
allocateDirect
(3 * VERTEX_SIZE);
byteBuffer.order(ByteOrder.
nativeOrder
());
vertices = byteBuffer.asFloatBuffer();
vertices.put(
new float
[] { 0.0f, 0.0f, 0.0f, 1.0f,
319.0f, 0.0f, 1.0f, 1.0f,
160.0f, 479.0f, 0.5f, 0.0f});
vertices.flip();
textureId = loadTexture("bobrgb888.png");
}
public int
loadTexture(String fileName) {
try
{
Bitmap bitmap = BitmapFactory.
decodeStream
(game.getFileIO().readAsset(fileName));
GL10 gl = glGraphics.getGL();