package net.ddns.mahaljsp.opengl_glsurfaceview;

import android.opengl.GLES20;

/**
 * Created by Thomas Wu(mahaljsp@gmail.com) on 2017/1/10.
 */

public class MyShaderFactory {
    public static final String FIELD_POSITION = "vPosition";
    public static final String FIELD_COLOR = "vColor";
    private static final String SHADER_CODE_VERTEX =
            "attribute vec4 " + FIELD_POSITION  + ";" +
                    "void main(){" +
                    "   gl_Position = " + FIELD_POSITION  + ";" +
                    "}";

    private static final String SHADER_CODE_FRAGMENT =
            "precision mediump float;" +
                    "uniform vec4 " + FIELD_COLOR + ";"  +
                    "void main(){" +
                    "   gl_FragColor = " + FIELD_COLOR + ";"  +
                    "}";
    public static int getInstanceShader(){
        MyShaderFactory factory=new MyShaderFactory();
        return factory.createShaderProgram();
    }
    private int createShaderProgram(){
        int shaderProgram= GLES20.glCreateProgram();
        int vertexShader=loadShader(GLES20.GL_VERTEX_SHADER, SHADER_CODE_VERTEX);
        int fragmentShader=loadShader(GLES20.GL_FRAGMENT_SHADER, SHADER_CODE_FRAGMENT);
        GLES20.glAttachShader(shaderProgram, vertexShader);
        GLES20.glAttachShader(shaderProgram, fragmentShader);
        GLES20.glLinkProgram(shaderProgram);
        return shaderProgram;
    }
    private int loadShader(int type, String shaderCode){
        int shader = GLES20.glCreateShader(type);
        GLES20.glShaderSource(shader, shaderCode);
        GLES20.glCompileShader(shader);
        return shader;
    }
}
