OpenGL Shading Language Tutorials

Uniform Variables: Communication between C++ and OGLSL Program


Uniform variables are used to communicate with your vertex or fragment shader. In your shader you use the 'uniform' qualifier to declare the variable, for example:

uniform float myVar;

Uniform variables are read-only and have the same value among all processed vertices. You can only change them within your C++ program.

A simple OGLSL Vertex Shader

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

In this example the z coordinate is being scaled with an uniform variable and then the scaled vertex is transformed with the concatenated modelview and projection matrix.

C++ Code

Setting variables is easy with the appropriate function in the object class:

// globals:

aShaderManager shadermanager;
aShaderObject* myShader;


// init:
myShader = shadermanager.loadfromFile("test.vert","test.frag");


// draw-loop:

myShader->begin();
myShader->sendUniform1f("Scale", 1.231f);
glutSolidTeapot();
myShader->end();

 


Go to Tutorial 3


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

 

 

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