Efficient Implementation of Dynamic Resources in Direct3D12

April 21, 2016
protect

Introduction

Dynamic resources is a convenient programming paradigm that is used to handle frequently changing resources in Direct3D11. For example, one way to render several models with different transformation matrices is to use dynamic constant buffer as in the following scenario:

  • Bind shaders, textures, constant buffers and other resources

  • For every model:

    • Map the constant buffer with WRITE_DISCARD flag, which tells the system that previous contents of the buffer is no longer needed and can be discarded

    • Write new matrices to the buffer

    • Issue draw command

From the application's point of view it looks like the buffer is the same, only the contents of the buffer is updated before every draw call. But under the hood Direct3D11 allocates new chunk of memory every time the buffer is mapped. Direct3D12 has no notion of dynamic resources. It is programmer's responsibility to allocate memory and synchronize access to it. This post describes one possible implementation of dynamic resources that is adopted in Diligent Engine 2.0.

Naive Implementation

Before we go into implementation details, let's take a look at a straightforward implementation. Since what we want is to have new data in the buffer before every draw call, let's try to do exactly this. We, however, cannot just copy data to the buffer, because the buffer may be used by the GPU at the same time when CPU wants to update it. Moreover, buffer memory may not be CPU accessible. So what we will have to do is to allocate new chunk of CPU accessible memory, for every update, write new data into this memory, and record copy command into the command list. This will ensure that buffer updates and draw commands will be executed in the right order in a GPU timeline. The host must make sure that all allocations are valid until all GPU commands that reference them are completed, and only after then can it reclaim the memory. Another important thing that Direct3D12 programmer is required to do is to notify the system about the resource state transitions. Before every copy command, a resource must be transitioned to D3D12_RESOURCE_STATE_COPY_DEST state and before being bound as constant buffer, it must be transitioned to D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER.

Now if we take a look at our implementation, it may seem that the biggest problem here is that every time we update the buffer, we copy data two times (the first time to the CPU-accessible memory and the second time - to the constant buffer). But the real problem is that we have to perform transitions between read and write states before every draw call. Every transition to D3D12_RESOURCE_STATE_COPY_DEST requires GPU to flush the pipeline, because it must make sure all possible read operations are complete before the new data can be safely written. This effectively results in serializing all draw commands. The figure below illustrates what is happening in CPU and GPU timelines:

Modern GPUs have deep pipelines and are able to process several commands in parallel. Serializing GPU execution has dramatic impact on performance. In our test scene with 50,000 separate draw commands, the total frame time was more than 300 ms.

Efficient Implementation

Diligent Engine 2.0 employs ring buffer strategy to implement dynamic resources and avoid GPU command serialization. Every time a dynamic buffer is mapped, new memory is allocated in the ring buffer. During every frame, the buffer grows and holds all dynamic allocations for that frame. When GPU is done with a frame, the system reclaims memory occupied by that frame's dynamic resources. The operation of a dynamic buffer is illustrated in the figure below.

The figure above depicts the following scenario:

  • Initial state: The buffer is empty and both head and tail point to the beginning of the allocated memory

  • Frames 0,1, and 2: Required space is reserved by advancing the tail; position of the frame tail is pushed into the queue when recording commands for the frame is complete

  • Frame 3: GPU completed rendering frame 0 and all memory can be reclaimed by moving head pointer to the recorded location of the frame 0 tail

  • Frame 4: GPU completed frame 1, and the memory can be reclaimed. Tail pointer reaches the end of the buffer and allocation continues from the beginning of the buffer

Basic Ring Buffer

The first component we need to implement dynamic resources is the ring buffer class that implements memory management strategy described above.


class RingBuffer
{
public:
    typedef size_t OffsetType;
    typedef std::pair<Uint64, OffsetType> FrameNumOffsetPair;

    static const OffsetType InvalidOffset = static_cast<OffsetType>(-1);

    RingBuffer(OffsetType MaxSize) : 
        m_MaxSize(MaxSize)
    {}

    RingBuffer(RingBuffer&& rhs);
    RingBuffer& operator = (RingBuffer&& rhs);
    RingBuffer(const RingBuffer&) = delete;
    RingBuffer& operator = (const RingBuffer&) = delete;

    OffsetType Allocate(OffsetType Size);

    void FinishCurrentFrame(Uint64 FrameNum);
    void ReleaseCompletedFrames(Uint64 NumCompletedFrames);

    OffsetType GetMaxSize()const{return m_MaxSize;}
    bool IsFull()const{ return m_UsedSize==m_MaxSize; };
    bool IsEmpty()const{ return m_UsedSize==0; };
    OffsetType GetUsedSize()const{return m_UsedSize;}

private:
    std::deque< FrameNumOffsetPair > m_CompletedFrameTails;
    OffsetType m_Head = 0;
    OffsetType m_Tail = 0;
    OffsetType m_MaxSize = 0;
    OffsetType m_UsedSize = 0;
};

There are two possible cases when allocating new space in the buffer: the tail is either behind or in front of the head. In both cases we first check if the tail can be moved without passing the buffer end or the head, correspondingly. If there is not enough space at the end of the buffer, we try to start allocating data from the beginning. The function tracks total used space and exits immediately if the buffer is full. This is important as without tracking the size, it is not possible to distinguish if the buffer is empty or completely full as in both cases m_Tail==m_Head. The following listing shows implementation of the Allocate() function:


OffsetType RingBuffer::Allocate(OffsetType Size)
{
    if(IsFull())
    {
        return InvalidOffset;
    }

    if (m_Tail >= m_Head )
    {
        //              Head            Tail     MaxSize
        //              |               |        |
        // [            xxxxxxxxxxxxxxxxx        ]
        if (m_Tail + Size <= m_MaxSize)
        {
             auto Offset = m_Tail;
             m_Tail += Size;
             m_UsedSize += Size;
             return Offset;
        }
        else if(Size <= m_Head)
        {
             // Allocate from the beginning of the buffer
             m_UsedSize += (m_MaxSize - m_Tail) + Size;
             m_Tail = Size;
             return 0;
        }
    }
    else if (m_Tail + Size <= m_Head )
    {
        //
        //     Tail    Head 
        //     |       |  
        // [xxxx       xxxxxxxxxxxxxxxxxxxxxxxxxx]
        auto Offset = m_Tail;
        m_Tail += Size;
        m_UsedSize += Size;
        return Offset;
    }
    return InvalidOffset;
}

When a frame is complete, we record the current tail position along with the frame number:


void RingBuffer::FinishCurrentFrame(Uint64 FrameNum)
{
     m_CompletedFrameTails.push_back(std::make_pair(FrameNum, m_Tail) );
}

When GPU is done rendering the frame, the memory can be reclaimed. This is performed by advancing the head:


void RingBuffer::ReleaseCompletedFrames(Uint64 NumCompletedFrames)
{
    while(!m_CompletedFrameTails.empty() && m_CompletedFrameTails.front().first < NumCompletedFrames)
    {
        auto &OldestFrameTail = m_CompletedFrameTails.front().second;
        if( m_UsedSize > 0 )
        {
            if (OldestFrameTail > m_Head)
            {
                //            m_Head     OldestFrameTail
                //            |          |
                // [          xxxxxxxxxxxxxxxxxxxxx         ]
                m_UsedSize -= OldestFrameTail - m_Head;
            }
            else
            {
                //            OldestFrameTail         m_Head      MaxSize
                //            |                       |           |
                // [xxxxxxxxxxxxxxxxxxxxxxxx          xxxxxxxxxxxx]
                m_UsedSize -= (m_MaxSize - m_Head);
                m_UsedSize -= OldestFrameTail;
            }
        }
        m_Head = OldestFrameTail;
        m_CompletedFrameTails.pop_front();
    }
}


GPU Ring Buffer

Now when we have basic implementation of the ring buffer management, we can implement GPU-based ring buffer.


struct DynamicAllocation
{
    DynamicAllocation(ID3D12Resource *pBuff, size_t ThisOffset, size_t ThisSize) : 
        pBuffer(pBuff), Offset(ThisOffset), Size(ThisSize) {}

    ID3D12Resource *pBuffer = nullptr;
    size_t Offset = 0;
    size_t Size = 0;
    void* CPUAddress = 0;
    D3D12_GPU_VIRTUAL_ADDRESS GPUAddress = 0;
};

class GPURingBuffer : public RingBuffer
{
public:
    GPURingBuffer(size_t MaxSize, ID3D12Device *pd3d12Device, bool AllowCPUAccess);

    GPURingBuffer(GPURingBuffer&& rhs);
    GPURingBuffer& operator =(GPURingBuffer&& rhs);
    GPURingBuffer(const GPURingBuffer&) = delete;
    GPURingBuffer& operator =(GPURingBuffer&) = delete;
    ~GPURingBuffer();

    DynamicAllocation Allocate(size_t SizeInBytes);

private:
    void Destroy();

    void* m_CpuVirtualAddress;
    D3D12_GPU_VIRTUAL_ADDRESS m_GpuVirtualAddress;
    CComPtr<ID3D12Resource> m_pBuffer;
};


Constructor of the GPU ring buffer class creates the buffer in GPU memory and persistently maps it. Note that unlike D3D11, in D3D12 it is perfectly legal to have the buffer mapped and used in draw operations as long as GPU does not access the same memory CPU is writing to.


GPURingBuffer::GPURingBuffer(size_t MaxSize, ID3D12Device *pd3d12Device, bool AllowCPUAccess) :
    RingBuffer(MaxSize),
    m_CpuVirtualAddress(nullptr),
    m_GpuVirtualAddress(0)
{
    D3D12_HEAP_PROPERTIES HeapProps;
    HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
    HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
    HeapProps.CreationNodeMask = 1;
    HeapProps.VisibleNodeMask = 1;


    D3D12_RESOURCE_DESC ResourceDesc;
    ResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
    ResourceDesc.Alignment = 0;
    ResourceDesc.Height = 1;
    ResourceDesc.DepthOrArraySize = 1;
    ResourceDesc.MipLevels = 1;
    ResourceDesc.Format = DXGI_FORMAT_UNKNOWN;
    ResourceDesc.SampleDesc.Count = 1;
    ResourceDesc.SampleDesc.Quality = 0;
    ResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;

    D3D12_RESOURCE_STATES DefaultUsage;
    if (AllowCPUAccess)
    {
        HeapProps.Type = D3D12_HEAP_TYPE_UPLOAD;
        ResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
        DefaultUsage = D3D12_RESOURCE_STATE_GENERIC_READ;
    }
    else
    {
        HeapProps.Type = D3D12_HEAP_TYPE_DEFAULT;
        ResourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
        DefaultUsage = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
    }
    ResourceDesc.Width = MaxSize;

    pd3d12Device->CreateCommittedResource(&HeapProps, D3D12_HEAP_FLAG_NONE, &ResourceDesc,
    DefaultUsage, nullptr, __uuidof(m_pBuffer), &m_pBuffer) );
    m_pBuffer->SetName(L"Upload Ring Buffer");

    m_GpuVirtualAddress = m_pBuffer->GetGPUVirtualAddress();

    if (AllowCPUAccess)
    {
        m_pBuffer->Map(0, nullptr, &m_CpuVirt

JikGuard.com, a high-tech security service provider focusing on game protection and anti-cheat, is committed to helping game companies solve the problem of cheats and hacks, and providing deeply integrated encryption protection solutions for games.

Read More>>