- Code Framework
- Where to Download the Examples
- Hello Triangle Example
- Building and Running the Examples
- Using the OpenGL ES 2.0 Framework
- Creating a Simple Vertex and Fragment Shader
- Compiling and Loading the Shaders
- Creating a Program Object and Linking the Shaders
- Setting the Viewport and Clearing the Color Buffer
- Loading the Geometry and Drawing a Primitive
- Displaying the Back Buffer
Compiling and Loading the Shaders
Now that we have the shader source code defined, we can go about loading the shaders to OpenGL ES. The LoadShader function in the Hello Triangle example is responsible for loading the shader source code, compiling it, and checking to make sure that there were no errors. It returns a shader object, which is an OpenGL ES 2.0 object that can later be used for attachment to a program object (these two objects are detailed in Chapter 4, “Shaders and Programs”).
Let's take a look at how the LoadShader function works. The shader object is first created using glCreateShader, which creates a new shader object of the type specified.
GLuint LoadShader(GLenum type, const char *shaderSrc) { GLuint shader; GLint compiled; // Create the shader object shader = glCreateShader(type); if(shader == 0) return 0;
The shader source code itself is loaded to the shader object using glShaderSource. The shader is then compiled using the glCompileShader function.
// Load the shader source glShaderSource(shader, 1, &shaderSrc, NULL); // Compile the shader glCompileShader(shader);
After compiling the shader, the status of the compile is determined and any errors that were generated are printed out.
// Check the compile status glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if(!compiled) { GLint infoLen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen); if(infoLen > 1) { char* infoLog = malloc(sizeof(char) * infoLen); glGetShaderInfoLog(shader, infoLen, NULL, infoLog); esLogMessage("Error compiling shader:\n%s\n", infoLog); free(infoLog); } glDeleteShader(shader); return 0; } return shader; }
If the shader compiles successfully, a new shader object is returned that will be attached to the program later. The details of these shader object functions are covered in the first sections of Chapter 4.