1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
package de.gamezock.metacraft.ui;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.media.opengl.GL2;
public class ShaderLoader {
private static Map<Entry<String, String>, Integer> programs = new HashMap<Entry<String, String>, Integer>();
static private void printInfoLog(GL2 gl, int object) {
IntBuffer lengthBuffer = IntBuffer.allocate(1);
gl.glGetObjectParameterivARB(object, GL2.GL_OBJECT_INFO_LOG_LENGTH_ARB, lengthBuffer);
int length = lengthBuffer.get(0);
if(length > 0) {
ByteBuffer log = ByteBuffer.allocate(length);
IntBuffer foo = IntBuffer.allocate(1);
gl.glGetInfoLogARB(object, length, foo, log);
System.err.println(new String(log.array()));
}
}
static private String readStream(InputStream stream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String ret = "", line;
while ((line = reader.readLine()) != null) {
ret += line + "\n";
}
return ret;
}
static private int loadShader(GL2 gl, String name, int type) {
int shader = gl.glCreateShaderObjectARB(type);
try {
InputStream stream = ShaderLoader.class.getResourceAsStream("/de/gamezock/metacraft/resources/shaders/" + name);
String source = readStream(stream);
gl.glShaderSourceARB(shader, 1, new String[] {source}, null);
gl.glCompileShaderARB(shader);
printInfoLog(gl, shader);
return shader;
} catch (IOException e) {
}
if(shader != 0)
gl.glDeleteObjectARB(shader);
return 0;
}
static public boolean load(GL2 gl, String vsName, String fsName) {
Integer savedProg = programs.get(new AbstractMap.SimpleEntry<String, String>(vsName, fsName));
if(savedProg != null) {
gl.glUseProgram(savedProg);
return true;
}
int vs = loadShader(gl, vsName, GL2.GL_VERTEX_SHADER);
int fs = loadShader(gl, fsName, GL2.GL_FRAGMENT_SHADER);
if(vs != 0 && fs != 0) {
int program = gl.glCreateProgramObjectARB();
gl.glAttachObjectARB(program, vs);
gl.glAttachObjectARB(program, fs);
gl.glLinkProgramARB(program);
printInfoLog(gl, program);
gl.glUseProgramObjectARB(program);
programs.put(new AbstractMap.SimpleEntry<String, String>(vsName, fsName), program);
return true;
}
return false;
}
}
|