创建1像素的纹理问题

Creating a 1 pixel Texture Issue.

本文关键字:问题 纹理 1像素 创建      更新时间:2023-10-16

我试图使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包含"parameter is incorrect".

有什么问题?

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

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

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]