WebGL Textures & Vertices

Beginner's Guide

Page Forty Five

The Vertex Shader

This section covers the default vertex shader line by line. The file GLControl.js defines a default vertex and default fragment shader. If a Web page includes a shader, then the controller uses the shader. Otherwise the controller uses shaders defined in GLControl.js. The book's examples all use the default shaders.

Vertex Shader Introduction

This section presents a number of new concepts for readers unfamiliar with shaders. Subsequent sections tie the information together. The sections titled WebGL API vertexAttribPointer() for Vertices and WebGL API vertexAttribPointer() for Texels explain how to specify attribute processing. The section titled 4 x 4 Matrices explains rotation and translation with a matrix. The section titled Perspective Projection introduces perspective with matrices. Perspective Projection also demonstrates how to upload values for uniforms.

The default vertex shader processes one vertex and one texel at a time. The vertices and texels originate from a JavaScript array. For example data from the aVertices array in the GLSquare constructor, eventually passes through the vertex shader.

Outputs from the vertex shader include gl_Position and v_tex_coord0. When the vertex shader completes processing, the built in variable gl_Position contains coordinates for one vertex. The shader modifies vertex coordinates to display rotation and perspective projection. The varying named v_tex_coord0, represents one texel from the original array.

The following listing includes the entire vertex shader. We added line numbers to identify each line for discussion.

1.attribute vec4 a_position;   
2.attribute vec2 a_tex_coord0;

3.varying vec2 v_tex_coord0;
4.uniform mat4 um4_matrix;
5.uniform mat4 um4_pmatrix;
6.void main(void) {

7.gl_Position = um4_pmatrix * um4_matrix * a_position;

8.v_tex_coord0 = a_tex_coord0;


Listing 42a: Vertex Shader with Line Numbers

WebGL Beginner's Guide Introduction WebGL Beginner's Guide
Copyright © 2015 Seven Thunder Software. All Rights Reserved.