using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics.Buffers.Enums;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Graphics.Interop;
using Microsoft.Toolkit.Diagnostics;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
namespace ComputeSharp.Graphics.Buffers.Abstract
{
///
/// A representing a typed buffer stored on GPU memory.
///
/// The type of items stored on the buffer.
public unsafe abstract class Buffer : NativeObject
where T : unmanaged
{
///
/// The instance currently mapped.
///
private ComPtr d3D12Resource;
///
/// The instance for the current resource.
///
internal readonly D3D12_CPU_DESCRIPTOR_HANDLE D3D12CpuDescriptorHandle;
///
/// The instance for the current resource.
///
/// This field is dynamically accessed when loading shader dispatch data.
internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle;
///
/// The size in bytes of the current buffer (this value is never negative).
///
protected readonly nint SizeInBytes;
///
/// 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 size in bytes of each buffer item (including padding, if any).
/// The resource type for the current buffer.
private protected Buffer(GraphicsDevice device, int length, uint elementSizeInBytes, ResourceType resourceType)
{
device.ThrowIfDisposed();
if (resourceType == ResourceType.Constant)
{
Guard.IsBetweenOrEqualTo(length, 1, FX.D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, nameof(length));
}
else
{
// The maximum length is set such that the aligned buffer size can't exceed uint.MaxValue
Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / elementSizeInBytes) & ~255, nameof(length));
}
SizeInBytes = checked((nint)(length * elementSizeInBytes));
GraphicsDevice = device;
Length = length;
this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, (ulong)SizeInBytes, device.IsCacheCoherentUMA);
device.RentShaderResourceViewDescriptorHandles(out D3D12CpuDescriptorHandle, out D3D12GpuDescriptorHandle);
switch (resourceType)
{
case ResourceType.Constant:
device.D3D12Device->CreateConstantBufferView(this.d3D12Resource, SizeInBytes, D3D12CpuDescriptorHandle);
break;
case ResourceType.ReadOnly:
device.D3D12Device->CreateShaderResourceView(this.d3D12Resource, (uint)length, elementSizeInBytes, D3D12CpuDescriptorHandle);
break;
case ResourceType.ReadWrite:
device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource, (uint)length, elementSizeInBytes, D3D12CpuDescriptorHandle);
break;
}
}
///
/// Gets the associated with the current instance.
///
public GraphicsDevice GraphicsDevice { get; }
///
/// Gets the length of the current buffer.
///
public int Length { get; }
///
/// Gets whether or not there is some padding between elements in the current buffer.
///
internal bool IsPaddingPresent
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => SizeInBytes > (nint)Length * sizeof(T);
}
///
/// Gets the instance currently mapped.
///
internal ID3D12Resource* D3D12Resource => this.d3D12Resource;
///
/// Reads the contents of the specified range from the current instance and writes them into a target memory area.
///
/// The input memory area to write data to.
/// The size of the memory area to write data to.
/// The offset to start reading data from.
internal abstract void GetData(ref T destination, nint size, int offset);
///
/// Writes the contents of a given memory area to a specified area of the current instance.
///
/// The input memory area to read data from.
/// The size of the input memory area to read data from.
/// The offset to start writing data to.
internal abstract void SetData(ref T source, nint size, int offset);
///
/// Writes the contents of a given to the current instance.
///
/// The input to read data from.
public abstract void SetData(Buffer source);
///
/// Writes the contents of a given to the current instance, using a temporary CPU buffer.
///
/// The input to read data from.
protected void SetDataWithCpuBuffer(Buffer source)
{
T[] array = ArrayPool.Shared.Rent(source.Length);
try
{
source.GetData(ref MemoryMarshal.GetArrayDataReference(array), source.Length, 0);
SetData(ref MemoryMarshal.GetArrayDataReference(array), source.Length, 0);
}
finally
{
ArrayPool.Shared.Return(array);
}
}
///
protected override bool OnDispose()
{
this.d3D12Resource.Dispose();
if (GraphicsDevice?.IsDisposed == false)
{
GraphicsDevice.ReturnShaderResourceViewDescriptorHandles(D3D12CpuDescriptorHandle, D3D12GpuDescriptorHandle);
}
return true;
}
///
/// Throws a if the target device doesn't match the current one.
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void ThrowIfDeviceMismatch(GraphicsDevice device)
{
if (GraphicsDevice != device)
{
GraphicsDeviceMismatchException.Throw(this, device);
}
}
}
}