-
Notifications
You must be signed in to change notification settings - Fork 0
/
initShaders.js
81 lines (61 loc) · 1.94 KB
/
initShaders.js
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
//////////////////////////////////////////////////////////////////////////////
//
// initShaders.js
//
// Getting, compiling and linking the vertex and the fragment shaders
//
// J. Madeira - October 2015
//
//////////////////////////////////////////////////////////////////////////////
// Getting and compiling a shader
function getShader(gl, id) {
var shaderScript = document.getElementById(id);
if (!shaderScript) {
return null;
}
var str = "";
var k = shaderScript.firstChild;
while (k) {
if (k.nodeType == 3) {
str += k.textContent;
}
k = k.nextSibling;
}
var shader;
if (shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null;
}
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
//----------------------------------------------------------------------------
// Initializing the shader program
function initShaders( gl ) {
var fragmentShader = getShader(gl, "shader-fs");
var vertexShader = getShader(gl, "shader-vs");
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
gl.useProgram(shaderProgram);
// Shader input
// Vertex Coordinates
shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "vPosition");
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
// Vertex Normals
shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "vNormal");
gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);
return shaderProgram;
}