C++ – Loading Mesh from X File with Direct X 9 in C++

c++directxmesh

I have been having problems on making a Load Mesh function in C++ for Direct X. I seem to get this error: "Unhandled exception at 0x00401e64 in _.exe: 0xC00000005: Access violation reading loaction 0x83e05597". I know it is crashing on this line:

D3DXMATERIAL* tempMaterials = (D3DXMATERIAL*)bufMaterial->GetBufferPointer();

The whole function looks like this (I have been following along directxtutorial.com so far for direct X help).

void LoadModel(Model* model, LPCTSTR File){
LPD3DXBUFFER bufMaterial;

D3DXLoadMeshFromX(File, D3DXMESH_SYSTEMMEM, d3ddev, NULL, &bufMaterial, NULL,
                  &model->numMaterials, &model->Mesh);
OutputDebugString("LOAD MESH \n");

D3DXMATERIAL* tempMaterials = (D3DXMATERIAL*)bufMaterial->GetBufferPointer();
OutputDebugString("GET BUFFER\n");

model->Material = new D3DMATERIAL9[model->numMaterials];
model->Texture = new LPDIRECT3DTEXTURE9[model->numMaterials];

OutputDebugString("LOAD MESH \n");

for(DWORD index = 0; index < model->numMaterials; index++)
{
    model->Material[index] = tempMaterials[index].MatD3D;
    model->Material[index].Ambient = model->Material[index].Diffuse;

    // if there is a texture to load, load it
    if(FAILED(D3DXCreateTextureFromFileA(d3ddev,
                                     tempMaterials[index].pTextureFilename,
                                     &model->Texture[index])))
        model->Texture[index] = NULL;    // if there is no texture, set the texture to NULL
}   

return;}

I call it like this:

LoadModel(networkBase, TEXT("E:\\C++\\Skirmish\\X\\gridbox.x"));

But, I have found my old Beginning DirectX book and another web site source that all use this type casting of the material buffer from the temporary material buffer like the line that is crashing is doing. Please help!

Best Solution

The bug is not the cast to D3DXMATERIAL*, but probably that bufMaterial is not a valid pointer.

LPD3DXBUFFER is a typedef for ID3DXBuffer * and therefore a pointer to a ID3DXBuffer wich has to be initialized before using it. You could do this like so:

D3DXCreateBuffer(NumBytes, &bufMaterial);

NumBytes should be an integer which specifies the size of the buffer.