CS155 Computer Graphics

OpenGL Lighting Tutorial

We'll continue with OpenGL tutorial to add lights.
  1. Modify your project as follows:
    Recompile and run your program. You should see the the purple (somewhat clunky) sphere. It looks more like a circle than a sphere because there is no lighting in the scene to provide visual cues as to the 3D shape. We'll add that next.

  2. Lighting: Specify light
    The first step is to specify the light. Add the following code to the init() function.
    	
    	GLfloat white[] = {1,1,1,1};				// light color
    	GLfloat lightPosition[]={-1,1,1,1};			// light position
    	glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);	// setlight position
    	glLightfv(GL_LIGHT0, GL_DIFFUSE, white);		// set diffuse light color
    	glLightfv(GL_LIGHT0, GL_SPECULAR, white);		// set specular light color
    	glEnable(GL_LIGHT0);
    
    The glLightfv() command takes three arguments. The first is the light number, which should be one of the OpenGL constants GL_LIGHTi. The second is the lighting parameter to be set, also one of the OpenGL constants. The final argument is the value the parameter should be set to. In this case,the value is a vector of floats, as specified by the fv in the command glLightfv(). (See Woo for a full description of argument specifications.) Note that OpenGL lighting is more flexible than the model we used for raytracing in that a light can provide different colors for diffuse and specular. (For more details on the possible parameters see Woo chapter 5.)

    You might be asking yourself how this specifies a point vs. a directional light. The answer is in the 4th value of the light position. A (-1,1,1,1) means the light is positioned at in the scene at (-1,1,1) while (-1,1,1,0) means that the light is at infinity and falls in direction <-1,1,1>. (I know... I'm just the messenger!)

  3. Lighting: Specify material properties
    The next step is to specify the material properties of the sphere. Replace the glColor3f()command in display() with the following code:
    	GLfloat white[] = {1,1,1,1};			// white
    	GLfloat purple[] = {1,0,1,1};			// purple
    	
    	glMaterialfv(GL_FRONT, GL_DIFFUSE, purple);
    	glMaterialfv(GL_FRONT, GL_DIFFUSE, white);
    	glMateriali(GL_FRONT,GL_SHININESS,50);	
    
    
    Just as with colors, the most recently defined properties apply to an object when it is drawn.
  4. Lighting: Enable
    The final step is to enable lighting. Add the following code to init().
    	
    	glEnable(GL_LIGHTING);
    

    Recompile your code and run it. You should now see the effects of lighting.


Created 10/07/em>