Lights Camera

In real life you have light sources such as the sun, headlights, torches, or glowing lava pools. OpenGL lets you define up to eight light sources in your scene. There are two parts to lighting—a light and something to shine it on. Let's start with the light.

All 3D graphics libraries support three types of lighting:

• Ambient: A general glow that the light contributes to the entire scene, even to objects facing away from the light. It's important to have a little ambient light so you can pick out details even in the shadows.

• Diffuse: Soft directional lighting, as you might get from a fluorescent panel. Most of the light contributed to your scene will typically come from diffuse sources.

Figure 10.3: Drawing an unshaded cube

• Specular: Shiny light, usually from bright point sources. Combined with shiny materials, this gives you highlights (glints) that add realism.

A single light source can contribute all three types of light. These values go into a lighting equation that determines the color and brightness of each pixel on the screen.

The lighting is defined in the GLRenderer.onSurfaceCreated() method:

Download OpenGL/src/org/example/opengl/GLRenderer.java

float lightAmbient[] = new float[] { 0.2f, 0.2f, 0.2f, 1 }; float lightDiffuse[] = new float[] { 1, 1, 1, 1 }; float[] lightPos = new float[] { 1, 1, 1, 1 }; gl.glEnable(GL10.GL_LIGHTING); gl.glEnable(GL10.GL_LIGHT0);

gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, lightAmbient, 0); gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightDiffuse, 0); gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_P0SITIQN, lightPos, 0);

Figure 10.4: Lighting the scene

In our code we define one light source at position (1, 1, 1). It's a white omnidirectional light that has a bright diffuse component and a dim ambient component. In this example, we're not using specular lighting.

Next, we need to tell OpenGL about the materials our cube is made of. Light reflects differently off different materials, such as metal, plastic, or paper. To simulate this in OpenGL, add this code in onSurfaceCre-ated( ) to define how the material reacts with the three types of light: ambient, diffuse, and specular:

Download OpenGL/src/org/example/opengl/GLRenderer.java

float matAmbient[] = new float[] { 1, 1, 1, 1 }; float matDiffuse[] = new float[] { 1, 1, 1, 1 }; gl.glMaterialfv(GL10.GL_FR0NT_AND_BACK, GL10.GL_AMBIENT, matAmbient, 0); gl.glMaterialfv(GL10.GL_FR0NT_AND_BACK, GL10.GL_DIFFUSE, matDiffuse, 0);

The object will appear to have a dull finish, as if it were made out of paper (see Figure 10.4, on the previous page). The top-right corner of the cube is closer to the light, so it appears brighter.

0 0

Post a comment