# OpenGL:Tutorials:Vertex operations with GLSL

## An OpenGL Shader Tutorial

This tutorial is intended to demonstrate the basic use of a vertex shader. Familiarity with OpenGL and its extension system is assumed. The code contained here is C++, OpenGL Version 1.4 with the use of ARB Extensions. For OpenGL Version 2.0 and higher, the ARB suffix on identifiers may be removed.

## Vertex Transformation

A rather interesting application of a shader is to flatten a model.

void main(void) { //A new temporary position variable, since gl_Vertex is read only vec4 position = vec4(gl_Vertex); position.z = 0.0; //Set the z coordinate of the vertex to zero. //gl_ModelViewProjectionMatrix is a precalculated matrix. it is equal to gl_ModelViewMatrix * gl_ProjectionMatrix gl_Position = gl_ModelViewProjectionMatrix * position; //Transform it. }

This code will result in a flat model, since the Z component of all the input vertexes is set to zero before the world transformation.

## Waving the model

Mathematical functions can also be used in the vertex shader. A simple application would be to modify the z coordinate of the model, based on its x position. This will create a simple waving effect.

void main(void) { //Another new temporary position variable, since gl_Vertex is read only vec4 position = vec4(gl_Vertex); //Now, the z coordinate is the result of sin(position.x); This will create a wavy model position.z = sin(position.x); //Translate the vertex. gl_Position = gl_ModelViewProjectionMatrix * position; }

This works by setting the Z component of the input vertex to the sine of the x component. This makes the model wave up and down as it progresses along the x axis.

## Fragment Shader

The fragment shader used for these demostrations is trivial.

void main() { //Set the result as a white model. gl_FragColor = vec4(1, 1, 1, 1); }