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..bde98d3e --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -0,0 +1,73 @@ +using System; +using System.Buffers; +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); + + /// + /// Writes the contents of a given to the current instance + /// + /// 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 + /// + /// 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(0, 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/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/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; + } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index c86d4084..5bab1210 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -1,4 +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 @@ -7,14 +11,28 @@ 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) * 16, HeapType.Upload) + { + PaddedElementSizeInBytes = SizeInBytes / Size; + IsPaddingPresent = PaddedElementSizeInBytes > ElementSizeInBytes; + } + + /// + /// Gets the size in bytes of the current 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 @@ -22,5 +40,88 @@ 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) + { + 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(true); + } + else SetDataWithCpuBuffer(buffer); + } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index ded6d1e9..c0d5c50f 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -1,4 +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 @@ -7,14 +11,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 : 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 +30,48 @@ 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(true); + + 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(true); + } + + /// + 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(true); + } + else SetDataWithCpuBuffer(buffer); + } } } 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/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}} 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 8b9e43eb..b58a597b 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,9 @@ 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 buffers = new List(); int readWriteBuffersCount = 0; + int readOnlyBuffersCount = 0; foreach (FieldInfo fieldInfo in ShaderFields) { @@ -124,11 +125,23 @@ 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++); } + 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((GraphicsResource)fieldValue); + + string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); + processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, false); + } else if (HlslKnownTypes.IsKnownScalarType(fieldType)) { // Static scalar field @@ -141,7 +154,7 @@ namespace ComputeSharp.Shaders.Translation } RootParameters = descriptorRanges.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray(); - ReadWriteBuffers = readWriteBuffers; + Buffers = buffers; } /// diff --git a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs index 90300354..5040ea07 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; @@ -10,10 +11,9 @@ namespace ComputeSharp.NetCore.Tests public class BufferTests { [TestMethod] - public void ReadWriteBufferGetSetData() + public void ReadWriteBufferGetSetDataFromArray() { - 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(); @@ -22,15 +22,74 @@ namespace ComputeSharp.NetCore.Tests } [TestMethod] - public void ReadOnlyBufferGetSetData() + public void ReadOnlyBufferGetSetDataFromArray() { - 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(); 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)); + } } } 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