OpenGL Shading Language Tutorials

Loading, Compiling and Linking OGLSL Programs


A simple OGLSL Example

Vertex Shader
Incoming x and y components are scaled with a factor 0.5 and then the scaled vertex is transformed with the concatenated modelview and projection matrix.

void main(void)
{
 vec4 a = gl_Vertex;
 a.x = a.x * 0.5;
 a.y = a.y * 0.5; 
 gl_Position = gl_ModelViewProjectionMatrix * a;
}

 

Fragment Shader
We set every fragment to green! Output color (gl_FragColor) is a vector with r,g,b,a components.

void main (void)
{
   gl_FragColor = vec4 (0.0, 1.0, 0.0, 1.0);
}
 


C++ helper classes

I wrote 4 classes to simplify managing OpenGL Extensions, loading, compiling and linking shader programs. In this and in future tutorials we can concentrate on OGLSL programs and not on C, C++ code to actually load and compile programs.

Using ShaderManager to load/compile/link Programs

aShaderManager is a class to simplify loading and compiling shader programs. The idea is to reduce this process to 1-2 statements: The following code example draws a solid sphere using a OGLSL vertex and fragment program:

// globals: 
aShaderManager shadermanager;
aShaderObject* shader;
// init:

shader = shadermanager.loadfromFile("test.vert","test.frag");


//draw:
shader->begin()
glutSolidSphere(1.0,32,32);
shader->end();

 

The ShaderManager has the following methods:

aShaderObject* loadfromFile(char* vertexFile, char* fragmentFile); // load vertex/fragment shader from file
aShaderObject* loadfromMemory(const char* vertexMem, const char* fragmentMem);
bool free(aShaderObject* o);


loadFromFile: loads shader source code from file, compiles, links and returns a shader object.
loadfromMemory: instead of using files you can specify memory addresses containing a null terminated char array of the program string.
free: if you don't need a shader anymore you can free it. Usually this function isn't needed, the destructor of the ShaderManager frees memory.


We will learn more about the aShaderObject class in future tutorials.

 

Without aShaderManager

If you want to do define advanced shader objects that need to be linked together the process is a bit more. You can go ahead to to Tutorial 2 this part isn't really important for most users.

You want to see the advanced method of creating shader objects with custom compiler error messages etc ? continue here


Author: Martin Christen, christen@clockworkcoders.com
(source code is included in Tutorial Version 0.1 and higher)

 

 

© 2004 by Martin Christen. All Rights Reserved.
christen@clockworkcoders.com