Handles all the opengl GLES20 calls to load and compile a vertex Shader - Android android.opengl

Android examples for android.opengl:OpenGL Shader

Description

Handles all the opengl GLES20 calls to load and compile a vertex Shader

Demo Code


//package com.java2s;

import android.opengl.GLES20;

public class Main {
    /**/*from w w w.  j a v  a  2  s .c o m*/
     * Handles all the GLES20 calls to load and compile a vertexShader
     * Some code taken from learnopengles.com
     * @param shader
     * @return
     */
    public static int loadShader(final int typeOfShader, final String shader) {
        if (typeOfShader == GLES20.GL_VERTEX_SHADER) {
            int vertexShaderHandle = GLES20
                    .glCreateShader(GLES20.GL_VERTEX_SHADER);

            if (vertexShaderHandle != 0) {
                //Pass in the shader source.
                GLES20.glShaderSource(vertexShaderHandle, shader);

                //Compile the shader.
                GLES20.glCompileShader(vertexShaderHandle);
                //Get the compile status, if it remains 0, terminate the shader.
                int[] compileStatus = { 0 };
                GLES20.glGetShaderiv(vertexShaderHandle,
                        GLES20.GL_COMPILE_STATUS, compileStatus, 0);

                if (compileStatus[0] == 0) {
                    GLES20.glDeleteShader(vertexShaderHandle);
                    vertexShaderHandle = 0;
                }
            }
            //If the shader didn't get created properly, throw an exception.
            if (vertexShaderHandle == 0) {
                throw new RuntimeException(
                        "The Vertex shader didn't get created");
            }

            return vertexShaderHandle;
        } else if (typeOfShader == GLES20.GL_FRAGMENT_SHADER) {
            int fragmentShaderHandle = GLES20
                    .glCreateShader(GLES20.GL_FRAGMENT_SHADER);

            //Create and compile the shader source.
            if (fragmentShaderHandle != 0) {
                //Pass in the shader source.
                GLES20.glShaderSource(fragmentShaderHandle, shader);
                //Compile the shader.
                GLES20.glCompileShader(fragmentShaderHandle);
                //Get compile status. If it's 0, terminate the shader.
                int[] compileStatus = { 0 };
                GLES20.glGetShaderiv(fragmentShaderHandle,
                        GLES20.GL_COMPILE_STATUS, compileStatus, 0);
                if (compileStatus[0] == 0) {
                    GLES20.glDeleteShader(fragmentShaderHandle);
                    fragmentShaderHandle = 0;
                }
            }
            return fragmentShaderHandle;
        }
        return 0;
    }
}

Related Tutorials