using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Helpers;
using SharpDX.Direct3D12;
namespace ComputeSharp.Graphics.Buffers
{
///
/// A representing a typed buffer stored on GPU memory
///
/// The type of items stored on the buffer
public sealed class Buffer : GraphicsResource where T : unmanaged
{
///
/// Creates a new instance with the specified parameters
///
/// The associated with the current instance
/// The number of items to store in the current buffer
/// The heap type for the current buffer
internal Buffer(GraphicsDevice device, int size, HeapType heapType) : base(device)
{
Size = size;
ElementSizeInBytes = Unsafe.SizeOf();
SizeInBytes = Size * ElementSizeInBytes;
HeapType = heapType;
ResourceFlags flags = heapType == HeapType.Default ? ResourceFlags.AllowUnorderedAccess : ResourceFlags.None;
ResourceDescription description = ResourceDescription.Buffer(SizeInBytes, flags);
ResourceStates resourceStates = heapType switch
{
HeapType.Upload => ResourceStates.GenericRead,
HeapType.Readback => ResourceStates.CopyDestination,
_ => ResourceStates.Common
};
NativeResource = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(heapType), HeapFlags.None, description, resourceStates);
(NativeCpuDescriptorHandle, NativeGpuDescriptorHandle) = heapType switch
{
HeapType.Default => CreateUnorderedAccessView(),
HeapType.Upload => CreateConstantBufferView(),
_ => default
};
}
///
/// Creates the descriptors for a constant buffer
///
/// The CPU and GPU handles for a constant buffer
[Pure]
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateConstantBufferView()
{
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
int constantBufferSize = (SizeInBytes + 255) & ~255;
ConstantBufferViewDescription description = new ConstantBufferViewDescription
{
BufferLocation = NativeResource!.GPUVirtualAddress,
SizeInBytes = constantBufferSize
};
GraphicsDevice.NativeDevice.CreateConstantBufferView(description, cpuHandle);
return (cpuHandle, gpuHandle);
}
///
/// Creates the descriptors for a read write buffer
///
/// The CPU and GPU handles for a read write buffer
[Pure]
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateUnorderedAccessView()
{
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
UnorderedAccessViewDescription description = new UnorderedAccessViewDescription
{
Format = SharpDX.DXGI.Format.R32_Float,
Dimension = UnorderedAccessViewDimension.Buffer,
Buffer = { ElementCount = Size }
};
GraphicsDevice.NativeDevice.CreateUnorderedAccessView(NativeResource, null, description, cpuHandle);
return (cpuHandle, gpuHandle);
}
///
/// Gets the size of the current buffer, as in the number of values it contains
///
public int Size { get; }
///
/// Gets the size in bytes of the current buffer
///
public int SizeInBytes { get; }
///
/// Gets the size in bytes of each value contained in the buffer
///
public int ElementSizeInBytes { get; }
///
/// Gets the heap type being targeted by the current buffer
///
public HeapType HeapType { get; }
///
/// Gets or sets a single value from the current buffer
///
/// The index of the value to get or set
/// This API can only be used from a compute shader, and will always throw if used anywhere else
public T this[uint i]
{
get => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader");
set => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader");
}
///
/// Reads the contents of the current instance and returns an array
///
/// A array with the contents of the current buffer
[Pure]
public T[] GetData()
{
T[] data = new T[Size];
GetData(data);
return data;
}
///
/// Reads the contents of the current instance and writes them into a target
///
/// The input to write data to
public void GetData(Span span)
{
// Create a temporary readback buffer if the current buffer type is read write (can't be read from directly)
if (HeapType == HeapType.Default)
{
using Buffer readbackBaffer = new Buffer(GraphicsDevice, Size, HeapType.Readback);
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
copyCommandList.CopyBufferRegion(this, 0, readbackBaffer, 0, SizeInBytes);
copyCommandList.Flush(true);
readbackBaffer.GetData(span);
}
else
{
// Map and read the memory back directly
Map(0);
MemoryHelper.Copy(MappedResource, span);
Unmap(0);
}
}
///
/// Writes the contents of a given to the current instance
///
/// The input to read data from
public void SetData(Span span)
{
// Create a temporary upload buffer if the current buffer type is read write (can't be written to directly)
if (HeapType == HeapType.Default)
{
using Buffer uploadBuffer = new Buffer(GraphicsDevice, Size, HeapType.Upload);
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
uploadBuffer.SetData(span);
copyCommandList.CopyBufferRegion(uploadBuffer, 0, this, 0, SizeInBytes);
copyCommandList.Flush(true);
}
else
{
// Map and copy the memory directly
Map(0);
MemoryHelper.Copy(span, MappedResource);
Unmap(0);
}
}
}
}