Pro OpenGL ES for iOS

(singke) #1

98 CHAPTER 4: Turning On the Lights^


Listing 4-1. Initializing the lights

-(void)initLighting
{
GLfloat diffuse[]={0.0,1.0,0.0,1.0}; //1
GLfloat pos[]={0.0,10.0,0.0,1.0}; //2

glLightfv(SS_SUNLIGHT,GL_POSITION,pos); //3
glLightfv(SS_SUNLIGHT,GL_DIFFUSE,diffuse); //4

glShadeModel(GL_FLAT); //5

glEnable(GL_LIGHTING); //6
glEnable(SS_SUNLIGHT); //7
}
This is what’s going on:
„ The lighting components are in the standard RGBA normalized form.
So in this case, there is no red, maximum green, and no blue. The final
value of alpha should be kept at 1.0 for now, because it will be
covered in more detail later.
„ Line 2 specifies the position of the light. It is at a y of +10 so, it will be
hovering above our sphere.
„ In lines 3 and 4, we set the light’s position and the diffuse component
to the diffuse color. glLightfv() is a new call and is used to set
various light-related parameters. You can retrieve any of this data at a
later time using glGetLightfv(), which retrieves any of the parameters
from a specific light.
„ In line 5 we specify a shading model. Flat means that a face is a single
solid color, while setting it to GL_SMOOTH will cause the colors to blend
smoothly across the face and from face to face.
„ And finally, line 6 tells the system we want to use lighting, while line 7
enables the one light we’ve created.

Note The final parameter of glLightfv() takes an array of four GLfloat values; the fv
suffix means “float-vector.” There is also a glLightf() call to set single-value parameters.

Now compile and run. Eh? What’s that, you say? You see only a black thing about the
size of the super-massive black hole at the center of the galaxy M31? Oh yes, we forgot
something, sorry. As previously mentioned, OpenGL in all of its varieties still remains a
relatively low-level library, so it is up to the programmer to handle all sorts of
housekeeping tasks that you’d expect a higher-level system to manage (and it gets
much worse on OpenGL ES 2.0). And once the lights are turned on, the predefined
vertex colors are ignored, so we get black. With that in mind, our sphere model needs
an extra layer of data to tell the system just how to light its facets, and that is done
through an array of normals for each vertex.
Free download pdf