XNA for C#
DirectX 9 for C#
DirectX 9 for C++
DirectX 9 for VB
Forum
   2D Series finished!
My Book: Out Now!
      
       Go to section on this site

Additional info


Latest Forum posts

 error x3000:syntax error
  Posted by: Anonymous
  When: 02/09/2010 at 06:55:17

 Reflection problem in corners ...
  Posted by: Anonymous
  When: 31/08/2010 at 20:53:30

 OcTree Question
  Posted by: radulph
  When: 31/08/2010 at 18:00:04

 model problems
  Posted by: Archenon
  When: 30/08/2010 at 05:54:27

 Changing computer breaks my game
  Posted by: Archenon
  When: 30/08/2010 at 05:49:50

 model problems
  Posted by: muffinman
  When: 28/08/2010 at 16:58:10

 Vertices problem
  Posted by: Anonymous
  When: 27/08/2010 at 15:35:36

 Changing computer breaks my game
  Posted by: radulph
  When: 27/08/2010 at 07:12:24

 effects file and XNA 4.0 (Beta)
  Posted by: radulph
  When: 26/08/2010 at 06:33:33

 Changing computer breaks my game
  Posted by: radulph
  When: 26/08/2010 at 06:27:59


Ads

Drawing your first Triangle

This chapter will cover the basics of drawing. First a few things you should know about.

Every object drawn in 3D is drawn using triangles. Even spheres can be represented using triangles, if you use enough of them. Surprisingly enough, a triangle is defined by 3 points. Every point is defined by a vector, specifying the X, Y and Z coordinates of the point. However, just knowing the coordinates of a point might not be enough. For example, you might want to define a color for the given point as well. This is where a vertex (pl. vertices) comes in: it is the list of properties of a given point, including the position, color and so on.

XNA has a structure that fits perfectly to hold our vertex information: the VertexPositionColor struct. A vertex of this type can hold a position and a color, which is perfect to begin with. To define a triangle, we’ll need 3 of those vertices, which we will store in an array. So let’s declare this variable at the top of our class:

 VertexPositionColor[] vertices;

Next, we will add a small method to our code, SetUpVertices, which will fill this array with 3 vertices:

 private void SetUpVertices()
 {
     vertices = new VertexPositionColor[3];
 
     vertices[0].Position = new Vector3(-0.5f, -0.5f, 0f);
     vertices[0].Color = Color.Red;
     vertices[1].Position = new Vector3(0, 0.5f, 0f);
     vertices[1].Color = Color.Green;
     vertices[2].Position = new Vector3(0.5f, -0.5f, 0f);
     vertices[2].Color = Color.Yellow;
 }

The array is initialized to hold 3 vertices, after which it is filled. For now, we’re using coordinates that are relative to the screen: the (0,0,0) point would be the middle of our screen, the (-1, -1, 0) point bottom-left and the (1, 1, 0) point top-right. So in the example above, the first point is halfway to the bottom left of the window, and the second point is halfway to the top in the middle of our screen. (As they are not really 3D coordinates, they don’t need to be transformed to 2D coords. Hence, the name of the technique: ‘Pretransformed’)

The 'f' behind some of the numbers indicates the values are floats, the format of preference when working with XNA. We set each of the vertices to different colors.

At this moment, we have stored the position and color data for 3 vertices inside an array. When we instruct XNA to render a triangle based on this data, XNA will put all this data in a byte stream and send it over to the graphics card. Our graphics card receives the byte stream, but doesn’t know what’s in there! So we first need to pass it a VertexDeclaration: this object tells the graphics device what kind of vertices it can expect.

The VertexDeclaration is very important, as you will always need it before you can render any triangle to the screen. Since a the VertexDeclaration will remain unchanged throughout our project, you should add this as a variable to your code and initialize it only once. (Moreover, re-creating this each frame would cause the compact .NET framework on the Xbox360 to crash) So add this variable to the top of your class:

 VertexDeclaration myVertexDeclaration;

And initialize it somewhere in your SetUpVertices method. This is the ideal spot, as the VertexDeclaration belongs to the type of vertices you just filled an array with.

 myVertexDeclaration = new VertexDeclaration(device, VertexPositionColor.VertexElements);

This declaration should be passed to our graphics card to inform it there are vertices of the VertexPositionColor type coming its way, which we’ll do in our Draw method later on.

We still need to call this SetUpVertices method. As it uses the device, call it at the end of the LoadContent method:

 SetUpVertices();

All we have to do now is tell the device to draw the triangle! Go to our Draw method, where we should draw the triangle between the calls to pass.Begin and pass.End:

 device.VertexDeclaration = myVertexDeclaration;
 device.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1);

The first line sends over the VertexDeclaration defined above, while the second line actually draws the triangle: we want to draw 1 triangle from the vertices array, starting at vertex 0. TriangleList means that our vertices array contains a list of triangles (in our case, a list of only 1 triangle). If you would want to draw 4 triangles, you would need an array of 12 vertices. Another possibility is to use a TriangleStrip, which can perform a lot faster, but is only useful to draw triangles that are connected to each other. More on all kinds of primitives in Recipe 5-1.

Running this code should give you this window:




DirectX Tutorial 3 - The first 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 or GameStudio A7
          Hi there, First off, great tutorials. However, ...
  • What does the 0 do in pretransformed
           VertexToPixel Output = (VertexToPixel)0; Pi...
  • InvalidOperationExcpetion
          Hi, and thanks for the tutorials. I have an Inval...
  • Error With the Effect File
          Um i downloaded your effect file, added it to my p...
  • strange behaviour with basic effect
          hey riemer, thank you for helping so many of us wi...
  • some advanced thoughts
          Hi everybody I already did some stuff with XNA,...
  • Vertices problem
          Hi, great tutorials, though when I run the program...
  • LineStrip color stealing texture
          Hey Riemer, Your tutorials are awesome, however...
  • Please Help me Anybody
          I'm having serious trouble, getting things to com...
  • effect.CurrentTechnique null value
          Code line: effect.CurrentTechnique = effect.Techn...
  • verify file location
          Your tutorial is neat and gets right to the point....
  • Novice stupid question
          Hi Riemer, Sorry for bothering u with this stup...
  • vertices problem
          private void SetUpVertices() { ...
  • Argument exception null was unhandled
          Hi, Thanks for the tutorial. It's great I fina...
  • Missing a step
          Hello, I'l loving the walk through so far, ver...
  • this.Invalidate(); buttons problem
          ... at least for me it doesn't :) Hello there ...
  • Errors in Step 2
          Hi, These tutorials are great! Thanks very much...
  • Cant change vertices position
          In SetUpVertices(), if you change the position of ...
  • Background color
          Hey there riemers! First off, thank you very mu...
  • Error @ step 3 of series 1
          I get this compliling error at step 3 of series 1....


    That's all there is to it! Running this code will already give you a colorful triangle on a blue background. Feel free to experiment with the colors and the coordinates.

    You can try these exercises to practice what you've learned:
  • Make the bottom-left corner of the triangle collide with the bottom-left corner of your window.
  • Render 2 triangles, covering your whole window.
    I've listed the total code below :

     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 XNAtutorial
     {
         public class Game1 : Microsoft.Xna.Framework.Game
         {
             GraphicsDeviceManager graphics;
             SpriteBatch spriteBatch;
             GraphicsDevice device;
             Effect effect;
             VertexPositionColor[] vertices;
             VertexDeclaration myVertexDeclaration;
     
             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 1";        
     
                 base.Initialize();
             }
     
             private void SetUpVertices()
             {
                 vertices = new VertexPositionColor[3];
     
                 vertices[0].Position = new Vector3(-0.5f, -0.5f, 0f);
                 vertices[0].Color = Color.Red;
                 vertices[1].Position = new Vector3(0, 0.5f, 0f);
                 vertices[1].Color = Color.Green;
                 vertices[2].Position = new Vector3(0.5f, -0.5f, 0f);
                 vertices[2].Color = Color.Yellow;
     
                 myVertexDeclaration = new VertexDeclaration(device, VertexPositionColor.VertexElements);
             }
     
             protected override void LoadContent()
             {
                 device = graphics.GraphicsDevice;
                 spriteBatch = new SpriteBatch(GraphicsDevice);

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

     
                 SetUpVertices();
             }
     
             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(Color.DarkSlateBlue);
     
                 effect.CurrentTechnique = effect.Techniques["Pretransformed"];
                 effect.Begin();
                 foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                 {
                     pass.Begin();
     
                     device.VertexDeclaration = myVertexDeclaration;
                     device.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 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 - 2009 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 3.0 using C# (89)
    2D Series: Shooters! (22)
    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)
    3D Series 3: HLSL (18)
    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!