WebGL Workshop 1
Intro to GPU Programming with WebGL
Tarek Sherif
We want to do this...
Even the longest journey begins with a single step...
The basic idea...
-
If we can draw triangles and color them, we can build Assassin's Creed
- (At least the graphical part)
Basic steps
- Describe surface geometry in triangles
- Tell the GPU how it should manipulate the triangles and color them
- Draw
Client/Server Model
- JavaScript code is the client
- GPU is the server
-
JavaScript code sends commands and data to the GPU via WebGL
- gl.bufferData(...)
- gl.drawArrays(...)
State Machine
-
WebGL commands set up state on the GPU
E.g. Geometry, colors, etc.
- That state is used in the next draw command.
State Machine
Describe Geometry
var positions = new Float32Array([
-0.5, -0.5, 0.0, // Vertex 1
0.5, -0.5, 0.0, // Vertex 2
0.0, 0.5, 0.0 // Vertex 3
]);
Basic steps on the GPU
- Move vertices around (vertex shader)
- Map triangles to pixels on the screen (rasterization)
- Color the pixels (fragment shader)
- Display the scene
The process
Pipeline Components
We control
- Vertex shader
- Set gl_Position to tell WebGL the final vertex position
// attribute means it comes from the geometry
// array we created!
attribute vec4 aPosition;
void main() {
gl_Position = aPosition;
}
Normalized Device Coordinates
- gl_Position is given in normalized device coordinates
We don't control
-
Rasterization
- GPU figures out which pixels are covered by each triangle
- Interpolates vertex data to pixels along triangle surface
We control
- Fragment shader
- Set gl_FragColor to tell WebGL the final color of a pixel
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
What we did
- Shaders
- Programs
- Attributes
- Array buffers
- Varyings
- Uniforms
Shaders
- Vertex shader moves each vertex to its final NDC position
- Fragment shader colors a pixel covered by a triangle
Programs
- Combination of a vertex and a fragment shader
Attributes
- Per vertex data passed to vertex shader
- Includes positions, colors, normals, texture coordinates, etc.
Array buffers
- Storage location on GPU for vertex data
- Data has to be passed from the program into an array buffer
- Array buffer has to be bound to an attribute in the vertex shader
- Pointer must be enabled to tell GPU how to traverse the array
Varyings
- Data passed from vertex to fragment shader
- Output from vertex shader as per-vertex data
- Interpolated across triangle surface in rasterization step
- Interpolated values passed to fragment shader as per-pixel data
Uniforms
- Data passed from program to both vertex shader and fragment shader
- Remains constant for all vertices/pixels of a given object
- E.g. light position, camera position, time
That's pretty much it!
- That pretty much all the API you need to know to draw with WebGL
-
A couple of important ommissions: