Exemplo n.º 1
0
ID3DXMesh* CMesh::createD3DXMesh() const
{
    HRESULT hr;
    ID3DXMesh* dxMesh = 0;

    DWORD meshOpts = D3DXMESH_MANAGED;
    if( getIndexStride() == 4 )
        meshOpts |= D3DXMESH_32BIT;


    // get declaration
    D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE];
    UINT numElements;
    getVertexDecl().getObject()->GetDeclaration( decl, &numElements );
    // create mesh
    hr = D3DXCreateMesh( getIndexCount()/3, getVertexCount(), meshOpts, decl, &CD3DDevice::getInstance().getDevice(), &dxMesh );
    if( FAILED(hr) )
        return NULL;

    // copy VB
    {
        const void* srcVB = lockVBRead();
        void* dxVB = 0;
        hr = dxMesh->LockVertexBuffer( 0, &dxVB );
        if( FAILED(hr) ) {
            dxMesh->Release();
            return NULL;
        }
        memcpy( dxVB, srcVB, getVertexCount() * getVertexStride() );
        hr = dxMesh->UnlockVertexBuffer();
        unlockVBRead();
    }
    // copy IB
    {
        const void* srcIB = lockIBRead();
        void* dxIB = 0;
        hr = dxMesh->LockIndexBuffer( 0, &dxIB );
        if( FAILED(hr) ) {
            dxMesh->Release();
            return NULL;
        }
        memcpy( dxIB, srcIB, getIndexCount() * getIndexStride() );
        hr = dxMesh->UnlockIndexBuffer();
        unlockIBRead();
    }
    // copy groups
    {
        int ngroups = getGroupCount();
        D3DXATTRIBUTERANGE* attrs = new D3DXATTRIBUTERANGE[ngroups];
        DWORD* attrBuf = 0;
        hr = dxMesh->LockAttributeBuffer( 0, &attrBuf );
        if( FAILED(hr) ) {
            dxMesh->Release();
            return NULL;
        }
        for( int g = 0; g < ngroups; ++g ) {
            attrs[g].AttribId = g;
            const CMesh::CGroup& group = getGroup(g);
            attrs[g].VertexStart = group.getFirstVertex();
            attrs[g].VertexCount = group.getVertexCount();
            attrs[g].FaceStart = group.getFirstPrim();
            attrs[g].FaceCount = group.getPrimCount();
            for( int f = 0; f < group.getPrimCount(); ++f )
                *attrBuf++ = g;
        }
        dxMesh->UnlockAttributeBuffer();
        hr = dxMesh->SetAttributeTable( attrs, ngroups );
        delete[] attrs;
    }

    return dxMesh;
}