0% found this document useful (0 votes)
67 views

3 D Tutorial

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

3 D Tutorial

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Contents

• Intro
• Manage Directx 9 THIS IS TO HELP YOU UNDERSTAND
• Why use C# MICROSOFT DIRECTX C# TUTORIAL. I TRIED
• What you will need TO EXPLAIN AS BEST AS I COULD. AND
COMPILDE THE CODE TO TEST IT. UNLIKE
• Getting Started MICROSOFT. I KNOW THERE ARE A LOT OF
• Device GRAMMAR ERROR THAT PROOF THE AM
HUMAN AND NOT A ROBOT. ANYHOW HOPE
• Vertices THIS HELP YOU
• Matrices AND VISIT THE LINKS @ THE BUTTON
• Lights
• Texture
• Meshes
• Good links

Intro:- Hello 3D world


After reading this tutorial you would not be able to code a halo game. If that’s
was your intension sorry. However you will get the basic idea of manage DirectX 9 and
the major changes Microsoft made to help out programmers. I will try to make it as easy
as can be so everyone could understand it.

Manage Directx 9:- Gift from the gods

With DirectX 9.0, programmers can take advantage of DirectX multimedia


functionality and hardware acceleration while using managed code. DirectX 9.0 for
Managed Code enables access to most of the original unmanaged DirectX functionality.
The following are the managed code languages supported by DirectX 9.0 and
documented in the software development kit (SDK).

• Microsoft Visual C#®


• Microsoft Visual Basic® .NET
• Microsoft Visual C++®
• Microsoft JScript® .NET
Why use C#:- Hercules Hercules

C# is an elegant, simple, type-safe, object-oriented language that allows


programmers to build a breadth of applications. C# also gives you the capability to build
durable system-level components by virtue of the following features:

• Full COM/Platform support for existing code integration.


• Robustness through garbage collection and type safety.
• Security provided through intrinsic code trust mechanisms.
• Full support of extensible metadata concepts.

What you will need:- freeloaders

Compiler + Net Framework

 Ok we are going to use Sharp Develop a free .Net IDE


 To use Sharp Develop you need the .Net Framework (its free)

SDK

 You need the DirectX 9 SDK . know if you don’t get this right
you should not be coding at all. Get DirectX 9.0 SDK for
Managed Code Please get this right cause noob always get this
wrong.

Getting Started:- Its About Time

1. Run Sharp Develop >>Open a new Combine>>Open the Direct3d


application

1. Note: Add the refference if you have too, please don’t noob out
2. Note: Yes code will run on Visual C#. thats what am using
3. Note: Yes new virsion of Sharp Develop has DirectX 9 Keyword support
Now compile the project by pressing F8 and Run it With F5. This is just a test to
see if the compiler and the DirectX are both happy. If it did not work and you don’t know
what the problem is ask at csharp-home.com or better yet go to Sharp Develop Forum
and search, then post. Now delete everything in the file not the header declarations at the
top and let’s get this party started. Your file should look like this.

1. using System;
2. using System.Collections;
3. using System.ComponentModel;
4. using System.Drawing;
5. using System.Windows.Forms;
6. using Microsoft.DirectX;
7. using Microsoft.DirectX.Direct3D;

Ok time to create our window and set up our main loop. its nothing like c++, less
work and very important, Less Typing. 

1. namespace MYWIN
2. {
3. public class MYFORM : Form
4. {
5. public MYFORM ()
6. {
7. this.ClientSize = new System.Drawing.Size(200,200);
8. this.Text = "CSharp-Home Direct3D Tutorial";
9. }
10. static void Main()
11. {
12. using (MYFORM MYWIN = new MYFORM())
13. {
14. MYWIN.Show();
15. while(MYWIN.Created)
16. {
17. Application.DoEvents();
18. }
19. }
20. }
21. }
22. }

Line 3 public class MYFORM : Form is our class that inherit from the Form class
Line 5 public MYFORM () is the constructor
Line 12 using (MYFORM MYWIN = new MYFORM()) just create an object that is easy to find bugs in
Line 15 while (MYWIN.Created) is our main loop. In English it read. While the window is created, do events.

If everything works out fine, don’t get to happy, this is just the window with the title you
could do this with the design editor. In the next section you will learn how to create a
Device. But for now your program should look like this
Device:- Am In Control
Continuing with the above code, We are going to Add a function a to initialize a DirectX
9 Device to our Class. Right under the constructor create a public function call
InitializeDirectX(); Then go create a device object so that all function could see it. I
mean don’t put it in a method;
public Device device=null;
device is out Device object, the Device function looks like this

public Device(
int adapter,
DeviceType deviceType,
Control renderWindow,
CreateFlags behaviorFlags,
PresentParameters[] presentationParameters
);
All but the last parameters are built in. The PresentParameters struct have to be filed in
by you.
1. public bool InitializeDirectX()
2. {
3. try
{
4. PresentParameters presentParams = new PresentParameters();
5. presentParams.Windowed=true;
6. presentParams.SwapEffect = SwapEffect.Discard;
7. device = new Device(0, DeviceType.Hardware,this,
CreateFlags.SoftwareVertexProcessing,
presentParams);
return true;
}
8. catch (DirectXException) //sweet for error debuging
{
9. return false;
}
10. }
The next function is the Render function. This is not needed but it keeps everything
clean. It goes in the main loop and or in the OnPaint function.

11. private void Render()


12. {
13. if (device == null)
14. return;
15. //Clear the backbuffer to a blue color
16. device.Clear(ClearFlags.Target,
System.Drawing.Color.Blue, 1.0f, 0);
17. //Begin the scene
18. device.BeginScene();
19. // Rendering of scene objects can happen here
20. //End the scene
21. device.EndScene();
22. device.Present();
23. }

Now Go back to the main function and add both functions to the execution. In the correct
place
1. using (MYFORM MYWIN = new MYFORM())
2. {
3. MYWIN.Show();
4. MYWIN.InitializeDirectX();
5. while(MYWIN.Created)
6. {
7. MYWIN.Render();
8. Application.DoEvents();
9. }
10. }

Your program should now look like this


Vertices:- hey, this is no 3D?

Before we continue lets add some use less function to our program. Well not useless but we not going
to use it a lot. I like to put it under the main function

1. protected override void OnPaint


(System.Windows.Forms.PaintEventArgs e)
2. {
this.Render(); // Render on painting
3. }

4. protected override void OnKeyPress


(System.Windows.Forms.KeyPressEventArgs e)
5. {
6. if ((int)(byte)e.KeyChar == (int)
System.Windows.Forms.Keys.Escape)
7. this.Close(); // Esc was pressed
8. }

Back to work. First we start by creating a VertexBuffer


VertexBuffer vertexBuffer = null;

What is VertexBuffer? A Buffer of Vertex. What is a Vertex? Why did you cut math
class ?. Look in the msdn for all noob answers. www.msdn.com. Ok VertexBuffer object
is used to store and render vertices.
Now we are going to add some more function to out program.

1. public void OnCreateDevice(object sender, EventArgs e)


2. {
3. Device dev = (Device)sender;
4. // Now Create the vertexBuffer
5. vertexBuffer = new
VertexBuffer(typeof(CustomVertex.TransformedColored), 3, dev, 0,
CustomVertex.TransformedColored.Format, Pool.Default);
6. vertexBuffer.Created += new
System.EventHandler(this.OnCreateVertexBuffer);
7. this.OnCreateVertexBuffer(vertexBuffer, null); // don’t painc wait
8. }

As you could see most of the code is c#. But CustomVertex.TransformedColored


might make you cry. TransformedColored vertices also do not use Direct3D lighting;
they supply their own diffuse color. So we initializing the vertex buffer with the
CustomVertex.TransformedColored structure. Later on in the tutorial we are going to
use other member of CustomVertex struct

Next is our OnCreateVertexBuffer function. The code will tell our VertexBuffer
what to render and Color to render it in.
1. public void OnCreateVertexBuffer(object sender, EventArgs e)
2. {
3. VertexBuffer vb = (VertexBuffer)sender; // c#
4. GraphicsStream stm = vb.Lock(0, 0, 0);
5. CustomVertex.TransformedColored[] verts = new
CustomVertex.TransformedColored[3];

6. verts[0].X=150;verts[0].Y=50;verts[0].Z=0.5f; verts[0].Rhw=1;
verts[0].Color = System.Drawing.Color.Aqua.ToArgb();
7. verts[1].X=250;verts[1].Y=250;verts[1].Z=0.5f; verts[1].Rhw=1;
verts[1].Color = System.Drawing.Color.Brown.ToArgb();
8. verts[2].X=50;verts[2].Y=250;verts[2].Z=0.5f; verts[2].Rhw=1;
verts[2].Color = System.Drawing.Color.LightPink.ToArgb();
9. stm.Write(verts);
10. vb.Unlock();
11. }

Now to explain the above code


Line
• 4 grant direct CPU access to the vertex buffer data. Undo in line 10
• 6 install the points and set the color
• 9 provides the GraphicsStream object direct access to the vertex buffer

Am tired ! Red Bull time…. Ok Lets Update Our Render function

1. private void Render()


2. {
3. if (device == null)
4. return;
5. //Clear the backbuffer to a blue color (ARGB = 000000ff)
6. device.Clear(ClearFlags.Target, System.Drawing.Color.Blue,
1.0f, 0);
7. device.BeginScene();
8. device.SetStreamSource( 0, vertexBuffer, 0);
9. device.VertexFormat =
CustomVertex.TransformedColored.Format;
10. device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);
11. device.EndScene();
12. device.Present();
13. }

Explain lines
• 9 look up parameters
• 10 set the vertex format to be the same as the vertex
• 11 draws. change parameter to get a good idea

Add this this.OnCreateDevice(device, null); to the InitializeDirectX() function under the


Device creation. So it look like this
1. try
2. {
3. PresentParameters presentParams = new PresentParameters();
4. presentParams.Windowed=true;
5. presentParams.SwapEffect = SwapEffect.Discard;

6. device = new Device(0, DeviceType.Hardware,this,


7. CreateFlags.SoftwareVertexProcessing,
8. presentParams);

9. this.OnCreateDevice(device, null); //<---- added


10. return true;
11. }

Now compile and run the code and if the debugger don’t pop up BINGO
Your program should look like this

Matrices:- Not The Movie


In this section the vertex buffer is initialized with the CustomVertex.PositionColored
structure. Why ? Because this project will apply transformations to the triangle. First we
going To start by updating our public void OnCreateDevice(object sender, EventArgs e)
Function. Yes the one we did long ago. We not goanna make any major changes to this
function just some simple stuff. We going to update our
CustomVertex.TransformedColored to CustomVertex.PositionColored and change
the format too.
1. public void OnCreateDevice(object sender, EventArgs e)
2. {
3. Device dev = (Device)sender;
4. // Now Create the VB
5. vertexBuffer = new
VertexBuffer(typeof(CustomVertex.PositionColored), 3, dev, 0,
CustomVertex.PositionColored.Format, Pool.Default);
6. vertexBuffer.Created += new
System.EventHandler(this.OnCreateVertexBuffer);
7. this.OnCreateVertexBuffer(vertexBuffer, null);
8. }

Thats not the hard work, we have to add 2 function and update our render function. I
want to stop typing and go chat in yahoo Programming:1 room. I will stop after Matrix
for (;;) a while. Let’s add our functions. The first function is our public void
OnResetDevice(object sender, EventArgs e); Guess what this function does ? Something
when the device is reset right?

1. public void OnResetDevice(object sender, EventArgs e)


2. {
3. Device dev = (Device)sender;
4. // Turn off culling, so we see the front and back of the
triangle
5. dev.RenderState.CullMode = Cull.None;
6. // Turn off D3D lighting, since we are providing our own
vertex colors
7. dev.RenderState.Lighting = false;
8. }

Even thought the comments tell what it does. You should try different method to get a
good idea. Put lighting true and explore the Cull struct. Our next function is our private
void SetupMatrices(); I like to look at this as our cam you will see why.

1. private void SetupMatrices()


2. { //use for roation
3. int iTime = Environment.TickCount % 1000;
4. float fAngle = iTime * (2.0f * (float)Math.PI)/ 1000.0f;
5. //use for roation on the Y axis try to change Y to Z or X
6. device.Transform.World = Matrix.RotationY( fAngle );
7. //tell the cam where to look at Vector3 hold the 3 points
8. 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 ) );
9. // this if for projection an we use PerspectiveFovLH not RH google
left //hand 3d and right hand 3d
10. device.Transform.Projection = Matrix.PerspectiveFovLH(
(float)Math.PI / 4, 1.0f, 1.0f, 100.0f );
11. }
I know it look kind of nasty but in MSVC# is ship with 3 colors and you have to change
the IDE and I did not get time to change the IDE so.. I change it with MS word.
Time to update our program ;
First thing First
• make PresentParameters presentParams = new PresentParameters(); global
• This is our VertexBuffer I explain this. This is just our shape
1)public void OnCreateVertexBuffer(object sender, EventArgs e)
1) {
2) VertexBuffer vb = (VertexBuffer)sender;
3) CustomVertex.PositionColored[] verts =
(CustomVertex.PositionColored[])vb.Lock(0,0);
4) verts[0].X=-1.0f; verts[0].Y=-1.0f; verts[0].Z=0.0f; verts[0].Color =
System.Drawing.Color.DarkGoldenrod.ToArgb();
5) verts[1].X=1.0f; verts[1].Y=-1.0f ;verts[1].Z=0.0f; verts[1].Color =
System.Drawing.Color.MediumOrchid.ToArgb();
6) verts[2].X=0.0f; verts[2].Y=1.0f; verts[2].Z = 0.0f; verts[2].Color =
System.Drawing.Color.Cornsilk.ToArgb();
7) vb.Unlock();
8) }
• public bool InitializeDirectX() time to add on again. It should now look like this
1. try
2. {
3. // Now let's setup our D3D stuff
4. presentParams.Windowed=true;
5. presentParams.SwapEffect = SwapEffect.Discard;
6. device = new Device(0, DeviceType.Hardware, this,
CreateFlags.SoftwareVertexProcessing, presentParams);
7. device.DeviceReset += new System.EventHandler(this.OnResetDevice);
8. this.OnCreateDevice(device, null);
9. this.OnResetDevice(device, null);
10. return true;
11. }

• Last but not least our Render function

1) private void Render()


2) {
3) if (device == null)
4) return;
5) device.Clear(ClearFlags.Target, System.Drawing.Color.Blue,
1.0f, 0);
6) device.BeginScene();
7) SetupMatrices(); // just add our cam
8) device.SetStreamSource(0, vertexBuffer, 0);
9) device.VertexFormat = CustomVertex.PositionColored.Format;
10) device.DrawPrimitives(PrimitiveType.TriangleList,0, 1);
11) device.EndScene();
12) device.Present();
13) }

Ok if this don’t work it might not be you bug it might be mine. So look in the sdk and
see what wrong or ask in csharp-home.com forum. However it did work I tried it;
Your Program should look like this, with a spinning triangle. I install style Xp so the title
bar looks different

Lights: - Let there be lights;


To use lighting in D3D, you must create one or more lights, setup a material, and
make sure your geometry contains surface normals. Materials describe the surface of
your geometry, specifically, how it gets lit (diffuse color, ambient color, etc.).
Surface normals are part of a vertex, and are needed for the D3D's internal lighting
calculations. Let’s get to work……

Depth stencils enable applications to mask sections of the rendered image so that they are
not displayed.
We start by adding to our PresentParameters struct

presentParams.EnableAutoDepthStencil = true; // Turn on a Depth stencil


presentParams.AutoDepthStencilFormat = DepthFormat.D16; // And the
stencil format

Now its time to change our format in public void OnCreateDevice(object sender,
EventArgs e). so it should now look like this.

1. public void OnCreateDevice(object sender, EventArgs e)


2. {
3. Device dev = (Device)sender;
4. // Now Create the VB
5. vertexBuffer = new
VertexBuffer(typeof(CustomVertex.PositionNormal), 100, dev,
Usage.WriteOnly, CustomVertex.PositionNormal.Format,
Pool.Default);
6. vertexBuffer.Created += new
System.EventHandler(this.OnCreateVertexBuffer);
7. this.OnCreateVertexBuffer(vertexBuffer, null);
8. }
I highlight the changes so you will not noob out on me. Read the intro to light you will
know why we made the changes.

1. public void OnResetDevice(object sender, EventArgs e)


2. {
3. Device dev = (Device)sender;
4. // Turn off culling, so we see the front and back of the
triangle
5. device.RenderState.CullMode = Cull.None;
6. // Turn on the ZBuffer
7. device.RenderState.ZBufferEnable = true;
8. device.RenderState.Lighting = true; //make sure lighting is
enabled
9. }

Remember this function. You must have we just turned on lights.

Ok so this always freak you out. Its just math ok. So if you don’t get it don’t cry. Math is
done in an xfile and imported. (Later)

1. public void OnCreateVertexBuffer(object sender, EventArgs e)


2. {
3. VertexBuffer vb = (VertexBuffer)sender;
4. // Create a vertex buffer (100 customervertex)
5. CustomVertex.PositionNormal[] verts =
(CustomVertex.PositionNormal[])vb.Lock(0,0); // Lock the buffer
(which will return our structs)
6. for (int i = 0; i < 50; i++)
7. {
8. // Fill up our structs
9. float theta = (float)(2 * Math.PI * i) / 49;
10. verts[2 * i].Position = new Vector3((float)Math.Sin(theta), -1,
(float)Math.Cos(theta));
11. verts[2 * i].Normal = new Vector3((float)Math.Sin(theta), 0,
(float)Math.Cos(theta));
12. verts[2 * i + 1].Position = new Vector3((float)Math.Sin(theta), 1,
(float)Math.Cos(theta));
13. verts[2 * i + 1].Normal = new Vector3((float)Math.Sin(theta), 0,
(float)Math.Cos(theta));
14. }
15. // Unlock (and copy) the data
16. vb.Unlock();
17. }

I underline the most importing thing that you should know. Remember you don’t have to memorize
all theses stuff. That’s what the msdn is for; just make sure you get the concept down.

Ok we are going to update our private void SetupMatrices(). I don’t have to


explain it, its common sense. Cam setup and rotation (RotationAxis)
1. private void SetupMatrices()
2. {
3. device.Transform.World = Matrix.RotationAxis(new
Vector3((float)Math.Cos(Environment.TickCount /
250.0f),1,(float)Math.Sin(Environment.TickCount / 250.0f)),
Environment.TickCount / 3000.0f );
4. 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 ) );
5. device.Transform.Projection = Matrix.PerspectiveFovLH(
(float)Math.PI / 4.0f, 1.0f, 1.0f, 100.0f );
6. }

Lighting time. Now its time to play god and add light its very easy
1. private void SetupLights()
2. {
3. System.Drawing.Color col = System.Drawing.Color.White;

4. Direct3D.Material mtrl = new Direct3D.Material();


5. mtrl.Diffuse = col;
6. mtrl.Ambient = col;
7. device.Material = mtrl;

8. device.Lights[0].Type = LightType.Directional;
9. device.Lights[0].Diffuse = System.Drawing.Color.DarkTurquoise;
10. device.Lights[0].Direction = new
Vector3((float)Math.Cos(Environment.TickCount / 250.0f), 1.0f,
(float)Math.Sin(Environment.TickCount / 250.0f));

11. device.Lights[0].Enabled = true;

12. device.RenderState.Ambient =
System.Drawing.Color.FromArgb(0x202020);
13. }

The best way to under stand the above code to play with the struct . If you get an error for
this Direct3D.Material you are missing using Direct3D=Microsoft.DirectX.Direct3D;
Updating our render function

private void Render()


{
device.Clear(ClearFlags.Target | ClearFlags.ZBuffer,
System.Drawing.Color.Blue, 1.0f, 0); // underline changes msdn look up
device.BeginScene();
SetupLights(); //<-added
SetupMatrices();
device.SetStreamSource(0, vertexBuffer, 0);
device.VertexFormat = CustomVertex.PositionNormal.Format; //<-updated
device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, (4*25)-2); //<-
updated
//End the scene
device.EndScene();
// Update the screen
device.Present();
}
Texture:- hey am naked here
happy new year LOL 2005

3D objects look much more convincing when texture-mapped. Textures can be


thought of as a sort of wallpaper that is shrink-wrapped to fit an object. Like a vertex
buffer, textures have Lock() and Unlock() functions to access (read or write) the image
data. Textures have a width, height, miplevel, and pixel format. Lets get the party started

First we start by creating a global Texture Object

Texture texture = null;

Since we are using Texture we have to change our vertex buffer to


PositionNormalTextured

public void OnCreateDevice(object sender, EventArgs e)


{
Device dev = (Device)sender;
// Now Create the VB
vertexBuffer = new
VertexBuffer(typeof(CustomVertex.PositionNormalTextured), 100, dev,
Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format,
Pool.Default);
vertexBuffer.Created += new
System.EventHandler(this.OnCreateVertexBuffer);
this.OnCreateVertexBuffer(vertexBuffer, null);
}

Our public void OnResetDevice(object sender, EventArgs e) function will stay the same.
We will just load our texture.

texture=TextureLoader.FromFile(dev,“c:\\tx.bmp");//the string is our


pic
If you get a bug for the above line of code reff this Microsoft.DirectX.Direct3DX

1. public void OnCreateVertexBuffer(object sender, EventArgs e)


2. {
3. VertexBuffer vb = (VertexBuffer)sender;
4. // Create a vertex buffer (100 customervertex)
5. CustomVertex.PositionNormalTextured[] verts =
(CustomVertex.PositionNormalTextured[])vb.Lock(0,0); // Lock the buffer
(which will return our structs)
6. for (int i = 0; i < 50; i++)
7. {
8. // Fill up our structs
9. float theta = (float)(2 * Math.PI * i) / 49;
10. verts[2 * i].Position = new Vector3((float)Math.Sin(theta), -1,
(float)Math.Cos(theta));
11. verts[2 * i].Normal = new Vector3((float)Math.Sin(theta), 0,
(float)Math.Cos(theta));
12. verts[2 * i].Tu = ((float)i)/(50-1);
13. verts[2 * i].Tv = 1.0f;
14. verts[2 * i + 1].Position = new Vector3((float)Math.Sin(theta),
1, (float)Math.Cos(theta));
15. verts[2 * i + 1].Normal = new Vector3((float)Math.Sin(theta), 0,
(float)Math.Cos(theta));
16. verts[2 * i + 1].Tu = ((float)i)/(50-1);
17. verts[2 * i + 1].Tv = 0.0f;
18. }
19. // Unlock (and copy) the data
20. vb.Unlock();
21. }
Ok the above code is our is our math and our point for our texture to under stand it better
look at this function in the Light section and compare and contrast.

private void Render()


{
device.Clear(ClearFlags.Target | ClearFlags.ZBuffer,
System.Drawing.Color.Blue, 1.0f, 0);
device.BeginScene();
SetupMatrices();

//MSDN IS YOUR FRIEND


device.SetTexture(0,texture);
device.TextureState[0].ColorOperation = TextureOperation.Modulate;
device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor;
device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse;
device.TextureState[0].AlphaOperation = TextureOperation.Disable;

device.SetStreamSource(0, vertexBuffer, 0);


device.VertexFormat = CustomVertex.PositionNormalTextured.Format;
device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, (4*25)-2);
device.EndScene();
device.Present();
}
So I update my program why is my cylinder still black ?
You have to turn off the light

device.RenderState.Lighting = false;

“c:\\tx.bmp" = a pic on my drive

Meshes:- its about time

For advanced geometry, most apps will prefer to load pre-authored


meshes from a file. Fortunately, when using meshes, D3DX does most of the work for
this, parsing a geometry file and creating vertex buffers for us.

We start with our globals

1. Mesh mesh = null; // Our mesh object in sysmem


2. Direct3D.Material[] meshMaterials; // Materials for our mesh
3. Texture[] meshTextures; // Textures for our mesh

This Explain the code under I did not want to put code on a page break

Lines
• 3 ExtendedMaterial object that is used to capture the mesh file data to a Material
structure.
• 12 Load our mesh into our system memory
• 8 and turns on the z-buffer
• 10 and turns on white ambient lighting.
• 22 meshMaterials are initialized to the dimension (Length) of the materials
structure from the file.
• 24 meshTextures are initialized to the dimension (Length) of the materials
structure from the file
1. public void OnResetDevice(object sender, EventArgs e)
2. {
3. ExtendedMaterial[] materials = null;

4. // Set the directory up two to load the right data


5. Directory.SetCurrentDirectory(“c:\\”);
6. Device dev = (Device)sender;
7. // Turn on the zbuffer
8. dev.RenderState.ZBufferEnable = true;
9. // Turn on ambient lighting
10. dev.RenderState.Ambient = System.Drawing.Color.White;
11. // Load the mesh from the specified file
12. mesh = Mesh.FromFile("tiger.x", MeshFlags.SystemMemory,
device, out materials);

13. if (meshTextures == null)


14. {
15. // We need to extract the material properties and texture
names
16. meshTextures = new Texture[materials.Length];
17. meshMaterials = new Direct3D.Material[materials.Length];
18. for( int i=0; i<materials.Length; i++ )
19. {
20. meshMaterials[i] = materials[i].Material3D;
21. // Set the ambient color for the material (D3DX does not do
this)
22. meshMaterials[i].Ambient = meshMaterials[i].Diffuse;

23. // Create the texture


24. meshTextures[i] = TextureLoader.FromFile(dev,
materials[i].TextureFilename);
25. }
26. }
27. }

Updating our Render function


1. private void Render()
a. {
2. device.Clear(ClearFlags.Target | ClearFlags.ZBuffer,
System.Drawing.Color.Blue, 1.0f, 0);
3. device.BeginScene();
4. SetupMatrices();
5. // Meshes are divided into subsets, one for each material. Render them
6. // a loop
7. for( int i=0; i<meshMaterials.Length; i++ )
8. {
9. // Set the material and texture for this subset
10. device.Material = meshMaterials[i];
11. device.SetTexture(0, meshTextures[i]);
12. // Draw the mesh subset
13. mesh.DrawSubset(i);
14. }
15. //End the scene
16. device.EndScene();
17. device.Present();
18. }
The Material property of the device is set to the meshMaterials Material structure.

The device texture stage 0 is set to the meshTextures Texture structure.

The material subset is drawn with the DrawSubset method, which inherits from the
BaseMesh class.

If you load a giant mesh and cant see the full mesh in the window

Goto private void SetupMatrices(); and change


Matrix.LookAtLH( new Vector3( 7.0f, -7.0f,-7.0f ),

To some thing that looks better

Good links:-
http://www.xbdev.net/xbdev.php
http://csharp-home.com/
http://www.c-sharpcorner.com/Directx.asp
http://www.microsoft.com/downloads/details.aspx?FamilyID=592393a7-
c677-4023-8b27-94e61141e9c6&displaylang=en
http://opencpp.tk
http://users.pandora.be/riemer/keyboard.html
http://www.icsharpcode.net/OpenSource/SD/
if you find any code bug or error (none grammar) email me @
[email protected]

You might also like