マイペースなプログラミング日記

DTMやプログラミングにお熱なd-kamiがマイペースに書くブログ

シェーダの読み込み部分を作った

やっつけなんで例外処理が適当だけど。もう少し頑張ったらシェーダ読み込む。ShaderExceptionは自分で作った例外クラス。まだ使ってないので動くか不明

package net.d_kami.mmd.reader;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

import android.opengl.GLES20;

public class ShaderReader {
    public static int createProgram(InputStream vertex, InputStream fragment) throws IOException, ShaderException{
        int program = GLES20.glCreateProgram();
        int vertexShader = ShaderReader.createShader(vertex, GLES20.GL_VERTEX_SHADER);
        int fragmentShader = ShaderReader.createShader(fragment, GLES20.GL_FRAGMENT_SHADER);
        int[] ret = new int[1];
        
        GLES20.glAttachShader(program, vertexShader);
        GLES20.glAttachShader(program, fragmentShader);
        GLES20.glLinkProgram(program);
        GLES20.glGetProgramiv(program, GLES20.GL_COMPILE_STATUS, ret, 0);
        
        if(ret[0] == 0){
            throw new ShaderException(GLES20.glGetProgramInfoLog(program));
        }
        
        GLES20.glDeleteShader(vertexShader);
        GLES20.glDeleteShader(fragmentShader);
        
        return program;
    }
    
    public static int createShader(InputStream in, int type) throws IOException, ShaderException{
        int[] ret = new int[1];
        
        int shader = GLES20.glCreateShader(type);
        GLES20.glShaderSource(shader, ShaderReader.readAll(in));
        GLES20.glCompileShader(shader);
        GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, ret, 0);
        
        if(ret[0] == 0){
            throw new ShaderException(GLES20.glGetShaderInfoLog(shader));
        }
        
        return shader;
    }
    
    public static String readAll(InputStream in) throws IOException{
        BufferedReader reader = null;
        StringBuilder text = new StringBuilder();
        
        try{
            reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line;
            
            while((line = reader.readLine()) != null){
                text.append(line);
            }
        }finally{
            if(reader != null){
                try{
                    reader.close();
                }catch(IOException ex){
                    throw ex;
                }
            }
        }
        
        return text.toString();
    }
}