WebGL Beginner's Guide - Code / 1727_10 / ch10_PostProcessing.html

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

<head>
<title>WebGL Beginner's Guide - Chapter 10 - Post Process Effects</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/glMatrix-0.9.5.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/SceneTransforms.js'></script>
<script type='text/javascript' src='js/webgl/Texture.js'></script>
<script type='text/javascript' src='js/webgl/WebGLApp.js'></script>
<script type='text/javascript' src='js/webgl/PostProcess.js'></script>

<script id="shader-vs" type="x-shader/x-vertex">

attribute vec3 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec4 aVertexColor;
attribute vec2 aVertexTextureCoords;

uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform mat4 uNMatrix;
uniform vec3 uLightPosition;
uniform vec4 uMaterialDiffuse;
uniform bool uWireframe;
uniform bool uUseVertexColor;
uniform bool uUseTextures;

varying vec3 vNormal;
varying vec3 vLightRay;
varying vec3 vEyeVec;
varying vec4 vFinalColor;
varying vec2 vTextureCoord;

void main(void) {
    
 vFinalColor = uMaterialDiffuse;
 vTextureCoord = vec2(0.0);

 if (uUseVertexColor){
    vFinalColor = aVertexColor;
 }
 
 if (uUseTextures){
    vTextureCoord = aVertexTextureCoords;
 }

 vec4 vertex = uMVMatrix * vec4(aVertexPosition, 1.0);
 vNormal = vec3(uNMatrix * vec4(aVertexNormal, 1.0));
 vec4 light = vec4(uLightPosition,1.0);
 vLightRay = vertex.xyz-light.xyz;
 vEyeVec = -vec3(vertex.xyz);
 
 gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
 
}	
</script>

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

uniform bool uWireframe;
uniform bool uUseTextures; 

uniform vec4 uLightAmbient;
uniform vec4 uLightDiffuse;
uniform vec4 uMaterialAmbient;
uniform vec4 uMaterialDiffuse;
uniform bool uOffscreen;  

uniform sampler2D uSampler;  

varying vec3 vNormal; 
varying vec3 vLightRay;
varying vec3 vEyeVec;
varying vec4 vFinalColor;
varying vec2 vTextureCoord;

void main(void)
{
    if(uOffscreen){
        gl_FragColor = uMaterialDiffuse;
        return;
    }
    
    if(uWireframe){
        gl_FragColor = vFinalColor;
    }
    else{
        //ambient term
        vec4 Ia = uLightAmbient * uMaterialAmbient;
        
        //diffuse term
        vec3 L = normalize(vLightRay);
        vec3 N = normalize(vNormal);
        float lambertTerm = max(dot(N,-L),0.33);
        vec4 Id = uLightDiffuse * uMaterialDiffuse * lambertTerm; 
        
        //specular term
        vec3 E = normalize(vEyeVec);
        vec3 R = reflect(L, N);
        float specular = pow( max(dot(R, E), 0.5), 50.0);
        vec4 Is = vec4(0.5) * specular;

        //result
        vec4 finalColor = Ia + Id + Is;
        
        if (uMaterialDiffuse.a != 1.0) {   
            finalColor.a = uMaterialDiffuse.a; 
        }
        else {
            finalColor.a = 1.0;
        }
       
        if (uUseTextures){
            gl_FragColor =  finalColor * texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
        }
        else{
            gl_FragColor = finalColor;
        }
    }

}
</script>

<script id="post-common-vs" type="x-shader/x-vertex">
attribute vec2 aVertexPosition;
attribute vec2 aVertexTextureCoords;

varying vec2 vTextureCoord;

void main(void) {
    vTextureCoord = aVertexTextureCoords;
    gl_Position = vec4(aVertexPosition, 0.0, 1.0);
}
</script>

<script id="post-normal" type="x-shader/x-fragment">
precision highp float;

uniform sampler2D uSampler;

varying vec2 vTextureCoord;

void main(void)
{
    vec4 frameColor = texture2D(uSampler, vTextureCoord);
    gl_FragColor = frameColor;
}
</script>

<script id="post-greyscale" type="x-shader/x-fragment">
precision highp float;

uniform sampler2D uSampler;

varying vec2 vTextureCoord;

void main(void)
{
    vec4 frameColor = texture2D(uSampler, vTextureCoord);
    float luminance = frameColor.r * 0.3 + frameColor.g * 0.59 + frameColor.b * 0.11;
    gl_FragColor = vec4(luminance, luminance, luminance, frameColor.a);
}
</script>

<script id="post-invert" type="x-shader/x-fragment">
precision highp float;

uniform sampler2D uSampler;

varying vec2 vTextureCoord;

void main(void)
{
    vec4 frameColor = texture2D(uSampler, vTextureCoord);
    gl_FragColor = vec4(1.0-frameColor.r, 1.0-frameColor.g, 1.0-frameColor.b, frameColor.a);
}
</script>

<script id="post-blur" type="x-shader/x-fragment">
precision highp float;

uniform sampler2D uSampler;
uniform vec2 uInverseTextureSize;

varying vec2 vTextureCoord;

vec4 offsetLookup(float xOff, float yOff) {
    return texture2D(uSampler, vec2(vTextureCoord.x + xOff*uInverseTextureSize.x, vTextureCoord.y + yOff*uInverseTextureSize.y));
}

void main(void)
{
    vec4 frameColor = offsetLookup(-4.0, 0.0) * 0.05;
    frameColor += offsetLookup(-3.0, 0.0) * 0.09;
    frameColor += offsetLookup(-2.0, 0.0) * 0.12;
    frameColor += offsetLookup(-1.0, 0.0) * 0.15;
    frameColor += offsetLookup(0.0, 0.0) * 0.16;
    frameColor += offsetLookup(1.0, 0.0) * 0.15;
    frameColor += offsetLookup(2.0, 0.0) * 0.12;
    frameColor += offsetLookup(3.0, 0.0) * 0.09;
    frameColor += offsetLookup(4.0, 0.0) * 0.05;

    gl_FragColor = frameColor;
}
</script>

<script id="post-wavy" type="x-shader/x-fragment">
precision highp float;

uniform sampler2D uSampler;
uniform float uTime;

varying vec2 vTextureCoord;

const float speed = 15.0;
const float magnitude = 0.015;

void main(void)
{
    vec2 wavyCoord;
    wavyCoord.s = vTextureCoord.s + (sin(uTime+vTextureCoord.t*speed) * magnitude);
    wavyCoord.t = vTextureCoord.t + (cos(uTime+vTextureCoord.s*speed) * magnitude);
    vec4 frameColor = texture2D(uSampler, wavyCoord);
    gl_FragColor = frameColor;
}
</script>

<script id="post-filmgrain" type="x-shader/x-fragment">
precision highp float;

uniform sampler2D uSampler;
uniform sampler2D uNoiseSampler;
uniform vec2 uInverseTextureSize;
uniform float uTime;

varying vec2 vTextureCoord;

const float grainIntensity = 0.1;
const float scrollSpeed = 4000.0;

void main(void)
{
    vec4 frameColor = texture2D(uSampler, vTextureCoord);
    vec4 grain = texture2D(uNoiseSampler, vTextureCoord * 2.0 + uTime * scrollSpeed * uInverseTextureSize);
    gl_FragColor = frameColor - (grain * grainIntensity);
}
</script>

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

var camera 		= null;
var interactor 	= null;
var post 		= null;
var transforms	= null;
var showPickingImage 	= false;
var noiseTexture = 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.LESS);
	gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);
    
    //Creates and sets up the camera location
    camera = new Camera(CAMERA_ORBITING_TYPE);
    camera.goHome([0,0,40]);
    camera.setFocus([0.0,0.0,0.0]);
    camera.setElevation(-40);
    camera.setAzimuth(-30);
    camera.hookRenderer = render;
    
    
    var canvas  = document.getElementById('canvas-element-id');
    
    //Post Process
    post = new PostProcess(canvas, "post-normal");

    // Noise texture, for use in the "film grain" post process effect
    noiseTexture = new Texture();
    noiseTexture.setImage("textures/noise.png");
    
    //Creates and sets up the mouse and keyboard interactor
    interactor = new CameraInteractor(camera, canvas);
        
    //Scene Transforms
    transforms = new SceneTransforms(camera);
   
    //init transforms
    transforms.init();
    
    //Program
    attributeList = ["aVertexPosition",
                    "aVertexNormal",
                    "aVertexColor",
                    "aVertexTextureCoords"];

    uniformList = [	"uPMatrix", 
                    "uMVMatrix", 
                    "uNMatrix",
                    "uMaterialDiffuse",
                    "uMaterialAmbient",
                    "uLightAmbient",
                    "uLightDiffuse",
                    "uLightPosition",
                    "uWireframe",
                    "uAlpha",
                    "uUseVertexColor",
                    "uOffscreen",
                    "uSampler",
                    "uUseTextures"
                    ];
    
    
    Program.load(attributeList, uniformList);
    
    gl.uniform3fv(Program.uLightPosition,   [0,5,20]);
    gl.uniform4fv(Program.uLightAmbient,    [1.0,1.0,1.0,1.0]);
    gl.uniform4fv(Program.uLightDiffuse,    [1.0,1.0,1.0,1.0]);
    gl.uniform1f(Program.uAlpha, 1.0);
}

/**
* Loads the scene
*/
function load(){
    Floor.build(80,2);
    Scene.addObject(Floor);
    Scene.loadObject('models/geometry/ball.json',   'ball', {position:[  0, 0, -4],    scale:[3,3,3]});
    Scene.loadObject('models/geometry/ball.json',   'disk',{position:[  -10, 0, -10], scale:[3,0.5,3],  diffuse:[0.3,0.1,0.9,0.5]});
    Scene.loadObject('models/geometry/flag.json',   'flag', {position:[-10, 0 ,0],     scale:[1,1,1]});
    Scene.loadObject('models/geometry/cone.json',   'cone', {position:[ 10, 0, 5],     scale:[1,1,1]});
    Scene.loadObject('models/geometry/cone.json',   'cone2',{position:[ -7, 0, 2],     scale:[0.5,1,0.5], diffuse:[0.3,0.3,0.6,1.0]});
    Scene.loadObject('models/geometry/texCube.json','cube', {position:[1,2,7],         scale:[4,4,4],     ambient:[0.4,0.4,0.4,1.0]});
}

function render(){
    // Checks to see if the framebuffer needs to be resized to match the canvas
    post.validateSize();

    //Render scene to framebuffer
    gl.bindFramebuffer(gl.FRAMEBUFFER, post.framebuffer);
    draw();

    // Set up the post-process effect for rendering
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
    post.bind();

    // Do any additional post-process shader uniform setup here
    if(post.uniform.uNoiseSampler) {
        gl.activeTexture(gl.TEXTURE1);
        gl.bindTexture(gl.TEXTURE_2D, noiseTexture.tex);
        gl.uniform1i(post.uniform.uNoiseSampler, 1);
    }

    //Re-render scene from framebuffer with post process effect
    post.draw();
}

/**
* 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);
    transforms.updatePerspective();
    try{
        gl.useProgram(prg);
        var offscreen  = Program.getUniform(Program.uOffscreen);
        
        for (var i = 0; i < Scene.objects.length; i++){
                
            var object = Scene.objects[i];
            
            if(object.diffuse[3] < 1.0 && !offscreen) {
				gl.disable(gl.DEPTH_TEST);
				gl.enable(gl.BLEND);
			} else {
				gl.enable(gl.DEPTH_TEST);
				gl.disable(gl.BLEND);
			}

            transforms.calculateModelView();           
            transforms.push();
            if (object.alias != 'floor'){
                mat4.translate(transforms.mvMatrix, object.position);
                mat4.scale(transforms.mvMatrix, object.scale);
            }
            transforms.setMatrixUniforms();
            transforms.pop();

            //Setting uniforms
            gl.uniform4fv(Program.uMaterialDiffuse, object.diffuse);
            gl.uniform4fv(Program.uMaterialAmbient, object.ambient);
            gl.uniform1i(Program.uWireframe,object.wireframe);
            gl.uniform1i(Program.uUseVertexColor, false);
            gl.uniform1i(Program.uUseTextures, false);
            
            //Setting attributes
            gl.enableVertexAttribArray(Program.aVertexPosition);
            gl.disableVertexAttribArray(Program.aVertexNormal);
            gl.disableVertexAttribArray(Program.aVertexColor);
            gl.disableVertexAttribArray(Program.aVertexTextureCoords);
            
            //Bind Array Buffer
            gl.bindBuffer(gl.ARRAY_BUFFER, object.vbo);
            gl.vertexAttribPointer(Program.aVertexPosition, 3, gl.FLOAT, false, 0, 0);
            gl.enableVertexAttribArray(Program.aVertexPosition);

            //render scalars
            if (object.scalars != null){
                gl.enableVertexAttribArray(Program.aVertexColor);
                gl.uniform1i(Program.uUseVertexColor, true);
                gl.bindBuffer(gl.ARRAY_BUFFER, object.cbo);
                gl.vertexAttribPointer(Program.aVertexColor, 4, gl.FLOAT, false, 0, 0);
                
            }
            
            //render textures
            if (object.texture_coords){
                gl.enableVertexAttribArray(Program.aVertexTextureCoords);
                gl.uniform1i(Program.uUseTextures, true);
                gl.bindBuffer(gl.ARRAY_BUFFER, object.tbo);
                gl.vertexAttribPointer(Program.aVertexTextureCoords, 2, gl.FLOAT, false, 0, 0);
                gl.activeTexture(gl.TEXTURE0);
                gl.bindTexture(gl.TEXTURE_2D, object.texture.tex);
                gl.uniform1i(Program.uSampler, 0);
            }
            
            if(!object.wireframe){
                gl.bindBuffer(gl.ARRAY_BUFFER, object.nbo);
                gl.vertexAttribPointer(Program.aVertexNormal, 3, gl.FLOAT, false, 0, 0);
                gl.enableVertexAttribArray(Program.aVertexNormal);
            }
            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   = render;
    app.run();
}
</script>
</head>

<body onLoad='runWebGLApp()'>
<div id='top'>
<h1>WebGL Beginner's Guide - Chapter 10</h1>
<h2 id='title-id'>Post Process Effects</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>Filter:</td>
            <td>
            <div id='opt-filter' align='center'>
                <input type='radio' id='filter-normal' name='filter' checked='checked'/><label for='filter-normal'>Normal</label>
                <input type='radio' id='filter-greyscale' name='filter'/><label for='filter-greyscale'>Greyscale</label>
                <input type='radio' id='filter-invert' name='filter' /><label for='filter-invert'>Invert</label>
                <input type='radio' id='filter-wavy' name='filter' /><label for='filter-wavy'>Wavy</label>
                <input type='radio' id='filter-blur' name='filter' /><label for='filter-blur'>Blur</label>
                <input type='radio' id='filter-filmgrain' name='filter' /><label for='filter-filmgrain'>Film-Grain</label>
            </div>
            </td>
        </tr>
    </table>
    </td>
</table>
</div>
<script> 

$('#opt-filter').buttonset();

$('#filter-normal').click(function(){
    post.configureShader("post-normal");
});

$('#filter-greyscale').click(function(){
    post.configureShader("post-greyscale");
});

$('#filter-invert').click(function(){
    post.configureShader("post-invert");
});

$('#filter-wavy').click(function(){
    post.configureShader("post-wavy");
});

$('#filter-blur').click(function(){
    post.configureShader("post-blur");
});

$('#filter-filmgrain').click(function(){
    post.configureShader("post-filmgrain");
});

</script>
<script>cview.run(cview.MODE_VIEW,false,470);</script>
</body>
</html>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.