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

Recycling vertices using inidices

The triangle was nice, but what about a lot of triangles? You would need to specify 3 vertices for each triangle. Consider next example:



Only 4 out of 6 vertices are unique. So the other 2 are a waste of bandwidth to you AGP slot. It would be better to define the 4 vertices in an array from 0 to 3, and to define triangle 1 as vertices 1,2 and 3 and triangle 2 as vertices 2,3 and 4. This is exactly the idea behind IndexBuffers. Suppose we would like to draw these 2 triangles :



Normally we would have to define 6 vertices, now only 5. So these are the vertices we are going to define in our FillVertices method. Make this the new contents of the method:

 LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer;
 OURCUSTOMVERTEX cv_Vertices[]=
 {
     {0.0f, 0.0f, 0.0f, 0xffffffff},
     {5.0f, 0.0f, 0.0f, 0xffffffff},
     {10.0f, 0.0f, 0.0f, 0xffffffff},
     {5.0f, 5.0f, 0.0f, 0xffffffff},
     {10.0f, 5.0f, 0.0f, 0xffffffff},
 };
 
 if (FAILED(p_dx_Device->CreateVertexBuffer(5*sizeof(OURCUSTOMVERTEX), 0, D3DFVF_XYZ|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, 5*sizeof(OURCUSTOMVERTEX), (void**)&p_Vertices, 0)))
 {
     MessageBox(han_Window,"Error trying to lock","FillVertices()",MB_OK);
 }else{
     memcpy(p_Vertices, cv_Vertices, 5*sizeof(OURCUSTOMVERTEX));
     p_dx_VertexBuffer->Unlock();
 }
 
 return p_dx_VertexBuffer;

The first lines are simply a shorter way of defining the contents of our matrix. You see we have defined the coordinates and the color of 5 vertices. Then you have to adjust the size of the VertexBuffer, because now it should be able to contain 5 vertices instead of only 3.

Next, we are going to define a new method, called FillIndices. This contains the simple numbers, which link the corners of every triangle to a vertex in our VertexBuffer. We want to be able to send error messages from withing the method, so we need to supply it with the handle to our window. We’ll also need a pointer to the device:

 LPDIRECT3DINDEXBUFFER9 FillIndices(HWND han_Window, LPDIRECT3DDEVICE9 p_dx_Device)
 {
     short s_Indices[6];
 
     s_Indices[0]=3;
     s_Indices[1]=1;
     s_Indices[2]=0;
     s_Indices[3]=4;
     s_Indices[4]=2;
     s_Indices[5]=1;
 }

Take another look at the image above. These are the six points that define our triangles. Again, DirectX cannot use our matrix in this format. It needs the data supplied in a special IndexBuffer, which we are now going to create:

 LPDIRECT3DINDEXBUFFER9 p_dx_IndexBuffer;
 if (FAILED(p_dx_Device->CreateIndexBuffer(6*sizeof(short), D3DUSAGE_WRITEONLY,D3DFMT_INDEX16,D3DPOOL_MANAGED,&p_dx_IndexBuffer,NULL)))
 {
     MessageBox(han_Window,"Error while creating IndexBuffer","FillIndices()",MB_OK);
 }

You attach an IndexBuffer to our device, in which you will store six numbers of the type ‘short’. Don’t try using other formats, I once spent one hour just to find our that you cannot store ints or floats in an IndexBuffer.. We will only write to this buffer, in other words, our program is not going to read back the data we put in it. We let DirectX manage the memory in which the buffer is residing and we specify the place where DirectX should put the pointer to this buffer.

Now we have the memory delivered to us, we can simply lock it and copy the data from our s_Indices matrix to it:

 VOID* p_Indices;
 if (FAILED(p_dx_IndexBuffer->Lock(0, 6*sizeof(short), (void**)&p_Indices, 0)))
 {
     MessageBox(han_Window,"Error trying to lock","FillIndices()",MB_OK);
 }else{
     memcpy(p_Indices, s_Indices, 6*sizeof(short));
     p_dx_IndexBuffer->Unlock();
 }

At the end of the method, don’t forget to return the pointer to this IndexBuffer to the calling method:

 return p_dx_IndexBuffer;

OK that’s it! Just call the method from you WinMain immediately after you created the IndexBuffer and store the returned pointer:

 LPDIRECT3DINDEXBUFFER9 p_dx_IB = FillIndices(han_Window, p_Device);

Now we’ll be updating the DrawScene method to draw from the IndicesBuffer. First remove all the lines that made your scene rotate and translate, we’ll come back to that in a later chapter. First change the interface of the method so it’ll also accept a pointer to the IndexBuffer:

void DrawScene(LPDIRECT3DDEVICE9 p_dx_Device, LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer, LPDIRECT3DINDEXBUFFER9 p_dx_IndexBuffer)
{
    // other code
}

Now we’re going to update the code between the BeginScene and EndScene calls. Our SetStreamSource call remains the same, because the actual coordinates are still being stores in our VertexBuffer. The FVF, the type of information stored in our VertexBuffer also stays the same. The third line, the call to DrawPrimitive however, is going to be deleted. Replace it by these two lines:

 p_dx_Device->SetIndices(p_dx_IndexBuffer);
 p_dx_Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,5,0,2);

First we set our IndexBuffer as active IndexBuffer of the device. Then we indicate that the buffer contains a list of triangles (and this a multitude of 3 entries). The 2 zeroes indicate that the numbers stored in our IndexBuffer are related to our VertexBuffer, starting at position 0. The we indicate that this call we are going to use 5 vertices from our VertexBuffer. Then the position where DirectX should start reading from our IndexBuffer, followed by the number of triangles DirectX should actually draw.

OK, that should do.. Now simply change the call to your DrawScene method from within WinMain to reflect the changes you made to its interface:

 DrawScene(p_Device, p_dx_VB, p_dx_IB);

Which also passes the pointer to the IndexBuffer to the DrawScene method. Compiling and running this code should display the 2 triangles displayed above and below. These are of course solid triangles. If you want to draw only the lines, add this additional line immediately after you create your device:

 p_dx_Device->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME);

That should give you exactly the same image as displayed here below:




DirectX Tutorial 9 - Indices

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:
  • the fill indeces part
          yes this is the best tutorial i have seen yet but ...



    The code for this chapter:


    #include<windows.h>
    #include<d3d9.h>
    #include<d3dx9.h>
    struct OURCUSTOMVERTEX
    {
        float x,y,z;
        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);
            }
    }

        p_dx_Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
        p_dx_Device->SetRenderState(D3DRS_LIGHTING,false);

         p_dx_Device->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
     
         return p_dx_Device;
     }
     
     void DrawScene(LPDIRECT3DDEVICE9 p_dx_Device, LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer, LPDIRECT3DINDEXBUFFER9 p_dx_IndexBuffer)
     {
         p_dx_Device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(72,61,139), 1.0f, 0);
         p_dx_Device->BeginScene();
     
         p_dx_Device->SetStreamSource( 0, p_dx_VertexBuffer, 0, sizeof(OURCUSTOMVERTEX) );
      p_dx_Device->SetFVF(D3DFVF_XYZ|D3DFVF_DIFFUSE);
         p_dx_Device->SetIndices(p_dx_IndexBuffer);
         p_dx_Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,5,0,2);
     
         p_dx_Device->EndScene();
         p_dx_Device->Present(NULL, NULL, NULL, NULL);
     }
     
     LPDIRECT3DVERTEXBUFFER9 FillVertices(HWND han_Window, LPDIRECT3DDEVICE9 p_dx_Device)
     {
         LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer;
         OURCUSTOMVERTEX cv_Vertices[]=
         {
             {0.0f, 0.0f, 0.0f, 0xffffffff},
             {5.0f, 0.0f, 0.0f, 0xffffffff},
             {10.0f, 0.0f, 0.0f, 0xffffffff},
             {5.0f, 5.0f, 0.0f, 0xffffffff},
             {10.0f, 5.0f, 0.0f, 0xffffffff},
         };
     
         if (FAILED(p_dx_Device->CreateVertexBuffer(5*sizeof(OURCUSTOMVERTEX), 0, D3DFVF_XYZ|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, 5*sizeof(OURCUSTOMVERTEX), (void**)&p_Vertices, 0)))
         {
             MessageBox(han_Window,"Error trying to lock","FillVertices()",MB_OK);
         }else{
             memcpy(p_Vertices, cv_Vertices, 5*sizeof(OURCUSTOMVERTEX));
             p_dx_VertexBuffer->Unlock();
         }
     
         return p_dx_VertexBuffer;
     }
     
     LPDIRECT3DINDEXBUFFER9 FillIndices(HWND han_Window, LPDIRECT3DDEVICE9 p_dx_Device)
     {
         short s_Indices[6];
         LPDIRECT3DINDEXBUFFER9 p_dx_IndexBuffer;
     
         s_Indices[0]=3;
      s_Indices[1]=1;
      s_Indices[2]=0;
      s_Indices[3]=4;
      s_Indices[4]=2;
      s_Indices[5]=1;
     
         if (FAILED(p_dx_Device->CreateIndexBuffer(6*sizeof(short),D3DUSAGE_WRITEONLY,D3DFMT_INDEX16,D3DPOOL_MANAGED,&p_dx_IndexBuffer,NULL)))
      {
      MessageBox(han_Window,"Error while creating IndexBuffer","FillIndices()",MB_OK);
      }
     
         VOID* p_Indices;
      if (FAILED(p_dx_IndexBuffer->Lock(0, 6*sizeof(short), (void**)&p_Indices, 0)))
      {
             MessageBox(han_Window,"Error trying to lock","FillIndices()",MB_OK);
         }else{
             memcpy(p_Indices, s_Indices, 6*sizeof(short));
             p_dx_IndexBuffer->Unlock();
         }
     
         return p_dx_IndexBuffer;
     }
     
     void SetUpCamera(LPDIRECT3DDEVICE9 p_dx_Device)
     {
         D3DXVECTOR3 m_EyePos(0, 0, -30);
         D3DXVECTOR3 m_TargetPos(0, 0, 0);
         D3DXVECTOR3 m_UpVector(0, 1, 0);
         D3DXMATRIXA16 m_View;
         D3DXMatrixLookAtLH(&m_View, &m_EyePos, &m_TargetPos, &m_UpVector);
         p_dx_Device->SetTransform(D3DTS_VIEW, &m_View);
     
         D3DXMATRIX m_Projection;
         D3DXMatrixPerspectiveFovLH(&m_Projection, D3DX_PI/4, 500/500, 1, 50);
         p_dx_Device->SetTransform(D3DTS_PROJECTION, &m_Projection);
     }
     
     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);
         LPDIRECT3DINDEXBUFFER9 p_dx_IB = FillIndices(han_Window, p_Device);
         SetUpCamera(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_dx_IB);
         }
     
         p_dx_VB->Release();
         p_dx_IB->Release();
         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!