DK10
DK10

Reputation: 168

Direct3D C++ texture mapping

Hey guys can anybody help me with texture mapping in Direct3D C++. I have created a basic game and want to texture the enviroment. I have looked at numerous online tutorials but have had no luck so far

I am creating a custom vertex for my drawing code:

struct CUSTOMVERTEX
{
    FLOAT x, y, z; // The position for the vertex
    DWORD color;        // The vertex color
};

This is how I would draw a square:

CUSTOMVERTEX g_Vertices[] =
{

   {-1.0f,-1.0f,-1.0f,0xFF0000FF},{-1.0f, 1.0f,-1.0f,0xFF0000FF},
   { 1.0f, 1.0f,-1.0f,0xFF0000FF}, { 1.0f, 1.0f,-1.0f,0xFF0000FF},
   { 1.0f,-1.0f,-1.0f,0xFF0000FF},{-1.0f,-1.0f,-1.0f,0xFF0000FF},

};

Here is the buffer:

//*************************** Vertex Buffer ****************************
if( FAILED( g_pd3dDevice->CreateVertexBuffer( numberOfVertecies*sizeof(CUSTOMVERTEX), 
        0 /* Usage */, D3DFVF_CUSTOMVERTEX,D3DPOOL_MANAGED, &g_pVB, NULL ) ) )
    MessageBox(hwnd,"Vertex Buffer problem",NULL,NULL);

VOID* pVertices;

if( FAILED( g_pVB->Lock( 0, sizeof(g_Vertices), (void**)&pVertices, 0 ) ) )
    MessageBox(hwnd,"Vertex Lock Problem",NULL,NULL);

memcpy( pVertices, g_Vertices, sizeof(g_Vertices) );

g_pVB->Unlock();

and here is the square:

g_pd3dDevice->SetTransform( D3DTS_WORLD, &g_matWorld );
g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof(CUSTOMVERTEX) );
g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 20);

I just want to see how to texture the square so I can go on to texturing my whole enviroment?

Upvotes: 0

Views: 2007

Answers (1)

Tiago Costa
Tiago Costa

Reputation: 4251

If you want to implement texture mapping you have to change your vertex structure to

struct CUSTOMVERTEX
{
    FLOAT x, y, z; // The position for the vertex
    FLOAT tu, tv; // Texture Coordinates
};

When you create the vertices change that color values to texture coordinates (dont forget that the (0,0) coordinate corresponds to the top-left corner of the texture map.

You also have to adapt your vertex stream declaration:

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_TEX1)

Load a texture using D3DXCreateTextureFromFile(). And you also have to tell the device to use the loaded texture. Check DirectX SDK Tutorial 5 to learn how to do that.

If you just want to apply a texture (and not texture mapping and color per vertex, why would you want to give each vertex a color if you can simply apply the texture???) so use the vertex struct I wrote instead of the one in the tutorial.

Upvotes: 2

Related Questions