Sei sulla pagina 1di 16

2018

PROJECT 4: WebGL 3D Project

SUBMITTED BY:
NAME:
WebGL 3D Project

A). PROJECT DISCRIPTION


3D-Visualization and gaming has come a long way since just two decades ago, when implementations
required a lot of overwork, including third-party plug-ins, and in some cases also required capturing of
motion graphics for commercial 3D gaming,
The results we found had always been awe-inspiring, but they often incurred huge costs and required
countless hours of work behind the scenes. However, the options that I used is WebGl to provide cross-
browser solutions for 3D visualization and gaming.

B). WHAT IS WEBGL?


WebGl is a JavaScript-based API that provides a medium to render interactive 3D and 2D graphics on
any compatible web browser. The advantage here lies in the fact that there is no dependency on plug-ins.
webgl does this with the help of control logic implemented with JavaScript and shader logic that is
executed on a Graphics Processing Unit (GPU), Code implementations for 30 graphics can be written
directly in WebGL but it comes with some caveats, like a very high learning curve and the absence of
graceful fall back in case of incompatibility. This is where two of the most flexible open source libraries,
Three,js and Babylon.js, come to the rescue.

C).WHAT ARE THREE.JS?


These are JavaScript-based frameworks that handle the complexities of webGL with ease and provide a
user-friendly way of implementing 3D graphics. While Three.js was designed as a tool for general
purpose web animations, it was designed to take a more targeted approach for web-based game
development and uses an extensive physics engine for collision detection and other intricacies involved
for 3D graphics
As a brief introduction. Let us take a look at the interiors of Three,js, For any 3D visualization, we
would require the following objects
• Camera
• Scene-represents a list of objects that is displayed on- screen, like 3D models and lights.
• Geometry-the shape of objects, like cube, sphere, cylinder
• Material-color, image, or texture that defines how a geometrical shape would he displayed.
• Mesh-composed of the geometry and material

Page 1
WebGL 3D Project

To begin, we would implement an animated cube. The declaration of objects that we would need comes
first:

var camera, scene, renderer;


var geometry, material, mesh;
We require two functions–init( ) and animate( ).

The init() function creates and sets the position of the camera, creates a cubic geometrical shape,
defines the material of the mesh that the shape would be composed of, adds the shape and the mesh onto
the scene, and renders the entire scene on a canvas element.
The code for the entire init() function is listed below;

var init = function() {


Camera = new Three.PerspectiveCamera(75, window.innerwidth / window, innerHeight, 1,
10000);
Camera.position.2 = 500;
Scene = new THREE.Scene();
//geometry = new THREE.IcosahedronGeometry( 200, 1 );
Geometry = new THREE.CubeGeometry(210, 210, 210, 1, 1, 1);
Material = new THREE.MeshnormalMaterial ({
Wireframe: false,
WireframeLinewidth: 1
)};
Mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
renderer = new THREE.CanvasRenderer();
renderer.setsize(window.innerwidth, window.innerHeight);
document.body.appendChild(renderer, docelement);
}

Page 2
WebGL 3D Project

 There are multiple types of camera classes provided by Three.js, out of which
THREE.PerspectivCamera is used for a perspective view of the scene. The scene can be added
with a mesh (where mesh is composed of a geometrical shape and the color, or texture, or image
that defines how the shape would look), which is implemented by using the
THREE.meshBasicMaterial class. Again, Three.js provides a vast collection of classes of
material that can be applied to different geometrical shapes.

 The most important aspect is the rendering of the objects that makes WebGL with Three.js or
Babylon.js easy to work with. Three.js provides a class THREE.CanvasRenderer that renders the
objects automatically on the HTML5 canvas element. This provides a very graceful fallback in
case WebGL (which is dependent on the compatibility of the latest browsers) is not compatible
with the browser being used at client end.

D). WebGl Working


WebGL stores geometric data in buffers that are sent to the GPU. These data are then used to transfer
shapes and figures to the screen using shader vertices and shader fragments. Shader vertex transforms
the coordinates of three-dimensional space points according to the rotation and position of the object and
the two-dimensional projection on the plane.

The animate () function makes use of the requestAnimationFrame() function to perform a call back of
the animate() function itself, which updates the animation before the next repaint takes place in the
browser. For this example, the rotation vector is updated for the mesh in the scene in any subsequent
repaints. The code for the animate() function is listed below:

var animate = function () {


requestAnimationFrame(animate);
mesh.rotation.x = Date. (now). = 0.00005;
mesh.rotation.y = Date. (now). = 0.001;
renderer.render(scent, camera);
}
init(); animate();

Page 3
WebGL 3D Project

Code
<!doctype html>
<html>
<body>
<canvas width = "570" height = "570" id = "my_Canvas"></canvas>

<script>

/*Creating a canvas */
var canvas = document.getElementById('my_Canvas');
gl = canvas.getContext('experimental-webgl');

/* defining and storing the geometry */

var vertices = [
-1,-1,-1, 1,-1,-1, 1, 1,-1, -1, 1,-1,
-1,-1, 1, 1,-1, 1, 1, 1, 1, -1, 1, 1,
-1,-1,-1, -1, 1,-1, -1, 1, 1, -1,-1, 1,
1,-1,-1, 1, 1,-1, 1, 1, 1, 1,-1, 1,
-1,-1,-1, -1,-1, 1, 1,-1, 1, 1,-1,-1,
-1, 1,-1, -1, 1, 1, 1, 1, 1, 1, 1,-1,
];

var colors = [

Page 4
WebGL 3D Project

5,3,7, 5,3,7, 5,3,7, 5,3,7,


1,1,3, 1,1,3, 1,1,3, 1,1,3,
0,0,1, 0,0,1, 0,0,1, 0,0,1,
1,0,0, 1,0,0, 1,0,0, 1,0,0,
1,1,0, 1,1,0, 1,1,0, 1,1,0,
0,1,0, 0,1,0, 0,1,0, 0,1,0
];

var indices = [
0,1,2, 0,2,3, 4,5,6, 4,6,7,
8,9,10, 8,10,11, 12,13,14, 12,14,15,
16,17,18, 16,18,19, 20,21,22, 20,22,23
];

// Create and store data into vertex buffer


var vertex_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

// Create and store data into color buffer


var color_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);

// Create and store data into index buffer


var index_buffer = gl.createBuffer ();

Page 5
WebGL 3D Project

gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices),
gl.STATIC_DRAW);

/*Adding Shades */

var vertCode = 'attribute vec3 position;'+


'uniform mat4 Pmatrix;'+
'uniform mat4 Vmatrix;'+
'uniform mat4 Mmatrix;'+
'attribute vec3 color;'+//the color of the point
'varying vec3 vColor;'+

'void main(void) { '+//pre-built function


'gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.);'+
'vColor = color;'+
'}';

var fragCode = 'precision mediump float;'+


'varying vec3 vColor;'+
'void main(void) {'+
'gl_FragColor = vec4(vColor, 1.);'+
'}';

var vertShader = gl.createShader(gl.VERTEX_SHADER);


gl.shaderSource(vertShader, vertCode);

Page 6
WebGL 3D Project

gl.compileShader(vertShader);

var fragShader = gl.createShader(gl.FRAGMENT_SHADER);


gl.shaderSource(fragShader, fragCode);
gl.compileShader(fragShader);

var shaderProgram = gl.createProgram();


gl.attachShader(shaderProgram, vertShader);
gl.attachShader(shaderProgram, fragShader);
gl.linkProgram(shaderProgram);

/* associating attributes to vertex shader */


var Pmatrix = gl.getUniformLocation(shaderProgram, "Pmatrix");
var Vmatrix = gl.getUniformLocation(shaderProgram, "Vmatrix");
var Mmatrix = gl.getUniformLocation(shaderProgram, "Mmatrix");

gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
var position = gl.getAttribLocation(shaderProgram, "position");
gl.vertexAttribPointer(position, 3, gl.FLOAT, false,0,0) ;

// Position
gl.enableVertexAttribArray(position);
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
var color = gl.getAttribLocation(shaderProgram, "color");
gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ;

Page 7
WebGL 3D Project

// Color
gl.enableVertexAttribArray(color);
gl.useProgram(shaderProgram);

/*= MATRIX =*/

function get_projection(angle, a, zMin, zMax) {


var ang = Math.tan((angle*.5)*Math.PI/180);//angle*.5
return [
0.5/ang, 0 , 0, 0,
0, 0.5*a/ang, 0, 0,
0, 0, -(zMax+zMin)/(zMax-zMin), -1,
0, 0, (-2*zMax*zMin)/(zMax-zMin), 0
];
}

var proj_matrix = get_projection(40, canvas.width/canvas.height, 1, 100);

var mov_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];


var view_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];

// translating z
view_matrix[14] = view_matrix[14]-6;//zoom

/*======= Rotation ======*/

Page 8
WebGL 3D Project

function rotateZ(m, angle) {


var c = Math.cos(angle);
var s = Math.sin(angle);
var mv0 = m[0], mv4 = m[4], mv8 = m[8];

m[0] = c*m[0]-s*m[1];
m[4] = c*m[4]-s*m[5];
m[8] = c*m[8]-s*m[9];

m[1]=c*m[1]+s*mv0;
m[5]=c*m[5]+s*mv4;
m[9]=c*m[9]+s*mv8;
}

function rotateX(m, angle) {


var c = Math.cos(angle);
var s = Math.sin(angle);
var mv1 = m[1], mv5 = m[5], mv9 = m[9];

m[1] = m[1]*c-m[2]*s;
m[5] = m[5]*c-m[6]*s;
m[9] = m[9]*c-m[10]*s;

m[2] = m[2]*c+mv1*s;
m[6] = m[6]*c+mv5*s;
m[10] = m[10]*c+mv9*s;

Page 9
WebGL 3D Project

function rotateY(m, angle) {


var c = Math.cos(angle);
var s = Math.sin(angle);
var mv0 = m[0], mv4 = m[4], mv8 = m[8];

m[0] = c*m[0]+s*m[2];
m[4] = c*m[4]+s*m[6];
m[8] = c*m[8]+s*m[10];

m[2] = c*m[2]-s*mv0;
m[6] = c*m[6]-s*mv4;
m[10] = c*m[10]-s*mv8;
}

/*================= Drawing ===========================*/


var time_old = 0;

var animate = function(time) {

var dt = time-time_old;
rotateZ(mov_matrix, dt*0.005);//time
rotateY(mov_matrix, dt*0.002);
rotateX(mov_matrix, dt*0.003);
time_old = time;

Page 10
WebGL 3D Project

gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.clearDepth(1.0);

gl.viewport(0.0, 0.0, canvas.width, canvas.height);


gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.uniformMatrix4fv(Pmatrix, false, proj_matrix);
gl.uniformMatrix4fv(Vmatrix, false, view_matrix);
gl.uniformMatrix4fv(Mmatrix, false, mov_matrix);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);

window.requestAnimationFrame(animate);
}
animate(0);

</script>

</body>
</html>

Animation Results

Page 11
WebGL 3D Project

Fig. 1 Animation result (A)

Page 12
WebGL 3D Project

Fig. 2 Animation result (B)

Page 13
WebGL 3D Project

Fig. 3 Animation result (C)

References
[1] https://www.3pillarglobal.com/
[2] https://www.merixstudio.com/blog/getting-started-WebGL-using-threejs/

Page 14
WebGL 3D Project

Page 15

Potrebbero piacerti anche