Source

WebGL Beginner's Guide - Code / 1727_04 / ch4_CameraTypes.html

Full commit
  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
<html>

<head>
<title>WebGL Beginner's Guide - Chapter 4 - Camera Types</title>
<meta http-equiv='content-type' content='text/html; charset=ISO-8859-1'>

<!-- CSS Styles //-->
<link href='css/styles.css'   type='text/css' rel='stylesheet'>
<link href='css/prettify_desert.css'  type='text/css' rel='stylesheet'/>
<link href='css/colorpicker.css'  type='text/css' rel='stylesheet'/>
<link href='css/smoothness/jquery-ui-1.8.13.custom.css' type='text/css' rel='stylesheet' />
<!-- GUI Libraries //-->
<script type='text/javascript' src='js/gui/jquery-1.5.1.min.js'></script>
<script type='text/javascript' src='js/gui/jquery-ui-1.8.13.custom.min.js'></script> 
<script type='text/javascript' src='js/gui/colorpicker.js'></script>
<script type='text/javascript' src='js/gui/prettify.js'></script>
<script type='text/javascript' src='js/gui/codeview.js'></script>
<!-- MATH Libraries //-->
<script type='text/javascript' src='js/math/gl-matrix-min.js'></script>
<!-- WEBGL Libraries //-->
<script type='text/javascript' src='js/webgl/Globals.js'></script>
<script type='text/javascript' src='js/webgl/Utils.js'></script>
<script type='text/javascript' src='js/webgl/Program.js'></script>
<script type='text/javascript' src='js/webgl/Scene.js'></script>
<script type='text/javascript' src='js/webgl/Axis.js'></script>
<script type='text/javascript' src='js/webgl/Floor.js'></script>
<script type='text/javascript' src='js/webgl/Camera.js'></script>
<script type='text/javascript' src='js/webgl/CameraInteractor.js'></script>
<script type='text/javascript' src='js/webgl/WebGLApp.js'></script>



<script id="shader-vs" type="x-shader/x-vertex">
attribute vec3 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec4 aVertexColor;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform mat4 uNMatrix;
uniform bool uUpdateLight;
uniform vec3 uLightPosition; 
uniform vec4 uLightAmbient;  
uniform vec4 uLightDiffuse;  
uniform vec4 uMaterialDiffuse;
uniform bool uWireframe;
uniform bool uPerVertexColor;

varying vec4 vFinalColor;

void main(void) {

    if (uWireframe) {
        if (uPerVertexColor){
            vFinalColor = aVertexColor;
        }
        else{
            vFinalColor = uMaterialDiffuse;
        }
    }
    else{
        vec3 N = vec3(uNMatrix * vec4(aVertexNormal, 0.0));  // This is a vector w = 0;
        vec3 L = normalize(-uLightPosition);                 // Given a light position, use the inverse is the direction (to the center of the world)
        if(uUpdateLight){
            L = vec3(uNMatrix*vec4(L,0.0));   // vector light direction
        }
        
        float lambertTerm = dot(N,-L);
        if (lambertTerm == 0.0) lambertTerm = 0.01;
        vec4 Ia = uLightAmbient;
        vec4 Id = uMaterialDiffuse * uLightDiffuse * lambertTerm;
        vFinalColor = Ia + Id;
        vFinalColor.a = 1.0;
    }
    
    //Transformed vertex position
    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition,1.0); // vertex w=1
    
}
</script>

<script id="shader-fs" type="x-shader/x-fragment">
#ifdef GL_ES
precision highp float;
#endif

varying vec4  vFinalColor;

void main(void)  {
 gl_FragColor = vFinalColor;
}
</script>

<script id='code-js' type="text/javascript">

/**
*   Defines the initial values for the transformation matrices
*/
function initTransforms(){
    //Initialize Model-View matrix
    mvMatrix = camera.getViewTransform();
    
    //Initialize Perspective matrix
    mat4.identity(pMatrix);
    mat4.perspective(30, c_width / c_height, 0.1, 1000.0, pMatrix);
    
    //Initialize Normal matrix
    mat4.identity(nMatrix);
    mat4.set(mvMatrix, nMatrix);
    mat4.inverse(nMatrix);
    mat4.transpose(nMatrix);
    
 }

/**
*   Updates the Model-View matrix if there is any translation or change in 
*   coordinate system (world->camera or camera->world). Updates the Normal matrix according to the translation.
*   Please notice that the normal matrix will ALWAYS operate in world coordinates.
*   Called once per rendering cycle.
*/
function updateTransforms(){
    mat4.perspective(30, c_width / c_height, 0.1, 1000.0, pMatrix);  // We can resize the screen at any point so the perspective matrix should be updated always.
}


/**
* Maps the matrices to shader matrix uniforms
*
* Called once per rendering cycle. 
*/
function setMatrixUniforms(){
    
    gl.uniformMatrix4fv(prg.uMVMatrix, false, camera.getViewTransform());        //Maps the Model-View matrix to the uniform prg.uMVMatrix
    
    gl.uniformMatrix4fv(prg.uPMatrix, false, pMatrix);    //Maps the Perspective matrix to the uniform prg.uPMatrix
    
    mat4.transpose(camera.matrix, nMatrix);               //Calculates the Normal matrix 
    gl.uniformMatrix4fv(prg.uNMatrix, false, nMatrix);    //Maps the Normal matrix to the uniform prg.uNMatrix
    
    displayMatrix(camera.matrix);
}

/**
*  Configures the gl context
*/
var camera = null;
var interactor = null;

function configure(){
    
    gl.clearColor(0.3,0.3,0.3, 1.0);
    gl.clearDepth(100.0);
    gl.enable(gl.DEPTH_TEST);
    gl.depthFunc(gl.LEQUAL);
    
    //Creates and sets up the camera location
    camera = new Camera(CAMERA_TRACKING_TYPE);
    camera.goHome([0,2,50]);
    camera.hookRenderer = draw;
    camera.hookGUIUpdate = updateSliders;
    
    //Creates and sets up the mouse and keyboard interactor
    var canvas = document.getElementById('canvas-element-id');
    interactor = new CameraInteractor(camera, canvas);
    
    //Update gui with camera settings
    initGUIWithCameraSettings();
    
    //init transforms
    initTransforms();
}


/**
* Loads the scene
*/
function load(){
  
    Floor.build(80,2);
    Axis.build(82);
    Scene.addObject(Floor);
    Scene.addObject(Axis);
    Scene.loadObject('models/geometry/cone.json','cone');
}


/**
* invoked on every rendering cycle
*/
function draw() {
    gl.viewport(0, 0, c_width, c_height);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
        
    try{
        
        updateTransforms();   
        setMatrixUniforms(); 
        
        gl.uniform1i(prg.uUpdateLight,updateLightPosition);
        
        for (var i = 0; i < Scene.objects.length; i++){
            
            var object = Scene.objects[i];
            
            //Setting uniforms
            gl.uniform4fv(prg.uMaterialDiffuse, object.diffuse);
            gl.uniform1i(prg.uWireframe,object.wireframe);
            gl.uniform1i(prg.uPerVertexColor, object.perVertexColor);
            
            //Setting attributes
            gl.enableVertexAttribArray(prg.aVertexPosition);
            gl.disableVertexAttribArray(prg.aVertexNormal);
            gl.disableVertexAttribArray(prg.aVertexColor);
            
            gl.bindBuffer(gl.ARRAY_BUFFER, object.vbo);
            gl.vertexAttribPointer(prg.aVertexPosition, 3, gl.FLOAT, false, 0, 0);
            gl.enableVertexAttribArray(prg.aVertexPosition);
            
            if(!object.wireframe){
                gl.bindBuffer(gl.ARRAY_BUFFER, object.nbo);
                gl.vertexAttribPointer(prg.aVertexNormal, 3, gl.FLOAT, false, 0, 0);
                gl.enableVertexAttribArray(prg.aVertexNormal);
            }
            
            if (object.perVertexColor){
                gl.bindBuffer(gl.ARRAY_BUFFER, object.cbo);
                gl.vertexAttribPointer(prg.aVertexColor,4,gl.FLOAT, false, 0,0);
                gl.enableVertexAttribArray(prg.aVertexColor);
            }
            
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, object.ibo);
            
            if (object.wireframe){
                gl.drawElements(gl.LINES, object.indices.length, gl.UNSIGNED_SHORT,0);
            }
            else{
                gl.drawElements(gl.TRIANGLES, object.indices.length, gl.UNSIGNED_SHORT,0);
            }
            gl.bindBuffer(gl.ARRAY_BUFFER, null);
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
            
        }
    }
    catch(err){
        alert(err);
        console.error(err.description);
    }
}

/**
* Entry point. This function is invoked when the page is loaded
*/
var app = null;
function runWebGLApp() {
    app = new WebGLApp("canvas-element-id")
    app.configureGLHook = configure;
    app.loadSceneHook   = load;
    app.drawSceneHook   = draw;
    app.run();

}
</script>
</head>

<body onLoad='runWebGLApp()'>
<div id='top'>
<h1>WebGL Beginner's Guide - Chapter 4</h1>
<h2>Camera Types</h2>
<div id='logo-packt'><img src='packt.gif'/></div>
<p></p>
</div>

<div id='contents'>
<div id='canvasContainer'>
<canvas id='canvas-element-id' width='480' height='400'>
Your browser does not support the HTML5 canvas element.
</canvas>
</div>
</div>

<div id='bottom'>
<table style='padding=0px'>
<tr>
    <td> 
    <table cellspacing=4px style='vertical-align:top'>
        <tr>
            <td style='text-align:center'><b>Dolly</b></td>
            <td style='text-align:center'><b>Position</b></td>
            <td style='text-align:center'><b>Rotation</b></td>
            <td style='text-align:center'><b>Matrix</b></td>
        </tr>
        <tr>
            <td style='vertical-align:center;background-color:#EAE1B0'>
                <table>
                <tr rowspan='3'> </tr>
                <tr>
                    <td id='slider-dolly-value'>0.0</td>
                    <td style='text-align:center'>units</td>
                    <td><div id='slider-dolly'/></td>
                </tr>
                </table>
            </td>
            <td style='vertical-align:center;background-color:#D3CA9B'>
                <table>
                <tr>
                    <td>X:</td><td id='slider-position-x-value'>0.0</td><td>units</td><td width='150px'><div id='slider-position-x'/></td>
                </tr>
                <tr>
                    <td>Y:</td><td id='slider-position-y-value'>2.0</td><td style='text-align:center'>units</td><td width='150px'><div id='slider-position-y'/></td>
                </tr>
                <tr>
                    <td>Z:</td> <td id='slider-position-z-value'>50.0</td><td align='center'>units</td><td width='150px'><div id='slider-position-z'/></td>
                </tr>
                </table>
            </td>
            <td style='vertical-align:center;background-color:#EAE1B0'>
                <table>
                <tr>
                    <td>Elevation:</td><td id='slider-angle-x-value'>0.0</td><td>degrees</td><td width='150px'><div id='slider-angle-x'/></td>
                </tr>
                <tr>
                    <td>Azimuth:</td><td id='slider-angle-y-value'>0.0</td><td style='text-align:center'>degrees</td><td width='150px'><div id='slider-angle-y'/></td>
                </tr>
                </table>
            </td>
            <td align='center' style='vertical-align:top'>
                <table id='tbl-matrix'>
                <tr><td id='m0' style='font-weight:bold'></td><td id='m4' style='font-weight:bold'></td><td id='m8' style='font-weight:bold'></td><td id='m12'></td></tr>
                <tr><td id='m1' style='font-weight:bold'></td><td id='m5' style='font-weight:bold'></td><td id='m9' style='font-weight:bold'></td><td id='m13'></td></tr>
                <tr><td id='m2' style='font-weight:bold'></td><td id='m6' style='font-weight:bold'></td><td id='m10' style='font-weight:bold'></td><td id='m14'></td></tr>
                <tr><td id='m3'></td><td id='m7'></td><td id='m11'></td><td id='m15'></td></tr>
                </table>
            </td>
        </tr>     
        <tr>
            <td align='center' colspan='2'>
            <div id='opt-type' >
                    <input type='radio' id='opt-tracking' name='typecam' checked='checked'/><label for='opt-tracking'>Tracking</label>
                    <input type='radio' id='opt-orbiting' name='typecam'/><label for='opt-orbiting'>Orbiting</label>
                </div>
                </td>
            <td align='center' colspan='1'>
                <button id='btnGoHome'>Go Home</button>
                
                <input type="checkbox" id="chkUpdateLight" /><label for="chkUpdateLight">Update Light Position</label>
            </td>
        </tr>
    </table>
    </td>
</tr>
</table>
</div>
<script> 
$('#chkUpdateLight').button();
$('#opt-type').buttonset();
$('#btnGoHome').button();


$('#slider-position-x').slider({value:0.0, min:-70.0, max:70.0, step:0.5, slide:function(){updatePosition('#slider-position-x');}});
$('#slider-position-y').slider({value:2.0, min:-70.0, max:70.0, step:0.5, slide:function(){updatePosition('#slider-position-y');}});
$('#slider-position-z').slider({value:50.0, min:-70.0, max:70.0, step:0.5, slide:function(){updatePosition('#slider-position-z');}});

$('#slider-angle-x').slider({value:0.0, min:-180.0, max:180, step:1, slide:function(){updateElevation();}});
$('#slider-angle-y').slider({value:0.0, min:-180.0, max:180.0, step:1, slide:function(){updateAzimuth();}});

$('#slider-dolly').slider({orientation: "vertical",value:0.0, min:-150, max:150, step:1, slide:function(){updateDolly();}});



$('#chkUpdateLight').click(toggleLight);

$('#opt-tracking').click(function(){
    camera.goHome();
    updateSliders();
    
    console.info('CameraType = Tracking');
    camera.setType(CAMERA_TRACKING_TYPE);
    
    app.refresh();
});

$('#opt-orbiting').click(function(){
    camera.goHome();
    updateSliders();
    
    console.info('CameraType = Orbiting');
    camera.setType(CAMERA_ORBIT_TYPE);
    
    app.refresh();
});

function initGUIWithCameraSettings(){
    if(camera){ //global variable. Not very orthodox but hey it is JavaScript!
        var pos = camera.position;
        var st = Math.max(pos[0],pos[1] ,pos[2])/100;
        var maxv = 2* Math.max(pos[0],pos[1] ,pos[2]);
        
        $('#slider-position-x').slider({value:0.0, min:-maxv, max:maxv, step:st, slide:function(){updatePosition('#slider-position-x');}});
        $('#slider-position-y').slider({value:0.0, min:-maxv, max:maxv, step:st, slide:function(){updatePosition('#slider-position-y');}});
        $('#slider-position-z').slider({value:0.0, min:-maxv, max:maxv, step:st, slide:function(){updatePosition('#slider-position-z');}});

        $('#slider-dolly').slider({orientation: "vertical",value:0.0, min:-maxv, max:maxv, step:st, slide:function(){updateDolly();}});
       updateSliders();

    }
}

function updateDolly(){
    var step = $('#slider-dolly').slider("value");
    $('#slider-dolly-value').html(step);
    camera.dolly(step);
    updateSliders();
    app.refresh();
}

function toggleLight(){
    updateLightPosition = !updateLightPosition;
}

function updateElevation(){
    var elevation = $('#slider-angle-x').slider("value");
    $('#slider-angle-x-value').html(elevation);
    camera.setElevation(elevation);
    updateSliders();
    app.refresh();
}

function updateAzimuth(){
    var azimuth = $('#slider-angle-y').slider("value");
    $('#slider-angle-y-value').html(azimuth);
    camera.setAzimuth(azimuth);
    updateSliders();
    app.refresh();
}

function updatePosition(selector){
    var pos = $(selector).slider("value");
    var p = camera.position;
    $(selector+'-value').html(pos);
    
    if(selector == '#slider-position-x'){
        p[0] = pos;
    }
    else if(selector == '#slider-position-y'){
        p[1] = pos;
    }
    else if (selector == '#slider-position-z'){
        p[2] = pos;
    }
    camera.setPosition(p);
    app.refresh();
}


function updateSliders(){
    $('#slider-angle-x').slider("value",camera.elevation);
    $('#slider-angle-y').slider("value",camera.azimuth);
    
    $('#slider-angle-x-value').html(camera.elevation.toFixed(1));
    $('#slider-angle-y-value').html(camera.azimuth.toFixed(1));

    $('#slider-position-x').slider("value",camera.position[0]);
    $('#slider-position-y').slider("value",camera.position[1]);
    $('#slider-position-z').slider("value",camera.position[2]);
    $('#slider-position-x-value').html(camera.position[0].toFixed(1));
    $('#slider-position-y-value').html(camera.position[1].toFixed(1));
    $('#slider-position-z-value').html(camera.position[2].toFixed(1));     
    $('#slider-dolly-value').html(camera.steps);
    $('#slider-dolly').slider("value", camera.steps);
}



$('#btnGoHome').click(
    function(){
        camera.goHome();
        updateSliders();
        app.refresh();
});

function displayMatrix(m){
    var selector = '';
    for(var i=0;i<16;i++){
        selector = '#m'+i;
        $(selector).html(m[i].toFixed(1));
    }
}


</script>
<script>cview.run(cview.MODE_VIEW);</script>
</body>
</html>