-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebGL_07_Normal_Map.html
More file actions
467 lines (404 loc) · 16.9 KB
/
WebGL_07_Normal_Map.html
File metadata and controls
467 lines (404 loc) · 16.9 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="HandheldFriendly" content="true" />
<meta charset="UTF-8">
<title>WebGL Demo 7: Normal Map</title>
<style>
html, body {
height: 100%;
}
body {
background-color: #111;
color: #DDD;
display: flex;
flex-direction: column;
font-family: Arial, Helvetica, sans-serif;
margin-top: 0px;
}
.flex {
flex: auto;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div><h1>WebGL Demo 7: Normal Map</h1></div>
<div class="flex">
<canvas id="renderCanvas">
Browser does not support HTML5
</canvas>
</div>
<div>Demo of the Earth with a normal map of the topology.</div>
</body>
<!-- Library for graphics related maxtrix math -->
<script src="lib/gl-matrix-min.js"></script>
<!-- Initialize WebGl canvas -->
<script>
function main(){
var canvas = document.getElementById("renderCanvas");
// load files and run the demo
loadAssets();
}
function loadAssets(){
var loadImage = function (url) {
return new Promise( function (resolve, reject) {
let img = new Image();
img.onload = function () {return resolve(img);};
img.onerror = function () {
return reject('Failed to load image from: ' + url);
};
img.src = url;
});
}
var loadText = async function (url) {
let responce = await fetch(url);
let status = responce.status;
if (200 <= status && status < 300){
return responce.text();
} else {
throw 'Failed to load text from: ' + url;
}
}
var loadJSON = async function (url) {
let responce = await fetch(url);
let status = responce.status;
if (200 <= status && status < 300){
return responce.json();
} else {
throw 'Failed to load JSON from: ' + url;
}
}
Promise.all([
loadImage('Earth/earth_true_color.jpg'),
loadText('Demo_7/vshader.glsl'),
loadText('Demo_7/fshader.glsl'),
loadJSON('sphere.json'),
loadImage('Earth/earth_specular.png'),
loadImage('Earth/earth_normMap.png')])
.then(function ([texture, vertShader, fragShader, model, specMap, normMap]) {
runDemo(vertShader, fragShader, model, texture, specMap, normMap);})
.catch(function (err) {console.error(err);});
}
function runDemo(vertexShaderText, fragmentShaderText, model, texture, specMap, normMap){
console.log('Working');
const canvas = document.getElementById('renderCanvas');
var context = 'webgl2';
var gl = canvas.getContext(context);
if(!gl){
context = 'webgl';
console.log('Attempting to use "' + context + '" context.');
gl = canvas.getContext(context);
}
if(!gl){
context = 'experimental-webgl';
console.log('Attempting to use "' + context + '" context.');
gl = canvas.getContext(context);
}
var internalFormat;
if(!gl){
console.error('WebGL not supported');
alert('WebGL not supported');
return;
} else if (context == 'webgl2'){
fragmentShaderText = '#define Convert_sRGB_to_Lin 0 \n' + fragmentShaderText;
internalFormat = gl.SRGB8_ALPHA8;
} else {
fragmentShaderText = '#define Convert_sRGB_to_Lin 1 \n' + fragmentShaderText;
internalFormat = gl.RGBA;
}
// Clears the canvas
gl.clearColor(0.05, 0.05, 0.05, 1.00);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.clear(gl.DEPTH_BUFFER_BIT);
// Prevent the back side (gl.BACK) of triangles from being drawn
// The front face is defined as counter-clockwise points (gl.CCW)
gl.enable(gl.CULL_FACE);
gl.frontFace(gl.CCW); // this is defualt front face
gl.cullFace(gl.BACK); // this is defualt culled face
//gl.cullFace(gl.FRONT);
// Only the closest geometry is visible (uses the depth buffer)
gl.enable(gl.DEPTH_TEST);
// Create Blank Shaders Object
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
// Set shader source code
gl.shaderSource(vertexShader, vertexShaderText);
gl.shaderSource(fragmentShader, fragmentShaderText);
// Compiler shader with source code
gl.compileShader(vertexShader);
gl.compileShader(fragmentShader);
// Check for compilation errors
if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)){
alert('ERROR compiling vertex shader!',
gl.getShaderInfoLog(vertexShader));
return;
}
if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)){
alert('ERROR compiling fragment shader!\n' + gl.getShaderInfoLog(fragmentShader));
return;
}
// Create and link the program to run the shaders
var program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
// Check for errors
if (!gl.getProgramParameter(program, gl.LINK_STATUS)){
alert('ERROR linking program\n' +
gl.getProgramInfoLog(program));
return;
}
gl.validateProgram(program);
if (!gl.getProgramParameter(program, gl.VALIDATE_STATUS)){
alert('ERROR validating program',
gl.getProgramInfoLog(program));
return;
}
// Specify vertices
// Typically this is 'model.meshes[i].vertices' in a JSON model;
var earthVertices = model.meshes[0].vertices;
// Specify normals
// Typically this is 'model.meshes[i].normals' in a JSON model;
var earthNormals = model.meshes[0].normals;
var earthTangents = model.meshes[0].tangents;
var earthBitangents = model.meshes[0].bitangents;
// Specify the texture coordinates
// Typically this is 'model.meshes[i].texturecoords[j]' in a JSON model;
var earthTexCoords = model.meshes[0].texturecoords[0];
// Specify the indices for each face
// Typically this is '[].concat.apply([], model.meshes[i].faces)' in a JSON model;
var earthIndices = [].concat.apply([], model.meshes[0].faces);
// Create buffers
// Set Attributes (shader inputs)
var earthVertexBufferObject = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, earthVertexBufferObject);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(earthVertices), gl.STATIC_DRAW);
var earthTexCoordBufferObject = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, earthTexCoordBufferObject);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(earthTexCoords), gl.STATIC_DRAW);
var earthNormBufferObject = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, earthNormBufferObject);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(earthNormals), gl.STATIC_DRAW);
var earthTanBufferObject = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, earthTanBufferObject);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(earthTangents), gl.STATIC_DRAW);
var earthBitanBufferObject = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, earthBitanBufferObject);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(earthBitangents), gl.STATIC_DRAW);
var earthIndexBufferObject = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, earthIndexBufferObject);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(earthIndices), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, earthVertexBufferObject);
var positionAttribLocation = gl.getAttribLocation(program, 'vertPosition');
gl.vertexAttribPointer(
positionAttribLocation, // Attribute location
3, // Number of elements per attribute (X, Y, Z)
gl.FLOAT, // Data type of the elements
gl.FALSE, // Whether the elements are normalized
3 * Float32Array.BYTES_PER_ELEMENT, // Size of an individual vertex
0 // Offset from the beginning of a single vertex to this attribute
);
gl.enableVertexAttribArray(positionAttribLocation); // Enables the attribute
gl.bindBuffer(gl.ARRAY_BUFFER, earthNormBufferObject);
var normalAttribLocation = gl.getAttribLocation(program, 'vertNormal');
gl.vertexAttribPointer(
normalAttribLocation, // Attribute location
3, // Number of elements per attribute (X, Y, Z)
gl.FLOAT, // Data type of the elements
gl.TRUE, // Whether the elements are normalized
3 * Float32Array.BYTES_PER_ELEMENT, // Size of an individual vertex
0 // Offset from the beginning of a single vertex to this attribute
);
gl.enableVertexAttribArray(normalAttribLocation); // Enables the attribute
gl.bindBuffer(gl.ARRAY_BUFFER, earthTanBufferObject);
var tangentAttribLocation = gl.getAttribLocation(program, 'vertTangent');
gl.vertexAttribPointer(
tangentAttribLocation, // Attribute location
3, // Number of elements per attribute (X, Y, Z)
gl.FLOAT, // Data type of the elements
gl.TRUE, // Whether the elements are normalized
3 * Float32Array.BYTES_PER_ELEMENT, // Size of an individual vertex
0 // Offset from the beginning of a single vertex to this attribute
);
gl.enableVertexAttribArray(tangentAttribLocation); // Enables the attribute
gl.bindBuffer(gl.ARRAY_BUFFER, earthNormBufferObject);
var bitanAttribLocation = gl.getAttribLocation(program, 'vertBitan');
gl.vertexAttribPointer(
bitanAttribLocation, // Attribute location
3, // Number of elements per attribute (X, Y, Z)
gl.FLOAT, // Data type of the elements
gl.TRUE, // Whether the elements are normalized
3 * Float32Array.BYTES_PER_ELEMENT, // Size of an individual vertex
0 // Offset from the beginning of a single vertex to this attribute
);
gl.enableVertexAttribArray(bitanAttribLocation); // Enables the attribute
gl.bindBuffer(gl.ARRAY_BUFFER, earthTexCoordBufferObject);
var texCoordAttribLocation = gl.getAttribLocation(program, 'vertTexCoord');
gl.vertexAttribPointer(
texCoordAttribLocation, // Attribute location
2, // Number of elements per attribute (S, T)
gl.FLOAT, // Data type of the elements
gl.FALSE, // Whether the elements are normalized
2 * Float32Array.BYTES_PER_ELEMENT, // Size of an individual vertex
0 // Offset from the beginning of a single vertex to this attribute
);
gl.enableVertexAttribArray(texCoordAttribLocation); // Enables the attribute
// Create texture
var earthTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, earthTexture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.texImage2D(
gl.TEXTURE_2D, // target (a 2D texture)
0, // level (level 0 is the base image)
internalFormat, // internal format
gl.RGBA, // format (in WebGL this needs to match the internal format)
gl.UNSIGNED_BYTE, // type (8 bits per channel for gl.SRGB)
texture // pixels (HTMLImageElement)
);
gl.generateMipmap(gl.TEXTURE_2D);
var earthSpec = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, earthSpec);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.texImage2D(
gl.TEXTURE_2D, // target (a 2D texture)
0, // level (level 0 is the base image)
gl.LUMINANCE, // internal format
gl.LUMINANCE, // format (in WebGL this needs to match the internal format)
gl.UNSIGNED_BYTE, // type (8 bits)
specMap // pixels (HTMLImageElement)
);
gl.generateMipmap(gl.TEXTURE_2D);
var earthNorm = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, earthNorm);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.texImage2D(
gl.TEXTURE_2D, // target (a 2D texture)
0, // level (level 0 is the base image)
gl.RGBA, // internal format
gl.RGBA, // format (in WebGL this needs to match the internal format)
gl.UNSIGNED_BYTE, // type (8 bits)
normMap // pixels (HTMLImageElement)
);
gl.generateMipmap(gl.TEXTURE_2D);
// Tells WebGL what program to use
gl.useProgram(program);
// Set uniforms (shader constants)
// Textures
var earthTextLoc = gl.getUniformLocation(program, "samplerText");
var earthSpecLoc = gl.getUniformLocation(program, "samplerSpec");
var earthNormLoc = gl.getUniformLocation(program, "samplerNorm");
gl.uniform1i(earthTextLoc, 0);
gl.uniform1i(earthSpecLoc, 1);
gl.uniform1i(earthNormLoc, 2);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, earthTexture);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, earthSpec);
gl.activeTexture(gl.TEXTURE2);
gl.bindTexture(gl.TEXTURE_2D, earthNorm);
// Matrices
var viewPositionLocation = gl.getUniformLocation(program, 'viewPos');
var matWorldUniformLocation = gl.getUniformLocation(program, 'mWorld');
var matViewUniformLocation = gl.getUniformLocation(program, 'mView');
var matProjUniformLocation = gl.getUniformLocation(program, 'mProj');
var viewPosition = [0, -5, 0];
var matWorld = new Float32Array(16);
var matView = new Float32Array(16);
var matProj = new Float32Array(16);
glMatrix.mat4.identity(matWorld);
glMatrix.mat4.lookAt(matView, viewPosition, [0, 0, 0], [0, 0, 1]);
glMatrix.mat4.perspective(matProj, glMatrix.glMatrix.toRadian(30), canvas.width / canvas.height, 0.1, 1000);
gl.uniform3fv(viewPositionLocation, new Float32Array(viewPosition));
gl.uniformMatrix4fv(matWorldUniformLocation, gl.FALSE, matWorld);
gl.uniformMatrix4fv(matViewUniformLocation, gl.FALSE, matView);
gl.uniformMatrix4fv(matProjUniformLocation, gl.FALSE, matProj);
// Lighting information
gl.useProgram(program);
var ambLightIntUniformLocation = gl.getUniformLocation(program, 'ambLightInt');
var sunlightIntUniformLocation = gl.getUniformLocation(program, 'sun.color');
var sunlightDirUniformLocation = gl.getUniformLocation(program, 'sun.direction');
gl.uniform3f(ambLightIntUniformLocation, 0.01, 0.01, 0.01);
gl.uniform3f(sunlightIntUniformLocation, 1.0, 1.0, 1.0);
gl.uniform3f(sunlightDirUniformLocation, 4.0, -3.0, 0.0);
// Main render loop for something like a game in JS (just for info)
/*
var loop = function () {
updateWorld();
renderWorld();
if (running)
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
*/
// Our main render loop
var identityMatrix = new Float32Array(16);
var xRotMat = new Float32Array(16);
var zRotMat = new Float32Array(16);
glMatrix.mat4.identity(identityMatrix);
var ang = 0;
function loop(){
// rotates the earth
ang = performance.now() / 1000 / 20 * 2 * Math.PI;
glMatrix.mat4.rotate(zRotMat, identityMatrix, ang, [0, 0, 1]);
glMatrix.mat4.rotate(xRotMat, identityMatrix, Math.PI/3*Math.sin(ang/3), [1, 0, 0]);
glMatrix.mat4.mul(matWorld, xRotMat, zRotMat);
gl.uniformMatrix4fv(matWorldUniformLocation, gl.FALSE, matWorld)
// Resize canvas
var resized = resizeCanvas(gl);
if (resized) {
var minFOV = glMatrix.glMatrix.toRadian(30);
var vertFOV = minFOV;
if (canvas.height > canvas.width) {
var distFOV = canvas.width / Math.tan(minFOV);
vertFOV = Math.atan(canvas.height / distFOV);
}
glMatrix.mat4.perspective(matProj, vertFOV, canvas.width / canvas.height, 0.1, 1000);
}
gl.uniformMatrix4fv(matProjUniformLocation, gl.FALSE, matProj)
// Clears the canvas
gl.clear(gl.COLOR_BUFFER_BIT);
gl.clear(gl.DEPTH_BUFFER_BIT);
// gl.bindTexture(gl.TEXTURE_2D, earthTexture);
// gl.activeTexture(gl.TEXTURE0);
gl.drawElements(gl.TRIANGLES, earthIndices.length, gl.UNSIGNED_SHORT, 0);
requestAnimationFrame(loop); // loop is called when a frame is requested
}
requestAnimationFrame(loop);
}
function resizeCanvas(gl) {
var canvas = gl.canvas;
if (!canvas)
return false;
var canvasBox = canvas.getBoundingClientRect();
var DPR = window.devicePixelRatio || 1;
var displayWidth = Math.round(canvasBox.width * DPR);
var displayHeight = Math.round(canvasBox.height * DPR);
if (canvas.width != displayWidth || canvas.height != displayHeight) {
canvas.width = displayWidth;
canvas.height = displayHeight;
gl.viewport(0, 0, displayWidth, displayHeight);
return true;
}
return false;
}
window.onload = main;
</script>
</html>