Lightning in OpenGL with Material Effect
This is second tutorial on Lightning in OpenGL. In this tutorial, I will discuss about producing Material Effect in OpenGL. Material parameters specify how a surface reflects light. Applications change OpenGL material parameters to emulate different colored materials, shiny and flat materials, high gloss materials such as pool ball, etc.
The routine glColor3f(), sets the primary color and is a good idea to call this routine as long as we are not using lighting effects. The OpenGL lighting doesn’t use the primary color, instead uses the material colors. Hence it is important to introduce materials while talking about lighting.
So far we have seen a simple lighting example which has no material effects. But, in order to make the scene more attractive, we have to make use of materials. In the following code, we have used a green material. We make use of GL_SPECULAR, GL_AMBIENT, GL_SHININESS depending on the
scene requirements. The same parameters are also applicable to lighting methods.
Source Code:
#include <windows.h>#include <GL/glut.h>static double yVal=50.0;void drawSphere(){GLUquadricObj* cyl;GLfloat light_position[] = { 0.0, 40.0, yVal, 0.0 };glLightfv(GL_LIGHT0, GL_POSITION, light_position);GLfloat mat_specular[] = { 0.3f, 1.0f, 0.3f, 1.0f }; // Green color materialGLfloat mat_shininess[] = { 70.0 }; // Defines shininessglMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); // Using materialsglMaterialfv(GL_FRONT, GL_AMBIENT, mat_specular);glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);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, 50);glFlush();}void display(void){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-bufferglMatrixMode (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);glEnable(GL_LIGHT0);}void keyboard(unsigned char key, int x, int y){switch (key) {case 27: // “esc” on keyboardexit(0);break;case 97: // “a” on keyboardyVal = 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 ("Light Material effect - Programming Techniques");init ();glutDisplayFunc(display);glutKeyboardFunc(keyboard);glutMainLoop();return 0;}Output