50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
Introducao ao Curso Anselmo Cardoso de Paiva Ufma
1. Apresentação do Curso
Universidade Federal do Ma
Depto de Informática
Introdução à Computação Gráfica
Prof. Anselmo C. de Paiva
“A picture is a poem without words.”
― Horace
2. } Lecture Notes:
} Prof. Anselmo Paiva - UFMA
} Prof. Andy van Dam – Brown Univ.
} CS123 – INTR. TO COMPUTER GRAPHICS
} Book: Computer Graphics: Principles and Practice (3rd Ed.)
} Prof. Edward Angel - Univ. of New Mexico
} CS 352: Computer Graphics
} Book:
¨ Ed Angel and Dave Shreiner, Interactive Computer Graphics, A Top-down Approach with WebGL(Eighth Edition),
Addison-Wesley
¨ interactivecomputergraphics.com
} www.cs.unm.edu/~angel/BOOK/INTERACTIVE_COMPUTER_GRAPHICS
} Prof. Fredo Durand and Barb Cutler - MIT
} MIT EECS 6.837
Material do curso baseado em
2
3. Recursos na Web
} www.cs.unm.edu/~angel/BOOK
} Interactivecomputergraphics.com
} www.opengl.org
} get.webgl.org
} www.kronos.org/webgl
} www.chromeexperiments.com/webgl
} learningwebgl.com
3
4. } Introdução
} Dispositivos Gráficos
} Software Gráfico 2D
} Transformações Geométrica 2D e 3D
} Geometria Computacional
} 3D Rendering
} Projeções
} Modelos de Iluminação
} Rasterização e Clipping
} Ray Tracing
Programa
4
5. } Frequências:
} Resumo de cada aula a ser postado no google classroom até 48 horas após a aula
} Notas:
} Provas (Pi), Listas de exercício (Li), Trabalhos de Implementação (Ti)
Notai = 0,7 *Pi+ 0,2 *Ti+0,1*Li
} Listas de Exercício:
} Manuscritas (digitalizadas/fotografadas) e inseridas no Google Classroom
} Trabalhos de Implementação
} Individuais apresentado para o professor
} Regras da Resolução seguidas rigorosamente.
Avaliação
Prof. Anselmo C. de Paiva - DEINF-UFMA - Introdução à Computação Gráfica 5
6. } Polygons are rendered
} Normally one at a time
} Into a frame buffer.
} Is fast
} Support simplistic lighting models
} images do not necessarily look realistic.
} Single primitive
} the polygon
} everything must be made up of flat surfaces.
Polygon Based Rendering
22. } Example: Draw a triangle
} Each application consists of (at least) two files
} HTML file and a JavaScript file
} HTML
} describes page
} includes utilities
} includes shaders
} JavaScript
} contains the graphics
WebGL Introduction
22
23. } Can run WebGL on any recent browser
} Chrome
} Firefox
} Safari
} IE
} Code written in JavaScript (JS)
} JS runs within browser
} Use local resources
} Uses local GPU
Coding in WebGL
23
25. Example Triangle.html
Vertex Shader
<html>
<script id="vertex-shader" type="x-
shader/x-vertex">
#version 300 es
in vec4 aPosition;
void main()
{
gl_Position = aPosition;
}
</script>
Fragment Shader
<script id="fragment-shader" type="x-
shader/x-fragment">
#version 300 es
precision mediump float;
out vec4 fColor;
void main()
{
fColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}
</script>
25
26. "use strict";
var gl;
var points;
window.onload = function init()
{
var canvas = document.getElementById( "gl-canvas" );
gl = canvas.getContext('webgl2');
if (!gl) { alert( "WebGL 2.0 not available"); }
// Initialize data
points = new Float32Array([-1, -1 , 0, 1 , 1, -1 ]);
// Configure WebGL
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 1.0, 1.0, 1.0, 1.0 );
// Load shaders and init attribute buffers
var program = initShaders( gl, "vertex-shader", "fragment-shader"
);
gl.useProgram( program );
// Load the data into the GPU
var bufferId = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
gl.bufferData( gl.ARRAY_BUFFER, points, gl.STATIC_DRAW );
// Associate out shader variables buffer
var aPosition = gl.getAttribLocation(program, "aPosition" );
gl.vertexAttribPointer( aPosition, 2, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( aPosition );
render();
};
function render() {
gl.clear( gl.COLOR_BUFFER_BIT );
gl.drawArrays( gl.TRIANGLES, 0, 3 );
}
JS File
26
27. Exercise
} Download triangle.html and triangle.js to your computer from
Google Classroom
} Run the file
} Edit the two files to change the color and display more than one
triangle
27
28. } JavaScript (JS) is the language of the Web
} All browsers will execute JS code
} JavaScript is an interpreted object-oriented language
} References
} Flanagan, JavaScript: The Definitive Guide, O’Reilly
} Crockford, JavaScript, The Good Parts, O’Reilly
} Many Web tutorials
} Is JS slow?
} JS engines in browsers are getting much faster
} Not a key issues for graphics since once we get the data to the GPU it doesn’t matter how we got the data
there
} JS is a (too) big language
} We don’t need to use it all
} Choose parts we want to use
} Don’t try to make your code look like C or Java
JavaScript Notes
28
29. } Very few native types:
} numbers
} strings
} booleans
} Only one numerical type: 32 bit float
} var x = 1;
} var x = 1.0; // same
} potential issue in loops
} two operators for equality == and ===
} Dynamic typing
} Scoping
} Different from other languages
} Function scope
} variables are hoisted within a function
} can use a variable before it is declared
} Note functions are first class objects in
JS
JS Notes
29
30. } JS arrays are objects
} inherit methods
} var a = [1, 2, 3];
is not the same as in C++ or Java
} a.length // 3
} a.push(4); // length now 4
} a.pop(); // 4
} avoids use of many loops and indexing
} Problem for WebGL which expects C-
style arrays
} Typed Arrays
} JS has typed arrays that are like C
arrays
var a = new Float32Array(3)
var b = new Uint8Array(3)
} Generally, we work with standard JS
arrays and convert to typed arrays
only when we need to send data to
the GPU with the flatten function in
MV.js
JS Arrays
30
31. } We will use only core JS and HTML
} no extras or variants
} No additional packages
} CSS
} JQuery
} Focus on graphics
} examples may lack beauty
} You are welcome to use other variants as long as I can run them from your URL
A Minimalist Approach
31
33. Rendering Pipeline
Scene Description:
} Geometric Model
} Polygon Mesh Vertex
} Polygon Vertex
} View (camera specification)
} Lighting Data
} Texture Data
33
Image:
– Color values for pixels
frame buffer
34. } Primitives are processed in a series of stages
} Each stage forwards its result on to the next stage
} Can be drawn and implemented in different ways
} Stages in hardware or software
} Optimizations & additional programmability are available at some
stages
Rendering Pipeline
35. } 3D models defined in their own coordinate system (object space)
} Modeling transforms orient the models within a common cordinate frame
(world space)
} Positioning in scene
Rendering Pipeline
36. } Vertices lit (shaded) according to material properties, surface properties
(normal) and light source
} Local lighting model (Diffuse, Ambient, Phong, etc.)
Rendering Pipeline
37. } Maps world space to eye space
} Viewing positions is transformed to original & direction is oriented along some
axis (usually z)
Rendering Pipeline
38. } Portions of the object outside the view volume (view frustum) are removed
Rendering Pipeline
39. } The objects are projected to the 2D image place (screen space)
Rendering Pipeline
39
40. } Rasterizes objects into pixels
} Interpolate values as we go (color, depth, etc.)
Rendering Pipeline
40
42. } Cg preferred way of 3d models
} Collection of polygons, or faces, that form “skin” of object
} More flexible, represents complex surfaces better
} Examples:
} Human face
} Animal structures
} Furniture, etc
} Set of surface polygons that enclose an object interior, polygon mesh
} De facto: triangles, triangle mesh.
Polygonal Meshes
42
43. } Ubiquitous in CG because:
} no restriction on the shape and complexity of object
to be modeled
} volumes bounded by planar surfaces
} approximate curved surfaces
} trade off accuracy and speed
} either closer piecewise linear approximation
} or less space and lower processing/rendering time
} accuracy is application dependent: CAD vs. games
} plenty of algorithms and hardware to render
visually appealing shaded versions of polygonal
objects
} computers are very good at executing repetitive,
simple tasks, fast
What is a polygonal mesh?
43
44. } connected mesh of simple planar polygons that encloses a finite amount of
space.
} special case of a polygon mesh that satisfies the following properties:
} Every edge is shared by exactly two faces.
} At least three edges meet at each vertex.
} Faces do not interpenetrate. Faces at most touch along a common edge.
} Euler’s formula
} If F, E, V represent the number of faces, vertices and edges of a polyhedron, then
V + F - E = 2.
Polyhedron
45. } Method 1:
} Vertex List
} Normal List
} Face List (Polygon List)
} Method 2:
} Vertex List
} Edge List
} Face List (Polygon List)
Polygon Mesh Representation
46. } Vertex list:
} Array with the (x,y,z) of each vertex
} Polygon list
} Array with vértices connected to each polygon face
Data Structures – Vertex List
47. } Shared Edges
} Are drawn twice
} Alternatively: can store mesh by edge list
Vertex List Issue
53. } Fill the lists for Method 1 and Method 2 of Polygion meshes representation for
the Thetrahedron of the figure.
Exercise
54. } If the object is defined only by a set of nodes (vertices), and a set of lines
connecting the nodes, then the resulting object representation is called a wire-
frame model.
} Very suitable for engineering applications.
} Simplest 3D Model - easy to construct.
} Easy to clip and manipulate.
} Not suitable for building realistic models.
Wire-Frame Models
57. } Use the right-hand rule = conter-clockwise encirclement of outward-pointing
normal
} Focus on direction of traversal
} Orders {v1, v0, v3} and {v3, v2, v1} are same (ccw)
} Order {v1, v2, v3} is diferent (clockwise)
} What is outward-pointing normal
Polygon Traversal Condition
57
58. } Direction each polygon is facing
} Each mesh polygon has a normal vector
} Used in shading
Normal Vector
58
59. } Vertex list:
} Array with the (x,y,z) of each vertex
} Polygon list
} Array with vértices connected to each polygon face
Data Structures – Vertex List
60. } Shared Edges
} Are drawn twice
} Alternatively: can store mesh by edge list
Vertex List Issue
61. } Define global arrays for vertices and colors
typedef vex3 point3;
point3 vertices[] = {point3(-1.0,-1.0,-1.0),
point3(1.0,-1.0,-1.0), point3(1.0,1.0,-1.0),
point3(-1.0,1.0,-1.0), point3(-1.0,-1.0,1.0),
point3(1.0,-1.0,1.0), point3(1.0,1.0,1.0),
point3(-1.0,1.0,1.0)};
typedef vec3 color3;
color3 colors[] = {color3(0.0,0.0,0.0),
color3(1.0,0.0,0.0), color3(1.0,1.0,0.0),
color(0.0,1.0,0.0), color3(0.0,0.0,1.0),
color3(1.0,0.0,1.0), color3(1.0,1.0,1.0),
color3(0.0,1.0,1.0});
Modeling a Cube
62. } Draw a triangle from a list of indices into the array vertices and assign a color to
each index
void triangle(int a, int b, int c, int d)
{
vcolors[i] = colors[d];
position[i] = vertices[a];
vcolors[i+1] = colors[d]);
position[i+1] = vertices[a];
vcolors[i+2] = colors[d];
position[i+2] = vertices[a];
i+=3;
}
Drawing a triangle from a list of indices
63. void colorcube( )
{
quad(0,3,2,1);
quad(2,3,7,6);
quad(0,4,7,3);
quad(1,2,6,5);
quad(4,5,6,7);
quad(0,1,5,4);
}
// quad generates two triangles for each face and assigns colors to the vertices
int Index = 0;
void quad( int a, int b, int c, int d )
{
colors[Index] = vertex_colors[a]; points[Index] = vertices[a];
Index++;
colors[Index] = vertex_colors[b]; points[Index] = vertices[b];
Index++;
colors[Index] = vertex_colors[c]; points[Index] = vertices[c];
Index++;
colors[Index] = vertex_colors[a]; points[Index] = vertices[a];
Index++;
colors[Index] = vertex_colors[c]; points[Index] = vertices[c];
Index++;
colors[Index] = vertex_colors[d]; points[Index] = vertices[d];
Index++;
}
Draw cube from faces
66. } Vertex and face tables, analogous to 2D vertex
and edge tables
} Each vertex listed once, triangles listed as
ordered triplets of indices into the vertex table
} Edges inferred from triangles
} It’s often useful to store associated faces with
vertices (i.e. computing normals: vertex
normal average of surrounding face normals)
} Vertices listed in counter clockwise order in
face table.
} No longer just because of convention. CCW
order differentiates front and back of face
TriangularMeshRepresentation
71. var gl;
var points;
window.onload = function init(){
var canvas = document.getElementById( "gl-canvas" );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" );
}
// Three Vertices
var vertices = [
vec2( -1, -1 ),
vec2( 0, 1 ),
vec2( 1, -1 )
];
// Configure WebGL
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 1.0, 1.0, 1.0, 1.0 );
// Load shaders and initialize attribute buffers
var program = initShaders( gl, "vertex-shader", "fragment-shader" );
gl.useProgram( program );
// Load the data into the GPU
var bufferId = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
gl.bufferData( gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW );
// Associate out shader variables with our data buffer
var vPosition = gl.getAttribLocation( program, "vPosition" );
gl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vPosition );
render();
};
function render() {
gl.clear( gl.COLOR_BUFFER_BIT );
gl.drawArrays( gl.TRIANGLES, 0, 3 );
}
triangle.js
72. Recap: Vertex Buffer and Shader Attributes
Within the Javascript code, we have:
var bufferId = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
gl.bufferData( gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW );
...
var vPosition = gl.getAttribLocation( program, "vPosition" );
gl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0 );
Within the vertex shader (in HTML), we have:
<script id="vertex-shader" type="x-shader/x-vertex">
attribute vec4 vPosition;
void main(){
gl_Position = vPosition;
}
73. Angel and Shreiner:
Interactive
In OpenGL, we use vertex
buffer data to define the 3
vertex positions of the
triangle.
The vertex shader then
computes the screen positions
of the vertices.
And then Fragment shader fills
the inside of the triangle with a
lot of pixels.
74. Today’s Exercise #1
} Change the shaders to display a green triangle.
} Q1: Do you need to change the JavaScript code?
} Q2: What if we want to change the color within the JavaScript code?
77. window.onload = function init()
{
var canvas = document.getElementById( "gl-canvas" );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" ); }
// Three Vertices
var vertices = [
vec3( -1, -1, 0 ),
vec3( -0.5, 1, 0 ),
vec3( 0, -1, 0 ),
vec3( 0, -1, 0 ),
vec3( 0.5, 1, 0 ),
vec3( 1, -1, 0 )
];
Example 1: Green & Blue Triangles
(JavaScript code)
78. // Associate our shader variables with our data buffer
var vPosition = gl.getAttribLocation( program,
"vPosition" );
gl.vertexAttribPointer( vPosition, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vPosition );
var fColor = gl.getUniformLocation( program, "fColor" );
gl.clear( gl.COLOR_BUFFER_BIT );
gl.uniform4f( fColor, 0.0, 1.0, 0.0, 1.0 );
gl.drawArrays( gl.TRIANGLES, 0, 3 );
gl.uniform4f( fColor, 0.0, 0.0, 1.0, 1.0 );
gl.drawArrays( gl.TRIANGLES, 3, 3 );
};
(JavaScript code)
// Configure WebGL
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 1.0, 1.0, 1.0, 1.0 );
// Load shaders and initialize attribute buffers
var program = initShaders( gl, "vertex-shader",
"fragment-shader" );
gl.useProgram( program );
// Load the data into the GPU
var bufferId = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
gl.bufferData( gl.ARRAY_BUFFER, flatten(vertices),
gl.STATIC_DRAW );
79. A Quick Summary So Far
} Uniform parameters offer communication between shaders and
main (JS) program.
} Q1: Any other types of communication?
} A: Will discuss vertex attributes later.
} Q2: I want to know more about shaders!
} Q3: I still don’t know how vertex array buffer works?
} A: Our next topics (using SIGGRAPH 2014 materials)
81. Vertex Shaders
} A shader that’s executed for each vertex
} Each instantiation can generate one vertex
} Outputs are passed on to rasterizer where they are interpolated and available
to fragment shaders
} Position output in clip coordinates
} There are lots of effects we can do in vertex shaders
} Changing coordinate systems
} Moving vertices
} Per vertex lighting: height fields
82. } A shader that’s executed for each “potential” pixel
} fragments still need to pass several tests before making it to the framebuffer
} There are lots of effects we can do in fragment shaders
} Per-fragment lighting
} Texture and bump Mapping
} Environment (Reflection) Maps
Fragment Shaders
83. GLSL
} OpenGL Shading Language
} C like language with some C++ features
} 2-4 dimensional matrix and vector types
} Both vertex and fragment shaders are written in GLSL
} Each shader has a main()
85. } Standard C/C++ arithmetic and logic operators
} Overloaded operators for matrix and vector operations
mat4 m;
vec4 a, b, c;
b = a*m;
c = m*a;
Operators
86. } Access vector components using either:
} [ ] (C-style array indexing)
} xyzw, rgba or strq (named components)
} For example:
vec3 v;
v[1], v.y, v.g, v.t - all refer to the same element
} Component swizzling:
vec3 a, b;
a.xy = b.yx;
Components and Swizzling
87. } attribute
} vertex attributes from application
} varying
} copy vertex attributes and other variables from vertex shaders to fragment shaders
} values are interpolated by rasterizer
varying vec2 texCoord;
varying vec4 color;
} uniform
} shader-constant variable from application
uniform float time;
uniform vec4 rotation;
Qualifiers
88. Functions
} Built in
} Arithmetic: sqrt, power, abs
} Trigonometric: sin, asin
} Graphical: length, reflect
} User defined
89. } gl_Position
} (required) output position from vertex shader
} gl_FragColor
} (required) output color from fragment shader
} gl_FragCoord
} input fragment position
} gl_FragDepth
} input depth value in fragment shader
Built-in Variables
92. } Shaders need to be compiled
and linked to form an
executable shader program
} WebGL provides the compiler
and linker
} A WebGL program must contain
vertex and fragment shaders
Getting Your Shaders into WebGL
Create
Shader
Load Shader
Source
Compile Shader
Create Program
Attach Shader
to Program
Link Program
gl.createProgram()
gl.shaderSource()
gl.compileShader()
gl.createShader()
gl.attachShader()
gl.linkProgram()
Use Program gl.useProgram()
These steps
need to be
repeated for
each type of
shader in
the shader
program
93. A Simpler Way
} We’ve created a function for this course to make it easier to load your
shaders
} available at course website
initShaders(vFile, fFile );
} initShaders takes two filenames
} vFile path to the vertex shader file
} fFile for the fragment shader file
} Fails if shaders don’t compile, or program doesn’t link
95. } Geometric objects are represented using vertices
} A vertex is a collection of generic attributes
} positional coordinates
} colors
} texture coordinates
} any other data associated with that point in space
} Position stored in 4 dimensional homogeneous coordinates
} Vertex data must be stored in vertex buffer objects (VBOs)
Representing Geometric Objects
p =
x
y
z
w
é
ë
ê
ê
ê
ê
ù
û
ú
ú
ú
ú
96. } All primitives are specified by vertices
OpenGL Geometric Primitives
GL_TRIANGLE_STRIP
GL_TRIANGLE_FAN
GL_LINES GL_LINE_LOOP
GL_LINE_STRIP
GL_TRIANGLES
GL_POINTS
97. } Vertex data must be stored in a Vertex Buffer Object (VBO)
} To set up a VBO we must
} create an empty by calling gl.createBuffer(); ()
} bind a specific VBO for initialization by calling
gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );
} load data into VBO using (for our points)
gl.bufferData( gl.ARRAY_BUFFER, flatten(points),
gl.STATIC_DRAW );
Storing Vertex Attributes
99. A Quick Note on Buffers & Attributes
} createBuffer(), bindBuffer(), and bufferData() tell
OpenGL where the actual data is stored in the
memory.
} vertexAttribPointer() and
enableVertexAttribArray() tells OpenGL which
shader attributes will use them.
100. } So far, we ignore the last three parameters of vertexAttribPointer(), e.g.,
vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );
} Exercise #1: Look up the definition of vertexAttribPointer()
https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glVer
} Exercise #2: See a different use of vertexAttribPointer() at:
https://github.com/openglredbook/examples/blob/master/src/04-
gouraud/04-gouraud.cpp
vertexAttribPointer()
103. } HTML code
<script id="vertex-shader" type="x-shader/x-vertex">
attribute vec4 vPosition;
attribute vec4 vColor;
varying vec4 fColor;
void main() {
fColor = vColor;
gl_Position = vPosition;
}
</script>
<script id="fragment-shader" type="x-shader/x-fragment">
precision mediump float;
varying vec4 fColor; // Note that this will be interpolated ...
void main() {
gl_FragColor = fColor;
}
</script>
Example 2: Per-Vertex Color
104. } window.onload = function init() {
var canvas = document.getElementById( "gl-
canvas" );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't
available" ); }
// Three Vertices
var vertices = [
vec3( -1, -1, 0 ),
vec3( 0, 1, 0 ),
vec3( 1, -1, 0 )
];
var colors = [
vec3( 1, 0, 0 ),
vec3( 0, 1, 0 ),
vec3( 0, 0, 1 )
];
// Configure WebGL
//
gl.viewport( 0, 0, canvas.width,
canvas.height );
gl.clearColor( 1.0, 1.0, 1.0, 1.0 );
// Load shaders and initialize attribute
buffers
var program = initShaders( gl, "vertex-shader",
"fragment-shader" );
gl.useProgram( program );
// Load the data into the GPU
var bufferId = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
gl.bufferData( gl.ARRAY_BUFFER,
flatten(vertices), gl.STATIC_DRAW );
Example 2: Per-Vertex Color - Javascript Code
105. // Associate our shader variables with our data buffer
var vPosition = gl.getAttribLocation( program, "vPosition" );
gl.vertexAttribPointer( vPosition, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vPosition );
// Repeat the above process for the color attributes of the vertices.
var cBufferId = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, cBufferId );
gl.bufferData( gl.ARRAY_BUFFER, flatten(colors), gl.STATIC_DRAW );
var vColor = gl.getAttribLocation( program, "vColor" );
gl.vertexAttribPointer( vColor, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vColor );
render();
};
Example 2: Per-Vertex Color - Javascript Code
106. Debugging Tips
} Typos in JavaScript code may not produce any error message.
} Try typing a wrong variable name (e.g., vColor à fColor) or wrong
function name (e.g., getAttributeLocation) and see what happens.
} Syntax errors like these will show up in the Console panel of the
Chrome Developer Tools.
107. Homework #1
} Draw at least two triangles like Example 1, with per-vertex colors
like Example 2.
108. • Render a cube with a different color for each face
• Our example demonstrates:
– simple object modeling
• building up 3D objects from geometric primitives
• building geometric primitives from vertices
– initializing vertex data
– organizing data for rendering
– interactivity
– animation
Our Second Program
109. } We’ll build each cube face from individual triangles
} Need to determine how much storage is required
} (6 faces)(2 triangles/face)(3 vertices/triangle)
var numVertices = 36;
} To simplify communicating with GLSL, we’ll use a package MV.js which contains a vec3
object similar to GLSL’s vec3 type
Initializing the Cube’s Data
110. } Before we can initialize our VBO, we need to stage the data
} Our cube has two attributes per vertex
} position
} color
} We create two arrays to hold the VBO data
var points = [];
var colors = [];
Initializing the Cube’s Data (cont’d)
111. } Vertices of a unit cube centered at
origin
} sides aligned with axes
var vertices = [
vec4( -0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, -0.5, -0.5, 1.0 ),
vec4( -0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, -0.5, -0.5, 1.0 )
];
} We’ll also set up an array of RGBA colors
} We can use vec3 or vec4 or just JS array
var vertexColors = [
[ 0.0, 0.0, 0.0, 1.0 ], // black
[ 1.0, 0.0, 0.0, 1.0 ], // red
[ 1.0, 1.0, 0.0, 1.0 ], // yellow
[ 0.0, 1.0, 0.0, 1.0 ], // green
[ 0.0, 0.0, 1.0, 1.0 ], // blue
[ 1.0, 0.0, 1.0, 1.0 ], // magenta
[ 0.0, 1.0, 1.0, 1.0 ], // cyan
[ 1.0, 1.0, 1.0, 1.0 ] // white
];
Cube Data
1
7
4
6
7
2
3
0
112. } A JS array is an object with attributes and methods such as length, push() and
pop()
} fundamentally different from C-style array
} cannot send directly to WebGL functions
} use flatten() function to extract data from JS array
gl.bufferData( gl.ARRAY_BUFFER, flatten(colors), gl.STATIC_DRAW );
Arrays in JS
113. } To simplify generating the geometry, we use a convenience function quad()
} create two triangles for each face and assigns colors to the vertices
function quad(a, b, c, d) {
var indices = [ a, b, c, a, c, d ];
for ( var i = 0; i < indices.length; ++i ) {
points.push( vertices[indices[i]] );
// for vertex colors use
//colors.push( vertexColors[indices[i]] );
// for solid colored faces use
colors.push(vertexColors[a]);
}
Generating a Cube Face from Vertices