0

I have some code that is very the same on the sample on android dev website. I must quite confuse as to why some programmers or tutorials put the getting of uniform location and the setting of attribporinter

 GLES20.glUseProgram(mProgram);

        // get handle to vertex shader's vPosition member
        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");

        // Enable a handle to the triangle vertices
        GLES20.glEnableVertexAttribArray(mPositionHandle);

        // Prepare the triangle coordinate data
        GLES20.glVertexAttribPointer(
                mPositionHandle, COORDS_PER_VERTEX,
                GLES20.GL_FLOAT, false,
                vertexStride, vertexBuffer);

        // get handle to fragment shader's vColor member
        mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");

        // Set color for drawing the triangle
        GLES20.glUniform4fv(mColorHandle, 1, color, 0);

        // get handle to shape's transformation matrix
        mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
        MyGLRenderer.checkGlError("glGetUniformLocation");

        // Apply the projection and view transformation
        GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
        MyGLRenderer.checkGlError("glUniformMatrix4fv");

        // Draw the triangle
        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);

        // Disable vertex array
        GLES20.glDisableVertexAttribArray(mPositionHandle);

to the on draw method?. From what i understand draw method is a loop. SO putting the declaration there will make the app slow?. Others on the other hand put that code on on surface created even though they have the same code. Which is the preferred way here?

genpfault
  • 51,148
  • 11
  • 85
  • 139
gamdevNoobie
  • 357
  • 1
  • 3
  • 8

2 Answers2

1

Fetching the attribute- and uniform-pointers in your initialization code, is the way to go, as they won't change throughout the lifetime of the application. I, suggest some tutorials initialize the pointers in onDraw() mostly for simplicity. Performance-wise, it won't make any noticeable difference anyways.

Harry Silver
  • 397
  • 2
  • 11
0

I always set those handles in onSurfaceCreated. As you correctly note, the onDraw method runs in a continuous loop (unless you've set the mode to RENDERMODE_WHEN_DIRTY) and those handles aren't going to change between iterations since you compile the vertex/fragment shaders just once in onSurfaceCreated.

However, it actually makes very little difference and won't make your app slow if you do put it in onDraw. OpenGL is doing a huge amount of work in onDraw, such as applying transformations and rendering primitives. Setting those handles is trivial in comparison and the additional overhead is tiny and won't be noticeable.

NigelK
  • 8,255
  • 2
  • 30
  • 28