XNA for C#
DirectX 9 for C#
DirectX 9 for C++
DirectX 9 for VB
Forum
   August 27: 2D-7: Writing text
My Book: Out Now!
      
       Go to section on this site

Additional info


Latest Forum posts

 DX vs XNA vs OGL
  Posted by: Rich_Zap
  When: 28/08/2008 at 10:54:39

 understanding of SetUpIndices
  Posted by: YoYoFreakCJ
  When: 28/08/2008 at 05:51:04

 billboard does not rotate after scaling
  Posted by: kigunda
  When: 28/08/2008 at 04:55:29

 exception error
  Posted by: Rich_Zap
  When: 28/08/2008 at 03:34:29

 exception error
  Posted by: besi
  When: 28/08/2008 at 00:14:11

 Having trouble with effect file
  Posted by: Anonymous
  When: 27/08/2008 at 22:15:15

 Polygon Clipping for Octree
  Posted by: lbmurali
  When: 27/08/2008 at 18:13:55

 understanding of SetUpIndices
  Posted by: vToMy
  When: 27/08/2008 at 18:05:45

 A Typo with loading the Font
  Posted by: riemer
  When: 27/08/2008 at 15:26:43

 mistake found
  Posted by: riemer
  When: 27/08/2008 at 15:22:31


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 XNA app. This means we have implemented the Colored technique from my default effects.fx file!

A logical next step would be to load a texture from within our XNA app, and have our pixel shader sample the correct color for each pixel.

The first part would be to load the texture in our XNA 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 XNA code:

 Texture2D streetTexture;

Import the image into your Solution Explorer as seen in the chapter Textures of Series 2. Add this line to our LoadContent method:


streetTexture = Content.Load<Texture2D> ("streettexture");
The next thing to do would be to update the MyOwnVertex structure at the top of our code, so it can handle texture coordinates. We’ll remove the Color entry, as we’ll no longer use it:

 struct MyOwnVertexFormat
 {
     private Vector3 position;
     private Vector2 texCoord;
 
     public MyOwnVertexFormat(Vector3 position, Vector2 texCoord)
     {
         this.position = position;
         this.texCoord = texCoord;
     }
 }

To specify the position in a texture, you need a X and Y coordinate, so we’ll store a Vector2.

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

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

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


 public static VertexElement[] VertexElements =
 {
     new VertexElement(0, 0, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Position, 0),
     new VertexElement(0, sizeof(float)*3, VertexElementFormat.Vector2, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 0),
 };
 
 public static int SizeInBytes = sizeof(float) * (3 + 2);


You see we have replaced the Color entry by this TextureCoordinate entry, which is stored in a Vector2. The second argument has remained the same, as the texture coordinate can still be found at the same position as where the color was: immediately after the positional data.

Also note, that each vector now takes up (3+2) floats, since a color was stored as 1 float and a Vector2 needs 2 floats. So we need to adjust our SizeInBytes for correct operation.

So far for the XNA part, 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 xTexture;

sampler TextureSampler = sampler_state { texture = <xTexture> ; 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 XNA 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 Recipe 5-2 for examples on all different kinds of texture addressing modes, and the note in Recipe 3-7 for the what and why on mipmaps.

We set the texture coordinate states to mirror, which means that, for example, texture coordinate (2.2f, 1.4f) will be automatically mapped to the [0,1] region and will thus be replaced by (0.2f, 0.6f).

Next, we’ll instruct our vertex shader to simply route the texture coordinates from its input to its output. Therefore, we first need to adjust its output structure, VertexToPixel, so our vertex shader is expected to generate a texture coordinate instead of a color:

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

Once again, we’re using the TEXCOORD0 semantic to pass additional data from our vertex shader to our pixel shader. Although we’re only passing 2 floats instead of the maximum 4, this is the correct choice. Now update our 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;
}

2 major changes:
  • The first line indicates that the shader expects the vertices to carry TEXCOORD0 information
  • This information is immediately routed towards the output of the vertex shader, the interpolator.

    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 sampled from our texture at the correct position.

    So change the line in your pixel shader to this:

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

    This command simply retrieves the color of the pixel in the xTexture image, corresponding to the 2D coordinate in PSIn.TexCoords.

    There remains only one thing to do: set the xTexture from within our XNA app. So add this line to our Draw method:

     effect.Parameters["xTexture"].SetValue(streetTexture);


    Which loads the streetTexture variable of our XNA app into the xTexture XNA-to-HLSL variable of our HLSL code.




    DirectX Tutorial 7 - 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:
  • XNA 2.0 Strugglers
          //XNA 2.0 -Textured triangle- using System; usin...
  • Texture filtering not in Extra Reading
          Hi Riemer, this tutorial says that the explanation...
  • Street Texture Missing
          Hi, the streettexture dds file is not a valid link...


    By now, you should have an idea of how the XNA app, the vertex shader and the pixel shader interact with each other. Next chapter, I’ll discuss something XNA 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..

    You can try these exercises to practice what you've learned:
  • In your vertex, override the texture coordinates so the xy coordinates of the 3D postion are stored as xy texture coordinates. This should add a lot of copies of the texture, see the next chapters to learn why.

    The HLSL code:
    float4x4 xViewProjection;


     Texture xTexture;

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

    struct VertexToPixel
    {
        float4 Position     : POSITION;    

         float2 TexCoords    : TEXCOORD0;

    };

    struct PixelToFrame
    {
        float4 Color        : COLOR0;
    };


     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(TextureSampler, PSIn.TexCoords);


        return Output;
    }

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


    .. And the XNA code:


     using System;
     using System.Collections.Generic;
     using Microsoft.Xna.Framework;
     using Microsoft.Xna.Framework.Audio;
     using Microsoft.Xna.Framework.Content;
     using Microsoft.Xna.Framework.GamerServices;
     using Microsoft.Xna.Framework.Graphics;
     using Microsoft.Xna.Framework.Input;
     using Microsoft.Xna.Framework.Net;
     using Microsoft.Xna.Framework.Storage;
     
     namespace XNAseries3
     {
         public class Game1 : Microsoft.Xna.Framework.Game
         {
             struct MyOwnVertexFormat
             {
                 private Vector3 position;
                 private Vector2 texCoord;
     
                 public MyOwnVertexFormat(Vector3 position, Vector2 texCoord)
                 {
                     this.position = position;
                     this.texCoord = texCoord;
                 }
     
                 public static VertexElement[] VertexElements =
                 {
                     new VertexElement(0, 0, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Position, 0),
                     new VertexElement(0, sizeof(float)*3, VertexElementFormat.Vector2, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 0),
                 };
                 public static int SizeInBytes = sizeof(float) * (3 + 2);
             }
     
             GraphicsDeviceManager graphics;
             GraphicsDevice device;
             
             Effect effect;
             Matrix viewMatrix;
             Matrix projectionMatrix;
             VertexBuffer vertexBuffer;
             VertexDeclaration vertexDeclaration;
             Vector3 cameraPos;
     
             Texture2D streetTexture;
     
             public Game1()
             {
                 graphics = new GraphicsDeviceManager(this);            
                 Content.RootDirectory = "Content";
             }
     
             protected override void Initialize()
             {
                 graphics.PreferredBackBufferWidth = 500;
                 graphics.PreferredBackBufferHeight = 500;
                 graphics.IsFullScreen = false;
                 graphics.ApplyChanges();
                 Window.Title = "Riemer's XNA Tutorials -- Series 3";
     
                 base.Initialize();
             }
     
             protected override void LoadContent()
             {
                 device = GraphicsDevice;

                effect = Content.Load<Effect> ("OurHLSLfile");

                streetTexture = Content.Load<Texture2D> ("streettexture");
     
                 SetUpVertices();
                 SetUpCamera();
             }
     
             private void SetUpVertices()
             {
                 MyOwnVertexFormat[] vertices = new MyOwnVertexFormat[3];
     
                 vertices[0] = new MyOwnVertexFormat(new Vector3(-2, 2, 0), new Vector2(0.0f, 0.0f));
                 vertices[1] = new MyOwnVertexFormat(new Vector3(2, -2, -2), new Vector2(0.125f, 1.0f));
                 vertices[2] = new MyOwnVertexFormat(new Vector3(0, 0, 2), new Vector2(0.25f, 0.0f));
     
                 vertexBuffer = new VertexBuffer(device, vertices.Length * MyOwnVertexFormat.SizeInBytes, BufferUsage.WriteOnly);
                 vertexBuffer.SetData(vertices);
     
                 vertexDeclaration = new VertexDeclaration(device, MyOwnVertexFormat.VertexElements);
             }
     
             private void SetUpCamera()
             {
                 cameraPos = new Vector3(0, 5, 6);
                 viewMatrix = Matrix.CreateLookAt(cameraPos, new Vector3(0, 0, 1), new Vector3(0, 1, 0));
                 projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 200.0f);
             }
     
             protected override void UnloadContent()
             {
             }
     
             protected override void Update(GameTime gameTime)
             {            
                 if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                     this.Exit();
     
                 base.Update(gameTime);
             }
     
             protected override void Draw(GameTime gameTime)
             {
                 device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
     
                 effect.CurrentTechnique = effect.Techniques["Simplest"];
                 effect.Parameters["xViewProjection"].SetValue(viewMatrix * projectionMatrix);
                 effect.Parameters["xTexture"].SetValue(streetTexture);
                 effect.Begin();
                 foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                 {
                     pass.Begin();
                     device.VertexDeclaration = vertexDeclaration;
                     device.Vertices[0].SetSource(vertexBuffer, 0, MyOwnVertexFormat.SizeInBytes);
                     device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);
                     pass.End();
                 }
                 effect.End();
     
                 base.Draw(gameTime);
             }
         }
     }
     


    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 - 2008 Riemer Grootjans
  • Translations

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

    Microsoft MVP Award



    2007 - 2008 MVP Award
    DirectX - XNA

    Contents

    News
    Home
    Forum
    XNA 2.0 Recipes Book (8)
    Downloads
    Extra Reading (3)
    Matrices: geometrical
    Matrix Mathematics
    Homogenous matrices
    Tutorials (145)
    XNA 2.0 using C# (74)
    2D Series: Shooters! (7)
    3D Series 1: Terrain (13)
    3D Series 2: Flightsim (14)
    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
    2D screen processing
    Preshaders
    3D Series 4: Adv. terrain (19)
    Short Tuts (3)
    DirectX using C# (54)
    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!