diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index c344e728..44d94af1 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -1,7 +1,7 @@ using System; using System.Buffers; using System.Diagnostics.Contracts; -using SharpDX.Direct3D12; +using ComputeSharp.Graphics.Buffers.Enums; namespace ComputeSharp.Graphics.Buffers.Abstract { @@ -17,8 +17,8 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// The associated with the current instance /// The number of items to store in the current buffer /// The size in bytes for the current buffer - /// The heap type for the current buffer - protected internal HlslBuffer(GraphicsDevice device, int size, int sizeInBytes, HeapType heapType) : base(device, size, sizeInBytes, heapType) { } + /// The buffer type for the current buffer + private protected HlslBuffer(GraphicsDevice device, int size, int sizeInBytes, BufferType bufferType) : base(device, size, sizeInBytes, bufferType) { } /// /// Reads the contents of the current instance and returns an array diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs new file mode 100644 index 00000000..944adb56 --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs @@ -0,0 +1,67 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Buffers.Enums; +using ComputeSharp.Graphics.Helpers; +using SharpDX.Direct3D12; +using CommandList = ComputeSharp.Graphics.Commands.CommandList; + +namespace ComputeSharp.Graphics.Buffers.Abstract +{ + /// + /// A representing a typed structured buffer stored on GPU memory + /// + /// The type of items stored on the buffer + public abstract class HlslStructuredBuffer : HlslBuffer 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 buffer type for the current buffer + internal HlslStructuredBuffer(GraphicsDevice device, int size, BufferType bufferType) : base(device, size, size * Unsafe.SizeOf(), bufferType) { } + + /// + public override void GetData(Span span) + { + using Buffer transferBuffer = new Buffer(GraphicsDevice, Size, SizeInBytes, BufferType.Transfer); + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + copyCommandList.CopyBufferRegion(this, 0, transferBuffer, 0, SizeInBytes); + copyCommandList.Flush(); + + transferBuffer.Map(0); + MemoryHelper.Copy(transferBuffer.MappedResource, span); + transferBuffer.Unmap(0); + } + + /// + public override void SetData(Span span) + { + using Buffer transferBuffer = new Buffer(GraphicsDevice, Size, SizeInBytes, BufferType.Transfer); + + transferBuffer.Map(0); + MemoryHelper.Copy(span, transferBuffer.MappedResource); + transferBuffer.Unmap(0); + + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + copyCommandList.CopyBufferRegion(transferBuffer, 0, this, 0, SizeInBytes); + copyCommandList.Flush(); + } + + /// + public override void SetData(HlslBuffer buffer) + { + if (!buffer.IsPaddingPresent) + { + // Directly copy the input buffer + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); + copyCommandList.Flush(); + } + else SetDataWithCpuBuffer(buffer); + } + } +} diff --git a/src/ComputeSharp.Graphics/Buffers/Buffer.cs b/src/ComputeSharp.Graphics/Buffers/Buffer{T}.cs similarity index 55% rename from src/ComputeSharp.Graphics/Buffers/Buffer.cs rename to src/ComputeSharp.Graphics/Buffers/Buffer{T}.cs index 2891999a..c08a8304 100644 --- a/src/ComputeSharp.Graphics/Buffers/Buffer.cs +++ b/src/ComputeSharp.Graphics/Buffers/Buffer{T}.cs @@ -1,6 +1,8 @@ -using System.Diagnostics.Contracts; +using System; +using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Buffers.Enums; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers @@ -17,29 +19,36 @@ namespace ComputeSharp.Graphics.Buffers /// The associated with the current instance /// The number of items to store in the current buffer /// The size in bytes for the current buffer - /// The heap type for the current buffer - protected internal Buffer(GraphicsDevice device, int size, int sizeInBytes, HeapType heapType) : base(device) + /// The buffer type for the current buffer + internal Buffer(GraphicsDevice device, int size, int sizeInBytes, BufferType bufferType) : base(device) { Size = size; SizeInBytes = sizeInBytes; // Not necessarily a multiple of the element size, as there could be padding ElementSizeInBytes = Unsafe.SizeOf(); - HeapType = heapType; + BufferType = bufferType; + PaddedElementSizeInBytes = sizeInBytes / size; - ResourceFlags flags = heapType == HeapType.Default ? ResourceFlags.AllowUnorderedAccess : ResourceFlags.None; - ResourceDescription description = ResourceDescription.Buffer(SizeInBytes, flags); - ResourceStates resourceStates = heapType switch + // Determine the right heap type and flags + (HeapType heapType, ResourceFlags flags, ResourceStates states) = bufferType switch { - HeapType.Upload => ResourceStates.GenericRead, - HeapType.Readback => ResourceStates.CopyDestination, - _ => ResourceStates.Common + BufferType.Constant => (HeapType.Upload, ResourceFlags.None, ResourceStates.GenericRead), + BufferType.ReadOnly => (HeapType.Default, ResourceFlags.None, ResourceStates.Common), + BufferType.ReadWrite => (HeapType.Default, ResourceFlags.AllowUnorderedAccess, ResourceStates.Common), + BufferType.ReadBack => (HeapType.Readback, ResourceFlags.None, ResourceStates.CopyDestination), + BufferType.Transfer => (HeapType.Upload, ResourceFlags.None, ResourceStates.GenericRead), + _ => throw new ArgumentException($"Invalid buffer type {bufferType}", nameof(bufferType)) }; - NativeResource = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(heapType), HeapFlags.None, description, resourceStates); + // Create the native resource + ResourceDescription description = ResourceDescription.Buffer(sizeInBytes, flags); + NativeResource = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(heapType), HeapFlags.None, description, states); - (NativeCpuDescriptorHandle, NativeGpuDescriptorHandle) = heapType switch + // Create the resource handles, if needed + (NativeCpuDescriptorHandle, NativeGpuDescriptorHandle) = bufferType switch { - HeapType.Default => CreateUnorderedAccessView(), - HeapType.Upload => CreateConstantBufferView(), + BufferType.Constant => CreateConstantBufferView(), + BufferType.ReadOnly => CreateShaderResourceView(), + BufferType.ReadWrite => CreateUnorderedAccessView(), _ => default }; } @@ -60,9 +69,19 @@ namespace ComputeSharp.Graphics.Buffers protected int ElementSizeInBytes { get; } /// - /// Gets the heap type being targeted by the current buffer + /// Gets the size in bytes of the current buffer /// - internal HeapType HeapType { get; } + internal int PaddedElementSizeInBytes { get; } + + /// + /// Gets whether or not there is some padding between elements in the current buffer + /// + internal bool IsPaddingPresent => PaddedElementSizeInBytes > ElementSizeInBytes; + + /// + /// Gets the buffer type for the current instance + /// + internal BufferType BufferType { get; } /// /// Creates the descriptors for a constant buffer @@ -86,6 +105,22 @@ namespace ComputeSharp.Graphics.Buffers return (cpuHandle, gpuHandle); } + private (CpuDescriptorHandle, GpuDescriptorHandle) CreateShaderResourceView() + { + (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(); + + ShaderResourceViewDescription description = new ShaderResourceViewDescription + { + Shader4ComponentMapping = 5768, + Dimension = ShaderResourceViewDimension.Buffer, + Buffer = { ElementCount = Size, StructureByteStride = ElementSizeInBytes } + }; + + GraphicsDevice.NativeDevice.CreateShaderResourceView(NativeResource, description, cpuHandle); + + return (cpuHandle, gpuHandle); + } + /// /// Creates the descriptors for a read write buffer /// @@ -98,11 +133,7 @@ namespace ComputeSharp.Graphics.Buffers UnorderedAccessViewDescription description = new UnorderedAccessViewDescription { Dimension = UnorderedAccessViewDimension.Buffer, - Buffer = - { - ElementCount = Size, - StructureByteStride = ElementSizeInBytes - } + Buffer = { ElementCount = Size, StructureByteStride = ElementSizeInBytes } }; GraphicsDevice.NativeDevice.CreateUnorderedAccessView(NativeResource, null, description, cpuHandle); diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs new file mode 100644 index 00000000..4ee092c8 --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -0,0 +1,115 @@ +using System; +using System.Buffers; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Buffers.Enums; +using ComputeSharp.Graphics.Helpers; +using SharpDX.Direct3D12; +using CommandList = ComputeSharp.Graphics.Commands.CommandList; + +namespace ComputeSharp.Graphics.Buffers +{ + /// + /// A representing a typed read write buffer stored on GPU memory + /// + /// The type of items stored on the buffer + public sealed class ConstantBuffer : HlslBuffer 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 + internal ConstantBuffer(GraphicsDevice device, int size) : base(device, size, size * (Unsafe.SizeOf() / 16 + 1) * 16, BufferType.Constant) { } + + /// + /// Gets a single value from the current constant buffer + /// + /// The index of the value to get + /// This API can only be used from a compute shader, and will always throw if used anywhere else + public T this[uint i] => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader"); + + /// + public override void GetData(Span span) + { + if (IsPaddingPresent) + { + // Create the temporary array + byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); + Span temporarySpan = temporaryArray.AsSpan(); + + // Copy the padded data to the temporary array + Map(0); + MemoryHelper.Copy(MappedResource, temporarySpan); + Unmap(0); + + ref byte tin = ref temporarySpan.GetPinnableReference(); + ref T tout = ref span.GetPinnableReference(); + + // Copy the padded data to the target span, removing the padding + for (int i = 0; i < Size; i++) + { + ref byte rsource = ref Unsafe.Add(ref tin, i * PaddedElementSizeInBytes); + Unsafe.Add(ref tout, i) = Unsafe.As(ref rsource); + } + + ArrayPool.Shared.Return(temporaryArray); + } + else + { + // Directly copy the data back if there is no padding + Map(0); + MemoryHelper.Copy(MappedResource, span); + Unmap(0); + } + } + + /// + public override void SetData(Span span) + { + if (IsPaddingPresent) + { + // Create the temporary array + byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); + Span temporarySpan = temporaryArray.AsSpan(0, SizeInBytes); // Array pool arrays can be longer + ref T tin = ref span.GetPinnableReference(); + ref byte tout = ref temporarySpan.GetPinnableReference(); + + // Copy the input data to the temporary array and add the padding + for (int i = 0; i < Size; i++) + { + ref byte rtarget = ref Unsafe.Add(ref tout, i * PaddedElementSizeInBytes); + Unsafe.As(ref rtarget) = Unsafe.Add(ref tin, i); + } + + // Copy the padded data to the GPU + Map(0); + MemoryHelper.Copy(temporarySpan, MappedResource); + Unmap(0); + + ArrayPool.Shared.Return(temporaryArray); + } + else + { + // Directly copy the input span if there is no padding + Map(0); + MemoryHelper.Copy(span, MappedResource); + Unmap(0); + } + } + + /// + public override void SetData(HlslBuffer buffer) + { + if (buffer is ConstantBuffer) + { + // Directly copy the input buffer, if possible + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); + copyCommandList.Flush(); + } + else SetDataWithCpuBuffer(buffer); + } + } +} diff --git a/src/ComputeSharp.Graphics/Buffers/Enums/BufferType.cs b/src/ComputeSharp.Graphics/Buffers/Enums/BufferType.cs new file mode 100644 index 00000000..44c282d7 --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/Enums/BufferType.cs @@ -0,0 +1,33 @@ +namespace ComputeSharp.Graphics.Buffers.Enums +{ + /// + /// An that indicates the type of a given HLSL buffer + /// + internal enum BufferType + { + /// + /// A constant buffer, with items aligned to 16 bytes, used for individual values or very small arrays, mapped to + /// + Constant, + + /// + /// A readonly buffer, that can store arbitrary arrays of values, mapped to + /// + ReadOnly, + + /// + /// A read write buffer, that can store arbitrary arrays with both read and write access, mapped to + /// + ReadWrite, + + /// + /// A readback buffer, used as temporary buffer to read data back from read write buffers, mapped to + /// + ReadBack, + + /// + /// A transfer buffer, used as a temporary buffer to set data to buffers in the default heap, mapped to + /// + Transfer + } +} diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs index 2f3c0ae3..5d1112ea 100644 --- a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs +++ b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs @@ -12,6 +12,152 @@ namespace ComputeSharp /// public static class BufferExtensions { + /// + /// Allocates a new constant buffer with the specified parameters + /// + /// The type of items to store in the buffer + /// The instance to use to allocate the buffer + /// The input array with the data to copy on the allocated buffer + /// A constant instance with the contents of the input array + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, T[] array) where T : unmanaged + { + return device.AllocateConstantBuffer(array.AsSpan()); + } + + /// + /// Allocates a new constant buffer with the specified parameters + /// + /// The type of items to store in the buffer + /// The instance to use to allocate the buffer + /// The input 2D array with the data to copy on the allocated buffer + /// A constant instance with the contents of the input 2D array + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, T[,] array) where T : unmanaged + { + fixed (T* p = array) + { + Span span = new Span(p, array.Length); + return device.AllocateConstantBuffer(span); + } + } + + /// + /// Allocates a new constant buffer with the specified parameters + /// + /// The type of items to store in the buffer + /// The instance to use to allocate the buffer + /// The input with the data to copy on the allocated buffer + /// A constant instance with the contents of the input + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, Span span) where T : unmanaged + { + ConstantBuffer buffer = new ConstantBuffer(device, span.Length); + buffer.SetData(span); + + return buffer; + } + + /// + /// Allocates a new constant buffer with the specified parameters + /// + /// The type of items to store in the buffer + /// The instance to use to allocate the buffer + /// The input with the data to copy on the allocated buffer + /// A constant instance with the contents of the input + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, HlslBuffer buffer) where T : unmanaged + { + ConstantBuffer constantBuffer = new ConstantBuffer(device, buffer.Size); + constantBuffer.SetData(buffer); + + return constantBuffer; + } + + /// + /// Allocates a new readonly buffer with the specified parameters + /// + /// The type of items to store in the buffer + /// The instance to use to allocate the buffer + /// The size of the buffer to allocate + /// A zeroed instance of size + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, int size) where T : unmanaged + { + return new ReadOnlyBuffer(device, size); + } + + /// + /// Allocates a new readonly buffer with the specified parameters + /// + /// The type of items to store in the buffer + /// The instance to use to allocate the buffer + /// The input array with the data to copy on the allocated buffer + /// A read write instance with the contents of the input array + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, T[] array) where T : unmanaged + { + return device.AllocateReadOnlyBuffer(array.AsSpan()); + } + + /// + /// Allocates a new readonly buffer with the specified parameters + /// + /// The type of items to store in the buffer + /// The instance to use to allocate the buffer + /// The input 2D array with the data to copy on the allocated buffer + /// A read write instance with the contents of the input 2D array + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, T[,] array) where T : unmanaged + { + fixed (T* p = array) + { + Span span = new Span(p, array.Length); + return device.AllocateReadOnlyBuffer(span); + } + } + + /// + /// Allocates a new readonly buffer with the specified parameters + /// + /// The type of items to store in the buffer + /// The instance to use to allocate the buffer + /// The input with the data to copy on the allocated buffer + /// A read write instance with the contents of the input + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, Span span) where T : unmanaged + { + ReadOnlyBuffer buffer = new ReadOnlyBuffer(device, span.Length); + buffer.SetData(span); + + return buffer; + } + + /// + /// Allocates a new readonly buffer with the specified parameters + /// + /// The type of items to store in the buffer + /// The instance to use to allocate the buffer + /// The input with the data to copy on the allocated buffer + /// A read write instance with the contents of the input + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, HlslBuffer buffer) where T : unmanaged + { + ReadOnlyBuffer readWriteBuffer = new ReadOnlyBuffer(device, buffer.Size); + readWriteBuffer.SetData(buffer); + + return readWriteBuffer; + } + /// /// Allocates a new read write buffer with the specified parameters /// @@ -91,71 +237,5 @@ namespace ComputeSharp return readWriteBuffer; } - - /// - /// Allocates a new constant buffer with the specified parameters - /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input array with the data to copy on the allocated buffer - /// A constant instance with the contents of the input array - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, T[] array) where T : unmanaged - { - return device.AllocateReadOnlyBuffer(array.AsSpan()); - } - - /// - /// Allocates a new constant buffer with the specified parameters - /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input 2D array with the data to copy on the allocated buffer - /// A constant instance with the contents of the input 2D array - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, T[,] array) where T : unmanaged - { - fixed (T* p = array) - { - Span span = new Span(p, array.Length); - return device.AllocateReadOnlyBuffer(span); - } - } - - /// - /// Allocates a new constant buffer with the specified parameters - /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input with the data to copy on the allocated buffer - /// A constant instance with the contents of the input - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, Span span) where T : unmanaged - { - ReadOnlyBuffer buffer = new ReadOnlyBuffer(device, span.Length); - buffer.SetData(span); - - return buffer; - } - - /// - /// Allocates a new constant buffer with the specified parameters - /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input with the data to copy on the allocated buffer - /// A constant instance with the contents of the input - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, HlslBuffer buffer) where T : unmanaged - { - ReadOnlyBuffer readOnlyBuffer = new ReadOnlyBuffer(device, buffer.Size); - readOnlyBuffer.SetData(buffer); - - return readOnlyBuffer; - } } } diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs index 2f1d952e..7ab8bb98 100644 --- a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs +++ b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs @@ -23,15 +23,15 @@ namespace ComputeSharp.Graphics.Buffers.Extensions /// /// The instance to use to allocate the buffer /// The input to copy to the allocated buffer - /// A constant instance (as a ) with the input data + /// A constant instance (as a ) with the input data [Pure] - public static GraphicsResource AllocateReadOnlyBufferFromReflectedSingleValue(this GraphicsDevice device, object data) + public static GraphicsResource AllocateConstantBufferFromReflectedSingleValue(this GraphicsDevice device, object data) { Type dataType = data.GetType(); if (!TypeMapping.TryGetValue(dataType, out var info)) { // Get the generic buffer constructor - Type bufferType = typeof(ReadOnlyBuffer<>).MakeGenericType(dataType); + Type bufferType = typeof(ConstantBuffer<>).MakeGenericType(dataType); info.Constructor = bufferType.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).First(); // Create the reusable array diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 89ebb6dd..f6aee2ec 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -1,128 +1,27 @@ using System; -using System.Buffers; -using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Helpers; -using SharpDX.Direct3D12; -using CommandList = ComputeSharp.Graphics.Commands.CommandList; +using ComputeSharp.Graphics.Buffers.Enums; namespace ComputeSharp.Graphics.Buffers { /// - /// A representing a typed read write buffer stored on GPU memory + /// A representing a typed readonly buffer stored on GPU memory /// /// The type of items stored on the buffer - public sealed class ReadOnlyBuffer : HlslBuffer where T : unmanaged + public sealed class ReadOnlyBuffer : HlslStructuredBuffer 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 - internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, size * (Unsafe.SizeOf() / 16 + 1) * 16, HeapType.Upload) - { - PaddedElementSizeInBytes = SizeInBytes / Size; - IsPaddingPresent = PaddedElementSizeInBytes > ElementSizeInBytes; - } + internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, BufferType.ReadOnly) { } /// - /// Gets the size in bytes of the current buffer + /// Gets or sets a single value from the current read write buffer /// - internal int PaddedElementSizeInBytes { get; } - - /// - /// Gets whether or not there is some padding between elements in the current buffer - /// - internal bool IsPaddingPresent { get; } - - /// - /// Gets a single value from the current read write buffer - /// - /// The index of the value to get + /// 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] => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader"); - - /// - public override void GetData(Span span) - { - if (IsPaddingPresent) - { - // Create the temporary array - byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); - Span temporarySpan = temporaryArray.AsSpan(); - - // Copy the padded data to the temporary array - Map(0); - MemoryHelper.Copy(MappedResource, temporarySpan); - Unmap(0); - - ref byte tin = ref temporarySpan.GetPinnableReference(); - ref T tout = ref span.GetPinnableReference(); - - // Copy the padded data to the target span, removing the padding - for (int i = 0; i < Size; i++) - { - ref byte rsource = ref Unsafe.Add(ref tin, i * PaddedElementSizeInBytes); - Unsafe.Add(ref tout, i) = Unsafe.As(ref rsource); - } - - ArrayPool.Shared.Return(temporaryArray); - } - else - { - // Directly copy the data back if there is no padding - Map(0); - MemoryHelper.Copy(MappedResource, span); - Unmap(0); - } - } - - /// - public override void SetData(Span span) - { - if (IsPaddingPresent) - { - // Create the temporary array - byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); - Span temporarySpan = temporaryArray.AsSpan(0, SizeInBytes); // Array pool arrays can be longer - ref T tin = ref span.GetPinnableReference(); - ref byte tout = ref temporarySpan.GetPinnableReference(); - - // Copy the input data to the temporary array and add the padding - for (int i = 0; i < Size; i++) - { - ref byte rtarget = ref Unsafe.Add(ref tout, i * PaddedElementSizeInBytes); - Unsafe.As(ref rtarget) = Unsafe.Add(ref tin, i); - } - - // Copy the padded data to the GPU - Map(0); - MemoryHelper.Copy(temporarySpan, MappedResource); - Unmap(0); - - ArrayPool.Shared.Return(temporaryArray); - } - else - { - // Directly copy the input span if there is no padding - Map(0); - MemoryHelper.Copy(span, MappedResource); - Unmap(0); - } - } - - /// - public override void SetData(HlslBuffer buffer) - { - if (buffer is ReadOnlyBuffer) - { - // Directly copy the input buffer, if possible - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); - - copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); - copyCommandList.Flush(); - } - else SetDataWithCpuBuffer(buffer); - } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index cd7c9158..b6f7cf2d 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -1,9 +1,6 @@ using System; -using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Helpers; -using SharpDX.Direct3D12; -using CommandList = ComputeSharp.Graphics.Commands.CommandList; +using ComputeSharp.Graphics.Buffers.Enums; namespace ComputeSharp.Graphics.Buffers { @@ -11,14 +8,14 @@ namespace ComputeSharp.Graphics.Buffers /// A representing a typed read write buffer stored on GPU memory /// /// The type of items stored on the buffer - public sealed class ReadWriteBuffer : HlslBuffer where T : unmanaged + public sealed class ReadWriteBuffer : HlslStructuredBuffer 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 - internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, size * Unsafe.SizeOf(), HeapType.Default) { } + internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, BufferType.ReadWrite) { } /// /// Gets or sets a single value from the current read write buffer @@ -30,48 +27,5 @@ namespace ComputeSharp.Graphics.Buffers 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"); } - - /// - public override void GetData(Span span) - { - using Buffer readbackBaffer = new Buffer(GraphicsDevice, Size, SizeInBytes, HeapType.Readback); - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); - - copyCommandList.CopyBufferRegion(this, 0, readbackBaffer, 0, SizeInBytes); - copyCommandList.Flush(); - - readbackBaffer.Map(0); - MemoryHelper.Copy(readbackBaffer.MappedResource, span); - readbackBaffer.Unmap(0); - } - - /// - public override void SetData(Span span) - { - using Buffer uploadBuffer = new Buffer(GraphicsDevice, Size, SizeInBytes, HeapType.Upload); - - uploadBuffer.Map(0); - MemoryHelper.Copy(span, uploadBuffer.MappedResource); - uploadBuffer.Unmap(0); - - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); - - copyCommandList.CopyBufferRegion(uploadBuffer, 0, this, 0, SizeInBytes); - copyCommandList.Flush(); - } - - /// - public override void SetData(HlslBuffer buffer) - { - if (buffer is ReadOnlyBuffer readOnlyBuffer && !readOnlyBuffer.IsPaddingPresent) - { - // Directly copy the input buffer - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); - - copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); - copyCommandList.Flush(); - } - else SetDataWithCpuBuffer(buffer); - } } } diff --git a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs index 0a6e5e36..56a9a633 100644 --- a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs @@ -27,6 +27,7 @@ namespace ComputeSharp.Shaders.Mappings [typeof(Vector4).FullName] = "float4", [typeof(Matrix4x4).FullName] = "float4x4", [typeof(ThreadIds).FullName] = "uint3", + [typeof(ReadOnlyBuffer<>).FullName] = "StructuredBuffer", [typeof(ReadWriteBuffer<>).FullName] = "RWStructuredBuffer" }; @@ -54,13 +55,13 @@ namespace ComputeSharp.Shaders.Mappings type == typeof(Matrix4x4); /// - /// Checks whether or not the input type is a value + /// Checks whether or not the input type is a value /// /// The input instance to check - /// A indicating whether the input is in fact a instance + /// A indicating whether the input is in fact a instance [Pure] - public static bool IsReadWriteBufferType(Type type) => type.IsGenericType && - type.GetGenericTypeDefinition() == typeof(ReadWriteBuffer<>); + public static bool IsConstantBufferType(Type type) => type.IsGenericType && + type.GetGenericTypeDefinition() == typeof(ConstantBuffer<>); /// /// Checks whether or not the input type is a value @@ -69,7 +70,16 @@ namespace ComputeSharp.Shaders.Mappings /// A indicating whether the input is in fact a instance [Pure] public static bool IsReadOnlyBufferType(Type type) => type.IsGenericType && - type.GetGenericTypeDefinition() == typeof(ReadOnlyBuffer<>); + type.GetGenericTypeDefinition() == typeof(ReadOnlyBuffer<>); + + /// + /// Checks whether or not the input type is a value + /// + /// The input instance to check + /// A indicating whether the input is in fact a instance + [Pure] + public static bool IsReadWriteBufferType(Type type) => type.IsGenericType && + type.GetGenericTypeDefinition() == typeof(ReadWriteBuffer<>); /// /// Checks whether or not a given is an HLSL known type diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/FieldInfoBase.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/FieldInfo.cs similarity index 79% rename from src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/FieldInfoBase.cs rename to src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/FieldInfo.cs index 93cff5c0..8c60411e 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/FieldInfoBase.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/FieldInfo.cs @@ -3,7 +3,7 @@ /// /// A that contains info on a shader field /// - internal abstract class FieldInfoBase + internal abstract class FieldInfo { /// /// Gets or sets the type of the current field @@ -16,11 +16,11 @@ public string FieldName { get; set; } /// - /// Creates a new instance with the specified parameters + /// Creates a new instance with the specified parameters /// /// The type of the current field /// The name of the current field - protected FieldInfoBase(string fieldType, string fieldName) + protected FieldInfo(string fieldType, string fieldName) { FieldType = fieldType; FieldName = fieldName; diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/HlslBufferInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/HlslBufferInfo.cs new file mode 100644 index 00000000..e5c0044e --- /dev/null +++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/HlslBufferInfo.cs @@ -0,0 +1,24 @@ +namespace ComputeSharp.Shaders.Renderer.Models.Fields.Abstract +{ + /// + /// A that contains info on a shader buffer field + /// + internal abstract class HlslBufferInfo : FieldInfo + { + /// + /// Gets or sets the index of the current buffer, relative to its own type + /// + public int BufferIndex { get; set; } + + /// + /// Creates a new instance with the specified parameters + /// + /// The type of the current field + /// The name of the current field + /// The index of the current buffer field + protected HlslBufferInfo(string fieldType, string fieldName, int bufferIndex) : base(fieldType, fieldName) + { + BufferIndex = bufferIndex; + } + } +} diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs index d79f85c4..ca47d290 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs @@ -5,10 +5,10 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields /// /// A that contains info on a constant buffer field /// - internal sealed class ConstantBufferFieldInfo : FieldInfoBase + internal sealed class ConstantBufferFieldInfo : HlslBufferInfo { /// - /// Gets whether or not the current instance represents a constant buffer (always ) + /// Gets whether or not the current instance represents a constant buffer (always ) /// public bool IsConstantBuffer { get; } = true; @@ -17,11 +17,6 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields /// public bool IsSingleValue { get; } - /// - /// Gets the index of the current constant buffer field - /// - public int ConstantBufferIndex { get; } - /// /// Creates a new instance with the specified parameters /// @@ -29,9 +24,8 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields /// The name of the current field /// The index of the current constant buffer field /// Whether or not this constant buffer actually contains a single, explicit variable - public ConstantBufferFieldInfo(string fieldType, string fieldName, int bufferIndex, bool singleValue) : base(fieldType, fieldName) + public ConstantBufferFieldInfo(string fieldType, string fieldName, int bufferIndex, bool singleValue) : base(fieldType, fieldName, bufferIndex) { - ConstantBufferIndex = bufferIndex; IsSingleValue = singleValue; } } diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadOnlyBufferFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadOnlyBufferFieldInfo.cs new file mode 100644 index 00000000..a8d826ee --- /dev/null +++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadOnlyBufferFieldInfo.cs @@ -0,0 +1,23 @@ +using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract; + +namespace ComputeSharp.Shaders.Renderer.Models.Fields +{ + /// + /// A that contains info on a readonly buffer field + /// + internal sealed class ReadOnlyBufferFieldInfo : HlslBufferInfo + { + /// + /// Gets whether or not the current instance represents a readonly buffer (always ) + /// + public bool IsReadOnlyBuffer { get; } = true; + + /// + /// Creates a new instance with the specified parameters + /// + /// The type of the current field + /// The name of the current field + /// The index of the current readonly buffer field + public ReadOnlyBufferFieldInfo(string fieldType, string fieldName, int bufferIndex) : base(fieldType, fieldName, bufferIndex) { } + } +} diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs index e7a9193e..170260dc 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs @@ -5,27 +5,19 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields /// /// A that contains info on a read write buffer field /// - internal sealed class ReadWriteBufferFieldInfo : FieldInfoBase + internal sealed class ReadWriteBufferFieldInfo : HlslBufferInfo { /// - /// Gets whether or not the current instance represents a read write buffer (always ) + /// Gets whether or not the current instance represents a read write buffer (always ) /// public bool IsReadWriteBuffer { get; } = true; - /// - /// Gets the index of the current read write buffer field - /// - public int ReadWriteBufferIndex { get; set; } - /// /// Creates a new instance with the specified parameters /// /// The type of the current field /// The name of the current field /// The index of the current read write buffer field - public ReadWriteBufferFieldInfo(string fieldType, string fieldName, int bufferIndex) : base(fieldType, fieldName) - { - ReadWriteBufferIndex = bufferIndex; - } + public ReadWriteBufferFieldInfo(string fieldType, string fieldName, int bufferIndex) : base(fieldType, fieldName, bufferIndex) { } } } diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs index e7d079ac..670abc20 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs @@ -5,10 +5,10 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields /// /// A that contains info on a static scalar field /// - internal sealed class StaticScalarFieldInfo : FieldInfoBase + internal sealed class StaticScalarFieldInfo : FieldInfo { /// - /// Gets whether or not the current instance represents a static scalar value (always ) + /// Gets whether or not the current instance represents a static scalar value (always ) /// public bool IsStaticScalarField { get; } = true; diff --git a/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs index f9961bfe..255c797a 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs @@ -13,7 +13,7 @@ namespace ComputeSharp.Shaders.Renderer.Models /// /// Gets the list of fields being present in the current shader /// - public IReadOnlyList FieldsList { get; set; } + public IReadOnlyList FieldsList { get; set; } /// /// Gets or sets the total number of threads to run on the X axis diff --git a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache index ef061a4b..382629c2 100644 --- a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache +++ b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache @@ -5,14 +5,18 @@ static {{&FieldType}} {{FieldName}} = {{FieldValue}}; {{/IsStaticScalarField}} {{!Constant buffer}} {{#IsConstantBuffer}} -cbuffer {{FieldName}}Buffer : register(b{{ConstantBufferIndex}}) +cbuffer {{FieldName}}Buffer : register(b{{BufferIndex}}) { {{&FieldType}} {{FieldName}}{{^IsSingleValue}}[2]{{/IsSingleValue}}; } {{/IsConstantBuffer}} +{{!Readonly buffer}} +{{#IsReadOnlyBuffer}} +{{&FieldType}} {{FieldName}} : register(t{{BufferIndex}}); +{{/IsReadOnlyBuffer}} {{!Read write buffer}} {{#IsReadWriteBuffer}} -{{&FieldType}} {{FieldName}} : SV_DispatchThreadId : register(u{{ReadWriteBufferIndex}}); +{{&FieldType}} {{FieldName}} : SV_DispatchThreadId : register(u{{BufferIndex}}); {{/IsReadWriteBuffer}} {{/FieldsList}} @@ -21,8 +25,8 @@ cbuffer {{FieldName}}Buffer : register(b{{ConstantBufferIndex}}) [NumThreads({{NumThreadsX}}, {{NumThreadsY}}, {{NumThreadsZ}})] void CSMain(uint3 {{ThreadsIdsVariableName}} : SV_DispatchThreadId) { -if ({{ThreadsIdsVariableName}}.x < {{ThreadsX}} && - {{ThreadsIdsVariableName}}.y < {{ThreadsY}} && - {{ThreadsIdsVariableName}}.z < {{ThreadsZ}}) + if ({{ThreadsIdsVariableName}}.x < {{ThreadsX}} && + {{ThreadsIdsVariableName}}.y < {{ThreadsY}} && + {{ThreadsIdsVariableName}}.z < {{ThreadsZ}}) {{&ShaderBody}} } diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index b9185bc5..5acaac28 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -99,7 +99,7 @@ namespace ComputeSharp.Shaders List buffers = new List(); foreach (var variable in shaderLoader.CapturedConstantBufferValues) { - GraphicsResource resource = device.AllocateReadOnlyBufferFromReflectedSingleValue(variable.Value); + GraphicsResource resource = device.AllocateConstantBufferFromReflectedSingleValue(variable.Value); commandList.SetComputeRootDescriptorTable(variable.Index, resource); buffers.Add(resource); } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index ee380182..6d650909 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -11,6 +11,7 @@ using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpDX.Direct3D12; +using FieldInfo = ComputeSharp.Shaders.Renderer.Models.Fields.Abstract.FieldInfo; #pragma warning disable CS8618 // Non-nullable field is uninitialized @@ -39,7 +40,7 @@ namespace ComputeSharp.Shaders.Translation /// /// The sequence of fields in the targeted closure /// - private readonly IReadOnlyList ShaderFields; + private readonly IReadOnlyList ShaderFields; /// /// Creates a new with the specified parameters @@ -68,12 +69,12 @@ namespace ComputeSharp.Shaders.Translation /// public IReadOnlyList<(int Index, object Value)> CapturedConstantBufferValues { get; private set; } - private readonly List _FieldsInfo = new List(); + private readonly List _FieldsInfo = new List(); /// - /// Gets the collection of items for the shader fields + /// Gets the collection of items for the shader fields /// - public IReadOnlyList FieldsInfo => _FieldsInfo; + public IReadOnlyList FieldsInfo => _FieldsInfo; /// /// Gets the name of the variable used as input for the shader method @@ -113,18 +114,42 @@ namespace ComputeSharp.Shaders.Translation List descriptorRanges = new List(); List<(int, GraphicsResource)> buffers = new List<(int, GraphicsResource)>(); List<(int, object)> variables = new List<(int, object)>(); - int readWriteBuffersCount = 0; + int constantBuffersCount = 0; int readOnlyBuffersCount = 0; + int readWriteBuffersCount = 0; - foreach (FieldInfo fieldInfo in ShaderFields) + foreach (System.Reflection.FieldInfo fieldInfo in ShaderFields) { Type fieldType = fieldInfo.FieldType; string fieldName = fieldInfo.Name; object fieldValue = fieldInfo.GetValue(ShaderInstance); - FieldInfoBase processedFieldInfo; + FieldInfo processedFieldInfo; - // Read write buffer - if (HlslKnownTypes.IsReadWriteBufferType(fieldType)) + // Constant buffer + if (HlslKnownTypes.IsConstantBufferType(fieldType)) + { + DescriptorRange range = new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount); + descriptorRanges.Add(range); + + // Reference to the underlying buffer + buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue)); + + string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); + processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, constantBuffersCount++, false); + } + else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType)) + { + // Root parameter for a readonly buffer + DescriptorRange range = new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, readOnlyBuffersCount); + descriptorRanges.Add(range); + + // Reference to the underlying buffer + buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue)); + + string typeName = HlslKnownTypes.GetMappedName(fieldType); + processedFieldInfo = new ReadOnlyBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++); + } + else if (HlslKnownTypes.IsReadWriteBufferType(fieldType)) { // Root parameter for a read write buffer DescriptorRange range = new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, readWriteBuffersCount); @@ -136,22 +161,10 @@ namespace ComputeSharp.Shaders.Translation string typeName = HlslKnownTypes.GetMappedName(fieldType); processedFieldInfo = new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++); } - else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType)) - { - // Read only buffer - DescriptorRange range = new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, readOnlyBuffersCount); - descriptorRanges.Add(range); - - // Reference to the underlying buffer - buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue)); - - string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); - processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, false); - } else if (HlslKnownTypes.IsKnownScalarType(fieldType)) { - // Read only buffer - DescriptorRange range = new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, readOnlyBuffersCount); + // Constant buffer + DescriptorRange range = new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount); descriptorRanges.Add(range); // Register the captured value @@ -159,7 +172,7 @@ namespace ComputeSharp.Shaders.Translation // Constant buffer field string typeName = HlslKnownTypes.GetMappedName(fieldType); - processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, true); + processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, constantBuffersCount++, true); } else throw new NotSupportedException($"Unsupported field of type {fieldType.FullName}"); diff --git a/tests/ComputeSharp.NetCore.Tests.Internals/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests.Internals/BufferTests.cs index ea37b67f..cf24f066 100644 --- a/tests/ComputeSharp.NetCore.Tests.Internals/BufferTests.cs +++ b/tests/ComputeSharp.NetCore.Tests.Internals/BufferTests.cs @@ -14,7 +14,7 @@ namespace ComputeSharp.NetCore.Tests.Internals { object value = 77; - using ReadOnlyBuffer buffer = (ReadOnlyBuffer)Gpu.Default.AllocateReadOnlyBufferFromReflectedSingleValue(value); + using ConstantBuffer buffer = (ConstantBuffer)Gpu.Default.AllocateConstantBufferFromReflectedSingleValue(value); int[] result = buffer.GetData(); Assert.IsTrue(result.Length == 1); @@ -26,7 +26,7 @@ namespace ComputeSharp.NetCore.Tests.Internals { object value = 3.14f; - using ReadOnlyBuffer buffer = (ReadOnlyBuffer)Gpu.Default.AllocateReadOnlyBufferFromReflectedSingleValue(value); + using ConstantBuffer buffer = (ConstantBuffer)Gpu.Default.AllocateConstantBufferFromReflectedSingleValue(value); float[] result = buffer.GetData(); Assert.IsTrue(result.Length == 1); diff --git a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs index 5040ea07..54553917 100644 --- a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs @@ -26,7 +26,7 @@ namespace ComputeSharp.NetCore.Tests { float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); - using ReadOnlyBuffer buffer = Gpu.Default.AllocateReadOnlyBuffer(array); + using ConstantBuffer buffer = Gpu.Default.AllocateConstantBuffer(array); float[] result = buffer.GetData(); Assert.IsTrue(array.AsSpan().ContentEquals(result)); @@ -52,7 +52,7 @@ namespace ComputeSharp.NetCore.Tests { float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); - using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(array); + using ConstantBuffer sourceBuffer = Gpu.Default.AllocateConstantBuffer(array); using ReadWriteBuffer destinationBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer); float[] sourceResult = sourceBuffer.GetData(); @@ -68,7 +68,7 @@ namespace ComputeSharp.NetCore.Tests float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); using ReadWriteBuffer sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(array); - using ReadOnlyBuffer destinationBuffer = Gpu.Default.AllocateReadOnlyBuffer(sourceBuffer); + using ConstantBuffer destinationBuffer = Gpu.Default.AllocateConstantBuffer(sourceBuffer); float[] sourceResult = sourceBuffer.GetData(); float[] destinationResult = destinationBuffer.GetData(); @@ -82,8 +82,8 @@ namespace ComputeSharp.NetCore.Tests { float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); - using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(array); - using ReadOnlyBuffer destinationBuffer = Gpu.Default.AllocateReadOnlyBuffer(sourceBuffer); + using ConstantBuffer sourceBuffer = Gpu.Default.AllocateConstantBuffer(array); + using ConstantBuffer destinationBuffer = Gpu.Default.AllocateConstantBuffer(sourceBuffer); float[] sourceResult = sourceBuffer.GetData(); float[] destinationResult = destinationBuffer.GetData(); diff --git a/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs b/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs index abda8eb8..9a23fcd5 100644 --- a/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs @@ -85,7 +85,7 @@ namespace ComputeSharp.NetCore.Tests { float[] source = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); - using ReadOnlyBuffer input = Gpu.Default.AllocateReadOnlyBuffer(source); + using ConstantBuffer input = Gpu.Default.AllocateConstantBuffer(source); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); Action action = id => buffer[id.X] = input[id.X];