From ee96c29f83445680f38fb9dfd0c1c3dde22d5bdd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 11:07:23 +0200 Subject: [PATCH 01/18] Updated mustache template for readonly buffers --- .../Renderer/Models/Fields/ConstantBufferFieldInfo.cs | 11 +++++++++-- .../Renderer/Templates/ShaderTemplate.mustache | 2 +- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs index 1f8c3160..4dbeeb51 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs @@ -12,10 +12,15 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields /// public bool IsConstantBuffer { get; } = true; + /// + /// Gets whether or not this constant buffer actually contains a single, explicit variable + /// + public bool IsSingleValue { get; } + /// /// Gets the index of the current constant buffer field /// - public int ConstantBufferIndex { get; set; } + public int ConstantBufferIndex { get; } /// /// Creates a new instance with the specified parameters @@ -23,9 +28,11 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields /// The type of the current field /// The name of the current field /// The index of the current constant buffer field - public ConstantBufferFieldInfo(string fieldType, string fieldName, int bufferIndex) : base(fieldType, fieldName) + /// 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) { ConstantBufferIndex = bufferIndex; + IsSingleValue = singleValue; } } } diff --git a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache index eee11e3e..70165909 100644 --- a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache +++ b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache @@ -7,7 +7,7 @@ static {{&FieldType}} {{FieldName}} = {{FieldValue}}; {{#IsConstantBuffer}} cbuffer {{FieldName}}Buffer : register(b{{ConstantBufferIndex}}) { -{{&FieldType}} {{FieldName}}; +{{&FieldType}} {{FieldName}}{{^IsSingleValue}}[2]{{/IsSingleValue}}; } {{/IsConstantBuffer}} {{!Read write buffer}} From 17e0be458f37513e14a07d45fe41fdc12585c7f1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 11:11:53 +0200 Subject: [PATCH 02/18] Added support for readonly buffers --- .../Mappings/HlslKnownTypes.cs | 9 +++++++++ .../Translation/ShaderLoader.cs | 14 ++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs index 32bf790d..aa25cae0 100644 --- a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs @@ -62,6 +62,15 @@ namespace ComputeSharp.Shaders.Mappings public static bool IsReadWriteBufferType(Type type) => type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ReadWriteBuffer<>); + /// + /// 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 IsReadOnlyBufferType(Type type) => type.IsGenericType && + type.GetGenericTypeDefinition() == typeof(ReadOnlyBuffer<>); + /// /// Checks whether or not a given is an HLSL known type /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 40859c0d..8039ddfb 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -107,7 +107,9 @@ namespace ComputeSharp.Shaders.Translation List descriptorRanges = new List(); List readWriteBuffers = new List(); + List readOnlyBuffers = new List(); int readWriteBuffersCount = 0; + int readOnlyBuffersCount = 0; foreach (FieldInfo fieldInfo in ShaderFields) { @@ -129,6 +131,18 @@ 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 + readOnlyBuffers.Add((GraphicsResource)fieldValue); + + string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); + processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, true); + } else if (HlslKnownTypes.IsKnownScalarType(fieldType)) { // Static scalar field From 50b754ac687580401409494ea346761e9b2d82bc Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 11:13:07 +0200 Subject: [PATCH 03/18] Fixed a bug in the constant buffer HLSL field declaration --- src/ComputeSharp.Shaders/Translation/ShaderLoader.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 8039ddfb..10c94663 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -141,7 +141,7 @@ namespace ComputeSharp.Shaders.Translation readOnlyBuffers.Add((GraphicsResource)fieldValue); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); - processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, true); + processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, false); } else if (HlslKnownTypes.IsKnownScalarType(fieldType)) { From cbb828033e2faf423c4dbacffa93f63cc1e39269 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 11:22:13 +0200 Subject: [PATCH 04/18] Fixed readonly buffers initialization --- src/ComputeSharp.Shaders/ShaderRunner.cs | 2 +- .../Translation/ShaderLoader.cs | 13 ++++++------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index 1b5cbe0e..150a5c2a 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -65,7 +65,7 @@ namespace ComputeSharp.Shaders commandList.SetPipelineState(pipelineState); // Load the captured buffers - foreach (var buffer in shaderLoader.ReadWriteBuffers.Select((r, i) => (Resource: r, Index: i))) + foreach (var buffer in shaderLoader.Buffers.Select((r, i) => (Resource: r, Index: i))) { commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource); } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 10c94663..2272dc18 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -59,9 +59,9 @@ namespace ComputeSharp.Shaders.Translation public RootParameter[] RootParameters { get; private set; } /// - /// Gets the ordered collection of read write buffers used as fields in the current shader + /// Gets the ordered collection of buffers used as fields in the current shader /// - public IReadOnlyList ReadWriteBuffers { get; private set; } + public IReadOnlyList Buffers { get; private set; } private readonly List _FieldsInfo = new List(); @@ -106,8 +106,7 @@ namespace ComputeSharp.Shaders.Translation if (ShaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body"); List descriptorRanges = new List(); - List readWriteBuffers = new List(); - List readOnlyBuffers = new List(); + List buffers = new List(); int readWriteBuffersCount = 0; int readOnlyBuffersCount = 0; @@ -126,7 +125,7 @@ namespace ComputeSharp.Shaders.Translation descriptorRanges.Add(range); // Reference to the underlying buffer - readWriteBuffers.Add((GraphicsResource)fieldValue); + buffers.Add((GraphicsResource)fieldValue); string typeName = HlslKnownTypes.GetMappedName(fieldType); processedFieldInfo = new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++); @@ -138,7 +137,7 @@ namespace ComputeSharp.Shaders.Translation descriptorRanges.Add(range); // Reference to the underlying buffer - readOnlyBuffers.Add((GraphicsResource)fieldValue); + buffers.Add((GraphicsResource)fieldValue); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, false); @@ -155,7 +154,7 @@ namespace ComputeSharp.Shaders.Translation } RootParameters = descriptorRanges.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray(); - ReadWriteBuffers = readWriteBuffers; + Buffers = buffers; } /// From 8699e037e7d59e61ecaa2a22d3af9dd48f2073f8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 11:34:48 +0200 Subject: [PATCH 05/18] Refactored some tests, removed unnecessary code --- .../ComputeSharp.NetCore.Tests/BufferTests.cs | 7 ++--- .../Extensions/SpanExtensions.cs | 15 ---------- .../Extensions/Types/ConcurrentRandom.cs | 28 ------------------- 3 files changed, 3 insertions(+), 47 deletions(-) delete mode 100644 tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs diff --git a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs index 90300354..444778cd 100644 --- a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using ComputeSharp.Graphics.Buffers; using ComputeSharp.NetCore.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -12,8 +13,7 @@ namespace ComputeSharp.NetCore.Tests [TestMethod] public void ReadWriteBufferGetSetData() { - float[] array = new float[4096]; - array.AsSpan().FillRandom(); + float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(array); float[] result = buffer.GetData(); @@ -24,8 +24,7 @@ namespace ComputeSharp.NetCore.Tests [TestMethod] public void ReadOnlyBufferGetSetData() { - float[] array = new float[4096]; - array.AsSpan().FillRandom(); + float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); using ReadOnlyBuffer buffer = Gpu.Default.AllocateReadOnlyBuffer(array); float[] result = buffer.GetData(); diff --git a/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs b/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs index bb52f8be..11ec9ddf 100644 --- a/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs +++ b/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs @@ -9,21 +9,6 @@ namespace ComputeSharp.NetCore.Tests.Extensions /// public static class SpanExtensions { - /// - /// Fills an input instance with random values - /// - /// The target to fill - public static void FillRandom(this Span span) - { - if (span.Length == 0) return; - - var l = span.Length; - ref var rspan = ref span.GetPinnableReference(); - - for (var i = 0; i < l; i++) - Unsafe.Add(ref rspan, i) = (float)ConcurrentRandom.Instance.NextDouble(); - } - /// /// The maximum threshold to validate two values as being equal /// diff --git a/tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs b/tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs deleted file mode 100644 index 5cbd72c0..00000000 --- a/tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Runtime.CompilerServices; -using System.Threading; - -namespace System -{ - /// - /// A thread-safe wrapper class - /// - public static class ConcurrentRandom - { - // Shared seed - private static int _Seed = Environment.TickCount; - - /// - /// The object that provides the instances - /// - private static readonly ThreadLocal _Instance = new ThreadLocal(() => new Random(Interlocked.Increment(ref _Seed))); - - /// - /// Gets a thread-safe instance - /// - public static Random Instance - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => _Instance.Value; - } - } -} \ No newline at end of file From a68ad249292acd24b268147e6061a39e3f2ea767 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 16:16:51 +0200 Subject: [PATCH 06/18] Added HlslBuffer class --- .../Buffers/Abstract/HlslBuffer{T}.cs | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs new file mode 100644 index 00000000..1d8fa479 --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -0,0 +1,47 @@ +using System; +using System.Diagnostics.Contracts; +using SharpDX.Direct3D12; + +namespace ComputeSharp.Graphics.Buffers.Abstract +{ + /// + /// A representing a typed buffer stored on GPU memory, that can be used from an HLSL shader + /// + /// The type of items stored on the buffer + public abstract class HlslBuffer : Buffer 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 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) { } + + /// + /// 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 abstract void GetData(Span span); + + /// + /// Writes the contents of a given to the current instance + /// + /// The input to read data from + public abstract void SetData(Span span); + } +} From 12198f9943e70b6bc77cb7f6e2c80c0cb1f8dcae Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 16:21:50 +0200 Subject: [PATCH 07/18] Updated buffer types to implement the new architecture --- src/ComputeSharp.Graphics/Buffers/Buffer.cs | 103 ++++-------------- .../Buffers/ReadOnlyBuffer{T}.cs | 26 ++++- .../Buffers/ReadWriteBuffer{T}.cs | 21 +++- 3 files changed, 62 insertions(+), 88 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Buffer.cs b/src/ComputeSharp.Graphics/Buffers/Buffer.cs index 703bc324..557e8428 100644 --- a/src/ComputeSharp.Graphics/Buffers/Buffer.cs +++ b/src/ComputeSharp.Graphics/Buffers/Buffer.cs @@ -1,8 +1,6 @@ -using System; -using System.Diagnostics.Contracts; +using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Helpers; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers @@ -18,12 +16,13 @@ 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, HeapType heapType) : base(device) + protected internal Buffer(GraphicsDevice device, int size, int sizeInBytes, HeapType heapType) : base(device) { Size = size; ElementSizeInBytes = Unsafe.SizeOf(); - SizeInBytes = Size * ElementSizeInBytes; + SizeInBytes = sizeInBytes; // Not necessarily a multiple of the element size, as there could be padding HeapType = heapType; ResourceFlags flags = heapType == HeapType.Default ? ResourceFlags.AllowUnorderedAccess : ResourceFlags.None; @@ -45,6 +44,21 @@ namespace ComputeSharp.Graphics.Buffers }; } + /// + /// 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 + /// + protected int SizeInBytes { get; } + + /// + /// Gets the size in bytes of each value contained in the buffer + /// + protected int ElementSizeInBytes { get; } + /// /// Creates the descriptors for a constant buffer /// @@ -88,88 +102,9 @@ namespace ComputeSharp.Graphics.Buffers 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; } - - /// - /// 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); - } - } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index c86d4084..f0f2a2a0 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -1,4 +1,6 @@ using System; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Buffers.Abstract; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers @@ -7,14 +9,22 @@ 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 ReadOnlyBuffer : Buffer where T : unmanaged + public sealed class ReadOnlyBuffer : 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 ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, HeapType.Upload) { } + internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, size * (Unsafe.SizeOf() / 16 + 1), HeapType.Upload) + { + PaddedElementSizeInBytes = SizeInBytes / Size; + } + + /// + /// Gets the size in bytes of the current buffer + /// + private int PaddedElementSizeInBytes { get; } /// /// Gets a single value from the current read write buffer @@ -22,5 +32,17 @@ namespace ComputeSharp.Graphics.Buffers /// 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) + { + throw new NotImplementedException(); + } + + /// + public override void SetData(Span span) + { + throw new NotImplementedException(); + } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index ded6d1e9..2a2a4c9e 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -1,4 +1,6 @@ using System; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Buffers.Abstract; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers @@ -7,14 +9,17 @@ 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 : Buffer where T : unmanaged + public sealed class ReadWriteBuffer : 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 ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, HeapType.Default) { } + internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, size * Unsafe.SizeOf(), HeapType.Default) + { + + } /// /// Gets or sets a single value from the current read write buffer @@ -26,5 +31,17 @@ 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) + { + throw new NotImplementedException(); + } + + /// + public override void SetData(Span span) + { + throw new NotImplementedException(); + } } } From 1298f1757a75d1c8eac148c6777208549a3da827 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 16:40:49 +0200 Subject: [PATCH 08/18] Reimplemented get and set methods to read write buffer --- .../Buffers/ReadWriteBuffer{T}.cs | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index 2a2a4c9e..446719b5 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -1,6 +1,7 @@ using System; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Helpers; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers @@ -16,10 +17,7 @@ namespace ComputeSharp.Graphics.Buffers /// /// 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, size * Unsafe.SizeOf(), HeapType.Default) { } /// /// Gets or sets a single value from the current read write buffer @@ -35,13 +33,29 @@ namespace ComputeSharp.Graphics.Buffers /// public override void GetData(Span span) { - throw new NotImplementedException(); + 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(true); + + readbackBaffer.Map(0); + MemoryHelper.Copy(readbackBaffer.MappedResource, span); + readbackBaffer.Unmap(0); } /// public override void SetData(Span span) { - throw new NotImplementedException(); + using Buffer uploadBuffer = new Buffer(GraphicsDevice, Size, SizeInBytes, HeapType.Upload); + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + uploadBuffer.Map(0); + MemoryHelper.Copy(span, uploadBuffer.MappedResource); + uploadBuffer.Unmap(0); + + copyCommandList.CopyBufferRegion(uploadBuffer, 0, this, 0, SizeInBytes); + copyCommandList.Flush(true); } } } From d6d1fc2624e362b9627daa2c8088b8f1ad1a7f46 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 16:55:25 +0200 Subject: [PATCH 09/18] Reimplemented get and set methods to readonly buffer --- .../Buffers/ReadOnlyBuffer{T}.cs | 39 ++++++++++++++++++- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index f0f2a2a0..5ede775c 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -1,6 +1,8 @@ using System; +using System.Buffers; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Helpers; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers @@ -36,13 +38,46 @@ namespace ComputeSharp.Graphics.Buffers /// public override void GetData(Span span) { - throw new NotImplementedException(); + byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); + Span temporarySpan = temporaryArray.AsSpan(); + + Map(0); + MemoryHelper.Copy(MappedResource, temporarySpan); + Unmap(0); + + ref byte tin = ref temporarySpan.GetPinnableReference(); + ref T tout = ref span.GetPinnableReference(); + + 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); } /// public override void SetData(Span span) { - throw new NotImplementedException(); + byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); + Span temporarySpan = temporaryArray.AsSpan(); + ref T tin = ref span.GetPinnableReference(); + ref byte tout = ref temporarySpan.GetPinnableReference(); + + temporarySpan.Clear(); + + 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); + } + + Map(0); + MemoryHelper.Copy(temporarySpan, MappedResource); + Unmap(0); + + ArrayPool.Shared.Return(temporaryArray); } } } From 5ff2b2d4e0381ed6eee264d4b4ad1f2042201207 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 19:50:35 +0200 Subject: [PATCH 10/18] Fixed a bug in the read only buffer initialization --- src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 5ede775c..2ff26f04 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -18,7 +18,7 @@ namespace ComputeSharp.Graphics.Buffers /// /// 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), HeapType.Upload) + internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, size * (Unsafe.SizeOf() / 16 + 1) * 16, HeapType.Upload) { PaddedElementSizeInBytes = SizeInBytes / Size; } @@ -61,7 +61,7 @@ namespace ComputeSharp.Graphics.Buffers public override void SetData(Span span) { byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); - Span temporarySpan = temporaryArray.AsSpan(); + Span temporarySpan = temporaryArray.AsSpan(0, SizeInBytes); // Array pool arrays can be longer ref T tin = ref span.GetPinnableReference(); ref byte tout = ref temporarySpan.GetPinnableReference(); From 96232a95384fdfc158a2edfc7b5b412c5d47de71 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:15:33 +0200 Subject: [PATCH 11/18] Readonly buffer optimized when no padding is needed --- .../Buffers/ReadOnlyBuffer{T}.cs | 82 ++++++++++++------- 1 file changed, 54 insertions(+), 28 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 2ff26f04..04a7d5c9 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -38,46 +38,72 @@ namespace ComputeSharp.Graphics.Buffers /// public override void GetData(Span span) { - byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); - Span temporarySpan = temporaryArray.AsSpan(); - - Map(0); - MemoryHelper.Copy(MappedResource, temporarySpan); - Unmap(0); - - ref byte tin = ref temporarySpan.GetPinnableReference(); - ref T tout = ref span.GetPinnableReference(); - - for (int i = 0; i < Size; i++) + // Directly copy the data back if there is no padding + if (PaddedElementSizeInBytes == ElementSizeInBytes) { - ref byte rsource = ref Unsafe.Add(ref tin, i * PaddedElementSizeInBytes); - Unsafe.Add(ref tout, i) = Unsafe.As(ref rsource); + Map(0); + MemoryHelper.Copy(MappedResource, span); + Unmap(0); } + else + { + // Create the temporary array + byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); + Span temporarySpan = temporaryArray.AsSpan(); - ArrayPool.Shared.Return(temporaryArray); + // 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); + } } /// public override void SetData(Span span) { - 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(); - - temporarySpan.Clear(); - - for (int i = 0; i < Size; i++) + // Directly copy the input span if there is no padding + if (PaddedElementSizeInBytes == ElementSizeInBytes) { - ref byte rtarget = ref Unsafe.Add(ref tout, i * PaddedElementSizeInBytes); - Unsafe.As(ref rtarget) = Unsafe.Add(ref tin, i); + Map(0); + MemoryHelper.Copy(span, MappedResource); + Unmap(0); } + else + { + // 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(); - Map(0); - MemoryHelper.Copy(temporarySpan, MappedResource); - Unmap(0); + temporarySpan.Clear(); - ArrayPool.Shared.Return(temporaryArray); + // 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); + } } } } From 244b3535d46fd1f47d5271b05703cfe678fcd05e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:16:17 +0200 Subject: [PATCH 12/18] Removed unnecessary buffer cleanup operation --- src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 04a7d5c9..52427119 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -88,8 +88,6 @@ namespace ComputeSharp.Graphics.Buffers ref T tin = ref span.GetPinnableReference(); ref byte tout = ref temporarySpan.GetPinnableReference(); - temporarySpan.Clear(); - // Copy the input data to the temporary array and add the padding for (int i = 0; i < Size; i++) { From 984d1113f820ae0b7ec4ee74823c51ad1a53c8a5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:33:52 +0200 Subject: [PATCH 13/18] Added APIs to set buffers from existing buffers --- .../Buffers/Abstract/HlslBuffer{T}.cs | 12 ++++ .../Buffers/ReadOnlyBuffer{T}.cs | 65 ++++++++++++++----- .../Buffers/ReadWriteBuffer{T}.cs | 47 +++++++++++++- 3 files changed, 106 insertions(+), 18 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index 1d8fa479..34d3befd 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -43,5 +43,17 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// /// The input to read data from public abstract void SetData(Span span); + + /// + /// Writes the contents of a given to the current instance + /// + /// The input to read data from + public abstract void SetData(ReadOnlyBuffer buffer); + + /// + /// Writes the contents of a given to the current instance + /// + /// The input to read data from + public abstract void SetData(ReadWriteBuffer buffer); } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 52427119..4ceeea12 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -21,12 +21,18 @@ namespace ComputeSharp.Graphics.Buffers internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, size * (Unsafe.SizeOf() / 16 + 1) * 16, HeapType.Upload) { PaddedElementSizeInBytes = SizeInBytes / Size; + IsPaddingPresent = PaddedElementSizeInBytes > ElementSizeInBytes; } /// /// Gets the size in bytes of the current buffer /// - private int PaddedElementSizeInBytes { get; } + 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 @@ -38,14 +44,7 @@ namespace ComputeSharp.Graphics.Buffers /// public override void GetData(Span span) { - // Directly copy the data back if there is no padding - if (PaddedElementSizeInBytes == ElementSizeInBytes) - { - Map(0); - MemoryHelper.Copy(MappedResource, span); - Unmap(0); - } - else + if (IsPaddingPresent) { // Create the temporary array byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); @@ -68,19 +67,19 @@ namespace ComputeSharp.Graphics.Buffers 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) { - // Directly copy the input span if there is no padding - if (PaddedElementSizeInBytes == ElementSizeInBytes) - { - Map(0); - MemoryHelper.Copy(span, MappedResource); - Unmap(0); - } - else + if (IsPaddingPresent) { // Create the temporary array byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); @@ -102,6 +101,38 @@ namespace ComputeSharp.Graphics.Buffers 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(ReadOnlyBuffer buffer) + { + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); + copyCommandList.Flush(true); + } + + /// + public override void SetData(ReadWriteBuffer buffer) + { + // Create a temporary array + T[] array = ArrayPool.Shared.Rent(buffer.Size); + Span span = array.AsSpan(buffer.Size); + + // Get the unpadded data from the read write buffer + buffer.GetData(span); + + // Set the data, adding the padding if needed + SetData(span); + + ArrayPool.Shared.Return(array); } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index 446719b5..4414c1b1 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Graphics.Helpers; @@ -48,14 +49,58 @@ namespace ComputeSharp.Graphics.Buffers public override void SetData(Span span) { using Buffer uploadBuffer = new Buffer(GraphicsDevice, Size, SizeInBytes, HeapType.Upload); - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); 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(true); } + + /// + public override void SetData(ReadOnlyBuffer buffer) + { + if (buffer.IsPaddingPresent) + { + // Create a temporary array + T[] array = ArrayPool.Shared.Rent(buffer.Size); + Span span = array.AsSpan(buffer.Size); + + // Get the data from the readonly array, removing the padding + buffer.GetData(span); + + // Set the data to the current buffer + SetData(span); + + ArrayPool.Shared.Return(array); + } + else + { + // Directly copy the input buffer + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); + copyCommandList.Flush(true); + } + } + + /// + public override void SetData(ReadWriteBuffer buffer) + { + // Create a temporary array + T[] array = ArrayPool.Shared.Rent(buffer.Size); + Span span = array.AsSpan(buffer.Size); + + // Get the unpadded data from the read write buffer + buffer.GetData(span); + + // Set the data to the current buffer + SetData(span); + + ArrayPool.Shared.Return(array); + } } } From 9edbdcfdc3b9d1bf55d7033f887d6dec618b804f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:38:39 +0200 Subject: [PATCH 14/18] Code refactoring --- .../Buffers/Abstract/HlslBuffer{T}.cs | 24 ++++++++++++-- .../Buffers/ReadOnlyBuffer{T}.cs | 16 ---------- .../Buffers/ReadWriteBuffer{T}.cs | 31 +------------------ 3 files changed, 23 insertions(+), 48 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index 34d3befd..d0873434 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers; using System.Diagnostics.Contracts; using SharpDX.Direct3D12; @@ -48,12 +49,31 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// Writes the contents of a given to the current instance /// /// The input to read data from - public abstract void SetData(ReadOnlyBuffer buffer); + public virtual void SetData(ReadOnlyBuffer buffer) => SetDataWithCpuBuffer(buffer); /// /// Writes the contents of a given to the current instance /// /// The input to read data from - public abstract void SetData(ReadWriteBuffer buffer); + public virtual void SetData(ReadWriteBuffer buffer) => SetDataWithCpuBuffer(buffer); + + /// + /// Writes the contents of a given to the current instance, using a temporary CPU buffer + /// + /// The input to read data from + protected void SetDataWithCpuBuffer(HlslBuffer buffer) + { + // Create a temporary array + T[] array = ArrayPool.Shared.Rent(buffer.Size); + Span span = array.AsSpan(buffer.Size); + + // Get the unpadded data from the read write buffer + buffer.GetData(span); + + // Set the data, adding the padding if needed + SetData(span); + + ArrayPool.Shared.Return(array); + } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 4ceeea12..8aac27b4 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -118,21 +118,5 @@ namespace ComputeSharp.Graphics.Buffers copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); copyCommandList.Flush(true); } - - /// - public override void SetData(ReadWriteBuffer buffer) - { - // Create a temporary array - T[] array = ArrayPool.Shared.Rent(buffer.Size); - Span span = array.AsSpan(buffer.Size); - - // Get the unpadded data from the read write buffer - buffer.GetData(span); - - // Set the data, adding the padding if needed - SetData(span); - - ArrayPool.Shared.Return(array); - } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index 4414c1b1..a444baa8 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -63,20 +63,7 @@ namespace ComputeSharp.Graphics.Buffers /// public override void SetData(ReadOnlyBuffer buffer) { - if (buffer.IsPaddingPresent) - { - // Create a temporary array - T[] array = ArrayPool.Shared.Rent(buffer.Size); - Span span = array.AsSpan(buffer.Size); - - // Get the data from the readonly array, removing the padding - buffer.GetData(span); - - // Set the data to the current buffer - SetData(span); - - ArrayPool.Shared.Return(array); - } + if (buffer.IsPaddingPresent) SetDataWithCpuBuffer(buffer); else { // Directly copy the input buffer @@ -86,21 +73,5 @@ namespace ComputeSharp.Graphics.Buffers copyCommandList.Flush(true); } } - - /// - public override void SetData(ReadWriteBuffer buffer) - { - // Create a temporary array - T[] array = ArrayPool.Shared.Rent(buffer.Size); - Span span = array.AsSpan(buffer.Size); - - // Get the unpadded data from the read write buffer - buffer.GetData(span); - - // Set the data to the current buffer - SetData(span); - - ArrayPool.Shared.Return(array); - } } } From 8abf928b4507a4e9c545bdca27f5ca2d81273f70 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:44:35 +0200 Subject: [PATCH 15/18] More code refactoring --- .../Buffers/Abstract/HlslBuffer{T}.cs | 12 +++--------- .../Buffers/ReadOnlyBuffer{T}.cs | 13 +++++++++---- .../Buffers/ReadWriteBuffer{T}.cs | 6 +++--- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index d0873434..f3f915e4 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -46,16 +46,10 @@ namespace ComputeSharp.Graphics.Buffers.Abstract public abstract void SetData(Span span); /// - /// Writes the contents of a given to the current instance + /// Writes the contents of a given to the current instance /// - /// The input to read data from - public virtual void SetData(ReadOnlyBuffer buffer) => SetDataWithCpuBuffer(buffer); - - /// - /// Writes the contents of a given to the current instance - /// - /// The input to read data from - public virtual void SetData(ReadWriteBuffer buffer) => SetDataWithCpuBuffer(buffer); + /// The input to read data from + public abstract void SetData(HlslBuffer buffer); /// /// Writes the contents of a given to the current instance, using a temporary CPU buffer diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 8aac27b4..09635da1 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -111,12 +111,17 @@ namespace ComputeSharp.Graphics.Buffers } /// - public override void SetData(ReadOnlyBuffer buffer) + public override void SetData(HlslBuffer buffer) { - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + if (buffer is ReadOnlyBuffer 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(true); + copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); + copyCommandList.Flush(true); + } + else SetDataWithCpuBuffer(buffer); } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index a444baa8..c0d5c50f 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -61,10 +61,9 @@ namespace ComputeSharp.Graphics.Buffers } /// - public override void SetData(ReadOnlyBuffer buffer) + public override void SetData(HlslBuffer buffer) { - if (buffer.IsPaddingPresent) SetDataWithCpuBuffer(buffer); - else + if (buffer is ReadOnlyBuffer readOnlyBuffer && !readOnlyBuffer.IsPaddingPresent) { // Directly copy the input buffer using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); @@ -72,6 +71,7 @@ namespace ComputeSharp.Graphics.Buffers copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); copyCommandList.Flush(true); } + else SetDataWithCpuBuffer(buffer); } } } From ea5e460c9f006512f0ab12503f04e3d49626baf7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:47:30 +0200 Subject: [PATCH 16/18] Added new buffer extension methods --- .../Buffers/Extensions/BufferExtensions.cs | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs index 33e0fe69..2f3c0ae3 100644 --- a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs +++ b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs @@ -3,6 +3,7 @@ using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers; +using ComputeSharp.Graphics.Buffers.Abstract; namespace ComputeSharp { @@ -74,6 +75,23 @@ namespace ComputeSharp return buffer; } + /// + /// Allocates a new read write 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 ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, HlslBuffer buffer) where T : unmanaged + { + ReadWriteBuffer readWriteBuffer = new ReadWriteBuffer(device, buffer.Size); + readWriteBuffer.SetData(buffer); + + return readWriteBuffer; + } + /// /// Allocates a new constant buffer with the specified parameters /// @@ -122,5 +140,22 @@ namespace ComputeSharp 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; + } } } From fc1589800836c2d4ad176790de1c3f76144be131 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:56:08 +0200 Subject: [PATCH 17/18] Minor bug fixes --- src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs | 2 +- src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index f3f915e4..bde98d3e 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -59,7 +59,7 @@ namespace ComputeSharp.Graphics.Buffers.Abstract { // Create a temporary array T[] array = ArrayPool.Shared.Rent(buffer.Size); - Span span = array.AsSpan(buffer.Size); + Span span = array.AsSpan(0, buffer.Size); // Get the unpadded data from the read write buffer buffer.GetData(span); diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 09635da1..5bab1210 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -113,7 +113,7 @@ namespace ComputeSharp.Graphics.Buffers /// public override void SetData(HlslBuffer buffer) { - if (buffer is ReadOnlyBuffer readOnlyBuffer) + if (buffer is ReadOnlyBuffer) { // Directly copy the input buffer, if possible using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); From 55e6daa89b494d0db5f46cf7d42d7957d4cfb18a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:57:24 +0200 Subject: [PATCH 18/18] Added tests for the new buffer APIs --- .../ComputeSharp.NetCore.Tests/BufferTests.cs | 64 ++++++++++++++++++- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs index 444778cd..5040ea07 100644 --- a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs @@ -11,7 +11,7 @@ namespace ComputeSharp.NetCore.Tests public class BufferTests { [TestMethod] - public void ReadWriteBufferGetSetData() + public void ReadWriteBufferGetSetDataFromArray() { float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); @@ -22,7 +22,7 @@ namespace ComputeSharp.NetCore.Tests } [TestMethod] - public void ReadOnlyBufferGetSetData() + public void ReadOnlyBufferGetSetDataFromArray() { float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); @@ -31,5 +31,65 @@ namespace ComputeSharp.NetCore.Tests Assert.IsTrue(array.AsSpan().ContentEquals(result)); } + + [TestMethod] + public void ReadWriteBufferGetSetDataFromReadWriteBuffer() + { + float[] array = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + using ReadWriteBuffer sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(array); + using ReadWriteBuffer destinationBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer); + + float[] sourceResult = sourceBuffer.GetData(); + float[] destinationResult = destinationBuffer.GetData(); + + Assert.IsTrue(array.AsSpan().ContentEquals(sourceResult)); + Assert.IsTrue(array.AsSpan().ContentEquals(destinationResult)); + } + + [TestMethod] + public void ReadWriteBufferGetSetDataFromReadOnlyBuffer() + { + float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); + + using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(array); + using ReadWriteBuffer destinationBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer); + + float[] sourceResult = sourceBuffer.GetData(); + float[] destinationResult = destinationBuffer.GetData(); + + Assert.IsTrue(array.AsSpan().ContentEquals(sourceResult)); + Assert.IsTrue(array.AsSpan().ContentEquals(destinationResult)); + } + + [TestMethod] + public void ReadOnlyBufferGetSetDataFromReadWriteBuffer() + { + 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); + + float[] sourceResult = sourceBuffer.GetData(); + float[] destinationResult = destinationBuffer.GetData(); + + Assert.IsTrue(array.AsSpan().ContentEquals(sourceResult)); + Assert.IsTrue(array.AsSpan().ContentEquals(destinationResult)); + } + + [TestMethod] + public void ReadOnlyBufferGetSetDataFromReadOnlyBuffer() + { + 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); + + float[] sourceResult = sourceBuffer.GetData(); + float[] destinationResult = destinationBuffer.GetData(); + + Assert.IsTrue(array.AsSpan().ContentEquals(sourceResult)); + Assert.IsTrue(array.AsSpan().ContentEquals(destinationResult)); + } } }