tutorial 4

We add a new action to our kGLView class to change the lighting. We also add some arrays to hold the lights that we will be creating, and a boolean so that we know what the current state of the lighting is. You will also set up your NIB to include a Lights menu item. Set it to initially be checked (or "on").


// we would need a set of these for however many lights we wanted to include
GLfloat LightAmbient [4]; GLfloat LightDiffuse [4]; GLfloat LightPosition[4];
// this boolean tells us whether lighting is taken into consideration or not
bool lighting; - (IBAction)changeLighting:(id)sender;

Here's the code for changeLighting. In this, we will be marking a check next to the state, so when lighting is on, there is a check beside the menu item, and when lighting is off, the menu item is left blank.


if( lighting )
// disable lighting and take the checkmark off of lighting menu item
{ glDisable( GL_LIGHTING ); [sender setState: NSOffState]; } else
// enable lighting and add a checkmark to lighting menu item
{ glEnable( GL_LIGHTING ); [sender setState: NSOnState]; } lighting = !lighting;

We need to add the lighting to initGL. We need to set up the light's position and color, then we need to turn the light on. If we don't turn the light on, then the scene will be black when we start (because lighting is enabled, there must be a light on if you don't want a dark screen).


// enable the lighting and set our boolean to true
glEnable(GL_LIGHTING); lighting = true;
// set light 1's ambient light color
LightAmbient[0] = 0.5f; LightAmbient[1] = 0.5f; LightAmbient[2] = 0.5f; LightAmbient[3] = 1.0f;
// set light 1's diffuse light color
LightDiffuse[0] = 1.0f; LightDiffuse[1] = 1.0f; LightDiffuse[2] = 1.0f; LightDiffuse[3] = 1.0f;
// position light 1's origin
LightPosition[0]= 0.0f; LightPosition[1]= 0.0f; LightPosition[2]= 2.0f; LightPosition[3]= 1.0f;
// tell OpenGL about what we just did and turn the light on
glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); glLightfv(GL_LIGHT1, GL_POSITION,LightPosition); glEnable(GL_LIGHT1);

Now, your lights will work. Go ahead, try it.

Oops, did I forget to mention they won't work normally? You need to specify normals for your lights to work properly! Luckily, this is a very simple operation in the case of our box. A normal is a line pointing outward from the box. Because it's a box, we will specify 8 normals, one for each side.

You call for your normal as soon as you enter your drawing mode. The normal will be different on each side, but is translated and rotated just like any of the other calls in OpenGL that have to do with drawing.


glBegin(drawing_type); glNormal3f( 0.0f, 1.0f, 0.0f);

There we go! Now your dice work exactly as you'd expect when it comes to lighting. Try turning the lighting on and off to see the different effect that lighting makes.


     Download the project builder files

 

return to deep cocoa / cocoagl tutorials