Diego Cantor avatar Diego Cantor committed 4f8ba8a

Working on Lights

Comments (0)

Files changed (14)

1727_05/js/webgl/Axis(2).js

-var Axis = {
-    alias           : 'axis',
-    dim             : 10,
-    vertices        : [-10,0.0,0.0, 10,0.0,0.0, 0.0,-10/2,0.0, 0.0,10/2,0.0, 0.0,0.0,-10, 0.0,0.0,10],
-    indices         : [ 	0, 1, 	2, 3, 	4, 5	],
-    colors          : [	1, 1, 0 ,1,	  1, 1, 0 ,1,	0, 1 ,0 ,1,	 0, 1 ,0 ,1,  0, 0, 1 ,1,	 0, 0, 1 ,1	],
-    wireframe       : true,
-    perVertexColor  : true,
-    build           : function(d){
-                        if (d) Axis.dim = d;
-                        Axis.vertices = [-d,0.0,0.0, d,0.0,0.0, 0.0,-d/2,0.0, 0.0,d/2,0.0, 0.0,0.0,-d, 0.0,0.0,d];
-                      }
-}
-
-

1727_05/js/webgl/Camera(2).js

-/**
-*   Camera
-*/
-
-var CAMERA_ORBITING_TYPE = 1;
-var CAMERA_TRACKING_TYPE = 2;
-
-function Camera(t){
-    this.matrix     = mat4.create();
-    this.up         = vec3.create();
-    this.right      = vec3.create();
-    this.normal     = vec3.create();
-    this.position   = vec3.create();
-    this.focus      = vec3.create();
-    this.azimuth    = 0.0;
-    this.elevation  = 0.0;
-    this.type       = t;
-    this.steps      = 0;
-    
-    this.home = vec3.create();
-      
-    this.hookRenderer = null;
-    this.hookGUIUpdate = null;
-}
-
-Camera.prototype.setType = function(t){
-    
-    this.type = t;
-    
-    if (t != CAMERA_ORBITING_TYPE && t != CAMERA_TRACKING_TYPE) {
-        alert('Wrong Camera Type!. Setting Orbitting type by default');
-        this.type = CAMERA_ORBITING_TYPE;
-    }
-}
-
-Camera.prototype.goHome = function(h){
-    if (h != null){
-        this.home = h;
-    }
-    
-    this.setPosition(this.home);
-    this.setAzimuth(0);
-    this.setElevation(0);
-    this.steps = 0;
-}
-
-Camera.prototype.dolly = function(s){
-    var c = this;
-    
-    var p =  vec3.create();
-    var n = vec3.create();
-    
-    p = c.position;
-    
-    var step = s - c.steps;
-    
-    vec3.normalize(c.normal,n);
-    
-    var newPosition = vec3.create();
-    
-    if(c.type == CAMERA_TRACKING_TYPE){
-        newPosition[0] = p[0] - step*n[0];
-        newPosition[1] = p[1] - step*n[1];
-        newPosition[2] = p[2] - step*n[2];
-    }
-    else{
-        newPosition[0] = p[0];
-        newPosition[1] = p[1];
-        newPosition[2] = p[2] - step; 
-    }
-	
-    c.setPosition(newPosition);
-    c.steps = s;
-}
-
-Camera.prototype.setPosition = function(p){
-    vec3.set(p, this.position);
-    this.update();
-}
-
-Camera.prototype.setFocus = function(f){
-	vec3.set(f, this.focus);
-	this.update();
-}
-
-Camera.prototype.setAzimuth = function(az){
-    this.changeAzimuth(az - this.azimuth);
-}
-
-Camera.prototype.changeAzimuth = function(az){
-    var c = this;
-    c.azimuth +=az;
-    
-    if (c.azimuth > 360 || c.azimuth <-360) {
-		c.azimuth = c.azimuth % 360;
-	}
-    c.update();
-}
-
-Camera.prototype.setElevation = function(el){
-    this.changeElevation(el - this.elevation);
-}
-
-Camera.prototype.changeElevation = function(el){
-    var c = this;
-    
-    c.elevation +=el;
-    
-    if (c.elevation > 360 || c.elevation <-360) {
-		c.elevation = c.elevation % 360;
-	}
-    c.update();
-}
-
-Camera.prototype.calculateOrientation = function(){
-	var m = this.matrix;
-    mat4.multiplyVec4(m, [1, 0, 0, 0], this.right);
-    mat4.multiplyVec4(m, [0, 1, 0, 0], this.up);
-    mat4.multiplyVec4(m, [0, 0, 1, 0], this.normal);
-}
-
-Camera.prototype.update = function(){
-	mat4.identity(this.matrix);
-	
-	this.calculateOrientation();
-    
-    if (this.type == CAMERA_TRACKING_TYPE){
-        mat4.translate(this.matrix, this.position);
-        mat4.rotateY(this.matrix, this.azimuth * Math.PI/180);
-        mat4.rotateX(this.matrix, this.elevation * Math.PI/180);
-    }
-    else {
-        var trxLook = mat4.create();
-        mat4.rotateY(this.matrix, this.azimuth * Math.PI/180);
-        mat4.rotateX(this.matrix, this.elevation * Math.PI/180);
-        mat4.translate(this.matrix,this.position);
-        //mat4.lookAt(this.position, this.focus, this.up, trxLook);
-        //mat4.inverse(trxLook);
-        //mat4.multiply(this.matrix,trxLook);
-    }
-
-    this.calculateOrientation();
-    
-    /**
-    * We only update the position if we have a tracking camera.
-    * For an orbiting camera we do not update the position. If
-    * you don't believe me, go ahead and comment the if clause...
-    * Why do you think we do not update the position?
-    */
-    if(this.type == CAMERA_TRACKING_TYPE){
-        mat4.multiplyVec4(this.matrix, [0, 0, 0, 1], this.position);
-    }
-    
-    console.info('------------- update -------------');
-    console.info(' right: ' + vec3.str(this.right)+', up: ' + vec3.str(this.up)+',normal: ' + vec3.str(this.normal));
-    console.info('   pos: ' + vec3.str(this.position));
-    console.info('   azimuth: ' + this.azimuth +', elevation: '+ this.elevation);
-    if(this.hookRenderer){
-        this.hookRenderer();
-    }
-    if(this.hookGUIUpdate){
-        this.hookGUIUpdate();
-    }
-    
-}
-
-Camera.prototype.getViewTransform = function(){
-    var m = mat4.create();
-    mat4.inverse(this.matrix, m);
-    return m;
-}
-

1727_05/js/webgl/CameraInteractor(2).js

-/**
-* Camera Interactor
-*
-* This object listens for mouse and keyboard events on the canvas, then, it interprets them and sends the intended instruction to the camera
-*/
-function CameraInteractor(camera,canvas){
-    
-    this.camera = camera;
-    this.canvas = canvas;
-    this.update();
-    
-    this.dragging = false;
-    this.x = 0;
-    this.y = 0;
-    this.lastX = 0;
-    this.lastY = 0;
-    this.button = 0;
-    this.ctrl = false;
-    this.key = 0;
-    
-    this.MOTION_FACTOR = 10.0;
-    this.dloc = 0;
-    this.dstep = 0;
-    
-}
-
-CameraInteractor.prototype.onMouseUp = function(ev){
-    this.dragging = false;
-}
-
-CameraInteractor.prototype.onMouseDown = function(ev){
-    this.dragging = true;
-    this.x = ev.clientX;
-	this.y = ev.clientY;
-	this.button = ev.button;
-	this.dstep = Math.max(this.camera.position[0],this.camera.position[1],this.camera.position[2])/100;
-}
-
-CameraInteractor.prototype.onMouseMove = function(ev){
-	this.lastX = this.x;
-	this.lastY = this.y;
-	this.x = ev.clientX;
-    this.y = ev.clientY;
-	
-	if (!this.dragging) return;
-	this.ctrl = ev.ctrlKey;
-	this.alt = ev.altKey;
-	var dx = this.x - this.lastX;
-	var dy = this.y - this.lastY;
-	
-	if (this.button == 0) { 
-		if(this.ctrl){
-			this.dolly(dy);
-		}
-		else{ 
-			this.rotate(dx,dy);
-		}
-	}
-}
-
-CameraInteractor.prototype.onKeyDown = function(ev){
-    var c = this.camera;
-	
-	this.key = ev.keyCode;
-	this.ctrl = ev.ctrlKey;
-	
-	if (!this.ctrl){
-		if (this.key == 38){
-			c.changeElevation(10);
-		}
-		else if (this.key == 40){
-			c.changeElevation(-10);
-		}
-		else if (this.key == 37){
-			c.changeAzimuth(-10);
-		}
-		else if (this.key == 39){
-			c.changeAzimuth(10);
-		}
-        else if (this.key == 87) {  //w
-            if(fovy) fovy+=5;
-            console.info('FovY:'+fovy);
-        }
-        else if (this.key == 78) { //n
-            if(fovy) fovy-=5;
-            console.info('FovY:'+fovy);
-        }
-	}
-     
-}
-
-CameraInteractor.prototype.onKeyUp = function(ev){
-    if (ev.keyCode == 17){
-		this.ctrl = false;
-	}
-}
-
-CameraInteractor.prototype.update = function(){
-    var self = this;
-	var canvas = this.canvas;
-	
-
-	canvas.onmousedown = function(ev) {
-		self.onMouseDown(ev);
-    }
-
-    canvas.onmouseup = function(ev) {
-		self.onMouseUp(ev);
-    }
-	
-	canvas.onmousemove = function(ev) {
-		self.onMouseMove(ev);
-    }
-	
-	window.onkeydown = function(ev){
-		self.onKeyDown(ev);
-	}
-	
-	window.onkeyup = function(ev){
-		self.onKeyUp(ev);
-	}
-}
-
-CameraInteractor.prototype.dolly = function(value){
- 	if (value>0){
- 		this.dloc += this.dstep;
- 	}
- 	else{
- 		this.dloc -= this.dstep;
- 	}
-	this.camera.dolly(this.dloc);
-}
-
-CameraInteractor.prototype.rotate = function(dx, dy){
-	
-	
-	var camera = this.camera;
-	var canvas = this.canvas;
-	
-	var delta_elevation = -20.0 / canvas.height;
-	var delta_azimuth   = -20.0 / canvas.width;
-				
-	var nAzimuth = dx * delta_azimuth * this.MOTION_FACTOR;
-	var nElevation = dy * delta_elevation * this.MOTION_FACTOR;
-	
-	camera.changeAzimuth(nAzimuth);
-	camera.changeElevation(nElevation);
-}

1727_05/js/webgl/Floor(2).js

-var Floor = {
-    alias       : 'floor',
-    wireframe   : true,
-    dim         : 50,
-    lines       : 50,
-    vertices    : [],
-    indices     : [],
-    diffuse : [0.7,0.7,0.7,1.0],
-    build : function(d,e){
-                    if (d) Floor.dim = d;
-                    if (e) Floor.lines = 2*Floor.dim/e;
-                    var inc = 2*Floor.dim/Floor.lines;
-                    var v = [];
-                    var i = [];
-
-                    for(var l=0;l<=Floor.lines;l++){
-                        v[6*l] = -Floor.dim; 
-                        v[6*l+1] = 0;
-                        v[6*l+2] = -Floor.dim+(l*inc);
-                        
-                        v[6*l+3] = Floor.dim;
-                        v[6*l+4] = 0;
-                        v[6*l+5] = -Floor.dim+(l*inc);
-                        
-                        v[6*(Floor.lines+1)+6*l] = -Floor.dim+(l*inc); 
-                        v[6*(Floor.lines+1)+6*l+1] = 0;
-                        v[6*(Floor.lines+1)+6*l+2] = -Floor.dim;
-                        
-                        v[6*(Floor.lines+1)+6*l+3] = -Floor.dim+(l*inc);
-                        v[6*(Floor.lines+1)+6*l+4] = 0;
-                        v[6*(Floor.lines+1)+6*l+5] = Floor.dim;
-                        
-                        i[2*l] = 2*l;
-                        i[2*l+1] = 2*l+1;
-                        i[2*(Floor.lines+1)+2*l] = 2*(Floor.lines+1)+2*l;
-                        i[2*(Floor.lines+1)+2*l+1] = 2*(Floor.lines+1)+2*l+1;        
-                    }
-                    Floor.vertices = v;
-                    Floor.indices = i;
-              }
-}
-
-
-
-

1727_05/js/webgl/Globals(2).js

-var gl = null;     // WebGL context
-var prg = null;    // The program (shaders)
-var c_width = 0;   // Variable to store the width of the canvas (updated when needed by codeview.js)
-var c_height = 0;  // Variable to store the height of the canvas (updated when needed by codeview.js)
-

1727_05/js/webgl/Program(2).js

-var Program = {
-
-    /**
-    * Utilitary function that allows to set up the shaders (program) using an embedded script (look at the beginning of this source code)
-    */
-    getShader : function(gl, id) {
-       var script = document.getElementById(id);
-       if (!script) {
-           return null;
-       }
-
-        var str = "";
-        var k = script.firstChild;
-        while (k) {
-            if (k.nodeType == 3) {
-                str += k.textContent;
-            }
-            k = k.nextSibling;
-        }
-
-        var shader;
-        if (script.type == "x-shader/x-fragment") {
-            shader = gl.createShader(gl.FRAGMENT_SHADER);
-        } else if (script.type == "x-shader/x-vertex") {
-            shader = gl.createShader(gl.VERTEX_SHADER);
-        } else {
-            return null;
-        }
-
-        gl.shaderSource(shader, str);
-        gl.compileShader(shader);
-
-        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
-            alert(gl.getShaderInfoLog(shader));
-            return null;
-        }
-        return shader;
-    },
-    
-    /**
-    * The program contains a series of instructions that tell the Graphic Processing Unit (GPU)
-    * what to do with every vertex and fragment that we pass it. 
-    * The vertex shader and the fragment shader together are called the program.
-    */
-    load : function() {
-
-     var fragmentShader          = Program.getShader(gl, "shader-fs");
-     var vertexShader            = Program.getShader(gl, "shader-vs");
-     
-     prg = gl.createProgram();
-     gl.attachShader(prg, vertexShader);
-     gl.attachShader(prg, fragmentShader);
-     gl.linkProgram(prg);
-
-     if (!gl.getProgramParameter(prg, gl.LINK_STATUS)) {
-      alert("Could not initialise shaders");
-     }
-
-     gl.useProgram(prg);
-
-     prg.aVertexPosition  = gl.getAttribLocation(prg, "aVertexPosition");
-     prg.aVertexNormal    = gl.getAttribLocation(prg, "aVertexNormal");
-     prg.aVertexColor     = gl.getAttribLocation(prg, "aVertexColor");
-     
-     prg.uPMatrix         = gl.getUniformLocation(prg, "uPMatrix");
-     prg.uMVMatrix        = gl.getUniformLocation(prg, "uMVMatrix");
-     prg.uNMatrix         = gl.getUniformLocation(prg, "uNMatrix");
-     
-     prg.uMaterialDiffuse  = gl.getUniformLocation(prg, "uMaterialDiffuse");
-     prg.uMaterialAmbient  = gl.getUniformLocation(prg, "uMaterialAmbient");
-     prg.uMaterialSpecular = gl.getUniformLocation(prg, "uMaterialSpecular");
-     prg.uLightAmbient     = gl.getUniformLocation(prg, "uLightAmbient");
-     prg.uLightDiffuse     = gl.getUniformLocation(prg, "uLightDiffuse");
-     prg.uLightSpecular    = gl.getUniformLocation(prg, "uLightSpecular");
-     prg.uLightPosition    = gl.getUniformLocation(prg, "uLightPosition");
-     prg.uShininess        = gl.getUniformLocation(prg, "uShininess");
-     prg.uUpdateLight      = gl.getUniformLocation(prg, "uUpdateLight");
-     prg.uWireframe        = gl.getUniformLocation(prg, "uWireframe");
-     prg.uPerVertexColor   = gl.getUniformLocation(prg, "uPerVertexColor");
-     
-
-     gl.uniform3fv(prg.uLightPosition,    [0, 120, 120]);
-     gl.uniform4fv(prg.uLightAmbient,      [0.20,0.20,0.20,1.0]);
-     gl.uniform4fv(prg.uLightDiffuse,      [1.0,1.0,1.0,1.0]);
-     gl.uniform4fv(prg.uLightSpecular,     [1.0,1.0,1.0,1.0]);
-     gl.uniform1f(prg.uShininess, 230.0); 
-    }
-}

1727_05/js/webgl/Scene(2).js

-var Scene = {
-    objects : [],
-    getObject : function(alias){
-        for(var i=0; i<Scene.objects.length; i++){
-            if (alias == Scene.objects[i].alias) return Scene.objects[i];
-        }
-        return null;
-    },
-
-    loadObject : function(filename,alias,attributes){
-        var request = new XMLHttpRequest();
-        console.info('Requesting ' + filename);
-        request.open("GET",filename);
-    
-        request.onreadystatechange = function() {
-            if (request.readyState == 4) {
-                if(request.status == 404) {
-                    console.info(filename + ' does not exist');
-                }
-                else {
-                    var o = JSON.parse(request.responseText);
-                    o.alias = (alias==null)?'none':alias;
-                    o.remote = true;
-                    Scene.addObject(o,attributes);
-                }
-            }
-        }
-        request.send();
-    },
-    
-    loadObjectByParts: function(path, alias, parts){
-        for(var i = 1; i <= parts; i++){
-            var partFilename =  path+''+i+'.json';
-            var partAlias = alias+''+i;
-            Scene.loadObject(partFilename,partAlias);
-        }
-    },
-    
-    addObject : function(object,attributes) {
-        
-        //initialize with defaults
-        if (object.perVertexColor   === undefined)    {   object.perVertexColor   = false;            }
-        if (object.wireframe        === undefined)    {   object.wireframe        = false;            }
-        if (object.diffuse          === undefined)    {   object.diffuse          = [1.0,1.0,1.0,1.0];}
-        if (object.ambient          === undefined)    {   object.ambient          = [0.1,0.1,0.1,1.0];}
-        if (object.specular         === undefined)    {   object.specular         = [1.0,1.0,1.0,1.0];}
-        
-        //set attributes
-       for(var key in attributes){
-            if(object.hasOwnProperty(key)) {object[key] = attributes[key];}
-        }   
-
-    
-        var vertexBufferObject = gl.createBuffer();
-        gl.bindBuffer(gl.ARRAY_BUFFER, vertexBufferObject);
-        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(object.vertices), gl.STATIC_DRAW);
-          
-        var normalBufferObject = gl.createBuffer();
-        gl.bindBuffer(gl.ARRAY_BUFFER, normalBufferObject);
-        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(Utils.calculateNormals(object.vertices, object.indices)), gl.STATIC_DRAW);
-    
-        var colorBufferObject;
-    
-       if (object.perVertexColor){
-            colorBufferObject = gl.createBuffer();
-            gl.bindBuffer(gl.ARRAY_BUFFER, colorBufferObject);
-            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(object.colors), gl.STATIC_DRAW);
-            object.cbo = colorBufferObject;
-        }
-    
-        var indexBufferObject = gl.createBuffer();
-        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBufferObject);
-        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(object.indices), gl.STATIC_DRAW);
-        
-        object.vbo = vertexBufferObject;
-        object.ibo = indexBufferObject;
-        object.nbo = normalBufferObject;
-
-        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
-        gl.bindBuffer(gl.ARRAY_BUFFER,null);
-    
-        Scene.objects.push(object);
-        
-        if (object.remote){
-            console.info(object.alias + ' has been added to the scene [Remote]');
-         }
-         else {
-            console.info(object.alias + ' has been added to the scene [Local]');
-         }
-    } 
-}

1727_05/js/webgl/SceneTransforms(2).js

-
-function SceneTransforms(c){
-	this.stack = [];
-	this.camera = c;
-	this.mvMatrix    = mat4.create();    // The Model-View matrix
-	this.pMatrix     = mat4.create();    // The projection matrix
-	this.nMatrix     = mat4.create();    // The normal matrix
-	this.cMatrix     = mat4.create();    // The camera matrix	
-};
-
-
-SceneTransforms.prototype.calculateModelView = function(){
-	this.mvMatrix = this.camera.getViewTransform();
-};
-
-SceneTransforms.prototype.calculateNormal = function(){
-	
-    mat4.identity(this.nMatrix);
-    mat4.set(this.mvMatrix, this.nMatrix);
-    mat4.inverse(this.nMatrix);
-    mat4.transpose(this.nMatrix);
-};
-
-SceneTransforms.prototype.calculatePerspective = function(){
-	//Initialize Perspective matrix
-    mat4.identity(this.pMatrix);
-    mat4.perspective(30, c_width / c_height, 0.1, 1000.0, this.pMatrix);
-};
-
-
-/**
-*   Defines the initial values for the transformation matrices
-*/
-SceneTransforms.prototype.init = function(){
-    this.calculateModelView();
-    this.calculatePerspective();
-    this.calculateNormal();
-};
-
-
-SceneTransforms.prototype.updatePerspective = function(){
-    mat4.perspective(30, c_width / c_height, 0.1, 1000.0, this.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. 
-*/
-SceneTransforms.prototype.setMatrixUniforms = function(){
-	this.calculateNormal();
-    gl.uniformMatrix4fv(prg.uMVMatrix, false, this.mvMatrix);  //Maps the Model-View matrix to the uniform prg.uMVMatrix
-    gl.uniformMatrix4fv(prg.uPMatrix, false, this.pMatrix);    //Maps the Perspective matrix to the uniform prg.uPMatrix
-    gl.uniformMatrix4fv(prg.uNMatrix, false, this.nMatrix);    //Maps the Normal matrix to the uniform prg.uNMatrix
-};
-
-
-SceneTransforms.prototype.push = function(){
-	var memento =  mat4.create();
-	mat4.set(this.mvMatrix, memento);
-	this.stack.push(memento);
-};
-
-SceneTransforms.prototype.pop = function(){
-	if(this.stack.length == 0) return;
-	this.mvMatrix  =  this.stack.pop();
-};

1727_05/js/webgl/Utils(2).js

-
-var	Utils = {
-	
-	/**
-	* Obtains a WebGL context for the canvas with id 'canvas-element-id'
-	* This function is invoked when the WebGL app is starting.
-	*/
-	getGLContext : function(name){
-	    
-		var canvas = document.getElementById(name);
-		var ctx = null;
-		
-		if (canvas == null){
-			alert('there is no canvas on this page');
-			return null;
-		}
-		else {
-			c_width = canvas.width;
-			c_height = canvas.height;
-		}
-				
-		var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
-	
-		for (var i = 0; i < names.length; ++i) {
-		try {
-			ctx = canvas.getContext(names[i]);
-		} 
-		catch(e) {}
-			if (ctx) {
-				break;
-			}
-		}
-		if (ctx == null) {
-			alert("Could not initialise WebGL");
-			return null;
-		}
-		else {
-			return ctx;
-		}
-	},
-	
-	requestAnimFrame : function(o){
-		requestAnimFrame(o);
-	},
-    
-    //indices have to be completely defined NO TRIANGLE_STRIP only TRIANGLES
-    calculateNormals : function(vs, ind){
-        var x=0; 
-        var y=1;
-        var z=2;
-        
-        var ns = [];
-        for(var i=0;i<vs.length;i=i+3){ //for each vertex, initialize normal x, normal y, normal z
-            ns[i+x]=0.0;
-            ns[i+y]=0.0;
-            ns[i+z]=0.0;
-        }
-        
-        for(var i=0;i<ind.length;i=i+3){ //we work on triads of vertices to calculate normals so i = i+3 (i = indices index)
-            var v1 = [];
-            var v2 = [];
-            var normal = [];	
-            //p2 - p1
-            v1[x] = vs[3*ind[i+2]+x] - vs[3*ind[i+1]+x];
-            v1[y] = vs[3*ind[i+2]+y] - vs[3*ind[i+1]+y];
-            v1[z] = vs[3*ind[i+2]+z] - vs[3*ind[i+1]+z];
-            //p0 - p1
-            v2[x] = vs[3*ind[i]+x] - vs[3*ind[i+1]+x];
-            v2[y] = vs[3*ind[i]+y] - vs[3*ind[i+1]+y];
-            v2[z] = vs[3*ind[i]+z] - vs[3*ind[i+1]+z];
-            //cross product by Sarrus Rule
-            normal[x] = v1[y]*v2[z] - v1[z]*v2[y];
-            normal[y] = v1[z]*v2[x] - v1[x]*v2[z];
-            normal[z] = v1[x]*v2[y] - v1[y]*v2[x];
-            for(j=0;j<3;j++){ //update the normals of that triangle: sum of vectors
-                ns[3*ind[i+j]+x] =  ns[3*ind[i+j]+x] + normal[x];
-                ns[3*ind[i+j]+y] =  ns[3*ind[i+j]+y] + normal[y];
-                ns[3*ind[i+j]+z] =  ns[3*ind[i+j]+z] + normal[z];
-            }
-        }
-        //normalize the result
-        for(var i=0;i<vs.length;i=i+3){ //the increment here is because each vertex occurs with an offset of 3 in the array (due to x, y, z contiguous values)
-        
-            var nn=[];
-            nn[x] = ns[i+x];
-            nn[y] = ns[i+y];
-            nn[z] = ns[i+z];
-            
-            var len = Math.sqrt((nn[x]*nn[x])+(nn[y]*nn[y])+(nn[z]*nn[z]));
-            if (len == 0) len = 1.0;
-            
-            nn[x] = nn[x]/len;
-            nn[y] = nn[y]/len;
-            nn[z] = nn[z]/len;
-            
-            ns[i+x] = nn[x];
-            ns[i+y] = nn[y];
-            ns[i+z] = nn[z];
-        }
-        
-        return ns;
-    },
- 
-
-    calculateTangents : function(vertices, normals)
-    {
-        var vs = vertices;
-        var ts = [];
-        for(var i=0;i<vs.length; i++){
-            ts[i]=0.0;
-        }
-        return ts;
-    }
-}
-	
-	/**
-	* Provides requestAnimationFrame in a cross browser way.
-	*/
-	requestAnimFrame = (function() {
-    return window.requestAnimationFrame ||
-         window.webkitRequestAnimationFrame ||
-         window.mozRequestAnimationFrame ||
-         window.oRequestAnimationFrame ||
-         window.msRequestAnimationFrame ||
-         function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
-           window.setTimeout(callback, 1000/60);
-         };
-	})();
-	

1727_05/js/webgl/WebGLApp(2).js

-var WEBGLAPP_RENDER = undefined;
-var WEBGLAPP_TIMER_ID = -1;
-var WEBGLAPP_RENDER_RATE = 500;
-
-function WebGLApp(canvas) {
-    this.loadSceneHook = undefined;
-    this.configureGLHook = undefined;
-    gl = Utils.getGLContext(canvas);
-    Program.load();  
-}
-  
-WebGLApp.prototype.run = function(){
-        if (this.configureGLHook == undefined){
-            alert('The WebGL application cannot start because the configureGLHook has not been specified'); return;
-        }
-        if (this.loadSceneHook == undefined){
-            alert('The WebGL application cannot start because the loadSceneHook has not been specified'); return;
-        }
-        if (this.drawSceneHook == undefined){
-            alert('The WebGL application cannot start because the drawSceneHook has not been specified'); return;
-        }
-        
-        this.configureGLHook();
-        
-        this.loadSceneHook();
-        
-        WEBGLAPP_RENDER = this.drawSceneHook;
-        
-        renderLoop();
- }
- 
- /**
- * Causes immediate rendering
- */
- WebGLApp.prototype.refresh = function(){
-    if (WEBGLAPP_RENDER) WEBGLAPP_RENDER();
- }
-     
-renderLoop = function(){
-     WEBGLAPP_TIMER_ID = setInterval(WEBGLAPP_RENDER, WEBGLAPP_RENDER_RATE);
-}
-
-window.onblur = function(){
-    clearInterval(WEBGLAPP_TIMER_ID);
-    console.info('Rendering stopped');
-}
-
-window.onfocus = function(){
-    renderLoop();
-    console.info('Rendering resumed');
-}
-

Binary file modified.

1727_06/ch6_ColorsOnWall.html

 <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/Lights.js'></script>
 <script type='text/javascript' src='js/webgl/WebGLApp.js'></script>
 
 
     camera = new Camera(CAMERA_ORBITING_TYPE);
     camera.goHome([0,5,30]);
     camera.setFocus([0.0,0.0,0.0]);
-	camera.setAzimuth(-47);
+	camera.setAzimuth(0);
 	camera.setElevation(-3);
     camera.hookRenderer = draw;
     
     //init transforms
     transforms.init();
 	
-	//
+	//init Lights
+	var redLight = new Light('red');
+	redLight.setPosition([0,7,3]);
+	redLight.setDiffuse([1.0,0.0,0.0,1.0]);
+	
+	var greenLight = new Light('green');
+	greenLight.setPosition([2.5,3,3]);
+	greenLight.setDiffuse([0.0,1.0,0.0,1.0]);
+	
+	var blueLight = new Light('blue');
+	blueLight.setPosition([-2.5,3,3]);
+	blueLight.setDiffuse([0.0,0.0,1.0,1.0]);
+	
+	Lights.add(redLight);
+	Lights.add(greenLight);
+	Lights.add(blueLight);
+	
 	attributeList = ["aVertexPosition",
 					"aVertexNormal",
 					"aVertexColor"];
 	
 	Program.load(attributeList, uniformList);
 	
-	gl.uniform3fv(Program.uPositionLightOne,    [0, 7, 3]);
-	gl.uniform3fv(Program.uPositionLightTwo,    [2.5, 3, 3]);
-	gl.uniform3fv(Program.uPositionLightThree,  [-2.5,3, 3]);
+	gl.uniform3fv(Program.uPositionLightOne,    redLight.position);
+	gl.uniform3fv(Program.uPositionLightTwo,    greenLight.position);
+	gl.uniform3fv(Program.uPositionLightThree,  blueLight.position);
 	
-	gl.uniform4fv(Program.uLightAmbient ,  [1.0,1.0,1.0,1.0]);
-	
-	gl.uniform4fv(Program.uLightDiffuseOne,   [1.0,0.0,0.0,1.0]);
-	gl.uniform4fv(Program.uLightDiffuseTwo,   [0.0,1.0,0.0,1.0]);
-	gl.uniform4fv(Program.uLightDiffuseThree, [0.0,0.0,1.0,1.0]);
+	gl.uniform4fv(Program.uLightDiffuseOne,   redLight.diffuse);
+	gl.uniform4fv(Program.uLightDiffuseTwo,   greenLight.diffuse);
+	gl.uniform4fv(Program.uLightDiffuseThree, Lights.get('blue').diffuse);
 	
-	gl.uniform1f(Program.uCutOff, 0.6);
-
+	gl.uniform1f(Program.uCutOff, 0.4);
+	gl.uniform4fv(Program.uLightAmbient ,  [1.0,1.0,1.0,1.0]);
 	
 }
 
 $('#slider-y3').slider({value:3.0,  min:-15, max:15, step:0.1, slide:function(){updateLightPosition(3)}, 	change:function(){updateLightPosition(3)}});
 $('#slider-z3').slider({value:3.0,  min:-15, max:15, step:0.1, slide:function(){updateLightPosition(3)}, 	change:function(){updateLightPosition(3)}});
 
-$('#slider-cutoff').slider({value:0.6, min:0.0, max:1, step:0.05, slide:updateCutOff});
+$('#slider-cutoff').slider({value:0.4, min:0.0, max:1, step:0.05, slide:updateCutOff});
 
 function updateCutOff(){
     var v = $('#slider-cutoff').slider("value");

1727_06/ch6_ColorsOnWall_LightArrays.html

     transforms.init();
 	
 	//init Lights
-	var redLight = new Light([0,7,3]);
-	redLight.addDiffuse([1.0,0.0,0.0,1.0]);
+	var redLight = new Light('red');
+	redLight.setPosition([0,7,3]);
+	redLight.setDiffuse([1.0,0.0,0.0,1.0]);
 	
-	var greenLight = new Light([2.5,3,3]);
-	greenLight.addDiffuse([0.0,1.0,0.0,1.0]);
+	var greenLight = new Light('green');
+	greenLight.setPosition([2.5,3,3]);
+	greenLight.setDiffuse([0.0,1.0,0.0,1.0]);
 	
-	var blueLight = new Light([-2.5,3,3]);
-	blueLight.addDiffuse([0.0,0.0,1.0,1.0]);
+	var blueLight = new Light('blue');
+	blueLight.setPosition([-2.5,3,3]);
+	blueLight.setDiffuse([0.0,0.0,1.0,1.0]);
 	
 	Lights.add(redLight);
 	Lights.add(greenLight);
-	Lights.add(blueLight);
+	Lights.add(blueLight);	
 	
 	//init Program
 	var attributeList = ["aVertexPosition",
 					"uLightSource",
 					"uCutOff"
 					];
+				
 	
 	
 	Program.load(attributeList, uniformList);	
 	gl.uniform4fv(Program.uLightAmbient ,  [1.0,1.0,1.0,1.0]);
 	gl.uniform3fv(Program.uPositionLight, Lights.getArray('position'));
 	gl.uniform4fv(Program.uLightDiffuse,  Lights.getArray('diffuse'));
-	gl.uniform1f(Program.uCutOff, 0.6);
+	gl.uniform1f(Program.uCutOff, 0.4);
 
 }
 
 <body onLoad='runWebGLApp()'>
 <div id='top'>
 <h1>WebGL Beginner's Guide - Chapter 6</h1>
-<h2>Using GLSL Arrays to handle Multiple Lights</h2>
+<h2>Using GLSL Array Uniforms to handle Multiple Lights</h2>
 <div id='logo-packt'><img src='packt.gif'/></div>
 <p></p>
 </div>
 $('#slider-y3').slider({value:3.0,  min:-15, max:15, step:0.1, slide:function(){updateLightPosition(3)}, 	change:function(){updateLightPosition(3)}});
 $('#slider-z3').slider({value:3.0,  min:-15, max:15, step:0.1, slide:function(){updateLightPosition(3)}, 	change:function(){updateLightPosition(3)}});
 
-$('#slider-cutoff').slider({value:0.6, min:0.0, max:1, step:0.05, slide:updateCutOff});
+$('#slider-cutoff').slider({value:0.4, min:0.0, max:1, step:0.05, slide:updateCutOff});
 
 function updateCutOff(){
     var v = $('#slider-cutoff').slider("value");

1727_06/js/webgl/Lights.js

-function Light(pos){
-	this.position = pos;
+function Light(name){
+	this.id = name;
+	this.position = [0.0,0.0,0.0];
 	this.ambient = [0.0,0.0,0.0,0.0];
 	this.diffuse = [0.0,0.0,0.0,0.0];
 	this.specular = [0.0,0.0,0.0,0.0];
 }
 
-Light.prototype.addDiffuse = function (d){
+Light.prototype.setPosition = function(p){
+	this.position = p.slice(0);
+}
+Light.prototype.setDiffuse = function (d){
 	this.diffuse = d.slice(0);
 }
 
-Light.prototype.addAmbient = function(a){
+Light.prototype.setAmbient = function(a){
 	this.ambient = a.slice(0);
 }
 
-Light.prototype.addSpecular = function(s){
+Light.prototype.setSpecular = function(s){
 	this.specular = s.slice(0);
 }
 
 		for(var i = 0, max = this.list.length; i < max; i+=1){
 			a = a.concat(this.list[i][type]);
 		}
-		console.info(type+':'+a+'');
 		return a;
 	},
 
 	get: function(idx){
-		if (idx >= 0 && idx < this.list.length){
+		if ((typeof idx == 'number') && idx >= 0 && idx < this.list.length){
 			return this.list[idx];
 		}
+		else if (typeof idx == 'string'){
+			for(var i=0, max = this.list.length; i < max; i+=1){
+				if (this.list[i].id == idx) return this.list[i];
+			}
+			throw 'Light ' + idx + ' does not exist';
+		}
+		else {
+			throw 'Unknown parameter';
+		}
 	}
 }
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.