最近我拿起一本书,开始学习使用 Direct3D 和 DirectX 进行游戏编程。到目前为止一切都很好,但问题是我无法将纹理从文件加载到具有透明背景颜色的后备缓冲区。
这里是初始化 Direct3D 的源代码
BOOL Init_Direct3D(HWND hWnd,int width,int height,BOOL fullscreen)
{
// initialize Direct3D object
d3d = Direct3DCreate9(D3D_SDK_VERSION);
if(d3d==NULL)
{
MessageBox(NULL,TEXT("Fail to initialize Direct3D object"),TEXT("Error"),MB_ICONERROR);
return FALSE;
}
// initialize Direct3D presentation parameter
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp,sizeof(d3dpp));
d3dpp.Windowed = !fullscreen;
d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;
d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
d3dpp.BackBufferCount = 1;
d3dpp.BackBufferWidth = width;
d3dpp.BackBufferHeight = height;
d3dpp.hDeviceWindow = hWnd;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
d3d->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hWnd,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&d3dpp,&d3ddev);
if(d3ddev == NULL)
{
MessageBox(NULL,TEXT("Fail to initialize Direct3D device"),TEXT("Error"),MB_ICONERROR);
return FALSE;
}
d3ddev->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
d3ddev->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
d3ddev->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
d3ddev->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
// get Direct3D backbuffer
d3ddev->GetBackBuffer(0,NULL,D3DBACKBUFFER_TYPE_MONO,&backbuffer);
if(backbuffer == NULL)
{
MessageBox(NULL,TEXT("Fail to get Direct3D backbuffer"),TEXT("Error"),MB_ICONERROR);
return FALSE;
}
return TRUE;
}
这里是加载纹理的代码
LPDIRECT3DTEXTURE9 LoadTexture(char *filename,D3DCOLOR transcolor)
{
LPDIRECT3DTEXTURE9 texture = NULL;
D3DXIMAGE_INFO texture_info;
HRESULT result;
// get image info
result = D3DXGetImageInfoFromFile(filename,&texture_info);
if(result != D3D_OK)
return NULL;
// create texture
result = D3DXCreateTextureFromFileEx(d3ddev,filename,texture_info.Width,texture_info.Height,1,D3DPOOL_DEFAULT,D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,D3DX_DEFAULT,D3DX_DEFAULT,transcolor,NULL,NULL,&texture);
if(result != D3D_OK)
return NULL;
return texture;
}
这就是我渲染屏幕的方式
// start render
if(d3ddev->BeginScene())
{
d3ddev->StretchRect(back,NULL,backbuffer,NULL,D3DTEXF_NONE);
sprite_handler->Begin(D3DXSPRITE_ALPHABLEND);
D3DXVECTOR3 position((float)doki.x,(float)doki.y,0.0f);
sprite_handler->Draw(doki_img,&rect,NULL,&position,D3DCOLOR_XRGB(255,255,255));
sprite_handler->End();
d3ddev->EndScene();
}
d3ddev->Present(NULL,NULL,NULL,NULL);
我做错了什么?