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

 Tutorial 3 for Windows Phone 7
  Posted by: Anonymous
  When: 20/05/2013 at 02:30:13

 No download link for 2d series: shooter
  Posted by: zaboleq
  When: 07/05/2013 at 15:46:28

 Collision Class?
  Posted by: Anonymous
  When: 05/05/2013 at 19:03:59

 stack overflow
  Posted by: cityguy
  When: 07/04/2013 at 01:58:38

 Meshes looks strange.
  Posted by: ab_saratov
  When: 01/04/2013 at 04:31:08

 Lamppost Not loaded
  Posted by: Anonymous
  When: 22/03/2013 at 06:43:52

 Collision Class?
  Posted by: Da_Boom
  When: 21/03/2013 at 01:23:09

 Math boggles me
  Posted by: cityguy
  When: 17/03/2013 at 03:44:48

 Collision Class?
  Posted by: Da_Boom
  When: 16/03/2013 at 03:44:42

 Tree update
  Posted by: Anonymous
  When: 15/03/2013 at 21:11:22


Ads

Texturing our triangle using the Pixel Shader

When you take another look at our flowchart, you’ll see we’ve already seen the most part of it. We’ve covered pretty much everything starting from our vertex stream to the output of the pixel shader. We’ve also set a shader constant, xViewProjection, from within our DirectX app. This means our next goal should be to load a texture from within our DirectX app, and have our pixel shader sample the correct color for each pixel.

The first part would be to load the texture in our DirectX app, and to update the vertex stream as well as the VertexDeclaration, so they also send texture coordinate information to the vertex shader.

We will immediately start by loading our street texture, which you can download here. I got them from this site, it has a lot of very nice textures you can use in your own app. You can already put this line at the top of your DirectX code:

 private Texture StreetTexture;

And this line in your FillResources method:

 StreetTexture = TextureLoader.FromFile(device, "streettexture.jpg");

The next thing to do would be to update the myownvertexformat structure at the top of your code, so it can handle texture coordinates. We’ll remove the Color entry, as we’ll no longer use it:

 struct myownvertexformat
 {
     public Vector3 Pos;
     public Vector2 TexCoord;
 
     public myownvertexformat(Vector3 _Pos, float texx, float texy)
     {
         Pos = _Pos;
         TexCoord.X = texx;
         TexCoord.Y = texy;
     }
 }

Now each vertex can now hold a position as well as a texture coordinate, so let’s update them:

 vertices[0] = new myownvertexformat(new Vector3(2, -2, -2), 0.0f, 0.0f);
 vertices[1] = new myownvertexformat(new Vector3(0, 2, 0), 0.125f, 1.0f);
 vertices[2] = new myownvertexformat(new Vector3(-2, -2, 2), 0.25f, 0.0f);

This defines the 3D position as well as the 2D texture coordinate. Remember, to have this correctly connected to you vertex shader, you also need to update your VertexDeclaration accordingly:

 VertexElement[] velements = new VertexElement[]
 {
     new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
     new VertexElement(0, 12, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0),
                 VertexElement.VertexDeclarationEnd
 };

You see we have replaced the Color entry by this TextureCoordinate entry, which takes up 2 floats.

So far for the DirectX again, let’s turn to our HLSL file again. Before moving on to our shaders, let’s first add these lines to the top of our code:

Texture xColoredTexture;

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

The first line defines a variable that will hold our texture. We’ll need to fill this variable from within our DirectX app. The second line sets up the sampler. A sampler is linked to a texture, and describes how the texture should be processed. We set the min- and magfilters, together with the mipfilter, to linear, so we’ll always get nicely shader colors, even when the camera is very close to the triangle. See the chapter ‘Texture filtering’ in series 2 for moer info. We set the texture coordinate states to mirror, which means that texture coordinate (2.2f, 1.4f) will be automatically replaced by (0.2f, 0.6f).

Next, we’ll instruct our vertex shader to simply route the texture coodinates from its input to its output. Therefore, we first need to adjust its output structure, VertexToPixel:

struct VertexToPixel
{
    float4 Position     : POSITION;
    float2 TexCoords    : TEXCOORD0;
};

Once again, we’re using the TEXCOORD0 semantic. Although we’re only passing 2 floats instead of the maximum 4, this is the correct choice. Now update your vertex shader to this:

VertexToPixel SimplestVertexShader( float4 inPos : POSITION, float2 inTexCoords : TEXCOORD0)
{
    VertexToPixel Output = (VertexToPixel)0;
    
    Output.Position = mul(inPos, xViewProjection);
    Output.TexCoords = inTexCoords;
    
    return Output;    
}

Where we transform our 3D postions into screen coordinates, and pass the texture coodinates through. Next in line is the pixel shader. Think of what the pixel shader receives from the interpolater: the interpolated 2D screen position and the interpolated 2D texture coordinate. The pixel shader needs to output the pixel color, which will be the corresponding pixel in our texture.

So change the correct line in your pixel shader to this:

Output.Color = tex2D(ColoredTextureSampler, PSIn.TexCoords);

This command simply retrieves the color of the pixel in the StreetTexture image, corresponding to the 2D coordinate in PSIn.TexCoords. When you hit Ctrl+S, the HLSL code should compile without problems. There remains only one thing to do: set the xColoredTexture from within our DirectX app. So put this line in your OnPaint method:

effect.SetValue("xColoredTexture", StreetTexture);

Which loads the StreetTexture variable of our DirectX app into the xColoredTexture variable of our HLSL code.




DirectX Tutorial 6 - Textured Triangle

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:
  • texture different picture
          i got 2 Triangles, how to texture different pictur...
  • Invalid subscript 'tex2D'
          Hey Riemer, I was working on your HLS...
  • Texture Link
          I hate to be the guy who brings up another problem...
  • Error in HLSL
          On the line that creates StreetTextureSampler, the...


    By now, you should have an idea of how the DirectX app, the vertex shader and the pixel shader interact with each other. Next chapter, I’ll discuss something DirectX specific again, because we won’t succeed in achieving the final image of this Series without expanding our scene. After that one, we’ll go back to HLSL..

    The HLSL code:

    struct VertexToPixel
    {
        float4 Position     : POSITION;

         float2 TexCoords    : TEXCOORD0;

    };

    struct PixelToFrame
    {
        float4 Color : COLOR0;
    };

    float4x4 xViewProjection;


     Texture xColoredTexture;

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

     VertexToPixel SimplestVertexShader( float4 inPos : POSITION, float2 inTexCoords : TEXCOORD0)

    {
        VertexToPixel Output = (VertexToPixel)0;
        
        Output.Position = mul(inPos, xViewProjection);

         Output.TexCoords = inTexCoords;

        
        return Output;    
    }

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


         Output.Color = tex2D(ColoredTextureSampler, PSIn.TexCoords);


        return Output;
    }

    technique Simplest
    {
        pass Pass0
        {        
            VertexShader = compile vs_1_1 SimplestVertexShader();
            PixelShader = compile ps_1_1 OurFirstPixelShader();
        }
    }


    .. And 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 Vector2 TexCoord;
     
             public myownvertexformat(Vector3 _Pos, float texx, float texy)
             {
                 Pos = _Pos;
                 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 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[3];
                 vertices[0] = new myownvertexformat(new Vector3(2, -2, -2), 0.0f, 0.0f);
                 vertices[1] = new myownvertexformat(new Vector3(0, 2, 0), 0.125f, 1.0f);
                 vertices[2] = new myownvertexformat(new Vector3(-2, -2, 2), 0.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.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0),
                     VertexElement.VertexDeclarationEnd
                 };
                 vd = new VertexDeclaration(device, velements);
     
                 StreetTexture = TextureLoader.FromFile(device, "streettexture.jpg");
             }
     
             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);
                 effect.SetValue("xColoredTexture", StreetTexture);
                 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)
    Chapter 1
    Chapter 2
    Chapter 3
    Chapter 4
    Chapter 5
    Chapter 6
    Chapter 7
    Chapter 8
    XNA 3.0 Recipes Book (8)
    Chapter 1
    Chapter 2
    Chapter 3
    Chapter 4
    Chapter 5
    Chapter 6
    Chapter 7
    Chapter 8
    Downloads
    Extra Reading (3)
    Matrices: geometrical
    Matrix Mathematics
    Homogenous matrices
    Community Projects (1)
    Team Project (1)
    News
    Tutorials (160)
    XNA 4.0 using C# (89)
    2D Series: Shooters (22)
    Starting a project
    Drawing fullscreen images
    Positioning images
    SpriteBatch.Draw()
    Rotation
    Keyboard input
    Writing text
    Angle to Direction
    Direction to Angle
    Smoke trail
    Manual texture creation
    Random terrain
    Texture to Colors
    Coll Detection Overview
    Coll Detection Matrices
    Putting CD into practice
    Particles
    Additive alpha blending
    Particle engine
    Adding craters
    Sound in XNA
    Resolution independency
    3D Series 1: Terrain (13)
    Starting a project
    The effect file
    The first triangle
    World space
    Rotation - translation
    Indices
    Terrain basics
    Terrain from file
    Keyboard
    Adding colors
    Lighting basics
    Terrain lighting
    VertexBuffer & IndexBuffer
    3D Series 2: Flightsim (14)
    Starting point
    Textures
    Loading the floorplan
    Creating the 3D city
    Loading a Model
    Ambient and diffuse
    Quaternion camera
    Flight kinematics
    Collision detection
    Adding targets
    Point sprites
    Alpha blending
    Skybox
    Camera delay
    3D Series 3: HLSL (18)
    Starting point
    HLSL introduction
    Vertex format
    Vertex shader
    Pixel shader
    Per-pixel colors
    Textured triangle
    Triangle strip
    World transform
    World normals
    Per-pixel lighting
    Shadow map
    Render to texture
    Projective texturing
    Real shadow
    Shaping the light
    Preshaders
    3D Series 4: Adv. terrain (19)
    Starting code
    Mouse camera
    Textured terrain
    Multitexturing
    Adding detail
    Skydome
    The water technique
    Refraction map
    Reflection map
    Perfect mirror
    Ripples
    The Fresnel term
    Moving water
    Specular highlights
    Billboarding
    Region growing
    Billboarding renderstates
    Perlin noise
    Gradient skybox
    Short Tuts (3)
    Run XNA on older pcs
    MessageBox in XNA
    Normal generation
    DirectX using C# (54)
    Series 1:Terrain (14)
    Opening a window
    Linking to the Device
    Drawing a triangle
    Camera
    Rotation - Translation
    Indices
    Terrain creation
    Terrain from file
    DirectInput
    Importing bmp files
    Colored vertices
    DirectX Light basics
    Mesh creation
    Mesh lighting
    Series 2: Flightsim (19)
    Starting code
    Textures
    The floorplan
    Creating the 3D City
    Meshloading from file
    Ambient light
    Action
    Flight kinematics
    Collision detection
    Skybox
    Texture filtering
    Adding targets
    Point sprites
    Alpha blending
    DirectSound
    Sounds in 3D
    Playing MP3 files
    Displaying text
    Going fullscreen
    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)
    Resizing problem
    Checking Device caps
    DirectX using C++ (15)
    Series 1: Terrain (15)
    Opening a window
    Ending the game loop
    Linking to the Device
    Clearing your window
    Drawing a triangle
    Culling
    Camera
    Rotation - Translation
    Indices
    Terrain creation
    Terrain from file
    DirectInput
    Importing .bmp files
    Adding colors
    DirectX Light basics
    DirectX using VB (2)
    Series 1: Intro (2)
    The first triangle
    Rotation - translation
    -- Tree view --


    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!