-
Notifications
You must be signed in to change notification settings - Fork 4
/
J3DI.js
606 lines (528 loc) · 20.5 KB
/
J3DI.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
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
/*
* Copyright (C) 2009 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//
// initWebGL
//
// Initialize the Canvas element with the passed name as a WebGL object and return the
// WebGLRenderingContext.
function initWebGL(canvasName, vshader, fshader, attribs, clearColor, clearDepth)
{
var canvas = document.getElementById(canvasName);
return gl = WebGLUtils.setupWebGL(canvas);
}
function log(msg) {
if (window.console && window.console.log) {
window.console.log(msg);
}
}
// Load shaders with the passed names and create a program with them. Return this program
// in the 'program' property of the returned context.
//
// For each string in the passed attribs array, bind an attrib with that name at that index.
// Once the attribs are bound, link the program and then use it.
//
// Set the clear color to the passed array (4 values) and set the clear depth to the passed value.
// Enable depth testing and blending with a blend func of (SRC_ALPHA, ONE_MINUS_SRC_ALPHA)
//
// A console function is added to the context: console(string). This can be replaced
// by the caller. By default, it maps to the window.console() function on WebKit and to
// an empty function on other browsers.
//
function simpleSetup(gl, vshader, fshader, attribs, clearColor, clearDepth)
{
// create our shaders
var vertexShader = loadShader(gl, vshader);
var fragmentShader = loadShader(gl, fshader);
// Create the program object
var program = gl.createProgram();
// Attach our two shaders to the program
gl.attachShader (program, vertexShader);
gl.attachShader (program, fragmentShader);
// Bind attributes
for (var i = 0; i < attribs.length; ++i)
gl.bindAttribLocation (program, i, attribs[i]);
// Link the program
gl.linkProgram(program);
// Check the link status
var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked && !gl.isContextLost()) {
// something went wrong with the link
var error = gl.getProgramInfoLog (program);
log("Error in program linking:"+error);
gl.deleteProgram(program);
gl.deleteProgram(fragmentShader);
gl.deleteProgram(vertexShader);
return null;
}
gl.useProgram(program);
gl.clearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
gl.clearDepth(clearDepth);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
return program;
}
//
// loadShader
//
// 'shaderId' is the id of a <script> element containing the shader source string.
// Load this shader and return the WebGLShader object corresponding to it.
//
function loadShader(ctx, shaderId)
{
var shaderScript = document.getElementById(shaderId);
if (!shaderScript) {
log("*** Error: shader script '"+shaderId+"' not found");
return null;
}
if (shaderScript.type == "x-shader/x-vertex")
var shaderType = ctx.VERTEX_SHADER;
else if (shaderScript.type == "x-shader/x-fragment")
var shaderType = ctx.FRAGMENT_SHADER;
else {
log("*** Error: shader script '"+shaderId+"' of undefined type '"+shaderScript.type+"'");
return null;
}
// Create the shader object
var shader = ctx.createShader(shaderType);
// Load the shader source
ctx.shaderSource(shader, shaderScript.text);
// Compile the shader
ctx.compileShader(shader);
// Check the compile status
var compiled = ctx.getShaderParameter(shader, ctx.COMPILE_STATUS);
if (!compiled && !ctx.isContextLost()) {
// Something went wrong during compilation; get the error
var error = ctx.getShaderInfoLog(shader);
log("*** Error compiling shader '"+shaderId+"':"+error);
ctx.deleteShader(shader);
return null;
}
return shader;
}
//
// makeBox
//
// Create a box with vertices, normals and texCoords. Create VBOs for each as well as the index array.
// Return an object with the following properties:
//
// normalObject WebGLBuffer object for normals
// texCoordObject WebGLBuffer object for texCoords
// vertexObject WebGLBuffer object for vertices
// indexObject WebGLBuffer object for indices
// numIndices The number of indices in the indexObject
//
function makeBox(ctx)
{
// box
// v6----- v5
// /| /|
// v1------v0|
// | | | |
// | |v7---|-|v4
// |/ |/
// v2------v3
//
// vertex coords array
var vertices = new Float32Array(
[ 1, 1, 1, -1, 1, 1, -1,-1, 1, 1,-1, 1, // v0-v1-v2-v3 front
1, 1, 1, 1,-1, 1, 1,-1,-1, 1, 1,-1, // v0-v3-v4-v5 right
1, 1, 1, 1, 1,-1, -1, 1,-1, -1, 1, 1, // v0-v5-v6-v1 top
-1, 1, 1, -1, 1,-1, -1,-1,-1, -1,-1, 1, // v1-v6-v7-v2 left
-1,-1,-1, 1,-1,-1, 1,-1, 1, -1,-1, 1, // v7-v4-v3-v2 bottom
1,-1,-1, -1,-1,-1, -1, 1,-1, 1, 1,-1 ] // v4-v7-v6-v5 back
);
// normal array
var normals = new Float32Array(
[ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // v0-v1-v2-v3 front
1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // v0-v3-v4-v5 right
0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // v0-v5-v6-v1 top
-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // v1-v6-v7-v2 left
0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, // v7-v4-v3-v2 bottom
0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1 ] // v4-v7-v6-v5 back
);
// texCoord array
var texCoords = new Float32Array(
[ 1, 1, 0, 1, 0, 0, 1, 0, // v0-v1-v2-v3 front
0, 1, 0, 0, 1, 0, 1, 1, // v0-v3-v4-v5 right
1, 0, 1, 1, 0, 1, 0, 0, // v0-v5-v6-v1 top
1, 1, 0, 1, 0, 0, 1, 0, // v1-v6-v7-v2 left
0, 0, 1, 0, 1, 1, 0, 1, // v7-v4-v3-v2 bottom
0, 0, 1, 0, 1, 1, 0, 1 ] // v4-v7-v6-v5 back
);
// index array
var indices = new Uint8Array(
[ 0, 1, 2, 0, 2, 3, // front
4, 5, 6, 4, 6, 7, // right
8, 9,10, 8,10,11, // top
12,13,14, 12,14,15, // left
16,17,18, 16,18,19, // bottom
20,21,22, 20,22,23 ] // back
);
var retval = { };
retval.normalObject = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.normalObject);
ctx.bufferData(ctx.ARRAY_BUFFER, normals, ctx.STATIC_DRAW);
retval.texCoordObject = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.texCoordObject);
ctx.bufferData(ctx.ARRAY_BUFFER, texCoords, ctx.STATIC_DRAW);
retval.vertexObject = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.vertexObject);
ctx.bufferData(ctx.ARRAY_BUFFER, vertices, ctx.STATIC_DRAW);
ctx.bindBuffer(ctx.ARRAY_BUFFER, null);
retval.indexObject = ctx.createBuffer();
ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, retval.indexObject);
ctx.bufferData(ctx.ELEMENT_ARRAY_BUFFER, indices, ctx.STATIC_DRAW);
ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, null);
retval.numIndices = indices.length;
return retval;
}
//
// makeSphere
//
// Create a sphere with the passed number of latitude and longitude bands and the passed radius.
// Sphere has vertices, normals and texCoords. Create VBOs for each as well as the index array.
// Return an object with the following properties:
//
// normalObject WebGLBuffer object for normals
// texCoordObject WebGLBuffer object for texCoords
// vertexObject WebGLBuffer object for vertices
// indexObject WebGLBuffer object for indices
// numIndices The number of indices in the indexObject
//
function makeSphere(ctx, radius, lats, longs)
{
var geometryData = [ ];
var normalData = [ ];
var texCoordData = [ ];
var indexData = [ ];
for (var latNumber = 0; latNumber <= lats; ++latNumber) {
for (var longNumber = 0; longNumber <= longs; ++longNumber) {
var theta = latNumber * Math.PI / lats;
var phi = longNumber * 2 * Math.PI / longs;
var sinTheta = Math.sin(theta);
var sinPhi = Math.sin(phi);
var cosTheta = Math.cos(theta);
var cosPhi = Math.cos(phi);
var x = cosPhi * sinTheta;
var y = cosTheta;
var z = sinPhi * sinTheta;
var u = 1-(longNumber/longs);
var v = latNumber/lats;
normalData.push(x);
normalData.push(y);
normalData.push(z);
texCoordData.push(u);
texCoordData.push(v);
geometryData.push(radius * x);
geometryData.push(radius * y);
geometryData.push(radius * z);
}
}
for (var latNumber = 0; latNumber < lats; ++latNumber) {
for (var longNumber = 0; longNumber < longs; ++longNumber) {
var first = (latNumber * (longs+1)) + longNumber;
var second = first + longs + 1;
indexData.push(first);
indexData.push(second);
indexData.push(first+1);
indexData.push(second);
indexData.push(second+1);
indexData.push(first+1);
}
}
var retval = { };
retval.normalObject = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.normalObject);
ctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array(normalData), ctx.STATIC_DRAW);
retval.texCoordObject = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.texCoordObject);
ctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array(texCoordData), ctx.STATIC_DRAW);
retval.vertexObject = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.vertexObject);
ctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array(geometryData), ctx.STATIC_DRAW);
retval.numIndices = indexData.length;
retval.indexObject = ctx.createBuffer();
ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, retval.indexObject);
ctx.bufferData(ctx.ELEMENT_ARRAY_BUFFER, new Uint16Array(indexData), ctx.STREAM_DRAW);
return retval;
}
// Array of Objects curently loading
var g_loadingObjects = [];
// Clears all the Objects currently loading.
// This is used to handle context lost events.
function clearLoadingObjects() {
for (var ii = 0; ii < g_loadingObjects.length; ++ii) {
g_loadingObjects[ii].onreadystatechange = undefined;
}
g_loadingObjects = [];
}
//
// loadObj
//
// Load a .obj file from the passed URL. Return an object with a 'loaded' property set to false.
// When the object load is complete, the 'loaded' property becomes true and the following
// properties are set:
//
// normalObject WebGLBuffer object for normals
// texCoordObject WebGLBuffer object for texCoords
// vertexObject WebGLBuffer object for vertices
// indexObject WebGLBuffer object for indices
// numIndices The number of indices in the indexObject
//
function loadObj(ctx, url)
{
var obj = { loaded : false };
obj.ctx = ctx;
var req = new XMLHttpRequest();
req.obj = obj;
g_loadingObjects.push(req);
req.onreadystatechange = function () { processLoadObj(req) };
req.open("GET", url, true);
req.send(null);
return obj;
}
function processLoadObj(req)
{
log("req="+req)
// only if req shows "complete"
if (req.readyState == 4) {
g_loadingObjects.splice(g_loadingObjects.indexOf(req), 1);
doLoadObj(req.obj, req.responseText);
}
}
function doLoadObj(obj, text)
{
vertexArray = [ ];
normalArray = [ ];
textureArray = [ ];
indexArray = [ ];
var vertex = [ ];
var normal = [ ];
var texture = [ ];
var facemap = { };
var index = 0;
// This is a map which associates a range of indices with a name
// The name comes from the 'g' tag (of the form "g NAME"). Indices
// are part of one group until another 'g' tag is seen. If any indices
// come before a 'g' tag, it is given the group name "_unnamed"
// 'group' is an object whose property names are the group name and
// whose value is a 2 element array with [<first index>, <num indices>]
var groups = { };
var currentGroup = [-1, 0];
groups["_unnamed"] = currentGroup;
var lines = text.split("\n");
for (var lineIndex in lines) {
var line = lines[lineIndex].replace(/[ \t]+/g, " ").replace(/\s\s*$/, "");
// ignore comments
if (line[0] == "#")
continue;
var array = line.split(" ");
if (array[0] == "g") {
// new group
currentGroup = [indexArray.length, 0];
groups[array[1]] = currentGroup;
}
else if (array[0] == "v") {
// vertex
vertex.push(parseFloat(array[1]));
vertex.push(parseFloat(array[2]));
vertex.push(parseFloat(array[3]));
}
else if (array[0] == "vt") {
// normal
texture.push(parseFloat(array[1]));
texture.push(parseFloat(array[2]));
}
else if (array[0] == "vn") {
// normal
normal.push(parseFloat(array[1]));
normal.push(parseFloat(array[2]));
normal.push(parseFloat(array[3]));
}
else if (array[0] == "f") {
// face
if (array.length != 4) {
log("*** Error: face '"+line+"' not handled");
continue;
}
for (var i = 1; i < 4; ++i) {
if (!(array[i] in facemap)) {
// add a new entry to the map and arrays
var f = array[i].split("/");
var vtx, nor, tex;
if (f.length == 1) {
vtx = parseInt(f[0]) - 1;
nor = vtx;
tex = vtx;
}
else if (f.length = 3) {
vtx = parseInt(f[0]) - 1;
tex = parseInt(f[1]) - 1;
nor = parseInt(f[2]) - 1;
}
else {
obj.ctx.console.log("*** Error: did not understand face '"+array[i]+"'");
return null;
}
// do the vertices
var x = 0;
var y = 0;
var z = 0;
if (vtx * 3 + 2 < vertex.length) {
x = vertex[vtx*3];
y = vertex[vtx*3+1];
z = vertex[vtx*3+2];
}
vertexArray.push(x);
vertexArray.push(y);
vertexArray.push(z);
// do the textures
x = 0;
y = 0;
if (tex * 2 + 1 < texture.length) {
x = texture[tex*2];
y = texture[tex*2+1];
}
textureArray.push(x);
textureArray.push(y);
// do the normals
x = 0;
y = 0;
z = 1;
if (nor * 3 + 2 < normal.length) {
x = normal[nor*3];
y = normal[nor*3+1];
z = normal[nor*3+2];
}
normalArray.push(x);
normalArray.push(y);
normalArray.push(z);
facemap[array[i]] = index++;
}
indexArray.push(facemap[array[i]]);
currentGroup[1]++;
}
}
}
// set the VBOs
obj.normalObject = obj.ctx.createBuffer();
obj.ctx.bindBuffer(obj.ctx.ARRAY_BUFFER, obj.normalObject);
obj.ctx.bufferData(obj.ctx.ARRAY_BUFFER, new Float32Array(normalArray), obj.ctx.STATIC_DRAW);
obj.texCoordObject = obj.ctx.createBuffer();
obj.ctx.bindBuffer(obj.ctx.ARRAY_BUFFER, obj.texCoordObject);
obj.ctx.bufferData(obj.ctx.ARRAY_BUFFER, new Float32Array(textureArray), obj.ctx.STATIC_DRAW);
obj.vertexObject = obj.ctx.createBuffer();
obj.ctx.bindBuffer(obj.ctx.ARRAY_BUFFER, obj.vertexObject);
obj.ctx.bufferData(obj.ctx.ARRAY_BUFFER, new Float32Array(vertexArray), obj.ctx.STATIC_DRAW);
obj.numIndices = indexArray.length;
obj.indexObject = obj.ctx.createBuffer();
obj.ctx.bindBuffer(obj.ctx.ELEMENT_ARRAY_BUFFER, obj.indexObject);
obj.ctx.bufferData(obj.ctx.ELEMENT_ARRAY_BUFFER, new Uint16Array(indexArray), obj.ctx.STREAM_DRAW);
obj.groups = groups;
obj.loaded = true;
}
// Array of images curently loading
var g_loadingImages = [];
// Clears all the images currently loading.
// This is used to handle context lost events.
function clearLoadingImages() {
for (var ii = 0; ii < g_loadingImages.length; ++ii) {
g_loadingImages[ii].onload = undefined;
}
g_loadingImages = [];
}
//
// loadImageTexture
//
// Load the image at the passed url, place it in a new WebGLTexture object and return the WebGLTexture.
//
function loadImageTexture(ctx, url)
{
var texture = ctx.createTexture();
ctx.bindTexture(ctx.TEXTURE_2D, texture);
ctx.texImage2D(ctx.TEXTURE_2D, 0, ctx.RGBA, 1, 1, 0, ctx.RGBA, ctx.UNSIGNED_BYTE, null);
var image = new Image();
g_loadingImages.push(image);
image.onload = function() { doLoadImageTexture(ctx, image, texture) }
image.src = url;
return texture;
}
function doLoadImageTexture(ctx, image, texture)
{
g_loadingImages.splice(g_loadingImages.indexOf(image), 1);
ctx.bindTexture(ctx.TEXTURE_2D, texture);
ctx.texImage2D(
ctx.TEXTURE_2D, 0, ctx.RGBA, ctx.RGBA, ctx.UNSIGNED_BYTE, image);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, ctx.LINEAR);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, ctx.LINEAR);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_S, ctx.CLAMP_TO_EDGE);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_T, ctx.CLAMP_TO_EDGE);
//ctx.generateMipmap(ctx.TEXTURE_2D)
ctx.bindTexture(ctx.TEXTURE_2D, null);
}
//
// Framerate object
//
// This object keeps track of framerate and displays it as the innerHTML text of the
// HTML element with the passed id. Once created you call snapshot at the end
// of every rendering cycle. Every 500ms the framerate is updated in the HTML element.
//
Framerate = function(id)
{
this.numFramerates = 10;
this.framerateUpdateInterval = 500;
this.id = id;
this.renderTime = -1;
this.framerates = [ ];
self = this;
var fr = function() { self.updateFramerate() }
setInterval(fr, this.framerateUpdateInterval);
}
Framerate.prototype.updateFramerate = function()
{
var tot = 0;
for (var i = 0; i < this.framerates.length; ++i)
tot += this.framerates[i];
var framerate = tot / this.framerates.length;
framerate = Math.round(framerate);
document.getElementById(this.id).innerHTML = "Framerate:"+framerate+"fps";
}
Framerate.prototype.snapshot = function()
{
if (this.renderTime < 0)
this.renderTime = new Date().getTime();
else {
var newTime = new Date().getTime();
var t = newTime - this.renderTime;
if (t == 0)
return;
var framerate = 1000/t;
this.framerates.push(framerate);
while (this.framerates.length > this.numFramerates)
this.framerates.shift();
this.renderTime = newTime;
}
}