4 Coding Geometries in WebGL
4 Coding Geometries in WebGL
in WebGL
Bhupendra Singh
[email protected]
Assistant Professor
UPES, Dehradun
1
Simple Geometries
2
Default Coordinate system in WebGL
3
Drawing below geometry?
4
First: Draw geometry’s coordinates and
indexing
5
Second: Specify vertices information in
WebGL
Define vertex data in JS array variable
var vertices = [
// X Y Z R G B
-0.5, -0.5, 0, 0, 0, 0, //1
-0.5, 0.5, 0, 0, 0, 0, //2
0, 0.9, 0, 0, 0, 0, //3
0.5, 0.5, 0, 0, 0, 0, //4
0.5, -0.5, 0, 0, 0, 0 //5
];
6
Third: Break the geometry into constituent
triangles
7
Fourth: Number the triangles
8
Five: Specify the triangles containing
corresponding vertex number in clockwise
order
• Step 3: Define vertex data in JS array variable
var pentagonIndices = [
0, 1, 4, //1st triangle
1, 2, 3, //2nd triangle
1, 3, 4 //3rd triangle
];
9
Six: Create buffer for vertices as VBO
• Step 4: Create buffer (in GPU) for vertex data
• Step 5: Load the JS array (defined in Step 3) for vertex data onto the
GPU buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices),
gl.STATIC_DRAW);
10
Seven: Create buffer for indices as IBO
Create Index Buffer Object (in GPU) for vertex data
var pentgonIndexBufferObject = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,
pentgonIndexBufferObject);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(pentagonIndices),
gl.STATIC_DRAW);
11
Eight: Draw the geometry with
drawElement() Call
Draw the geometry
gl.drawElements(gl.TRIANGLES,
pentagonIndices.length,
gl.UNSIGNED_SHORT,
0);
12
Application Output
13
Let’s now draw geometry with colors
14
Required geometry
15
Which one color to apply on common
vertices?
16
Idea:
17
18
Divide ‘1’ vertex into Three
Red Color
-0.5, 0.5, 0, 1, 0, 0, //1 1
Green Color
-0.5, 0.5, 0, 0, 1, 0, //2 1’
Blue Color
-0.5, 0.5, 0, 0, 0, 1, //3 1''
19
Divide ‘3’ vertex into Two
Blue
0.5, 0.5, 0, 0, 0, 1, //5 3
Green
0.5, 0.5, 0, 0, 1, 0, //6 3'
20
Divide ‘4’ vertex into Two
Red
0.5, -0.5, 0, 1, 0, 0, //7 4
Green
0.5, -0.5, 0, 0, 1, 0 //8 4'
21
Vertices definition in the JS array
Define vertex data in JS array variable
var vertices = [
// XY Z R G B
-0.5, -0.5, 0, 1, 0, 0, //0
-0.5, 0.5, 0, 1, 0, 0, //1 1
-0.5, 0.5, 0, 0, 1, 0, //2 1'
-0.5, 0.5, 0, 0, 0, 1, //3 1''
0, 0.9, 0, 0, 0, 1, //4 2
0.5, 0.5, 0, 0, 0, 1, //5 3
0.5, 0.5, 0, 0, 1, 0, //6 3'
0.5, -0.5, 0, 1, 0, 0, //7 4
0.5, -0.5, 0, 0, 1, 0 //8 4'
];
22
Corresponding triangles indices
Define index data in JS array variable
var pentagonIndices = [
0, 1, 7,
3, 4, 5,
2, 6, 8
];
23
Exercise: Draw the below figure with
specified colors
24
Thank you
25