Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.content.Context;

import java.io.BufferedReader;
import java.io.IOException;

import java.io.InputStreamReader;

import static android.opengl.GLES20.GL_FRAGMENT_SHADER;

import static android.opengl.GLES20.GL_VERTEX_SHADER;
import static android.opengl.GLES20.glAttachShader;

import static android.opengl.GLES20.glCompileShader;
import static android.opengl.GLES20.glCreateProgram;
import static android.opengl.GLES20.glCreateShader;

import static android.opengl.GLES20.glLinkProgram;
import static android.opengl.GLES20.glShaderSource;

public class Main {
    public static String SOURCE_DEFAULT_NAME_FRAGMENT = "fragment.glsl";
    public static String SOURCE_DEFAULT_NAME_VERTEX = "vertex.glsl";

    public static int getProgram(Context context) {
        String vertexStr = getShaderSource(context, SOURCE_DEFAULT_NAME_VERTEX);
        String fragmentStr = getShaderSource(context, SOURCE_DEFAULT_NAME_FRAGMENT);
        return getProgram(vertexStr, fragmentStr);
    }

    public static int getProgram(String vertexStr, String fragmentStr) {
        int program = glCreateProgram();
        int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
        int vertexShader = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertexShader, vertexStr);
        glShaderSource(fragmentShader, fragmentStr);
        glCompileShader(vertexShader);
        glCompileShader(fragmentShader);
        glAttachShader(program, vertexShader);
        glAttachShader(program, fragmentShader);
        glLinkProgram(program);

        System.out.println("program:" + program);
        return program;
    }

    public static String getShaderSource(Context context, String sourseName) {
        StringBuffer shaderSource = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(context.getAssets().open(sourseName)));
            String tempStr = null;
            while (null != (tempStr = br.readLine())) {
                shaderSource.append(tempStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return shaderSource.toString();
    }
}