首先我们来学习一下Vertex Buffer的技术。我喜欢先看代码再讲理论,否则看了理论也找不到北。
struct CUSTOMVERTEX
{
FLOATx, y, z, rhw; // The transformed position for the vertex
DWORDcolor; // The vertex color
};
// Our custom FVF, which describes our custom vertex structure
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE)
typedef struct SObjVertex
{
FLOATx, y, z; // position
FLOATnx, ny, nz; // normal
DWORDdiffuse; // diffuse color
DWORDspecular; // specular color
FLOATtu, tv; // first pair of texture coordinates
FLOATtu2, tv2, tw2; // second pair of texture coordinates
FLOATtu3, tv3; // third pair of texture coordinates
FLOATtu4, tv4; // fourth pair of texture coordinates
} SObjVertex;
const DWORD gSObjVertexFVF = (D3DFVF_XYZ |
D3DFVF_DIFFUSE |
D3DFVF_SPECULAR |
D3DFVF_NORMAL |
D3DFVF_TEX4 |
D3DFVF_TEXCOORDSIZE2( 0 ) |
D3DFVF_TEXCOORDSIZE3( 1 ) |
D3DFVF_TEXCOORDSIZE2( 2 ) |
D3DFVF_TEXCOORDSIZE2( 3 ) );
LPDIRECT3DVERTEXBUFFER9g_pVB = NULL; // Buffer to hold vertices
HRESULTCALLBACKOnCreateDevice( IDirect3DDevice9 * pd3dDevice, constD3DSURFACE_DESC * pBackBufferSurfaceDesc, void * pUserContext )
{
// Initialize three vertices for rendering a triangle
CUSTOMVERTEX vertices[] =
{
// x, y, z, rhw, color
{ 150.0f , 50.0f , 0.5f , 1.0f , 0xffff0000 , },
{ 250.0f , 250.0f , 0.5f , 1.0f , 0xff00ff00 , },
{ 50.0f , 250.0f , 0.5f , 1.0f , 0xff00ffff , },
};
if ( FAILED( pd3dDevice -> CreateVertexBuffer(
3 * sizeof (CUSTOMVERTEX),
0 , D3DFVF_CUSTOMVERTEX,
D3DPOOL_MANAGED, & g_pVB, NULL ) ) )
{
return E_FAIL;
}
// Now we fill the vertex buffer. To do this, we need to Lock()
// the VB togain access to the vertices. This mechanism is
// required becuase vertexbuffers may be in device memory.
VOID * pVertices;
if ( FAILED( g_pVB -> Lock( 0 , sizeof (vertices), ( void ** ) & pVertices, 0 ) ) )
returnE_FAIL;
memcpy( pVertices, vertices, sizeof (vertices) );
g_pVB -> Unlock();
}
pd3dDevice -> SetStreamSource( 0 , g_pVB, 0 , sizeof (CUSTOMVERTEX) );
pd3dDevice -> SetFVF( D3DFVF_CUSTOMVERTEX );
pd3dDevice -> DrawPrimitive( D3DPT_TRIANGLELIST, 0 , 1 );
typedef enum _D3DPRIMITIVETYPE
{
D3DPT_POINTLIST = 1 ,
D3DPT_LINELIST = 2 ,
D3DPT_LINESTRIP = 3 ,
D3DPT_TRIANGLELIST = 4 ,
D3DPT_TRIANGLESTRIP = 5 ,
D3DPT_TRIANGLEFAN = 6 ,
D3DPT_FORCE_DWORD = 0x7fffffff ,
} D3DPRIMITIVETYPE;