using System; using System.Buffers; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Core.Interop; using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Buffers.Enums; using ComputeSharp.Graphics.Extensions; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_SRV_DIMENSION; using static TerraFX.Interop.D3D12_UAV_DIMENSION; 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_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 buffer type for the current buffer. internal Buffer(GraphicsDevice device, int length, uint elementSizeInBytes, BufferType bufferType) { device.ThrowIfDisposed(); Guard.IsGreaterThanOrEqualTo(length, 0, nameof(length)); SizeInBytes = checked((nint)(length * elementSizeInBytes)); GraphicsDevice = device; Length = length; this.d3D12Resource = device.D3D12Device->CreateCommittedResource(bufferType, (ulong)SizeInBytes); GraphicsDevice.AllocateShaderResourceViewDescriptorHandles(out D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle, out D3D12GpuDescriptorHandle); switch (bufferType) { case BufferType.Constant: CreateConstantBufferView(d3D12CpuDescriptorHandle); break; case BufferType.ReadOnly: CreateShaderResourceView(d3D12CpuDescriptorHandle); break; case BufferType.ReadWrite: CreateUnorderedAccessView(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 the size in bytes of each value contained in the buffer. /// protected int ElementSizeInBytes { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => Unsafe.SizeOf(); } /// /// Gets whether or not there is some padding between elements in the current buffer. /// internal bool IsPaddingPresent { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => SizeInBytes > Length * Unsafe.SizeOf(); } /// /// Gets the instance currently mapped. /// internal ID3D12Resource* D3D12Resource => this.d3D12Resource; /// /// Reads the contents of the current instance and returns an array. /// /// A array with the contents of the current buffer. [Pure] public T[] GetData() => GetData(0, Length); /// /// Reads the contents of the current instance in a given range and returns an array. /// /// The offset to start reading data from. /// The number of items to read. /// A array with the contents of the specified range from the current buffer. [Pure] public T[] GetData(int offset, int count) { T[] data = GC.AllocateUninitializedArray(count); GetData(data, offset, count); 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 destination) => GetData(destination, 0, Length); /// /// Reads the contents of the specified range from the current instance and writes them into a target . /// /// The input to write data to. /// The offset to start reading data from. /// The number of items to read. public abstract void GetData(Span destination, int offset, int count); /// /// Writes the contents of a given array to the current instance. /// /// The input array to read data from. public void SetData(T[] source) => SetData(source.AsSpan()); /// /// Writes the contents of a given array to a specified area of the current instance. /// /// The input array to read data from. /// The offset to start writing data to. /// The number of items to write. public void SetData(T[] source, int offset, int count) => SetData(source.AsSpan(), offset, count); /// /// Writes the contents of a given to the current instance. /// /// The input to read data from. public void SetData(ReadOnlySpan source) => SetData(source, 0, Length); /// /// Writes the contents of a given to a specified area of the current instance. /// /// The input to read data from. /// The offset to start writing data to. /// The number of items to write. public abstract void SetData(ReadOnlySpan source, int offset, int count); /// /// 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 { Span span = array.AsSpan(0, source.Length); source.GetData(span); SetData(span); } finally { ArrayPool.Shared.Return(array); } } /// /// Creates a view for a constant buffer. /// /// The instance for the current resource. private void CreateConstantBufferView(D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle) { uint constantBufferSize = checked((uint)((SizeInBytes + 255) & ~255)); D3D12_CONSTANT_BUFFER_VIEW_DESC d3D12ConstantBufferViewDescription; d3D12ConstantBufferViewDescription.BufferLocation = D3D12Resource->GetGPUVirtualAddress(); d3D12ConstantBufferViewDescription.SizeInBytes = constantBufferSize; GraphicsDevice.D3D12Device->CreateConstantBufferView(&d3D12ConstantBufferViewDescription, d3D12CpuDescriptorHandle); } /// /// Creates a view for a readonly buffer. /// /// The instance for the current resource. private void CreateShaderResourceView(D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle) { D3D12_SHADER_RESOURCE_VIEW_DESC d3D12ShaderResourceViewDescription = default; d3D12ShaderResourceViewDescription.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; d3D12ShaderResourceViewDescription.Shader4ComponentMapping = FX.D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; d3D12ShaderResourceViewDescription.Buffer.NumElements = (uint)Length; d3D12ShaderResourceViewDescription.Buffer.StructureByteStride = (uint)ElementSizeInBytes; GraphicsDevice.D3D12Device->CreateShaderResourceView(D3D12Resource, &d3D12ShaderResourceViewDescription, d3D12CpuDescriptorHandle); } /// /// Creates a view for a buffer than be both read and written to. /// /// The instance for the current resource. private void CreateUnorderedAccessView(D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle) { D3D12_UNORDERED_ACCESS_VIEW_DESC d3D12UnorderedAccessViewDescription = default; d3D12UnorderedAccessViewDescription.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; d3D12UnorderedAccessViewDescription.Buffer.NumElements = (uint)Length; d3D12UnorderedAccessViewDescription.Buffer.StructureByteStride = (uint)ElementSizeInBytes; GraphicsDevice.D3D12Device->CreateUnorderedAccessView(D3D12Resource, null, &d3D12UnorderedAccessViewDescription, d3D12CpuDescriptorHandle); } /// protected override void OnDispose() { this.d3D12Resource.Dispose(); } /// /// Throws a if the target device doesn't match the current one. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ThrowIfDeviceMismatch(GraphicsDevice device) { if (GraphicsDevice != device) { void Throw() => throw GraphicsDeviceMismatchException.Create(this, device); Throw(); } } } }