11. OpenGL Lighting

This opengl tutorial will show you how to use opengl light within your opengl application. Lighting is also very easily achieved in OpenGL.
You enable the depth, the lighting, and which light you are using.

Lighting is something that you must have to achieve the appearance of a
3d object.

Luckily OpenGL comes with its own lights.

To get our lighting up and running, we need to enable our depth support.

I have done it with this:
The first line clears the depth buffer
glClearDepth(1);
The second line enables depth testing
glEnable(GL_DEPTH_TEST);

Next we need to enable the OpenGL lighting support.
To do this simply call the line:
glEnable(GL_LIGHTING);

Now that we have depth and lighting, we need lights. OpenGL has direct
support for about 8 lights.

To enable a light, just call:
glEnable(GL_LIGHT0);

There is also:
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glEnable(GL_LIGHT2);
glEnable(GL_LIGHT3);
glEnable(GL_LIGHT4);

… etc.

Now that we have some, depth and lighting, run the program and you will
see that our cube is now lit. But it is only white and grey.
This is because we have not set the colours of our lights or the object
in which we are lighting. And also, even though we have set colours for the
objects in the past with:
glColor3f(1,0,0);
That won’t work with lights unless you enable:
glEnable(GL_COLOR_MATERIAL);

Now if you have any problems, feel free to email me at swiftless@gmail.com

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
    #include <GL/gl.h>
#include <GL/glut.h>

GLfloat angle = 0.0;

void cube (void) {
    glRotatef(angle, 1.0, 0.0, 0.0);
    glRotatef(angle, 0.0, 1.0, 0.0);
    glRotatef(angle, 0.0, 0.0, 1.0);
    glColor3f(1.0, 0.0, 0.0);
    glutSolidCube(2);
}

void init (void) {
    glEnable (GL_DEPTH_TEST);
    glEnable (GL_LIGHTING);
    glEnable (GL_LIGHT0);
}

void display (void) {
    glClearColor (0.0,0.0,0.0,1.0);
    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();  
    gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    cube();
    glutSwapBuffers();
    angle ++;
}

void reshape (int w, int h) {
    glViewport (0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity ();
    gluPerspective (60, (GLfloat)w / (GLfloat)h, 1.0, 100.0);
    glMatrixMode (GL_MODELVIEW);
}

int main (int argc, char **argv) {
    glutInit (&argc, argv);
    glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH
);
    glutInitWindowSize (500, 500);
    glutInitWindowPosition (100, 100);
    glutCreateWindow (“A basic OpenGL Window);
    init ();
    glutDisplayFunc (display);
    glutIdleFunc (display);
    glutReshapeFunc (reshape);
    glutMainLoop ();
    return 0;
}

  • March 25, 2010
  • 12