473,406 Members | 2,273 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

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 InitializeGraphics() method.

Could you please tell me what is wrong? You can download this project
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
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Direct3D=Microsoft.DirectX.Direct3D;
using System.Diagnostics;

namespace MatricesTutorial
{
public class Matrices : Form
{
// Our global variables for this project
Device device = null; // Our rendering device
VertexBuffer vertexBuffer = null;
IndexBuffer MyIndexBuffer = null;
PresentParameters presentParams = new PresentParameters();
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 InitializeGraphics()
{
try
{
// Now let's setup our D3D stuff
presentParams.Windowed=true;
presentParams.AutoDepthStencilFormat = DepthFormat.D16;
presentParams.EnableAutoDepthStencil= true;
presentParams.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this,
CreateFlags.SoftwareVertexProcessing, presentParams);
device.DeviceReset += new System.EventHandler(this.OnResetDevice);
this.OnCreateDevice(device, null);
this.OnResetDevice(device, null);
device.RenderState.Lighting = true;
device.RenderState.NormalizeNormals = true;
device.RenderState.SpecularEnable = true;
SetupMaterials();
SetupLights();
pause = false;
return true;
}
catch (DirectXException)
{
return false;
}
}
public void OnCreateDevice(object sender, EventArgs e)
{
Debug.WriteLine("OnCreateDevice");
Device dev = (Device)sender;
// Now Create the VB
vertexBuffer = new
VertexBuffer(typeof(CustomVertex.PositionNormal), 24, dev, 0,
CustomVertex.PositionNormal.Format, Pool.Default);
vertexBuffer.Created += new
System.EventHandler(this.OnCreateVertexBuffer);
MyIndexBuffer = new IndexBuffer(typeof(short), 36, dev, 0,
Pool.Default);
MyIndexBuffer.Created += new EventHandler(OnCreateMyIndexBuffer);
this.OnCreateVertexBuffer(vertexBuffer, null);
}
void OnCreateMyIndexBuffer(object sender, EventArgs e)
{
IndexBuffer id = (IndexBuffer)sender;
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(object 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 OnCreateVertexBuffer(object sender, EventArgs e)
{
VertexBuffer vb = (VertexBuffer)sender;
CustomVertex.PositionNormal[] verts =
(CustomVertex.PositionNormal[])vb.Lock(0,0);
int index = 0;
//Front
verts[index++] = new CustomVertex.PositionNormal(0, -1, 1, 0, -1,
0);
verts[index++] = new CustomVertex.PositionNormal(1, -1, 1, 0, -1,
0);
verts[index++] = new CustomVertex.PositionNormal(0, -1, 0, 0, -1,
0);
verts[index++] = new CustomVertex.PositionNormal(1, -1, 0, 0, -1,
0);
//Right
verts[index++] = new CustomVertex.PositionNormal(1, -1, 1, 1,0, 0);
verts[index++] = new CustomVertex.PositionNormal(1, 0, 1, 1, 0, 0);
verts[index++] = new CustomVertex.PositionNormal(1, -1, 0, 1, 0,
0);
verts[index++] = new CustomVertex.PositionNormal(1, 0, 0, 1, 0, 0);
//Back
verts[index++] = new CustomVertex.PositionNormal(1, 0, 1, 0, 1, 0);
verts[index++] = new CustomVertex.PositionNormal(0, 0, 1, 0, 1, 0);
verts[index++] = new CustomVertex.PositionNormal(1, 0, 0, 0, 1, 0);
verts[index++] = new CustomVertex.PositionNormal(0, 0, 0, 0, 1, 0);
//Left
verts[index++] = new CustomVertex.PositionNormal(0, 0, 1, -1, 0,
0);
verts[index++] = new CustomVertex.PositionNormal(0, -1, 1, -1, 0,
0);
verts[index++] = new CustomVertex.PositionNormal(0, 0, 0, -1, 0,
0);
verts[index++] = new CustomVertex.PositionNormal(0, -1, 0, -1, 0,
0);
//Top
verts[index++] = new CustomVertex.PositionNormal(0, 0, 1, 0, 0, 1);
verts[index++] = new CustomVertex.PositionNormal(1, 0, 1, 0, 0, 1);
verts[index++] = new CustomVertex.PositionNormal(0, -1, 1, 0, 0,
1);
verts[index++] = new CustomVertex.PositionNormal(1, -1, 1, 0, 0,
1);
//Bottom
verts[index++] = new CustomVertex.PositionNormal(1, 0, 0, 0, 0,
-1);
verts[index++] = new CustomVertex.PositionNormal(0, 0, 0, 0, 0,
-1);
verts[index++] = new CustomVertex.PositionNormal(1, -1, 0, 0, 0,
-1);
verts[index++] = new CustomVertex.PositionNormal(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(ClearFlags.Target|ClearFlags.ZBuffer ,
System.Drawing.Color.White, 1.0f, 0);
//Begin the scene
device.BeginScene();
// Setup the world, view, and projection matrices
SetupMatrices();
device.SetStreamSource(0, vertexBuffer, 0);
device.VertexFormat = CustomVertex.PositionNormal.Format;
device.Indices = MyIndexBuffer;
device.DrawIndexedPrimitives(PrimitiveType.Triangl eList, 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.SpecularSharpness = 15.0F;

device.Material = mat;
// Very important - without this there is no specularity
device.RenderState.SpecularEnable = 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
radians)
// 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.TickCount % 7000;
float fAngle = iTime * (2.0f * (float)Math.PI) / 7000.0f;
device.Transform.World = Matrix.RotationYawPitchRoll(fAngle,
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.Transform.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.Transform.Projection =
Matrix.PerspectiveFovLH( (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.Directional;
device.Lights[0].Direction = new Vector3(1, -1, 0);

device.Lights[0].Update();

device.Lights[0].Enabled = true;
device.RenderState.Ambient = Color.FromArgb(0x40, 0x40, 0x40);
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs
e)
{
this.Render(); // Render on painting
}
protected override void
OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
if ((int)(byte)e.KeyChar == (int)System.Windows.Forms.Keys.Escape)
this.Close(); // Esc was pressed
}
protected override void OnResize(System.EventArgs e)
{
pause = ((this.WindowState == FormWindowState.Minimized)
|| !this.Visible);
}

/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
using (Matrices frm = new Matrices())
{
if (!frm.InitializeGraphics()) // 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.Created)
{
frm.Render();
Application.DoEvents();
}
}
}
}
}

Sep 22 '07 #1
0 1476

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

Similar topics

1
by: Sebastian Aguilera | last post by:
Hi everyone. I have some troubles using the unserialize() function. I have serialized an array and that works perfect: echo '<input type="hidden" name="vardekedja" value="'.serialize($_POST...
63
by: IAmIronMan | last post by:
This individual is stealing other peoples code and claiming it as his own. The proof is when I asked him to explain his code he would not. For proof view these threads in dotnet.languages.vb ...
10
by: sp | last post by:
The application is written in Visual Basic / .NET and working without problems under Windows XP, Windows 2000, Windows 2003 but it isn't working under Windows ME and Windows 98 - the computer...
2
by: PrinceMhul | last post by:
var objListBox = document.getElementById('catalist'); var val = objListBox.value; var txt = dyevalue00.value; document.getElementById(val).value = txt; To explain real quick, this is for a...
9
by: Ecohouse | last post by:
I have a main form with two subforms. The first subform has the child link to the main form identity key. subform1 - Master Field: SK Child Field: TrainingMasterSK The second subform has a...
11
by: drumsticksplinter | last post by:
Hi, I'm quite new to all this so please forgive my lack of technical description. Project background: Basically I have had the vision of creating a home lighting control system for the last 3...
0
by: Now You Know | last post by:
Christmas Decor Residential Commercial decoration Lighting install Los Angeles http://christmaslightinginstall.blogspot.com/
7
by: nassausky | last post by:
I acquired a very basic redirect script from: http://www.minisitegallery.com/blog/php-javascript-countdown-script-with-timezone-setting.html which is supposed to count down to a specified date and...
12
by: Hendor | last post by:
Hi all. I've recently set up Apache 2.2 with PHP 5.2 and MySQL 5.1. I played around with SQL a bit, and now I'm trying to access it with PHP. I currently have the code: <?php #...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.