I am very new to Direct X 11. I want to create a simple 2d texture (of type ID3D11Texture2D). I have read document about CreateTexture2D and I understand that:
pDesc is how we define the image.
pInitialData contains the array of bytes presents every pixel of the image texture
ppTexture2D is our result - the 2D texture for DirectX 11.
I want to create a very simple 2D texture: a pink rectangle. But I don't know how to create the array of bytes for the pink rectangle. I have the code below:
D3D11_TEXTURE2D_DESC Desc;
D3D11_SUBRESOURCE_DATA InitialData;
ID3D11Texture2D* pTexture2D;
Desc.Usage = D3D11_USAGE_DEFAULT;
BYTE* array;//How to have an array of Pink rectangle?
InitialData.pSysMem = array;
InitialData.SysMemPitch = 0;
InitialData.SysMemSlicePitch = 0;
m_device->CreateTexture2D(&Desc, &InitialData, &pTexture2D);//ID3D11Device m_device has been created before.
Thank you very much.
Assuming you define pink as RGB (255, 174, 201) this creates a 1x1 pink texture:
ComPtr<ID3D11ShaderResourceView> texSRV;
{
static const uint32_t s_pixel = 0xffc99aff;
D3D11_SUBRESOURCE_DATA initData = { &s_pixel, sizeof(uint32_t), 0 };
D3D11_TEXTURE2D_DESC desc = {};
desc.Width = desc.Height = desc.MipLevels = desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_IMMUTABLE;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
ComPtr<ID3D11Texture2D> tex;
HRESULT hr = mDevice->CreateTexture2D( &desc, &initData, tex.GetAddressOf() );
if (SUCCEEDED(hr))
{
D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {};
SRVDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
SRVDesc.Texture2D.MipLevels = 1;
hr = mDevice->CreateShaderResourceView( tex.Get(),
&SRVDesc, texSRV.GetAddressOf() );
}
if (FAILED(hr))
// error!
}
I'm using the recommended C++ smart-pointer for COM
Microsoft::WRL::ComPtr
in this code rather than 'raw' pointers which are harder to ensure proper reference counts. See this page for more.
Of course, that's not typically how you create textures. You usually use image files, and more often than not use DDS
files which have mipmap chains and use specialized texture compression formats.
See How to: Initialize a Texture From a File on MSDN.
A good place to start with DirectX 11 using C++ is DirectX Tool Kit for DirectX 11 and the tutorials for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With