473,903 Members | 3,525 Online

# Why isn't the lighting working?

There's a sample project in the DirectX SDK that draws a revolving
triangle. From it, I've written a simple program that draws a
revolving box. The problem is, even though I have set the material and
the light, the box is completly black. I don't know what's wrong.

The C# tutorial on an internet site, which I have read to write this,
calls SetupLights() each time in the Render(), but the example
(written in Visual C++) on my textbook initialzes lights and materials
only once at the setup() function. I thought the later way is better
so I initialized them at the InitializeGraph ics() method.

file at
http://www.gloomywind.com/box.rar
Or see the complete code below.
Thanks.

//-----------------------------------------------------------------------------
// File: Matrices.cs
//
// Desc: Now that we know how to create a device and render some 2D
vertices,
// this tutorial goes the next step and renders 3D geometry. To
deal with
// 3D geometry we need to introduce the use of 4x4 matrices to
transform
// the geometry with translations, rotations, scaling, and
setting up our
// camera.
//
// Geometry is defined in model space. We can move it
(translation),
// rotate it (rotation), or stretch it (scaling) using a world
transform.
// The geometry is then said to be in world space. Next, we need
to
// position the camera, or eye point, somewhere to look at the
geometry.
// Another transform, via the view matrix, is used, to position
and
// rotate our view. With the geometry then in view space, our
last
// transform is the projection transform, which "projects" the
3D scene
// into our 2D viewport.
//
// Note that in this tutorial, we are introducing the use of
D3DX, which
// is a set of helper utilities for D3D. In this case, we are
using some
// of D3DX's useful matrix initialization functions. To use
D3DX, simply
// include the D3DX reference in your project
//
//-----------------------------------------------------------------------------
using System;
using System.Drawing;
using System.Windows. Forms;
using Microsoft.Direc tX;
using Microsoft.Direc tX.Direct3D;
using Direct3D=Micros oft.DirectX.Dir ect3D;
using System.Diagnost ics;

namespace MatricesTutoria l
{
public class Matrices : Form
{
// Our global variables for this project
Device device = null; // Our rendering device
VertexBuffer vertexBuffer = null;
IndexBuffer MyIndexBuffer = null;
PresentParamete rs presentParams = new PresentParamete rs();
bool pause = false;

public Matrices()
{
// Set the initial size of our form
this.ClientSize = new System.Drawing. Size(400,300);
// And it's caption
this.Text = "Direct3D Tutorial 3 - Matrices";
}

public bool InitializeGraph ics()
{
try
{
// Now let's setup our D3D stuff
presentParams.W indowed=true;
presentParams.A utoDepthStencil Format = DepthFormat.D16 ;
presentParams.E nableAutoDepthS tencil= true;
presentParams.S wapEffect = SwapEffect.Disc ard;
device = new Device(0, DeviceType.Hard ware, this,
CreateFlags.Sof twareVertexProc essing, presentParams);
device.DeviceRe set += new System.EventHan dler(this.OnRes etDevice);
this.OnCreateDe vice(device, null);
this.OnResetDev ice(device, null);
device.RenderSt ate.Lighting = true;
device.RenderSt ate.NormalizeNo rmals = true;
device.RenderSt ate.SpecularEna ble = true;
SetupMaterials( );
SetupLights();
pause = false;
return true;
}
catch (DirectXExcepti on)
{
return false;
}
}
public void OnCreateDevice( object sender, EventArgs e)
{
Debug.WriteLine ("OnCreateDevic e");
Device dev = (Device)sender;
// Now Create the VB
vertexBuffer = new
VertexBuffer(ty peof(CustomVert ex.PositionNorm al), 24, dev, 0,
CustomVertex.Po sitionNormal.Fo rmat, Pool.Default);
vertexBuffer.Cr eated += new
System.EventHan dler(this.OnCre ateVertexBuffer );
MyIndexBuffer = new IndexBuffer(typ eof(short), 36, dev, 0,
Pool.Default);
MyIndexBuffer.C reated += new EventHandler(On CreateMyIndexBu ffer);
this.OnCreateVe rtexBuffer(vert exBuffer, null);
}
void OnCreateMyIndex Buffer(object sender, EventArgs e)
{
IndexBuffer id = (IndexBuffer)se nder;
short[] indices = (short[])id.Lock(0, 0);
int index = 0;
indices[index++] = 0;
indices[index++] = 2;
indices[index++] = 1;
indices[index++] = 1;
indices[index++] = 2;
indices[index++] = 3;

indices[index++] = 4;
indices[index++] = 6;
indices[index++] = 5;
indices[index++] = 5;
indices[index++] = 6;
indices[index++] = 7;

indices[index++] = 8;
indices[index++] = 10;
indices[index++] = 9;
indices[index++] = 9;
indices[index++] = 10;
indices[index++] = 11;

indices[index++] = 12;
indices[index++] = 14;
indices[index++] = 13;
indices[index++] = 13;
indices[index++] = 14;
indices[index++] = 15;

indices[index++] = 16;
indices[index++] = 18;
indices[index++] = 17;
indices[index++] = 17;
indices[index++] = 18;
indices[index++] = 19;

indices[index++] = 20;
indices[index++] = 22;
indices[index++] = 21;
indices[index++] = 21;
indices[index++] = 22;
indices[index++] = 23;

id.Unlock();
}
public void OnResetDevice(o bject sender, EventArgs e)
{
Device dev = (Device)sender;
// Turn off culling, so we see the front and back of the triangle
//dev.RenderState .CullMode = Cull.None;
// Turn off D3D lighting, since we are providing our own vertex
colors
//dev.RenderState .Lighting =false;
Debug.WriteLine ("Reset");
}
public void OnCreateVertexB uffer(object sender, EventArgs e)
{
VertexBuffer vb = (VertexBuffer)s ender;
CustomVertex.Po sitionNormal[] verts =
(CustomVertex.P ositionNormal[])vb.Lock(0,0);
int index = 0;
//Front
verts[index++] = new CustomVertex.Po sitionNormal(0, -1, 1, 0, -1,
0);
verts[index++] = new CustomVertex.Po sitionNormal(1, -1, 1, 0, -1,
0);
verts[index++] = new CustomVertex.Po sitionNormal(0, -1, 0, 0, -1,
0);
verts[index++] = new CustomVertex.Po sitionNormal(1, -1, 0, 0, -1,
0);
//Right
verts[index++] = new CustomVertex.Po sitionNormal(1, -1, 1, 1,0, 0);
verts[index++] = new CustomVertex.Po sitionNormal(1, 0, 1, 1, 0, 0);
verts[index++] = new CustomVertex.Po sitionNormal(1, -1, 0, 1, 0,
0);
verts[index++] = new CustomVertex.Po sitionNormal(1, 0, 0, 1, 0, 0);
//Back
verts[index++] = new CustomVertex.Po sitionNormal(1, 0, 1, 0, 1, 0);
verts[index++] = new CustomVertex.Po sitionNormal(0, 0, 1, 0, 1, 0);
verts[index++] = new CustomVertex.Po sitionNormal(1, 0, 0, 0, 1, 0);
verts[index++] = new CustomVertex.Po sitionNormal(0, 0, 0, 0, 1, 0);
//Left
verts[index++] = new CustomVertex.Po sitionNormal(0, 0, 1, -1, 0,
0);
verts[index++] = new CustomVertex.Po sitionNormal(0, -1, 1, -1, 0,
0);
verts[index++] = new CustomVertex.Po sitionNormal(0, 0, 0, -1, 0,
0);
verts[index++] = new CustomVertex.Po sitionNormal(0, -1, 0, -1, 0,
0);
//Top
verts[index++] = new CustomVertex.Po sitionNormal(0, 0, 1, 0, 0, 1);
verts[index++] = new CustomVertex.Po sitionNormal(1, 0, 1, 0, 0, 1);
verts[index++] = new CustomVertex.Po sitionNormal(0, -1, 1, 0, 0,
1);
verts[index++] = new CustomVertex.Po sitionNormal(1, -1, 1, 0, 0,
1);
//Bottom
verts[index++] = new CustomVertex.Po sitionNormal(1, 0, 0, 0, 0,
-1);
verts[index++] = new CustomVertex.Po sitionNormal(0, 0, 0, 0, 0,
-1);
verts[index++] = new CustomVertex.Po sitionNormal(1, -1, 0, 0, 0,
-1);
verts[index++] = new CustomVertex.Po sitionNormal(0, -1, 0, 0, 0,
-1);

vb.Unlock();
}

private void Render()
{
if (device == null)
return;

if (pause)
return;
//Clear the backbuffer to a blue color
device.Clear(Cl earFlags.Target |ClearFlags.ZBu ffer ,
System.Drawing. Color.White, 1.0f, 0);
//Begin the scene
device.BeginSce ne();
// Setup the world, view, and projection matrices
SetupMatrices() ;
device.SetStrea mSource(0, vertexBuffer, 0);
device.VertexFo rmat = CustomVertex.Po sitionNormal.Fo rmat;
device.Indices = MyIndexBuffer;
device.DrawInde xedPrimitives(P rimitiveType.Tr iangleList, 0, 0, 24,
0, 12);

//End the scene
device.EndScene ();
device.Present( );
}
protected void SetupMaterials( )
{
Material mat = new Material();
// Set the properties of the material
// The object itself will be blue
mat.Diffuse = Color.Red;
//mat.Emissive = Color.Orange;
//mat.Ambient = Color.Purple;

// We want it to look slightly dull, so maybe a grey
// wide highlight
mat.Specular = Color.LightGray ;
mat.SpecularSha rpness = 15.0F;

device.Material = mat;
// Very important - without this there is no specularity
device.RenderSt ate.SpecularEna ble = true;
}
private void SetupMatrices()
{
// For our world matrix, we will just rotate the object about the y-
axis.

// Set up the rotation matrix to generate 1 full rotation (2*PI
// every 1000 ms. To avoid the loss of precision inherent in very
high
// floating point numbers, the system time is modulated by the
rotation
// period before conversion to a radian angle.
int iTime = Environment.Tic kCount % 7000;
float fAngle = iTime * (2.0f * (float)Math.PI) / 7000.0f;
device.Transfor m.World = Matrix.Rotation YawPitchRoll(fA ngle,
fAngle,fAngle );

// Set up our view matrix. A view matrix can be defined given an
eye point,
// a point to lookat, and a direction for which way is up. Here, we
set the
// eye five units back along the z-axis and up three units, look at
the
// origin, and define "up" to be in the y-direction.
device.Transfor m.View = Matrix.LookAtLH ( new Vector3( 0.0f,
3.0f,-5.0f ), new Vector3( 0.0f, 0.0f, 0.0f ), new Vector3( 0.0f,
1.0f, 0.0f ) );

// For the projection matrix, we set up a perspective transform
(which
// transforms geometry from 3D view space to 2D viewport space,
with
// a perspective divide making objects smaller in the distance). To
build
// a perpsective transform, we need the field of view (1/4 pi is
common),
// the aspect ratio, and the near and far clipping planes (which
define at
// what distances geometry should be no longer be rendered).
device.Transfor m.Projection =
Matrix.Perspect iveFovLH( (float)Math.PI / 4, 1.0f, 1.0f, 100.0f );
}
protected void SetupLights()
{
device.Lights[0].Diffuse = Color.Yellow;
device.Lights[0].Specular = Color.Yellow;
device.Lights[0].Ambient = Color.Yellow;
device.Lights[0].Type = LightType.Direc tional;
device.Lights[0].Direction = new Vector3(1, -1, 0);

device.Lights[0].Update();

device.Lights[0].Enabled = true;
device.RenderSt ate.Ambient = Color.FromArgb( 0x40, 0x40, 0x40);
}
protected override void OnPaint(System. Windows.Forms.P aintEventArgs
e)
{
this.Render(); // Render on painting
}
protected override void
OnKeyPress(Syst em.Windows.Form s.KeyPressEvent Args e)
{
if ((int)(byte)e.K eyChar == (int)System.Win dows.Forms.Keys .Escape)
this.Close(); // Esc was pressed
}
protected override void OnResize(System .EventArgs e)
{
pause = ((this.WindowSt ate == FormWindowState .Minimized)
|| !this.Visible);
}

/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
using (Matrices frm = new Matrices())
{
if (!frm.Initializ eGraphics()) // Initialize Direct3D
{
MessageBox.Show ("Could not initialize Direct3D.
This tutorial will exit.");
return;
}
frm.Show();
frm.ClientSize = new Size(500, 500);
// While the form is still valid, render and process
messages
while(frm.Creat ed)
{
frm.Render();
Application.DoE vents();
}
}
}
}
}

Sep 22 '07 #1
0 1512

This thread has been closed and replies have been disabled. Please start a new discussion.