创建1像素纹理问题。

时间:2014-05-04 10:12:55

标签: c++ directx

我正在尝试制作1像素的纹理,颜色是传递给函数的变量,我有以下代码:

unsigned char texArray[4];
texArray[0] = (unsigned char) color.x;
texArray[1] = (unsigned char) color.y;
texArray[2] = (unsigned char) color.z;
texArray[3] = (unsigned char) color.w;

ID3D11Texture2D *pTexture = nullptr;

ID3D11ShaderResourceView* pShaderResourceView;

D3D11_TEXTURE2D_DESC texDesc;

ZeroMemory(&texDesc, sizeof(D3D11_TEXTURE2D_DESC));
texDesc.ArraySize = 1;
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texDesc.CPUAccessFlags = 0;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.MipLevels = 1;
texDesc.MiscFlags = 0;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.Height = 1;
texDesc.Width = 1;

D3D11_SUBRESOURCE_DATA texInitData;
ZeroMemory(&texInitData, sizeof(D3D11_SUBRESOURCE_DATA));
texInitData.pSysMem = texArray;

HRESULT hr;

hr = m_pDevice->CreateTexture2D(&texDesc, &texInitData, &pTexture);
hr = m_pDevice->CreateShaderResourceView(pTexture, NULL, &pShaderResourceView);

但它无法创建texture2D(return nullptr)& hr包含“参数不正确”。

有什么不对/遗失?

2 个答案:

答案 0 :(得分:1)

由于您正在创建2D纹理,因此需要在SysMemPitch中指定texInitData值,因为您正在创建2D纹理(即使在这种情况下它只是1x1像素) 。在这种情况下,您应该将其指定为sizeof(unsigned char) * 4,因为如果有另一行,则下一行将在该许多字节之后开始。

答案 1 :(得分:0)

在创建D3D设备时设置调试标志是一个好习惯,在这种情况下,在调试模式下运行时,您将从Visual Studio的输出窗口中获取更多信息。

UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;

#if defined( DEBUG ) || defined( _DEBUG )
    flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif 

HRESULT hr;
if (FAILED (hr = D3D11CreateDeviceAndSwapChain( NULL,
    D3D_DRIVER_TYPE_HARDWARE,
    NULL,
    flags,
    &FeatureLevelsRequested,
    numLevelsRequested,
    D3D11_SDK_VERSION,
    &sd, 
    &g_pSwapChain,
    &g_pd3dDevice,
    &FeatureLevelsSupported,
    &g_pImmediateContext )))
{
    return hr;
}

以下是我从您的代码中获得的内容,您可以轻松地从邮件中了解错误。

D3D11 ERROR: ID3D11Device::CreateTexture2D: pInitialData[0].SysMemPitch cannot be 0 [ STATE_CREATION ERROR #100: CREATETEXTURE2D_INVALIDINITIALDATA]
First-chance exception at 0x74891EE9 in Teapot.exe: Microsoft C++ exception: _com_error at memory location 0x00E4F668.
First-chance exception at 0x74891EE9 in Teapot.exe: Microsoft C++ exception: _com_error at memory location 0x00E4F668.
D3D11 ERROR: ID3D11Device::CreateTexture2D: Returning E_INVALIDARG, meaning invalid parameters were passed. [ STATE_CREATION ERROR #104: CREATETEXTURE2D_INVALIDARG_RETURN]