Texture Class

To reduce the code needed for subsequent examples, I wrote a little helper class called Texture. It will load a bitmap from an asset and create a texture object from it. It also has a few convenience methods to bind the texture and dispose of it. Listing 7-8 shows the code.

Listing 7-8. Texture.java, a Little OpenGL ES Texture Class package com.badlogic.androidgames.framework.gl;

import java.io.IOException; import java.io.InputStream;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLUtils;

import com.badlogic.androidgames.framework.FileIO; import com.badlogic.androidgames.framework.impl.GLGame; import com.badlogic.androidgames.framework.impl.GLGraphics;

public class Texture { GLGraphics glGraphics; FileIO fileIO; String fileName; int textureId; int minFilter; int magFilter;

public Texture(GLGame glGame, String fileName) { this.glGraphics = glGame.getGLGraphics(); this.filelO = glGame.getFileIO(); this.fileName = fileName; load();

private void load() {

GL10 gl = glGraphics.getGL(); int[] texturelds = new int[l]; gl.glGenTextures(1, textureIds, 0); textureld = textureIds[0];

InputStream in = null; try {

in = filelO.readAsset(fileName); Bitmap bitmap = BitmapFactory.decodeStream(in); gl.glBindTexture(GL10.GL_TEXTURE_2D, textureld); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); setFilters(GL10.GL_NEAREST, GL10.GL_NEAREST); gl.glBindTexture(GL10.GL_TEXTURE_2D, 0); } catch(IOException e) {

throw new RuntimeException("Couldn't load texture '" + fileName + , e);

setFilters(minFilter, magFilter);

glGraphics.getGL().glBindTexture(GL10.GL_TEXTURE_2D, 0);

public void setFilters(int minFilter, int magFilter) { this.minFilter = minFilter; this.magFilter = magFilter; GL10 gl = glGraphics.getGL();

gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, minFilter); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, magFilter);

public void bind() {

GL10 gl = glGraphics.getGL(); gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);

public void dispose() {

GL10 gl = glGraphics.getGL(); gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId); int[] textureIds = { textureId }; gl.glDeleteTextures(1, textureIds, 0);

The only interesting thing about this class is the reload() method, which we can use when the OpenGL ES context is lost. Also note that the setFilters() method will only work if the Texture is actually bound. Otherwise it will set the filters of the currently bound texture.

We could also write a little helper method for our vertices buffer. But before we can do this we have to discuss one more thing: indexed vertices.

Was this article helpful?

0 0

Post a comment