OpenGL Shading Language Tutorials

Simple Simulation of a bumpy Surface


This tutorial shows how to put a pattern on an object/light without using textures.

Vertex Shader:

varying vec3 N;
varying vec3 L;
varying vec3 v;
varying float pattern;             
const vec3 lightPos = vec3(0.0,5.0,5.0); // make this uniform
void main(void)
{
   v = vec3(gl_ModelViewMatrix * gl_Vertex);
   L = normalize(lightPos - v);
   N = normalize(gl_NormalMatrix * gl_Normal);
   pattern=fract(4.0*(gl_Vertex.y+gl_Vertex.x+gl_Vertex.z));
   gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
             

 

We create our pattern with this function:

pattern=fract(4.0*(gl_Vertex.y+gl_Vertex.x+gl_Vertex.z));

This pattern gives a certain 'noise' effect. (however, the noise factor is defined by the total amount of vertices, try it on a cube).


Our Fragment Shader is pretty simple:

varying vec3 N;
varying vec3 L;
varying vec3 v;
varying float pattern;
uniform vec4 color0; // Diffuse Color: 0.8, 0.0, 0.0, 1.0
uniform vec4 color1; // Ambient Color
uniform vec4 color2; // Specular Color: 0.8, 0.0, 0.0, 1.0
uniform vec3 eyePos; // Eye Position
#define shininess 10.0
void main (void)
{
vec3 E = normalize(eyePos - v); vec3 R = normalize(2.0 * dot(N,L) * N-L); // R = normalize(-reflect(L,N));
float spec = pow(max(dot(R,E),0.0), shininess);
float spec2= pattern*spec;
float diffuse = max(dot(N,L),0.0);
diffuse = smoothstep(diffuse, 0.0, 0.5);
gl_FragColor = color0*diffuse + color1 + color2*(spec+spec2);
}

The pattern is added to the specular value, this way we get the impression of a bumpy surface.

 

Go to Tutorial 10

 

 

 

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