Tuesday, May 17, 2011

Applying Texture to Point Sprite

After successfully drawing Point on screen, I want to apply texture to point sprite.

Texture image is

As usual code can be downloaded from Google Code.

Changes made compared to previous post are.

  1. Vertex Shader : No Changes
  2. Fragment Shader :
    1. Added a uniform variable for texture id.
    2. Instead of defining Fragment color, will read from texture
  3. Rendering :
    1. Activate and Bind Texture
    2. Point uniform variable declared Fragment Shader

Remaining everything is same.
Let's look into changes made in detail

Fragment Shader

String strFShader =
                            "precision mediump float;" +
                            "uniform sampler2D u_baseMap;" +
                                "void main()" +
                                "{" +
                                        "vec4 color;" +
                                        "color = texture2D(u_baseMap, gl_PointCoord);" +
                                        "gl_FragColor = color;" +

u_baseMap variable for holding texture id, specified in OnDrawFrame

texture2D , a built-in function to fetch texture map.


 public void onDrawFrame(GL10 gl) {
                GLES20.glVertexAttribPointer(iPosition, 3, GLES20.GL_FLOAT, false, 0, vertBuffer);
                GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texId);
                GLES20.glUniform1i(iBaseMap, 0);
                GLES20.glDrawArrays(GLES20.GL_POINTS, 0, 1);

Yup, Only 3 lines of code, and first 2 lines of code is very familiar

Last line, GLES20.glUniform1i(iBaseMap, 0), is to load the uniform variable. which tells the shader to use the texture indexed 0.