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

Coding the first Pixel Shader

Now we have written our first vertex shader and fed it with a small vertexstream, it’s time we have a look at the pixel shader. Using the vertex shader, we could only instruct the GPU to calculate the color of every pixel as linear interpolation between the colors of the corners of our triangles, the vertices.

When you take a look at the flowchart, you’ll notice there are 2 arrows going from the vertex shader to the pixel shader. The left one is necessary, as it is the position of the pixel in 2D screen coordinates. The tesselator and interpolator, as well as the pixel shader, need it to do their work. One remark: by default you can NOT use this position as input to your pixel shader. The bigger arrow is not necessary, but you’ll always want to use it, as it contains the data the pixel shader uses as input. This can be, for example, the interpolated color, interpolated normal, interpolated texture coordinates, etc. I guess by now you noticed the emphasis I put on the word ‘Interpolated’. If you want, you can also pass the 2D screen position in this arrow, so your pixel shader can use it.



I could go on with a theoretic description of the pixel shader, but I think it’s better to just start coding. First, we have to declare we’ll be using our own pixel shader, so change this line in your technique definition:

PixelShader = compile ps_1_1 OurFirstPixelShader();

This indicates every pixel will be drawn by the OurFirstPixelShader method, which has to be compiler as a pixel shader written in HLSL v1.1 language.

As with the vertex shader, I think it’s best practice to first define the output structure of our pixel shader. For every pixel, you only need to specify the color, as the 2D position is already known (again, interpolation between positions of the vertices). Optionally, you can also specify the value that has to be written in the Z-buffer, which is what we are going to do in a next chapter. For now, the color will be enough, so put this definition at the top of your code:

struct PixelToFrame
{
    float4 Color : COLOR0;
};

When you look at the flowchart, you’ll see the pixel shader eventually sends its output to the frame buffer. This is where multiple renderings get blended in case of alpha blending. More on this later, I just mentioned this to explain the name of the output struct.

So now we can go ahead and code our first pixel shader, which will simply route the color it receives from the interpolator to its output:

PixelToFrame OurFirstPixelShader(VertexToPixel PSIn)
{
    PixelToFrame Output = (PixelToFrame)0;

    Output.Color = PSIn.Color;

    return Output;
}

Pretty self-explaining: you initialize an output structure, and fill the Color member with the input you receive.

This would be the default pixel shader. When you run your DirectX app, you should see the same result as with the last chapter. You can try to experiment by setting the color of the pixel shader to a solid color, which again will give you a solid colored triangle:

Output.Color.rg = 1;

Now it’s time to show you something specific about pixel shaders: we’re going to program the color of each of the pixels separately. We’re going to do the exercise of last chapter again, only this time using a pixel shader. Remember, we want each of the 3 color channels to take the values of each of the three 3D-coordinates of the pixel.

What we need as input to our pixel shader, is the 3D coordinate of the pixel. The only coordinate we calculated is the 2D screen position (remember we cannot use this value in our pixel shader, as it is the left arrow in our flowchart). So what we need to do is pass the 3D coordinate from our vertex shader to our pixel shader. First redefine the output structure of your vertex shader:

struct VertexToPixel
{
    float4 Position     : POSITION;
    float4 Color        : COLOR0;
    float4 Position3D     : TEXCOORD0;
};

You see we added a member to store the 3D position. As semantic, we used TEXCOORD0. You can use TEXCOORD0 to TEXCOORD16 to pass float4 values from your vertex shader to your pixel shader.

Next we’ll update our vertex shader so it routes the 3D position it receives from the vertex stream to its output. To do this, we simply have to add the following line to our vertex shader:

Output.Position3D = inPos;

This will have our 3D position sent to the interpolator, which will interpolate the 3D position of every pixel in the triangle. For each pixel, this interpolated 3D coordinate will be sent to the pixel shader.

Now we will have our pixel shader set the color components to the value of this 3D coordinate. In your pixel shader, put this line as you color definition:

Output.Color.rgb = PSIn.Position3D.yxz;

By now you should know what this does: it sets the value of the y coordinate as the red color component, and so on. Compile the code by pressing Ctrl+S. When you did everything well, you shouldn’t see any error messages. Now go to Visual Studio, and run the code. You should see the same as the image below: a simple triangle, with pixels that display color that aren’t linear interpolations of the colors of the corner points. So we have programmed the color of every pixel individually!




DirectX Tutorial 5 - Pixel Shader

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:
  • Blu-ray to MP4
          Convert Blu-ray to MP4 preserving multitracks with...
  • Vertex and Pixel Shader Versions?
          Up to the beginning of the third C# series my lapt...
  • thx to riemer
          The riemer's tutorials are wonderful! I tried wri...


    Note we haven’t changed anything to our DirectX code, only the HLSL part has been changed. This means our CPU still has the same workload. Only the GPU will have to work a bit harder, but this still is nothing compared to the capabilities of the GPUs present on today’s Radeon and GeForce boards.

    The HLSL code:

    struct VertexToPixel
    {
        float4 Position     : POSITION;
        float4 Color        : COLOR0;

         float4 Position3D     : TEXCOORD0;

    };

    struct PixelToFrame
    {
        float4 Color : COLOR0;
    };

    float4x4 xViewProjection;

    VertexToPixel SimplestVertexShader( float4 inPos : POSITION, float4 inColor : COLOR0)
    {
        VertexToPixel Output = (VertexToPixel)0;
        
        Output.Position =mul(inPos, xViewProjection);
        Output.Color.rgb = inPos.yxz;

         Output.Position3D = inPos;

        
        return Output;    
    }


     PixelToFrame OurFirstPixelShader(VertexToPixel PSIn)
     {
         PixelToFrame Output = (PixelToFrame)0;
     
         Output.Color.rgb = PSIn.Position3D.yxz;
     
         return Output;
     }


    technique Simplest
    {
        pass Pass0
        {        
            VertexShader = compile vs_1_1 SimplestVertexShader();

             PixelShader = compile ps_1_1 OurFirstPixelShader();

        }
    }

    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 int Color;
     
             public myownvertexformat(Vector3 _Pos, int _Color)
             {
                 Pos = _Pos;
                 Color = _Color;
             }
         }
     
         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 Matrix matView;
             private Matrix matProjection;
     
             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), 3, 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[30];
     
                 vertices[0] = new myownvertexformat(new Vector3(2, -2, -2), Color.Red.ToArgb());
                 vertices[1] = new myownvertexformat(new Vector3(0, 2, 0), Color.Yellow.ToArgb());
                 vertices[2] = new myownvertexformat(new Vector3(-2, -2, 2), Color.Green.ToArgb());
     
                 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.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0),
                     VertexElement.VertexDeclarationEnd
                 };
                 vd = new VertexDeclaration(device, velements);
             }
     
             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) device.SetTexture(0, meshtextures[i]);
                     mesh.DrawSubset(i);
                 }
             }
     
             protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
             {
                 device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.DarkSlateBlue, 1.0f, 0);
                 device.BeginScene();
     
                 device.SetStreamSource(0, vb, 0);            
                 device.VertexDeclaration = vd;
                 effect.Technique = "Simplest";
                 effect.SetValue("xViewProjection", matView * matProjection);
                 int numpasses = effect.Begin(0);
                 for (int i = 0; i < numpasses; i++)
                 {
                     effect.BeginPass(i);
                     device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);
                     effect.EndPass();
                 }
                 effect.End();
     
                 UpdateFramerate();
     
                 device.EndScene();
                 device.Present();
                 this.Invalidate();    
             }
     
             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(0, -6, 5);
                 matProjection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 1f, 20f);
                 matView = Matrix.LookAtLH(CameraPos, new Vector3(0, -1, 0), new Vector3(0, 1, 1));
     
                 device.Transform.Projection = matProjection;
                 device.Transform.View = matView;
             }
     
             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!