XNA for C#
DirectX 9 for C#
DirectX 9 for C++
DirectX 9 for VB
Forum
   
My XNA Book
      
       Go to section on this site

Additional info


Latest Forum posts

 Account settings
  Posted by: Anonymous
  When: 07/05/2014 at 09:48:39

 forced subtitle
  Posted by: Applefly
  When: 07/05/2014 at 06:00:48

 convert DVD into PMS
  Posted by: Applefly
  When: 07/05/2014 at 05:55:25

 DVD to Digital Copy easily
  Posted by: VIKIVannessa
  When: 05/05/2014 at 06:52:29

 DVD on Xbox 360/Xbox One Console
  Posted by: VIKIVannessa
  When: 05/05/2014 at 06:51:47

 Extract .Srt Subtitles
  Posted by: Applefly
  When: 04/05/2014 at 03:54:38

 Encode Movie collection
  Posted by: Applefly
  When: 04/05/2014 at 03:52:41

 Convert DVD to WMV
  Posted by: Applefly
  When: 29/04/2014 at 05:53:50

 rip DVDs into digital files
  Posted by: Applefly
  When: 29/04/2014 at 05:51:20

 iTunes movies/music to Kindle Fire
  Posted by: ciciyu80
  When: 29/04/2014 at 05:10:20


Ads

Explanation of the Shadow Mapping algorithm

Now we know some HLSL basics and have defined our first light, it’s time for something more complex. Let’s see how we can add real shadowing to our scene. We want this shadowing algorithm to be completely dynamic: we want to define the position and direction of our light only one time, and every object within its range should automatically cast a shadow.

Let’s start with the car at the bottom left corner of our screen. Its headlights are shining light towards the right side of our scene. So the light hits the lampposts and the other car, which have to cast shadows on the wall. The question: how do we know which pixels on the wall are shadowed?

While I explain the Depth Mapping algorithm, you can have a look at the image below, where the 2 major steps are illustrated. The first step would be to draw the scene, as seen by the headlights. This means we have to move our camera position to the position of the headlights. Using this point of view, the only thing we are interested in is the distance of every pixel to the headlights. For example, the first lamppost would be 4 meters away of the headlights. Very important: the pixels of the wall behind this first lamppost are not seen by the headlights. At the location of these pixels, 4 meters was stored as distance to the headlights. We store this distance information of the whole scene in what is called a shadow map or depth map.

During the second phase, we draw the scene the usual way; that is, from our camera’s point of view. Only this time, for each pixel we calculate the distance to the headlights, and compare this depth to the depth stored in the depth map. For most objects, both distances will be the same. Our lamppost, for example, will still be 4 meters away from the headlights.

However, when we calculate the distance for the pixels of the wall behind the light, we find that the distance to the headlights is 5 meters. This is not the same as the distance of 4 meters that was stored for these pixels. This way, we know these pixels can not be seen by the headlights, and are in the shadow.



This will all be better illustrated as we move on to the first step: drawing the depth map. We’ll be defining a new technique for this in our HLSL code, ShadowMap, that renders the depth of the scene to the screen:

technique ShadowMap
{
    pass Pass0
    {
        VertexShader = compile vs_2_0 ShadowMapVertexShader();
        PixelShader = compile ps_2_0 ShadowMapPixelShader();
    }
}

At the end of this chapter you’ll see we won’t need a pixel shader yet to do this job, but we will need one later on in this series. Instead of dealing with it later by rewriting the whole code, we’ll already create the correct methods. Our vertex shader will be very simple, as this is the only output it needs to generate:

struct SMapVertexToPixel
{
    float4 Position     : POSITION;    
    float3 Position2D    : TEXCOORD0;
};

As always, we need to supply the interpolator and pixel shader with the 2D screen coordinates. Only this time, we need this information also in our pixel shader, thus we need to pass it using one of the TEXCOORDn semantics. We’ve already covered the biggest part of this, so this is our new vertex shader:

SMapVertexToPixel ShadowMapVertexShader( float4 inPos : POSITION)
{
    SMapVertexToPixel Output = (SMapVertexToPixel)0;
    
    Output.Position = mul(inPos, xLightWorldViewProjection);
    Output.Position2D = Output.Position;
    
    return Output;    
}

Something very important to notice here: we’re using xLightWorldViewProjection here instead of xWorldViewProjection, because this time we need to look at the scene as seen by the headlights, instead of as by our camera. This is a new matrix, so we need to initialize it at the top of our HLSL code:

float4x4 xLightWorldViewProjection;

Which we’ll fill from within our DirectX app later on in this chapter. Next, we’ll code our pixel shader, which again only has to calculate the color:

struct SMapPixelToFrame
{
    float4 Color : COLOR0;
};

And this will be our pixel shader:

SMapPixelToFrame ShadowMapPixelShader(SMapVertexToPixel PSIn)
{
    SMapPixelToFrame Output = (SMapPixelToFrame)0;

    Output.Color = PSIn.Position2D.z/xMaxDepth;

    return Output;
}

Remember HLSL values have to be between the [0, 1] interval. For this, we cannot simply use the Z component of the transformed position as the color, as the transformed Z coordinate indicates the distance from the object to the camera in DirectX units. We first need to divide this value by the maximum this value could possibly be, something like the far clipping plane. Of course, this value xMaxData needs to be set from within our DirectX app. This way, the normalized value will be smaller than 1.0f, and can be used as a color.

The last thing to do would be to initialize this xMaxDepth variable:

float xMaxDepth;

So far for the HLSL part. Let’s go to our DirectX code, where we can define a method GenerateShadowMap like this:

 private void GenerateShadowMap()
 {
     effect.Technique = "ShadowMap";
     effect.SetValue("xMaxDepth", 60);
     int numpasses = effect.Begin(0);
     for (int i = 0; i < numpasses; i++)
     {
         effect.BeginPass(i);
         DrawScene();
         effect.EndPass();
     }
     effect.End();
 }

You see we select the correct technique, and indicate that the largest distance between the headlights and any object in its view will be 60 units. Instead of putting all the drawing code between the for loop, I factorized it away to a method DrawScene. I also did this, because we will have to draw our scene twice: one time as seen by the headlights, and another time as seen by the camera (in one of the next chapters). So here is this method:

 private void DrawScene()
 {
     effect.SetValue("xWorldViewProjection", Matrix.Identity * matView * matProjection);
     effect.SetValue("xLightWorldViewProjection", Matrix.Identity * LightViewProjection);
     effect.SetValue("xRot", Matrix.Identity);
     effect.CommitChanges();
     device.SetStreamSource(0, vb, 0);
     device.VertexDeclaration = vd;
     device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 16);
 
     Matrix LamppostWorld = Matrix.Scaling(0.05f, 0.05f, 0.05f) * Matrix.RotationX((float)Math.PI / 2) * Matrix.Translation(-4.0f, 5, 1);
     effect.SetValue("xWorldViewProjection", LamppostWorld * matView * matProjection);
     effect.SetValue("xLightWorldViewProjection", LamppostWorld * LightViewProjection);
     effect.SetValue("xRot", Matrix.RotationX((float)Math.PI / 2));
     DrawMesh(Lamppost, LamppostMaterials, LamppostTextures);
 
     LamppostWorld = Matrix.Scaling(0.05f, 0.05f, 0.05f) * Matrix.RotationX((float)Math.PI / 2) * Matrix.Translation(-4.0f, 35, 1);
     effect.SetValue("xWorldViewProjection", LamppostWorld * matView * matProjection);
     effect.SetValue("xLightWorldViewProjection", LamppostWorld * LightViewProjection);
     effect.SetValue("xRot", Matrix.RotationX((float)Math.PI / 2));
     DrawMesh(Lamppost, LamppostMaterials, LamppostTextures);
 
     Matrix CarWorld = Matrix.Scaling(4f, 4f, 4f) * Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 2, (float)Math.PI / 2) * Matrix.Translation(3, 15, 0f);
     effect.SetValue("xWorldViewProjection", CarWorld * matView * matProjection);
     effect.SetValue("xLightWorldViewProjection", CarWorld * LightViewProjection);
     effect.SetValue("xRot", Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 2, (float)Math.PI / 2) * Matrix.Translation(3, 15, 0f));
     DrawMesh(Car, CarMaterials, CarTextures);
 
     CarWorld = Matrix.Scaling(4f, 4f, 4f) * Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 8, (float)Math.PI / 2) * Matrix.Translation(28, -1.9f, 0f);
     effect.SetValue("xWorldViewProjection", CarWorld * matView * matProjection);
     effect.SetValue("xLightWorldViewProjection", CarWorld * LightViewProjection);
     effect.SetValue("xRot", Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 2, (float)Math.PI / 2) * Matrix.Translation(3, 15, 0f));
     DrawMesh(Car, CarMaterials, CarTextures);
 }

We draw every object the same way: first we set the 2 ViewProjection matrices, as well as the rot matrix, then we pass these variables to the shaders by calling the CommitChanges method, and finally we draw the objects.

You should notice we haven’t yet declared this LightViewProjection matrix, so add it to the top of your code:

 private Matrix LightViewProjection;

Now we still need to fill this. We’ll put all code that deal with the headlights in a separate method as well:

 private void UpdateLightData()
 {
     Vector3 LightPos = new Vector3(18, 2, 5);
     float LightPower = 0.7f;
 
     LightViewProjection = Matrix.LookAtLH(LightPos, new Vector3(2, 10, -3), new Vector3(0, 0, 1)) * Matrix.PerspectiveFovLH((float)Math.PI / 2, this.Width / this.Height, 1f, 100f);
     effect.SetValue("xLightPos", new Vector4(LightPos.X, LightPos.Y, LightPos.Z, 1));
     effect.SetValue("xLightPower", LightPower);
 }

Nothing new in the LightPos or LightPower lines, you’ll notice only the LightViewmatProjection line is new. Because to draw the shadow map we need to draw the scene as seen by the headlights, we need to create a corresponding ViewProjection matrix (identically to setting up a camera).

So far for the new code of this chapter! Now we’ve nicely split up everything, we end up with a very simple OnPaint method:

 protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
 {
      UpdateLightData();
      device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
      device.BeginScene();
 
      GenerateShadowMap();
      UpdateFramerate();
 
      device.EndScene();
      device.Present();
      this.Invalidate();    
 }

Pretty easy to understand. Now when you run this code, you should see the image below. It might look pretty strange at first sight, but it’s perfect: it is the depth map of the scene as seen by the headlights of the car. The more white the pixel, the further away it is from the headlights.




DirectX Tutorial 11 - Shadow mapping

If you appreciate the amount of time I spend creating and updating
these pages, feel free to donate -- any amount is welcome !



Click here to go to the forum on this chapter!

Or click on one of the topics on this chapter to go there:
  • Translating meshes
          Wonderful tutorial Riemer! I have been experiment...
  • Can only get shadowmap
          I used the code right from the site but when I ren...
  • Depth Map with point light
          I really like your tutorial.. it has helped me add...
  • Drawing order affects shadows
          First, thanks for the tutorials, it has really hel...
  • Combining of Shadow Mapping and PRT
          I really wonder if shadow mapping can be combined ...


    Try experimenting with some parameters. Try changing the xMaxDepth value, or the position and target of the light. You might be concerned about the pixels of the street close to the camera being completely black. This is not true, as you can see by changing a line in your HLSL to this:

    Output.Color = PSIn.Position2D.z/xMaxDepth*15;

    If it would have been zero, 15 times 0 should still be 0, which isn’t the case as you can clearly see. Don’t forget to erase the *15 before moving to the next chapter.

    I’ve removed the non-used HLSL code from my file, only to make the site look cleaner. Later on, we’ll (of course) be re-using our other HLSL code.

     struct SMapVertexToPixel
     {
         float4 Position     : POSITION;    
         float3 Position2D    : TEXCOORD0;
     };
     
     struct SMapPixelToFrame
     {
         float4 Color : COLOR0;
     };


    float4x4 xWorldViewProjection;

     float4x4 xLightWorldViewProjection;

    float4x4 xRot;
    float4 xLightPos;
    float xLightPower;

     float xMaxDepth;


    Texture xColoredTexture;

    sampler ColoredTextureSampler = sampler_state { texture = <xColoredTexture> ; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = mirror; AddressV = mirror;};

    SMapVertexToPixel ShadowMapVertexShader( float4 inPos : POSITION)
    {
        SMapVertexToPixel Output = (SMapVertexToPixel)0;
        
        Output.Position = mul(inPos, xLightWorldViewProjection);
        Output.Position2D = Output.Position;
        
        return Output;    
    }

    SMapPixelToFrame ShadowMapPixelShader(SMapVertexToPixel PSIn)
    {
        SMapPixelToFrame Output = (SMapPixelToFrame)0;

        Output.Color = PSIn.Position2D.z/xMaxDepth;

        return Output;
    }

    technique ShadowMap
    {
        pass Pass0
        {
            VertexShader = compile vs_2_0 ShadowMapVertexShader();
            PixelShader = compile ps_2_0 ShadowMapPixelShader();
        }
    }

    The DirectX code:

     using System;
     using System.Drawing;
     using System.Collections;
     using System.ComponentModel;
     using System.Windows.Forms;
     using System.Data;
     using Microsoft.DirectX;
     using Microsoft.DirectX.Direct3D;
     using D3D = Microsoft.DirectX.Direct3D;
     
     namespace DirectX_Tutorial
     {
         struct myownvertexformat
         {
             public Vector3 Pos;
             public Vector3 Normal;
             public Vector2 TexCoord;
     
             public myownvertexformat(Vector3 _Pos, Vector3 _Normal, float texx, float texy)
             {
                 Pos = _Pos;
                 Normal = _Normal;
                 TexCoord.X = texx;
                 TexCoord.Y = texy;
             }
         }
     
         public class WinForm : System.Windows.Forms.Form
         {        
             private System.ComponentModel.Container components = null;
             private D3D.Device device;        
             private VertexBuffer vb;
             private Vector3 CameraPos;
             private VertexDeclaration vd;
             private Effect effect;
     
             private Texture StreetTexture;
             private Mesh Lamppost;
             private Material[] LamppostMaterials;
             private Texture[] LamppostTextures;
             private Mesh Car;
             private Material[] CarMaterials;
             private Texture[] CarTextures;
     
             private Matrix matView;
             private Matrix matProjection;
             private Matrix LightViewProjection;
     
             private int LastTickCount = 1;
             private int Frames = 0;
             private float LastFrameRate = 0;
             private D3D.Font text;
     
             public WinForm()
             {
                 InitializeComponent();
                 this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
             }
     
             public void InitializeDevice()
             {
                 PresentParameters presentParams = new PresentParameters();
                 presentParams.Windowed = true;
                 presentParams.SwapEffect = SwapEffect.Discard;
                 presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                 presentParams.EnableAutoDepthStencil = true;
     
                 Caps DevCaps = D3D.Manager.GetDeviceCaps(0, D3D.DeviceType.Hardware);
                 D3D.DeviceType DevType = D3D.DeviceType.Reference;
                 CreateFlags DevFlags = CreateFlags.SoftwareVertexProcessing;
                 if ((DevCaps.VertexShaderVersion >= new Version(2, 0)) && (DevCaps.PixelShaderVersion >= new Version(2, 0)))
                 {
                     DevType = D3D.DeviceType.Hardware;                
                     if (DevCaps.DeviceCaps.SupportsHardwareTransformAndLight)
                     {
                         DevFlags = CreateFlags.HardwareVertexProcessing;
                         if (DevCaps.DeviceCaps.SupportsPureDevice)
                         {
                             DevFlags |= CreateFlags.PureDevice;
                         }
                     }                
                 }
     
                 device = new D3D.Device(0, DevType, this, DevFlags, presentParams);
                 device.DeviceReset += new EventHandler(this.HandleDeviceReset);            
             }
     
             private void HandleDeviceReset(object sender, EventArgs e)
             {
                 FillResources();        
             }
     
             private void AllocateResources()
             {
                 vb = new VertexBuffer(typeof(myownvertexformat), 18, device, Usage.WriteOnly, VertexFormats.Position | VertexFormats.Normal | VertexFormats.Texture0, Pool.Managed);                        
                 InitializeFont();
                 effect = D3D.Effect.FromFile(device, @"../../OurHLSLFile.fx", null, null, ShaderFlags.None, null);
             }
     
             private void FillResources()
             {
                 myownvertexformat[] vertices = new myownvertexformat[18];
     
                 vertices[0] = new myownvertexformat(new Vector3(20, -10, 0), new Vector3(0, 0, 1), -0.25f, 25.0f);
                 vertices[1] = new myownvertexformat(new Vector3(20, 100, 0), new Vector3(0, 0, 1), -0.25f, 0.0f);
                 vertices[2] = new myownvertexformat(new Vector3(-2, -10, 0), new Vector3(0, 0, 1), 0.25f, 25.0f);                        
                 vertices[3] = new myownvertexformat(new Vector3(-2, 100, 0), new Vector3(0, 0, 1), 0.25f, 0.0f);
                 vertices[4] = new myownvertexformat(new Vector3(-2, -10, 0), new Vector3(1, 0, 0), 0.25f, 25.0f);                        
                 vertices[5] = new myownvertexformat(new Vector3(-2, 100, 0), new Vector3(1, 0, 0), 0.25f, 0.0f);
                 vertices[6] = new myownvertexformat(new Vector3(-2, -10, 1), new Vector3(1, 0, 0), 0.375f, 25.0f);
                 vertices[7] = new myownvertexformat(new Vector3(-2, 100, 1), new Vector3(1, 0, 0), 0.375f, 0.0f);
                 vertices[8] = new myownvertexformat(new Vector3(-2, -10, 1), new Vector3(0, 0, 1), 0.375f, 25.0f);
                 vertices[9] = new myownvertexformat(new Vector3(-2, 100, 1), new Vector3(0, 0, 1), 0.375f, 0.0f);
                 vertices[10] = new myownvertexformat(new Vector3(-3, -10, 1), new Vector3(0, 0, 1), 0.5f, 25.0f);
                 vertices[11] = new myownvertexformat(new Vector3(-3, 100, 1), new Vector3(0, 0, 1), 0.5f, 0.0f);
                 vertices[12] = new myownvertexformat(new Vector3(-13, -10, 1), new Vector3(0, 0, 1), 0.75f, 25.0f);
                 vertices[13] = new myownvertexformat(new Vector3(-13, 100, 1), new Vector3(0, 0, 1), 0.75f, 0.0f);
                 vertices[14] = new myownvertexformat(new Vector3(-13, -10, 1), new Vector3(1, 0, 0), 0.75f, 25.0f);
                 vertices[15] = new myownvertexformat(new Vector3(-13, 100, 1), new Vector3(1, 0, 0), 0.75f, 0.0f);
                 vertices[16] = new myownvertexformat(new Vector3(-13, -10, 21), new Vector3(1, 0, 0), 1.25f, 25.0f);
                 vertices[17] = new myownvertexformat(new Vector3(-13, 100, 21), new Vector3(1, 0, 0), 1.25f, 0.0f);
                 
                 vb.SetData(vertices, 0, LockFlags.None);
     
                 SetUpCamera();
     
                 VertexElement[] velements = new VertexElement[]
                 {
                     new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
                     new VertexElement(0, 12, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0),
                     new VertexElement(0, 24, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0),
                     VertexElement.VertexDeclarationEnd
                 };
                 vd = new VertexDeclaration(device, velements);
     
                 StreetTexture = TextureLoader.FromFile(device, "streettexture.jpg");
     
                 LoadMesh("lamppost.x", ref Lamppost, ref LamppostMaterials, ref LamppostTextures);
                 LoadMesh("car.x", ref Car, ref CarMaterials, ref CarTextures);
             }
     
             private void InitializeFont()
             {
                 System.Drawing.Font systemfont = new System.Drawing.Font("Arial", 12f, FontStyle.Regular);
                 text = new D3D.Font(device, systemfont);
             }
     
             private void DrawMesh(Mesh mesh, Material[] meshmaterials, Texture[] meshtextures)
             {
                 for (int i = 0; i < meshmaterials.Length; i++)
                 {
                     if (meshtextures.Length > 3) effect.SetValue("xColoredTexture", meshtextures[i]);
                     effect.CommitChanges();
                     mesh.DrawSubset(i);
                 }
             }
     
             protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
             {
                 UpdateLightData();
                 device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                 device.BeginScene();
     
     
                 GenerateShadowMap();
                 UpdateFramerate();
     
                 device.EndScene();
                 device.Present();
                 this.Invalidate();    
             }
     
             private void GenerateShadowMap()
             {
                 effect.Technique = "ShadowMap";
                 effect.SetValue("xMaxDepth", 60);
                 int numpasses = effect.Begin(0);
                 for (int i = 0; i < numpasses; i++)
                 {
                     effect.BeginPass(i);
                     DrawScene();
                     effect.EndPass();
                 }
                 effect.End();
             }
     
             private void UpdateLightData()
             {
                 Vector3 LightPos = new Vector3(18, 2, 5);
                 float LightPower = 0.7f;
     
                 LightViewProjection = Matrix.LookAtLH(LightPos, new Vector3(2, 10, -3), new Vector3(0, 0, 1)) * Matrix.PerspectiveFovLH((float)Math.PI / 2, this.Width / this.Height, 1f, 100f);
                 effect.SetValue("xLightPos", new Vector4(LightPos.X, LightPos.Y, LightPos.Z, 1));
                 effect.SetValue("xLightPower", LightPower);
             }
     
             private void DrawScene()
             {
                 effect.SetValue("xWorldViewProjection", Matrix.Identity * matView * matProjection);
                 effect.SetValue("xLightWorldViewProjection", Matrix.Identity * LightViewProjection);
                 effect.SetValue("xRot", Matrix.Identity);
                 effect.CommitChanges();
                 device.SetStreamSource(0, vb, 0);
                 device.VertexDeclaration = vd;
                 device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 16);
     
                 Matrix LamppostWorld = Matrix.Scaling(0.05f, 0.05f, 0.05f) * Matrix.RotationX((float)Math.PI / 2) * Matrix.Translation(-4.0f, 5, 1);
                 effect.SetValue("xWorldViewProjection", LamppostWorld * matView * matProjection);
                 effect.SetValue("xLightWorldViewProjection", LamppostWorld * LightViewProjection);
                 effect.SetValue("xRot", Matrix.RotationX((float)Math.PI / 2));
                 DrawMesh(Lamppost, LamppostMaterials, LamppostTextures);
     
                 LamppostWorld = Matrix.Scaling(0.05f, 0.05f, 0.05f) * Matrix.RotationX((float)Math.PI / 2) * Matrix.Translation(-4.0f, 35, 1);
                 effect.SetValue("xWorldViewProjection", LamppostWorld * matView * matProjection);
                 effect.SetValue("xLightWorldViewProjection", LamppostWorld * LightViewProjection);
                 effect.SetValue("xRot", Matrix.RotationX((float)Math.PI / 2));
                 DrawMesh(Lamppost, LamppostMaterials, LamppostTextures);
     
                 Matrix CarWorld = Matrix.Scaling(4f, 4f, 4f) * Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 2, (float)Math.PI / 2) * Matrix.Translation(3, 15, 0f);
                 effect.SetValue("xWorldViewProjection", CarWorld * matView * matProjection);
                 effect.SetValue("xLightWorldViewProjection", CarWorld * LightViewProjection);
                 effect.SetValue("xRot", Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 2, (float)Math.PI / 2) * Matrix.Translation(3, 15, 0f));
                 DrawMesh(Car, CarMaterials, CarTextures);
     
                 CarWorld = Matrix.Scaling(4f, 4f, 4f) * Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 8, (float)Math.PI / 2) * Matrix.Translation(28, -1.9f, 0f);
                 effect.SetValue("xWorldViewProjection", CarWorld * matView * matProjection);
                 effect.SetValue("xLightWorldViewProjection", CarWorld * LightViewProjection);
                 effect.SetValue("xRot", Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 2, (float)Math.PI / 2) * Matrix.Translation(3, 15, 0f));
                 DrawMesh(Car, CarMaterials, CarTextures);
             }
     
             private void UpdateFramerate()
             {
                 Frames++;
                 if (Math.Abs(Environment.TickCount - LastTickCount) > 1000)
                 {
                     LastFrameRate = (float)Frames * 1000 / Math.Abs(Environment.TickCount - LastTickCount);
                     LastTickCount = Environment.TickCount;
                     Frames = 0;
                 }
                 text.DrawText(null, string.Format("Framerate : {0:0.00} fps", LastFrameRate), new Point(10, 430), Color.Red);
             }
     
             private void SetUpCamera()
             {
                 CameraPos = new Vector3(20, -17, 10);
                 matProjection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 0.3f, 200f);
                 matView = Matrix.LookAtLH(CameraPos, new Vector3(0, 9, 2), new Vector3(0, 0, 1));
             }
     
             private void LoadMesh(string filename, ref Mesh mesh, ref Material[] meshmaterials, ref Texture[] meshtextures)
             {
                 ExtendedMaterial[] materialarray;
                 GraphicsStream adj = null;
     
                 mesh = Mesh.FromFile(filename, MeshFlags.Managed, device, out adj, out materialarray);
     
                 if ((materialarray != null) && (materialarray.Length > 0))
                 {
                     meshmaterials = new Material[materialarray.Length];
                     meshtextures = new Texture[materialarray.Length];
     
                     for (int i = 0; i < materialarray.Length; i++)
                     {
                         meshmaterials[i] = materialarray[i].Material3D;
                         meshmaterials[i].Ambient = meshmaterials[i].Diffuse;
     
                         if ((materialarray[i].TextureFilename != null) && (materialarray[i].TextureFilename != string.Empty))
                         {
                             meshtextures[i] = TextureLoader.FromFile(device, materialarray[i].TextureFilename);
                         }
                     }                
                 }
     
                 mesh = mesh.Clone(mesh.Options.Value, CustomVertex.PositionNormalTextured.Format, device);
                 mesh.ComputeNormals();
             }
     
             protected override void Dispose(bool disposing)
             {
                 if (disposing)
                 {
                     if (components != null)
                     {
                         components.Dispose();
                     }
                 }
                 base.Dispose(disposing);
             }
     
             private void InitializeComponent()
             {
                 this.components = new System.ComponentModel.Container();
                 this.Size = new System.Drawing.Size(500, 500);
                 this.Text = "Riemer's DirectX & HLSL Tutorial using C# -- Season 3";
             }
     
             static void Main()
             {
                 using (WinForm our_directx_form = new WinForm())
                 {
                     our_directx_form.InitializeDevice();                
                     our_directx_form.AllocateResources();
                     our_directx_form.FillResources();
                     Application.Run(our_directx_form);
                 }
             }
         }
     }


    Google
     
    Webwww.riemers.net


    If you appreciate the amount of time I spend creating and updating
    these pages, feel free to donate -- any amount is welcome !



    - Website design & XNA + DirectX code : Riemer Grootjans -
    ©2003 - 2011 Riemer Grootjans
  • Translations

    This site in English
    This site in Korean
    This site in Czech

    Microsoft MVP Award



    2007 - 2011 MVP Award
    DirectX - XNA

    Contents

    News
    Home
    Forum
    XNA 2.0 Recipes Book (8)
    XNA 3.0 Recipes Book (8)
    Downloads
    Extra Reading (3)
    Matrices: geometrical
    Matrix Mathematics
    Homogenous matrices
    Community Projects (1)
    Tutorials (160)
    XNA 4.0 using C# (89)
    DirectX using C# (54)
    Series 1:Terrain (14)
    Series 2: Flightsim (19)
    Series 3: HLSL (19)
    Starting point
    HLSL Introduction
    Vertex Shader
    Shaded triangle
    Pixel Shader
    Textured Triangle
    Triangle Strip
    World transform
    Adding normals
    The first light
    Shadow mapping
    Render To Texture
    Projective texturing
    The first shadow
    Shaping the light
    Preshaders
    Multiple lights
    Adjusting Z values
    Finishing touch
    Short Tuts (2)
    DirectX using C++ (15)
    DirectX using VB (2)
    -- Expand all --


    Thank you!

    Support this site --
    any amount is welcome !

    Stay up-to-date

    I don't have the time to keep a News section, so stay informed about the updates by clicking on this RSS file!