-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhello_webgl.js
executable file
·206 lines (175 loc) · 7.67 KB
/
hello_webgl.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
// This is a simplest WebGL program, which draw yellow square on the gray background.
const canvas = document.getElementById('webgl');
let gl = null; // WebGL rendering context
window.onload = initializeWebGL; // init WebGL when DOM is ready
window.addEventListener('resize', drawScene); // redraw when the window is resized
function initializeWebGL() {
if (!window.WebGLRenderingContext) {
console.log('WebGL is supported, but disabled :-(');
return;
}
gl = getWebGLContext(canvas); // initialize WebGL rendering context, if available
if (!gl) {
console.log('Your browser does not support WebGL.');
return;
}
console.log('WebGL is initialized.');
console.log(gl); // output the WebGL rendering context object to console for reference
console.log(gl.getSupportedExtensions()); // print list of supported extensions
// Vertex shader program
const vertexSource = `
attribute vec4 aVertexPosition;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
void main() {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
}
`;
// Fragment shader program
const fragmentSource = `
void main() {
gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0); // yellow color
}
`;
// Initialize a shader program; this is where all the lighting is established.
const shaderProgram = initShaderProgram(vertexSource, fragmentSource);
// Collect all the info needed to use the shader program. Look up which attribute
// shader program is using for aVertexPosition and look up uniform locations.
gl._programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
},
};
// Call the routine that builds all the drawing objects.
gl._buffers = initBuffers();
drawScene(); // draw the scene
}
// Get WebGL context, if standard is not available, then try on different alternatives
function getWebGLContext(canvas) {
return canvas.getContext('webgl') || // standard
canvas.getContext('experimental-webgl') || // Safari, etc.
canvas.getContext('moz-webgl') || // Firefox, Mozilla
canvas.getContext('webkit-3d'); // last try, Safari and maybe others
}
// Initialize a shader program, so WebGL knows how to draw the data.
function initShaderProgram(vertexSource, fragmentSource) {
const vertexShader = loadShader(gl.VERTEX_SHADER, vertexSource);
const fragmentShader = loadShader(gl.FRAGMENT_SHADER, fragmentSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));
return null;
}
return shaderProgram;
}
// Create shader of the given type, upload the source and compile it.
function loadShader(type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source); // send the source to the shader object
gl.compileShader(shader); // compile the shader program
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { // check if it compiled successfully
alert('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
// Initialize the buffers of a simple two-dimensional square.
function initBuffers() {
const positionBuffer = gl.createBuffer(); // create a buffer for the square's positions
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); // select the buffer
// Create an array of positions for the square.
const positions = [ 1.0, 1.0,
-1.0, 1.0,
1.0, -1.0,
-1.0, -1.0];
// Pass the list of positions into WebGL to build the shape by creating a Float32Array
// from the JavaScript array, then use it to fill the current buffer.
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
return { position: positionBuffer };
}
// Draw the scene.
function drawScene() {
resize(gl.canvas); // resize canvas if necessary
gl.clearColor(0.2, 0.2, 0.2, 1.0); // set screen clear color to gray, fully opaque
gl.clearDepth(1.0); // clear everything
gl.enable(gl.DEPTH_TEST); // enable depth testing
gl.depthFunc(gl.LEQUAL); // near things obscure far things
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // clear the canvas
const fieldOfView = 45 * Math.PI / 180; // FOV in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1; // see objects between 0.1 units and 100 units away from the camera
const zFar = 100.0;
const projectionMatrix = mat4.create();
// glmatrix.js always has the first argument as the destination to receive the result.
mat4.perspective(projectionMatrix,
fieldOfView,
aspect,
zNear,
zFar);
// Set the drawing position to the "identity" point, which is the center of the scene.
const modelViewMatrix = mat4.create();
// Move the drawing position a bit
mat4.translate(modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to translate
[-0.0, 0.0, -6.0]); // amount to translate
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
{
const numComponents = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, gl._buffers.position);
gl.vertexAttribPointer(
gl._programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset);
gl.enableVertexAttribArray(gl._programInfo.attribLocations.vertexPosition);
}
gl.useProgram(gl._programInfo.program); // tell WebGL to use our program when drawing
// Set the shader uniforms
gl.uniformMatrix4fv(
gl._programInfo.uniformLocations.projectionMatrix,
false,
projectionMatrix);
gl.uniformMatrix4fv(
gl._programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix);
{
const offset = 0;
const vertexCount = 4;
gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);
}
}
// Resize canvas if window is changed.
function resize(cnv) {
// Lookup the size the browser is displaying the canvas.
const displayWidth = cnv.clientWidth;
const displayHeight = cnv.clientHeight;
// Check if the canvas is not the same size.
if (cnv.width !== displayWidth ||
cnv.height !== displayHeight) {
// Make the canvas the same size
cnv.width = displayWidth;
cnv.height = displayHeight;
// First time WebGL set the viewport to match the size of the canvas,
// but after that it's up to you to set it.
gl.viewport(0, 0, cnv.width, cnv.height);
}
}