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

Drawing your first Triangle

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

Every object drawn by Direct3D is drawn using triangles. Surprisingly enough, a triangle is defined by 3 points. Every point is defined by a vector, giving 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. First let’s define a structure which would hold such features. For now, we will only use the position and the color, as well as a colorweight factor, which I will explain a little later.

 struct OURCUSTOMVERTEX
 {
     float x,y,z,weight;
     DWORD color;
 }; //mind this third ;

Now let’s create a method FillVertices that initialises an array containing 3 of these structures and fills it:

 void FillVertices()
 {
     OURCUSTOMVERTEX cv_Vertices[3];
 
     cv_Vertices[0].x = 150;
     cv_Vertices[0].y = 100;
     cv_Vertices[0].z = 0;
     cv_Vertices[0].weight = 1;
     cv_Vertices[0].color = 0xffff0000;
 
     cv_Vertices[1].x = 350;
     cv_Vertices[1].y = 100;
     cv_Vertices[1].z = 0;
     cv_Vertices[1].weight = 1;
     cv_Vertices[1].color = 0xff00ff00;
 
     cv_Vertices[2].x = 250;
     cv_Vertices[2].y = 300;
     cv_Vertices[2].z = 0;
     cv_Vertices[2].weight = 1;
     cv_Vertices[2].color = 0xff00ffff;}

The first line in the method reserves the space in memory for an array containing three of our structs. Then the array is filled: the positions of the three points are defined, with their color.

This is simply occupying general memory. We need to copy this data into special memory reserved for DirectX, called a VertexBuffer. First let’s create this vertexbuffer:

 LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer;
 
 if (FAILED(p_dx_Device->CreateVertexBuffer(3*sizeof(OURCUSTOMVERTEX), 0, D3DFVF_XYZRHW|D3DFVF_DIFFUSE, D3DPOOL_DEFAULT, &p_dx_VertexBuffer, NULL)))
 {
     MessageBox(han_Window,"Error while creating VertexBuffer","FillVertices()",MB_OK);
 }

This will try to reserve memory for a VertexBuffer, containing 3 of our structs. As parameters we mention that we are going to pass xyz and the colorweight info. If this fails, a messagebox will pop up. Notice that to open this messagebox, we again need a handle to our window, which should be passed to the method. We’ll do this later, first let’s actually copy the data from our array into the DirectX memory, the VertexBuffer. To do this, we first need to lock this memory, so no other application can access it while we’ve locked it. If the buffer has been locked, we can copy our data into it.

 VOID* p_Vertices;
 if (FAILED(p_dx_VertexBuffer->Lock(0, 3*sizeof(OURCUSTOMVERTEX), (void**)&p_Vertices, 0)))
 {
     MessageBox(han_Window,"Error trying to lock","FillVertices()",MB_OK);
 }else{
     memcpy(p_Vertices, cv_Vertices, 3*sizeof(OURCUSTOMVERTEX));
     p_dx_VertexBuffer->Unlock();
 }

This call takes the offset in the buffer and the amount of memory to lock, as well as a pointer where it should place a pointer to the locked memory. We then use this pointer to copy our data to using the standard C method memcpy. With the data copied, we can unlock our vertexbuffer again, so other applications can read from it.

Now this method has to return a pointer to this VertexBuffer. As you’ve noticed, the method has to receive a handle to the window, as well as a pointer to our device. So modify the interface of your method like this:

 LPDIRECT3DVERTEXBUFFER9 FillVertices(HWND han_Window, LPDIRECT3DDEVICE9 p_dx_Device)
 {
     //other code
 
     return p_dx_VertexBuffer;
 }

This completes the FillVertices method. Of course we still have to call it from our WinMain method. This has to be done only once, for example immediately after you have created your device:

 LPDIRECT3DVERTEXBUFFER9 p_dx_VB = FillVertices(han_Window, p_Device);

Which stores the pointer to our VertexBuffer in a variable called p_dx_VB. Now, during each iteration of our game loop, we are going to draw our triangle. To achieve this, the pointer should be passed to our DrawScene method:

 DrawScene(p_Device, p_dx_VB);

Finally we’re going to modify our DrawScene method. Change it to this:

 void DrawScene(LPDIRECT3DDEVICE9 p_dx_Device, LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer)
 {
     p_dx_Device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
     p_dx_Device->BeginScene();
 
     p_dx_Device->SetStreamSource(0, p_dx_VertexBuffer, 0, sizeof(OURCUSTOMVERTEX));
     p_dx_Device->SetFVF(D3DFVF_XYZRHW|D3DFVF_DIFFUSE);
     p_dx_Device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
 
     p_dx_Device->EndScene();
     p_dx_Device->Present(NULL, NULL, NULL, NULL);
 }

You see we’ve changed the interface so now it accepts the pointer to our vertexbuffer. From now on, we’re actually defining a scene: our triangle. The first line in the body tells DirectX it should find its data at the pointer pointing to our vertexbuffer. Next we indicate which data it should expect to find there and we say our VertexBuffer contains a list of triangles, of which only 1 has to be drawn, starting at position 0, so only the first one.

The last thing that has to be done is simply adjusting the call to this DrawScene method from our WinMain method, because we now also have to pass it the pointer to our VertexBuffer:

 DrawScene(p_Device, p_dx_VB);

Compiling this should display your first triangle, drawn by DirectX using C++:




DirectX Tutorial 5 - Drawing a 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:
  • Moving the vertices
          Hi! I was wondering how could I change the X an...
  • Antialiasing
          Hi All, I am drawing a line with rotation angle b...
  • color weight
          hi there i do not understand how changing the w...
  • Triangle not drawing in MY code
          Okay, I've worked through the tutorials that I ca...



    One last remark: remember the part where we defined our pionts of the triangle ? We defined the 3 coordinates and the color, as well al a 5th value, the color weight. Which always was 1 in our example. Try changing one of these values to 5 for example, compile the code and see what difference this makes.

    Here you find the code this far:


    #include<windows.h>
    #include<d3d9.h>
    #include<d3dx9.h>

     struct OURCUSTOMVERTEX
     {
         float x,y,z,weight;
         DWORD color;
     };
     
     int int_AppRunning = 1;
     
     LRESULT CALLBACK OurWindowProcedure(HWND han_Wind,UINT uint_Message,WPARAM parameter1,LPARAM parameter2)
     {
         switch(uint_Message)
         {
             case WM_KEYDOWN:
             {
                 int_AppRunning = 0;
                 break;
             }
             break;
         }
     
         return DefWindowProc(han_Wind,uint_Message,parameter1,parameter2);
     }
     
     HWND NewWindow(LPCTSTR str_Title,int int_XPos, int int_YPos, int int_Width, int int_Height)
     {
         WNDCLASSEX wnd_Structure;
     
         wnd_Structure.cbSize = sizeof(WNDCLASSEX);
         wnd_Structure.style = CS_HREDRAW | CS_VREDRAW;
         wnd_Structure.lpfnWndProc = OurWindowProcedure;
         wnd_Structure.cbClsExtra = 0;
         wnd_Structure.cbWndExtra = 0;
         wnd_Structure.hInstance = GetModuleHandle(NULL);
         wnd_Structure.hIcon = NULL;
         wnd_Structure.hCursor = NULL;
         wnd_Structure.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
         wnd_Structure.lpszMenuName = NULL;
         wnd_Structure.lpszClassName = "WindowClassName";
         wnd_Structure.hIconSm = LoadIcon(NULL,IDI_APPLICATION);
     
         RegisterClassEx(&wnd_Structure);
     
         return CreateWindowEx(WS_EX_CONTROLPARENT, "WindowClassName", str_Title, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE, int_XPos, int_YPos, int_Width, int_Height, NULL, NULL, GetModuleHandle(NULL), NULL);
     }
     
     LPDIRECT3DDEVICE9 InitializeDevice(HWND han_WindowToBindTo)
     {
         LPDIRECT3D9 p_dx_Object;
         LPDIRECT3DDEVICE9 p_dx_Device;
     
         p_dx_Object = Direct3DCreate9(D3D_SDK_VERSION);
         if (p_dx_Object == NULL)
         {
             MessageBox(han_WindowToBindTo,"DirectX Runtime library not installed!","InitializeDevice()",MB_OK);
         }
     
         D3DPRESENT_PARAMETERS dx_PresParams;
         ZeroMemory( &dx_PresParams, sizeof(dx_PresParams) );
         dx_PresParams.Windowed = TRUE;
         dx_PresParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
         dx_PresParams.BackBufferFormat = D3DFMT_UNKNOWN;
     
      if (FAILED(p_dx_Object->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, han_WindowToBindTo, D3DCREATE_HARDWARE_VERTEXPROCESSING, &dx_PresParams, &p_dx_Device)))
      {
             if (FAILED(p_dx_Object->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_REF, han_WindowToBindTo, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &dx_PresParams, &p_dx_Device)))
             {
                 MessageBox(han_WindowToBindTo,"Failed to create even the reference device!","InitializeDevice()",MB_OK);
             }
      }
     
         return p_dx_Device;
     }
     
     void DrawScene(LPDIRECT3DDEVICE9 p_dx_Device, LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer)
     {
         p_dx_Device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
         p_dx_Device->BeginScene();
     
         p_dx_Device->SetStreamSource(0, p_dx_VertexBuffer, 0, sizeof(OURCUSTOMVERTEX));
         p_dx_Device->SetFVF(D3DFVF_XYZRHW|D3DFVF_DIFFUSE);
         p_dx_Device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
     
         p_dx_Device->EndScene();
         p_dx_Device->Present(NULL, NULL, NULL, NULL);
     }
     
     LPDIRECT3DVERTEXBUFFER9 FillVertices(HWND han_Window, LPDIRECT3DDEVICE9 p_dx_Device)
     {
         OURCUSTOMVERTEX cv_Vertices[3];
         LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer;
     
         cv_Vertices[0].x = 150;
         cv_Vertices[0].y = 100;
         cv_Vertices[0].z = 0;
         cv_Vertices[0].weight = 1;
         cv_Vertices[0].color = 0xffff0000;
     
         cv_Vertices[1].x = 350;
         cv_Vertices[1].y = 100;
         cv_Vertices[1].z = 0;
         cv_Vertices[1].weight = 1;
         cv_Vertices[1].color = 0xff00ff00;
     
         cv_Vertices[2].x = 250;
         cv_Vertices[2].y = 300;
         cv_Vertices[2].z = 0;
         cv_Vertices[2].weight = 1;
         cv_Vertices[2].color = 0xff00ffff;
     
         if (FAILED(p_dx_Device->CreateVertexBuffer(3*sizeof(OURCUSTOMVERTEX), 0, D3DFVF_XYZRHW|D3DFVF_DIFFUSE, D3DPOOL_DEFAULT, &p_dx_VertexBuffer, NULL ) ) )
         {
             MessageBox(han_Window,"Error while creating VertexBuffer","FillVertices()",MB_OK);
         }
     
         VOID* p_Vertices;
         if (FAILED(p_dx_VertexBuffer->Lock(0, 3*sizeof(OURCUSTOMVERTEX), (void**)&p_Vertices, 0)))
         {
             MessageBox(han_Window,"Error trying to lock","FillVertices()",MB_OK);
         }else{
             memcpy(p_Vertices, cv_Vertices, 3*sizeof(OURCUSTOMVERTEX));
             p_dx_VertexBuffer->Unlock();
         }
     
         return p_dx_VertexBuffer;
     }
     
     int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPreviousInstance,LPSTR lpcmdline,int nCmdShow)
     {
         MSG msg_Message;
     
         HWND han_Window = NewWindow("DirectX C++ Tutorial",100,100,500,500);
         LPDIRECT3DDEVICE9 p_Device = InitializeDevice(han_Window);
         LPDIRECT3DVERTEXBUFFER9 p_dx_VB = FillVertices(han_Window, p_Device);
     
         while(int_AppRunning)
         {
             if(PeekMessage(&msg_Message,han_Window,0,0,PM_REMOVE))
             {
                 DispatchMessage(&msg_Message);
             }
             DrawScene(p_Device, p_dx_VB);
         }
     
         p_Device->Release();
         DestroyWindow(han_Window);
     
         return 0;
     }


    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)
    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)
    -- 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!