Search code examples
graphics3ddirectxdirectx-12

How to create a view for a Structured Buffer under DirectX 12?


I am trying to implement instancing inside my DirectX 12 renderer.
To do so I want to use a structured buffer that store each instance transformation.
Here how it is declared in my vertex shader:

struct MeshTransform
{
    float4x4 mat;
};

StructuredBuffer<MeshTransform> meshTransforms : register(t0);

Now I need to upload that structured buffer from the CPU. To do so I simply create a default heap initialized with the mesh transforms. Here the problem, when I try to create the heap SRV I get this error:
D3D12 ERROR: ID3D12Device::CreateShaderResourceView: The Format (0, UNKNOWN) cannot be used when creating a View of a Buffer

Here how I create the SRV:

struct DirectX12StructuredBufferHandle
{
    DescriptorHandle srvDescriptorHandle;
    DescriptorHandle uavDescriptorHandle;
    ID3D12Resource* buffer = nullptr;
};

void DirectX12Renderer::createSRV(DirectX12StructuredBufferHandle& dst)
{
    D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
    srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
    srvDesc.Format = DXGI_FORMAT_UNKNOWN;
    srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;

    dst.srvDescriptorHandle = m_cbs_srv_uavAllocator->allocate({ dst.buffer }, srvDesc);
}

So DirectX doesn't like the specified DXGI_FORMAT_UNKNOWN. What should I put then?
I checked the Microsoft Mini Engine code they seems to use DXGI_FORMAT_UNKNOWN when creating buffers:
https://github.com/microsoft/DirectX-Graphics-Samples/blob/master/MiniEngine/Core/GpuBuffer.cpp?plain=1#L189-216

What am I missing? Thanks for helping!


Solution

  • You didn't fill out the D3D12_SHADER_RESOURCE_VIEW_DESC::Buffer member.

    With DXGI_FORMAT_UNKNOWN the runtime doesn't know the element stride so you have to specify in D3D12_BUFFER_SRV::StructureByteStride

    https://github.com/microsoft/DirectX-Graphics-Samples/blob/b5f92e2251ee83db4d4c795b3cba5d470c52eaf8/MiniEngine/Core/GpuBuffer.cpp?plain=1#L195-L197