alexrnov
alexrnov

Reputation: 2534

One pair of shaders for several objects in OpenGL ES 2.0

There are many simple similar 3D-objects in an android application. So that the initialization does not take very long, for all objects I used one pair of shaders (one linked program), like:

public class SceneRenderer implements GLSurfaceView.Renderer {
    
    private final int NUMBER = 400;
    private Object3D[] objects = new Object3D[NUMBER];
    
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config {
        LinkedProgram program = new LinkedProgram(vShader, fShader);
        int programObject = program.get();
        ...
        for (int i = 0; i < NUMBER; i++) {
            // use one program for all objects
            objects[i] = new Object3D(programObject);
        }
    }

    ...
    @Override
    public void onDrawFrame(GL10 gl) {
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, VBO[0]);
        for (int i = 0; i < NUMBER; i++) {
            objects[i].draw(); // draw all objects
        }
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
    }
}

Each 3D-object uses the same compiled program:

public class Object3D {
    ...
    public Object3D(int programObject) {
        this.programObject = programObject;
        mvpMatrixLink = GLES20.glGetUniformLocation(programObject, "mvp_matrix");
        colorLink = GLES20.glGetUniformLocation(programObject, "v_color");
        positionLink = GLES20.glGetAttribLocation(programObject, "a_position");
    }

    public draw() {
        GLES20.glUseProgram(programObject);
        GLES20.glUniformMatrix4fv(mvpMatrixLink, 1, false, mvpMatrix, 0);
        GLES20.glEnableVertexAttribArray(positionLink);
        GLES20.glVertexAttribPointer(positionLink, 3, GLES20.GL_FLOAT,
        false, 12, 0);
        GLES20.glUniform4fv(colorLink, 1, color, 0);
        ... // draw current 3D-object
    }
}

This works well - initialization is faster. But I have a question: is it safe to use this approach? Or should each 3D-object have its own compiled program?

Thank you for any comment/answer!

Upvotes: 0

Views: 94

Answers (1)

Columbo
Columbo

Reputation: 6766

is it safe to use this approach? Or should each 3D-object have its own compiled program?

Yes, it's safe. You should absolutely continue to do it this way, there are multiple benefits to doing so (reduced load time, reduced memory footprint, reduced state changes will reduce frame time).

Upvotes: 1

Related Questions