Wednesday, February 1, 2012

Lightning in OpenGL without material effect .

This is the first tutorial in Lightning in OpenGL. In this tutorial, I am going to show you how to produce a simple lightning effect in OpenGL without material effect. In later tutorial, I will discuss about material effect and also discuss about spot light. OpenGL implementations are required to have at least 8 primary lights ranging from GL_LIGHT0 to GL_LIGHT7. In order to use lighting in the code, we have to first enable lighting by calling the routine glEnable(GL_LIGHTING). A glLookAt() routine sets the camera position and we have can set the position of the lighting using glLightfv(). This routine actually sets the direction of the light, but not the actual position of the light. Though we are able to set a position for the light source, the light source behaves as if it is at an infinite distance. The following example creates a sphere and produces a simple light effect.
 Source Code

#include <windows.h>
#include <GL/glut.h>

static double yVal=50.0;

void drawSphere(){
    GLUquadricObj* cyl;
    GLfloat light_position[] = { 0.0, 20.0, yVal, 10.0 };
    glLightfv(GL_LIGHT0, GL_POSITION, light_position); // Using lighting (effects all the objects drawn below)
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(35.0, 1.0, 1.0, 100.0);
    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt (30.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
    cyl = gluNewQuadric();
    gluQuadricDrawStyle(cyl, GLU_FILL);
    gluSphere(cyl, 2.0, 50, 100);
    glFlush();
}

void display(void){
    /* clear all pixels */
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    drawSphere();
    glFlush ();
}

void init (void){
    glClearColor (0.5, 0.5, 0.5, 0.0);
    glEnable(GL_DEPTH_TEST); //enabling z-buffer
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(35.0, 1.0, 1.0, 100.0);
    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt (30.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
    glEnable(GL_LIGHTING); // Enable lighting
    glEnable(GL_LIGHT0); // Enable the first light (LIGHT0)
}

void keyboard(unsigned char key, int x, int y){
    switch (key) {
        case 27: // “esc” on keyboard
        exit(0);
        break;
        case 97: // “a” on keyboard
        yVal = yVal-5.0;
        glutPostRedisplay();
    break;
    }
}

int main(int argc, char** argv){
    glutInit(&argc, argv);
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize (600, 600);
    glutInitWindowPosition (100, 100);
    glutCreateWindow ("Simple Light example - Programming Technique");
    init ();
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMainLoop();
    return 0;
}



Output

LightningOpenGL

No comments:

Post a Comment