diff --git a/README.md b/README.md new file mode 100644 index 00000000..5ab5c062 --- /dev/null +++ b/README.md @@ -0,0 +1,83 @@ +![](https://i.imgur.com/ufWcoO6.png) +[![NuGet](https://img.shields.io/nuget/v/ComputeSharp.svg)](https://www.nuget.org/packages/ComputeSharp/) [![NuGet](https://img.shields.io/nuget/dt/ComputeSharp.svg)](https://www.nuget.org/stats/packages/ComputeSharp?groupby=Version) [![Twitter Follow](https://img.shields.io/twitter/follow/Sergio0694.svg?style=flat&label=Follow)](https://twitter.com/SergioPedri) + +# What is it? + +**ComputeSharp** is a .NET Standard 2.0 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders. The available APIs let you allocate GPU buffers and write compute shaders as simple lambda expressions or local methods, with all the captured variables being handled automatically and passed to the running shader. + +# Table of Contents + +- [Installing from NuGet](#installing-from-nuget) +- [Quick start](#quick-start) + - [Capturing variables](#capturing-variables) + - [Advanced usage](#advanced-usage) +- [Requirements](#requirements) + +# Installing from NuGet + +To install **ComputeSharp**, run the following command in the **Package Manager Console** + +``` +Install-Package ComputeSharp +``` + +More details available [here](https://www.nuget.org/packages/ComputeSharp/). + +# Quick start + +**ComputeSharp** exposes a `Gpu` class that acts as the entry point for all public APIs. It exposes the `Gpu.Default` property that let you access the main GPU device on the current machine, which can be used to allocate buffers and perform operations. + +The following sample shows how to allocate a writeable buffer, populate it with a compute shader, and read it back. + +```C# +// Allocate a writeable buffer on the GPU, with the contents of the array +using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1000); + +// Shader body +Action action = id => buffer[id.X] = id.X; + +// Run the shader +Gpu.Default.For(1000, action); + +// Get the data back +float[] array = buffer.GetData(); +``` + +## Capturing variables + +If the shader in C# is capturing some local variable, those will be automatically copied over to the GPU, so that the HLSL shader will be able to access them just like you'd expect. Just make sure to only capture valid HLSL types: either scalar types (`int`, `uint`, `float`, etc.), known HLSL structs (eg. `Vector3`) or unmanaged custom structs. + +## Advanced usage + +**ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for readonly buffers, and more. Here is a more advanced sample showcasing both these two features. + +```C# +int height = 10, width = 10; +float[] x = new float[height * width]; // Array to sum to y +float[] y = new float[height * width]; // Result array (assume both had some values) + +using ReadOnlyBuffer xBuffer = Gpu.Default.AllocateConstantBuffer(x); +using ReadWriteBuffer yBuffer = Gpu.Default.AllocateReadWriteBuffer(y); + +// Shader body +Action action = id => +{ + uint offset = id.X + id.Y * (uint)width; + yBuffer[offset] += xBuffer[offset]; +}; + +// Run the shader +Gpu.Default.For(width, height, action); + +// Get the data back and write it to the y array +yBuffer.GetData(y); +``` + +# Requirements + +The **ComputeSharp** library requires .NET Standard 2.0 support, and it is available for applications targeting: +- .NET Framework >= 4.6.1 +- .NET Core >= 2.0 +- UWP (from SDK 10.0.16299, and only in `Debug` mode for now) + +Additionally, you need an IDE with .NET Core 3.0 and C# 8.0 support to compile the library on your PC. 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 28dc83ff..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 /// @@ -83,9 +101,9 @@ namespace ComputeSharp /// A constant instance with the contents of the input array [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer AllocateConstantBuffer(this GraphicsDevice device, T[] array) where T : unmanaged + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, T[] array) where T : unmanaged { - return device.AllocateConstantBuffer(array.AsSpan()); + return device.AllocateReadOnlyBuffer(array.AsSpan()); } /// @@ -97,12 +115,12 @@ namespace ComputeSharp /// A constant instance with the contents of the input 2D array [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe ReadOnlyBuffer AllocateConstantBuffer(this GraphicsDevice device, T[,] array) where T : unmanaged + 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.AllocateConstantBuffer(span); + return device.AllocateReadOnlyBuffer(span); } } @@ -115,12 +133,29 @@ namespace ComputeSharp /// A constant instance with the contents of the input [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer AllocateConstantBuffer(this GraphicsDevice device, Span span) where T : unmanaged + 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/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.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index 8aeb3983..0a6adde2 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -2,6 +2,8 @@ using System.Threading; using SharpDX.Direct3D; using SharpDX.Direct3D12; +using SharpDX.DXGI; +using Device = SharpDX.Direct3D12.Device; namespace ComputeSharp.Graphics { @@ -9,12 +11,15 @@ namespace ComputeSharp.Graphics { private readonly AutoResetEvent fenceEvent = new AutoResetEvent(false); - public GraphicsDevice(bool enableDebugLayer = false) + /// + /// Creates a new instance for the input + /// + /// The to use for the new instance + /// The available info for the new instance + public GraphicsDevice(Device device, AdapterDescription description) { -#if DEBUG - if (enableDebugLayer) DebugInterface.Get().EnableDebugLayer(); -#endif - NativeDevice = new Device(null, FeatureLevel); + NativeDevice = device; + Description = description; WavefrontSize = NativeDevice.D3D12Options1.WaveLaneCountMin; NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Compute)); @@ -41,6 +46,11 @@ namespace ComputeSharp.Graphics CopyCommandList.Close(); } + /// + /// Gets the available info for the current instance + /// + public AdapterDescription Description { get; } + /// /// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width") /// diff --git a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs new file mode 100644 index 00000000..25547e65 --- /dev/null +++ b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs @@ -0,0 +1,40 @@ +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using SharpDX.DXGI; +using Device = SharpDX.Direct3D12.Device; + +namespace ComputeSharp.Graphics.Helpers +{ + /// + /// A with methods to inspect the available devices on the current machine + /// + public static class DeviceHelper + { + /// + /// Gets a collection of all the supported devices on the current machine + /// + /// The collection of objects with support for DX12.1 + [Pure] + public static IReadOnlyList<(Device, AdapterDescription)> QueryAllSupportedDevices() + { + using Factory factory = new Factory1(); + List<(Device, AdapterDescription)> devices = new List<(Device, AdapterDescription)>(); + + foreach (Adapter adapter in factory.Adapters) + { + if (adapter.Description.DedicatedVideoMemory == 0) continue; + try + { + Device device = new Device(adapter, GraphicsDevice.FeatureLevel); + devices.Add((device, adapter.Description)); + } + catch + { + // Unsupported device + } + } + + return devices; + } + } +} diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index 086f0e66..cc3f7086 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -13,8 +13,8 @@ - + 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/ShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs index f9aeb680..c9161fba 100644 --- a/src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs @@ -3,6 +3,7 @@ using System.Diagnostics.Contracts; using System.IO; using System.Reflection; using ComputeSharp.Shaders.Renderer.Models; +using Stubble.Core; namespace ComputeSharp.Shaders.Renderer { @@ -39,6 +40,6 @@ namespace ComputeSharp.Shaders.Renderer /// The input instance with the shader information /// The source code for the new HLSL shader [Pure] - public string Render(ShaderInfo info) => Nustache.Core.Render.StringToString(Template, info); + public string Render(ShaderInfo info) => StaticStubbleRenderer.Render(Template, info); } } 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/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index 20c2a95a..9a5682c3 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; +using System.Text.RegularExpressions; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.CSharp; using ICSharpCode.Decompiler.Metadata; @@ -97,6 +98,11 @@ namespace ComputeSharp.Shaders.Translation } } + /// + /// A uused to preprocess the entry point declaration for both lambda expressions and local methods + /// + private static readonly Regex LambdaMethodDeclarationRegex = new Regex(@"^(private|internal) void <\w+>[\w_|]+(?=\()", RegexOptions.Compiled); + /// /// Decompiles a target method and returns its and info /// @@ -117,10 +123,13 @@ namespace ComputeSharp.Shaders.Translation Decompilers.Add(assemblyPath, decompiler); } - string sourceCode = decompiler.DecompileAsString(methodHandle); + // Decompile the method source and fix the method declaration for local methods converted to lambdas + string + sourceCode = decompiler.DecompileAsString(methodHandle), + fixedCode = LambdaMethodDeclarationRegex.Replace(sourceCode, "internal void Main"); // Load the method syntax tree - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(fixedCode); rootNode = syntaxTree.GetRoot(); // Update the incremental compilation and retrieve the syntax tree for the method diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index acdeac27..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(); @@ -103,9 +103,12 @@ namespace ComputeSharp.Shaders.Translation { if (FieldsInfo.Count > 0) throw new InvalidOperationException("Shader fields already loaded"); + 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) { @@ -122,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 @@ -139,7 +154,7 @@ namespace ComputeSharp.Shaders.Translation } RootParameters = descriptorRanges.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray(); - ReadWriteBuffers = readWriteBuffers; + Buffers = buffers; } /// @@ -155,7 +170,7 @@ namespace ComputeSharp.Shaders.Translation root = syntaxRewriter.Visit(root); // Get the thread ids identifier name and shader method body - ConstructorDeclarationSyntax methodNode = root.ChildNodes().OfType().First(); + MethodDeclarationSyntax methodNode = root.ChildNodes().OfType().First(); ThreadsIdsVariableName = methodNode.ParameterList.Parameters.First().Identifier.Text; MethodBody = methodNode.Body.ToFullString(); diff --git a/src/ComputeSharp.sln b/src/ComputeSharp.sln index 56d82d29..daaf3fd2 100644 --- a/src/ComputeSharp.sln +++ b/src/ComputeSharp.sln @@ -18,6 +18,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_SolutionItems", "_Solution EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.NetCore.Tests", "..\tests\ComputeSharp.NetCore.Tests\ComputeSharp.NetCore.Tests.csproj", "{E91F4D24-922A-4921-A8D7-9C45A143C45D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -58,12 +62,21 @@ Global {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|Any CPU.Build.0 = Release|Any CPU {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|x64.ActiveCfg = Release|Any CPU {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|x64.Build.0 = Release|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|x64.ActiveCfg = Debug|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|x64.Build.0 = Debug|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|Any CPU.Build.0 = Release|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|x64.ActiveCfg = Release|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {7A48A85D-8866-4DED-A404-653ED09BF396} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} + {E91F4D24-922A-4921-A8D7-9C45A143C45D} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 57aeb7e6..9cb9e6f1 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -4,6 +4,17 @@ netstandard2.0 8.0 enable + 1.0.0-alpha+85bfe4f636407cb9f41ce1c8856c662b634399f0 + Sergio Pedri + true + true + A .NET Standard 2.0 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders + Copyright (c) 2019 Sergio Pedri + LICENSE + https://github.com/Sergio0694/ComputeSharp + https://github.com/Sergio0694/ComputeSharp + dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu + https://i.imgur.com/oo8dA0q.png @@ -17,4 +28,11 @@ + + + True + + + + diff --git a/src/ComputeSharp/Gpu.cs b/src/ComputeSharp/Gpu.cs index 7af82c16..0bfe9b60 100644 --- a/src/ComputeSharp/Gpu.cs +++ b/src/ComputeSharp/Gpu.cs @@ -1,4 +1,11 @@ -using ComputeSharp.Graphics; +using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Linq; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Helpers; +using SharpDX.DXGI; +using Device = SharpDX.Direct3D12.Device; namespace ComputeSharp { @@ -7,11 +14,34 @@ namespace ComputeSharp /// public static class Gpu { + /// + /// Gets whether or not the APIs can be used on the current machine (ie. if there is at least a supported GPU device) + /// + public static bool IsSupported { get; } = (_Devices = DeviceHelper.QueryAllSupportedDevices()).Any(); + private static GraphicsDevice _Default; /// /// Gets the default instance for the current machine /// - public static GraphicsDevice Default => _Default ??= new GraphicsDevice(true); + public static GraphicsDevice Default + { + get + { + if (!IsSupported) throw new NotSupportedException("There isn't a supported GPU device on the current machine"); + + return _Default ??= new GraphicsDevice(_Devices[0].Device, _Devices[0].Description); + } + } + + /// + /// Enumerates all the available objects on the current machine + /// + /// A sequence of supported objects that can be used to run compute shaders + [Pure] + public static IEnumerable EnumerateDevices() => _Devices.Select(device => new GraphicsDevice(device.Device, device.Description)); + + // The loaded collection of supported devices + private static IReadOnlyList<(Device Device, AdapterDescription Description)> _Devices; } } diff --git a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs new file mode 100644 index 00000000..5040ea07 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs @@ -0,0 +1,95 @@ +using System; +using System.Linq; +using ComputeSharp.Graphics.Buffers; +using ComputeSharp.NetCore.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.NetCore.Tests +{ + [TestClass] + [TestCategory("Buffers")] + public class BufferTests + { + [TestMethod] + public void ReadWriteBufferGetSetDataFromArray() + { + float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); + + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(array); + float[] result = buffer.GetData(); + + Assert.IsTrue(array.AsSpan().ContentEquals(result)); + } + + [TestMethod] + public void ReadOnlyBufferGetSetDataFromArray() + { + 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/ComputeSharp.NetCore.Tests.csproj b/tests/ComputeSharp.NetCore.Tests/ComputeSharp.NetCore.Tests.csproj new file mode 100644 index 00000000..32d0c982 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/ComputeSharp.NetCore.Tests.csproj @@ -0,0 +1,19 @@ + + + + netcoreapp3.0 + + false + + + + + + + + + + + + + diff --git a/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs b/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs new file mode 100644 index 00000000..11ec9ddf --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs @@ -0,0 +1,39 @@ +using System; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.NetCore.Tests.Extensions +{ + /// + /// An helper with methods to process fixed-size buffers + /// + public static class SpanExtensions + { + /// + /// The maximum threshold to validate two values as being equal + /// + private const float FloatThreshold = 0.00001f; + + /// + /// Checks whether or not the two input instances have the same content + /// + /// The first to check + /// The second to check + [Pure] + public static bool ContentEquals(this Span a, Span b) + { + if (a.Length != b.Length) return false; + if (a.Length == 0) return true; + + var l = a.Length; + ref var ra = ref a.GetPinnableReference(); + ref var rb = ref b.GetPinnableReference(); + + for (var i = 0; i < l; i++) + if (Math.Abs(Unsafe.Add(ref ra, i) - Unsafe.Add(ref rb, i)) > FloatThreshold) + return false; + + return true; + } + } +} diff --git a/tests/ComputeSharp.NetCore.Tests/InitializationTests.cs b/tests/ComputeSharp.NetCore.Tests/InitializationTests.cs new file mode 100644 index 00000000..4e3b4c0f --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/InitializationTests.cs @@ -0,0 +1,42 @@ +using System; +using System.Linq; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Buffers; +using ComputeSharp.NetCore.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.NetCore.Tests +{ + [TestClass] + [TestCategory("Initialization")] + public class InitializationTests + { + [TestMethod] + public void CheckIsSupportedAndGetDefaultDevice() + { + if (Gpu.IsSupported) Assert.IsNotNull(Gpu.Default); + else Assert.ThrowsException(() => Gpu.Default); + } + + [TestMethod] + public void RunShaderOnAllDevices() + { + foreach (GraphicsDevice gpu in Gpu.EnumerateDevices()) + { + using (ReadWriteBuffer buffer = gpu.AllocateReadWriteBuffer(100)) + { + Action action = id => buffer[id.X] = id.X; + + gpu.For(100, action); + + float[] array = buffer.GetData(); + float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + Assert.IsTrue(array.AsSpan().ContentEquals(expected)); + } + + gpu.Dispose(); + } + } + } +} diff --git a/tests/ComputeSharp.NetCore.Tests/InvalidShaderTests.cs b/tests/ComputeSharp.NetCore.Tests/InvalidShaderTests.cs new file mode 100644 index 00000000..a0693718 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/InvalidShaderTests.cs @@ -0,0 +1,19 @@ +using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.NetCore.Tests +{ + [TestClass] + [TestCategory("InvalidShader")] + public class InvalidShaderTests + { + [TestMethod] + public void EmptyShaderCompileError() + { + Action action = id => { }; + + Assert.ThrowsException(() => Gpu.Default.For(10, action)); + } + } +} + diff --git a/tests/ComputeSharp.NetCore.Tests/Properties/AssemblyInfo.cs b/tests/ComputeSharp.NetCore.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..8ed86d91 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[assembly: DoNotParallelize] diff --git a/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs b/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs new file mode 100644 index 00000000..18bad3b9 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs @@ -0,0 +1,100 @@ +using System; +using System.Linq; +using System.Numerics; +using ComputeSharp.Graphics.Buffers; +using ComputeSharp.NetCore.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.NetCore.Tests +{ + [TestClass] + [TestCategory("ShaderClosure")] + public class ShaderClosureTests + { + [TestMethod] + public void LocalScalarAssignToBuffer() + { + float value = 10; + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Action action = id => buffer[0] = value; + + Gpu.Default.For(1, action); + + float[] result = buffer.GetData(); + + Assert.IsTrue((int)result[0] == (int)value); + } + + [TestMethod] + public void LocalScalarAssignToBufferWithinLocalMethod() + { + float value = 10; + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + void Foo(ThreadIds id) => buffer[0] = value; + + Gpu.Default.For(1, Foo); + + float[] result = buffer.GetData(); + + Assert.IsTrue((int)result[0] == (int)value); + } + + [TestMethod] + public void LocalKnownVectorAssignToBuffer() + { + Vector4 vector4 = new Vector4(1, 2, 3, 4); + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(4); + + Action action = id => + { + if (id.X == 0) buffer[0] = vector4.X; + else if (id.X == 1) buffer[1] = vector4.Y; + else if (id.X == 2) buffer[2] = vector4.Z; + else if (id.X == 3) buffer[3] = vector4.W; + }; + + Gpu.Default.For(1, action); + + float[] result = buffer.GetData(); + float[] expected = { 1, 2, 3, 4 }; + + Assert.IsTrue(result.AsSpan().ContentEquals(expected)); + } + + [TestMethod] + public void CopyBetweenWriteableBuffers() + { + float[] source = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + using ReadWriteBuffer input = Gpu.Default.AllocateReadWriteBuffer(source); + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); + + Action action = id => buffer[id.X] = input[id.X]; + + Gpu.Default.For(source.Length, action); + + float[] result = buffer.GetData(); + + Assert.IsTrue(result.AsSpan().ContentEquals(source)); + } + + [TestMethod] + public void CopyBetweenReadOnlyAndWriteableBuffers() + { + float[] source = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + using ReadOnlyBuffer input = Gpu.Default.AllocateReadOnlyBuffer(source); + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); + + Action action = id => buffer[id.X] = input[id.X]; + + Gpu.Default.For(source.Length, action); + + float[] result = buffer.GetData(); + + Assert.IsTrue(result.AsSpan().ContentEquals(source)); + } + } +} diff --git a/tests/ComputeSharp.NetCore.Tests/ShaderDispatchTests.cs b/tests/ComputeSharp.NetCore.Tests/ShaderDispatchTests.cs new file mode 100644 index 00000000..7e912983 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/ShaderDispatchTests.cs @@ -0,0 +1,58 @@ +using System; +using System.Linq; +using ComputeSharp.Graphics.Buffers; +using ComputeSharp.NetCore.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.NetCore.Tests +{ + [TestClass] + [TestCategory("ShaderDispatch")] + public class ShaderDispatch + { + [TestMethod] + public void WriteToReadWriteBufferDispatch1D() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(100); + + Action action = id => buffer[id.X] = id.X; + + Gpu.Default.For(100, action); + + float[] array = buffer.GetData(); + float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + Assert.IsTrue(array.AsSpan().ContentEquals(expected)); + } + + [TestMethod] + public void WriteToReadWriteBufferDispatch2D() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(100); + + Action action = id => buffer[id.X + id.Y * 10] = id.X + id.Y * 10; + + Gpu.Default.For(10, 10, action); + + float[] array = buffer.GetData(); + float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + Assert.IsTrue(array.AsSpan().ContentEquals(expected)); + } + + [TestMethod] + public void WriteToReadWriteBufferDispatch3D() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1000); + + Action action = id => buffer[id.X + id.Y * 10 + id.Z * 100] = id.X + id.Y * 10 + id.Z * 100; + + Gpu.Default.For(10, 10, 10, action); + + float[] array = buffer.GetData(); + float[] expected = Enumerable.Range(0, 1000).Select(i => (float)i).ToArray(); + + Assert.IsTrue(array.AsSpan().ContentEquals(expected)); + } + } +}