Microsoft DirectX 8.1 (Visual Basic)

Step 2.2: Creating a Light

There are three types of lights available in Microsoft® Direct3D®. These are point lights, directional lights, and spotlights. The Lights sample project creates a directional light, which is a light that goes in one direction and oscillates the direction of the light.

The following code fragment uses the D3DLIGHT8 type to define a directional light.

Dim light As D3DLIGHT8
light.Type = D3DLIGHT_DIRECTIONAL

The following code fragment sets the diffuse color for this light to white.

light.diffuse.r = 1#
light.diffuse.g = 1#
light.diffuse.b = 1#

The following code fragment rotates the direction of the light around in a circle.

light.Direction.x = Cos(Timer * 2)
light.Direction.y = 1#
light.Direction.z = Sin(Timer * 2)

A range can be specified to tell Direct3D how far the light will have an effect. This member does not affect directional lights. The following code fragment assigns a range of 1000 units to this light.

light.Range = 1000#

The following code fragment assigns the light to the Direct3D device by calling Direct3DDevice8.SetLight.

g_D3DDevice.SetLight 0, light     'Let Direct3D know about the light.

The first parameter that SetLight accepts is the index that this light will be assigned to. Note that if a light already exists at that location, then it will be overwritten by the new light. The second parameter is a pointer to the light structure that defines the light. The Lights sample project places this light at index 0.

The code following fragment enables the light by calling Direct3DDevice8.LightEnable.

g_D3DDevice.LightEnable 0, 1

The first parameter that LightEnable accepts is the index of the light to enable. The second parameter is a value that tells whether to turn the light on (1) or off (0). In the Lights sample project, the light at index 0 is turned on.

The next step that this sample takes is to turn on ambient lighting by calling Direct3DDevice8.SetRenderState.

g_D3DDevice.SetRenderState D3DRS_AMBIENT, &H202020

The two parameters that SetRenderState accepts is which device state variable to modify and what value to set it to. The sample sets the D3DRS_AMBIENT device variable to a light gray color (&H202020). Ambient lighting will light up all objects by the given color.

Before using lights in Direct3D, they must be enabled. The following code fragment tells Direct3D to render lights by calling SetRenderState.

g_D3DDevice.SetRenderState D3DRS_LIGHTING, 1    'Make sure lighting is enabled.

This sample sets the D3DRS_LIGHTING device variable to 1(True), which has the effect of enabling the rendering of lights.

For more information on lighting, see Mathematics of Direct3D Lighting.

This tutorial has shown you how to use lights and materials. Tutorial 5: Using Texture Maps shows you how to add texture to surfaces.