Merge pull request #15 from Sergio0694/dev

New APIs, bug fixes, code refactoring
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2019-08-13 22:01:47 +02:00
コミット a76c2f8b77
27ファイル変更
+915 -114

検索条件に一致するファイルはありません

+83
ファイルの表示
@@ -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<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1000);
// Shader body
Action<ThreadIds> 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<float> xBuffer = Gpu.Default.AllocateConstantBuffer(x);
using ReadWriteBuffer<float> yBuffer = Gpu.Default.AllocateReadWriteBuffer(y);
// Shader body
Action<ThreadIds> 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.
+73
ファイルの表示
@@ -0,0 +1,73 @@
using System;
using System.Buffers;
using System.Diagnostics.Contracts;
using SharpDX.Direct3D12;
namespace ComputeSharp.Graphics.Buffers.Abstract
{
/// <summary>
/// A <see langword="class"/> representing a typed buffer stored on GPU memory, that can be used from an HLSL shader
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
public abstract class HlslBuffer<T> : Buffer<T> where T : unmanaged
{
/// <summary>
/// Creates a new <see cref="HlslBuffer{T}"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
/// <param name="sizeInBytes">The size in bytes for the current buffer</param>
/// <param name="heapType">The heap type for the current buffer</param>
protected internal HlslBuffer(GraphicsDevice device, int size, int sizeInBytes, HeapType heapType) : base(device, size, sizeInBytes, heapType) { }
/// <summary>
/// Reads the contents of the current <see cref="HlslBuffer{T}"/> instance and returns an array
/// </summary>
/// <returns>A <typeparamref name="T"/> array with the contents of the current buffer</returns>
[Pure]
public T[] GetData()
{
T[] data = new T[Size];
GetData(data);
return data;
}
/// <summary>
/// Reads the contents of the current <see cref="HlslBuffer{T}"/> instance and writes them into a target <see cref="Span{T}"/>
/// </summary>
/// <param name="span">The input <see cref="Span{T}"/> to write data to</param>
public abstract void GetData(Span<T> span);
/// <summary>
/// Writes the contents of a given <see cref="Span{T}"/> to the current <see cref="HlslBuffer{T}"/> instance
/// </summary>
/// <param name="span">The input <see cref="Span{T}"/> to read data from</param>
public abstract void SetData(Span<T> span);
/// <summary>
/// Writes the contents of a given <see cref="HlslBuffer{T}"/> to the current <see cref="HlslBuffer{T}"/> instance
/// </summary>
/// <param name="buffer">The input <see cref="HlslBuffer{T}"/> to read data from</param>
public abstract void SetData(HlslBuffer<T> buffer);
/// <summary>
/// Writes the contents of a given <see cref="HlslBuffer{T}"/> to the current <see cref="HlslBuffer{T}"/> instance, using a temporary CPU buffer
/// </summary>
/// <param name="buffer">The input <see cref="HlslBuffer{T}"/> to read data from</param>
protected void SetDataWithCpuBuffer(HlslBuffer<T> buffer)
{
// Create a temporary array
T[] array = ArrayPool<T>.Shared.Rent(buffer.Size);
Span<T> 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<T>.Shared.Return(array);
}
}
}
+19 -84
ファイルの表示
@@ -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
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
/// <param name="sizeInBytes">The size in bytes for the current buffer</param>
/// <param name="heapType">The heap type for the current buffer</param>
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<T>();
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
};
}
/// <summary>
/// Gets the size of the current buffer, as in the number of <typeparamref name="T"/> values it contains
/// </summary>
public int Size { get; }
/// <summary>
/// Gets the size in bytes of the current buffer
/// </summary>
protected int SizeInBytes { get; }
/// <summary>
/// Gets the size in bytes of each <typeparamref name="T"/> value contained in the buffer
/// </summary>
protected int ElementSizeInBytes { get; }
/// <summary>
/// Creates the descriptors for a constant buffer
/// </summary>
@@ -88,88 +102,9 @@ namespace ComputeSharp.Graphics.Buffers
return (cpuHandle, gpuHandle);
}
/// <summary>
/// Gets the size of the current buffer, as in the number of <typeparamref name="T"/> values it contains
/// </summary>
public int Size { get; }
/// <summary>
/// Gets the size in bytes of the current buffer
/// </summary>
public int SizeInBytes { get; }
/// <summary>
/// Gets the size in bytes of each <typeparamref name="T"/> value contained in the buffer
/// </summary>
public int ElementSizeInBytes { get; }
/// <summary>
/// Gets the heap type being targeted by the current buffer
/// </summary>
public HeapType HeapType { get; }
/// <summary>
/// Reads the contents of the current <see cref="Buffer{T}"/> instance and returns an array
/// </summary>
/// <returns>A <typeparamref name="T"/> array with the contents of the current buffer</returns>
[Pure]
public T[] GetData()
{
T[] data = new T[Size];
GetData(data);
return data;
}
/// <summary>
/// Reads the contents of the current <see cref="Buffer{T}"/> instance and writes them into a target <see cref="Span{T}"/>
/// </summary>
/// <param name="span">The input <see cref="Span{T}"/> to write data to</param>
public void GetData(Span<T> 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<T> readbackBaffer = new Buffer<T>(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);
}
}
/// <summary>
/// Writes the contents of a given <see cref="Span{T}"/> to the current <see cref="Buffer{T}"/> instance
/// </summary>
/// <param name="span">The input <see cref="Span{T}"/> to read data from</param>
public void SetData(Span<T> 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<T> uploadBuffer = new Buffer<T>(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);
}
}
}
}
+40 -5
ファイルの表示
@@ -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;
}
/// <summary>
/// Allocates a new read write buffer with the specified parameters
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="buffer">The input <see cref="HlslBuffer{T}"/> with the data to copy on the allocated buffer</param>
/// <returns>A read write <see cref="ReadWriteBuffer{T}"/> instance with the contents of the input <see cref="HlslBuffer{T}"/></returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, HlslBuffer<T> buffer) where T : unmanaged
{
ReadWriteBuffer<T> readWriteBuffer = new ReadWriteBuffer<T>(device, buffer.Size);
readWriteBuffer.SetData(buffer);
return readWriteBuffer;
}
/// <summary>
/// Allocates a new constant buffer with the specified parameters
/// </summary>
@@ -83,9 +101,9 @@ namespace ComputeSharp
/// <returns>A constant <see cref="ReadOnlyBuffer{T}"/> instance with the contents of the input array</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlyBuffer<T> AllocateConstantBuffer<T>(this GraphicsDevice device, T[] array) where T : unmanaged
public static ReadOnlyBuffer<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice device, T[] array) where T : unmanaged
{
return device.AllocateConstantBuffer(array.AsSpan());
return device.AllocateReadOnlyBuffer(array.AsSpan());
}
/// <summary>
@@ -97,12 +115,12 @@ namespace ComputeSharp
/// <returns>A constant <see cref="ReadOnlyBuffer{T}"/> instance with the contents of the input 2D array</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe ReadOnlyBuffer<T> AllocateConstantBuffer<T>(this GraphicsDevice device, T[,] array) where T : unmanaged
public static unsafe ReadOnlyBuffer<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice device, T[,] array) where T : unmanaged
{
fixed (T* p = array)
{
Span<T> span = new Span<T>(p, array.Length);
return device.AllocateConstantBuffer(span);
return device.AllocateReadOnlyBuffer(span);
}
}
@@ -115,12 +133,29 @@ namespace ComputeSharp
/// <returns>A constant <see cref="ReadOnlyBuffer{T}"/> instance with the contents of the input <see cref="Span{T}"/></returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlyBuffer<T> AllocateConstantBuffer<T>(this GraphicsDevice device, Span<T> span) where T : unmanaged
public static ReadOnlyBuffer<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice device, Span<T> span) where T : unmanaged
{
ReadOnlyBuffer<T> buffer = new ReadOnlyBuffer<T>(device, span.Length);
buffer.SetData(span);
return buffer;
}
/// <summary>
/// Allocates a new constant buffer with the specified parameters
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="buffer">The input <see cref="HlslBuffer{T}"/> with the data to copy on the allocated buffer</param>
/// <returns>A constant <see cref="ReadOnlyBuffer{T}"/> instance with the contents of the input <see cref="HlslBuffer{T}"/></returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlyBuffer<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice device, HlslBuffer<T> buffer) where T : unmanaged
{
ReadOnlyBuffer<T> readOnlyBuffer = new ReadOnlyBuffer<T>(device, buffer.Size);
readOnlyBuffer.SetData(buffer);
return readOnlyBuffer;
}
}
}
+103 -2
ファイルの表示
@@ -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 <see langword="class"/> representing a typed read write buffer stored on GPU memory
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
public sealed class ReadOnlyBuffer<T> : Buffer<T> where T : unmanaged
public sealed class ReadOnlyBuffer<T> : HlslBuffer<T> where T : unmanaged
{
/// <summary>
/// Creates a new <see cref="ReadOnlyBuffer{T}"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, HeapType.Upload) { }
internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, size * (Unsafe.SizeOf<T>() / 16 + 1) * 16, HeapType.Upload)
{
PaddedElementSizeInBytes = SizeInBytes / Size;
IsPaddingPresent = PaddedElementSizeInBytes > ElementSizeInBytes;
}
/// <summary>
/// Gets the size in bytes of the current buffer
/// </summary>
internal int PaddedElementSizeInBytes { get; }
/// <summary>
/// Gets whether or not there is some padding between elements in the current buffer
/// </summary>
internal bool IsPaddingPresent { get; }
/// <summary>
/// Gets a single <typeparamref name="T"/> value from the current read write buffer
@@ -22,5 +40,88 @@ namespace ComputeSharp.Graphics.Buffers
/// <param name="i">The index of the value to get</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else</remarks>
public T this[uint i] => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader");
/// <inheritdoc/>
public override void GetData(Span<T> span)
{
if (IsPaddingPresent)
{
// Create the temporary array
byte[] temporaryArray = ArrayPool<byte>.Shared.Rent(SizeInBytes);
Span<byte> 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<byte, T>(ref rsource);
}
ArrayPool<byte>.Shared.Return(temporaryArray);
}
else
{
// Directly copy the data back if there is no padding
Map(0);
MemoryHelper.Copy(MappedResource, span);
Unmap(0);
}
}
/// <inheritdoc/>
public override void SetData(Span<T> span)
{
if (IsPaddingPresent)
{
// Create the temporary array
byte[] temporaryArray = ArrayPool<byte>.Shared.Rent(SizeInBytes);
Span<byte> 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<byte, T>(ref rtarget) = Unsafe.Add(ref tin, i);
}
// Copy the padded data to the GPU
Map(0);
MemoryHelper.Copy(temporarySpan, MappedResource);
Unmap(0);
ArrayPool<byte>.Shared.Return(temporaryArray);
}
else
{
// Directly copy the input span if there is no padding
Map(0);
MemoryHelper.Copy(span, MappedResource);
Unmap(0);
}
}
/// <inheritdoc/>
public override void SetData(HlslBuffer<T> buffer)
{
if (buffer is ReadOnlyBuffer<T>)
{
// 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);
}
}
}
+49 -2
ファイルの表示
@@ -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 <see langword="class"/> representing a typed read write buffer stored on GPU memory
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
public sealed class ReadWriteBuffer<T> : Buffer<T> where T : unmanaged
public sealed class ReadWriteBuffer<T> : HlslBuffer<T> where T : unmanaged
{
/// <summary>
/// Creates a new <see cref="ReadWriteBuffer{T}"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, HeapType.Default) { }
internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, size * Unsafe.SizeOf<T>(), HeapType.Default) { }
/// <summary>
/// Gets or sets a single <typeparamref name="T"/> 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");
}
/// <inheritdoc/>
public override void GetData(Span<T> span)
{
using Buffer<T> readbackBaffer = new Buffer<T>(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);
}
/// <inheritdoc/>
public override void SetData(Span<T> span)
{
using Buffer<T> uploadBuffer = new Buffer<T>(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);
}
/// <inheritdoc/>
public override void SetData(HlslBuffer<T> buffer)
{
if (buffer is ReadOnlyBuffer<T> 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);
}
}
}
+15 -5
ファイルの表示
@@ -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)
/// <summary>
/// Creates a new <see cref="GraphicsDevice"/> instance for the input <see cref="Device"/>
/// </summary>
/// <param name="device">The <see cref="Device"/> to use for the new <see cref="GraphicsDevice"/> instance</param>
/// <param name="description">The available info for the new <see cref="GraphicsDevice"/> instance</param>
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();
}
/// <summary>
/// Gets the available info for the current <see cref="GraphicsDevice"/> instance
/// </summary>
public AdapterDescription Description { get; }
/// <summary>
/// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width")
/// </summary>
+40
ファイルの表示
@@ -0,0 +1,40 @@
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using SharpDX.DXGI;
using Device = SharpDX.Direct3D12.Device;
namespace ComputeSharp.Graphics.Helpers
{
/// <summary>
/// A <see langword="class"/> with methods to inspect the available devices on the current machine
/// </summary>
public static class DeviceHelper
{
/// <summary>
/// Gets a collection of all the supported devices on the current machine
/// </summary>
/// <returns>The collection of <see cref="Device"/> objects with support for DX12.1</returns>
[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;
}
}
}
+1 -1
ファイルの表示
@@ -13,8 +13,8 @@
</PackageReference>
<PackageReference Include="ICSharpCode.Decompiler" Version="5.0.0.4861-preview3" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.3.0-beta1-final" />
<PackageReference Include="Nustache" Version="1.16.0.10" />
<PackageReference Include="SharpDX.D3DCompiler" Version="4.2.1-beta0-g3060495c2a" />
<PackageReference Include="Stubble.Core" Version="1.4.12" />
</ItemGroup>
<ItemGroup>
+9
ファイルの表示
@@ -62,6 +62,15 @@ namespace ComputeSharp.Shaders.Mappings
public static bool IsReadWriteBufferType(Type type) => type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(ReadWriteBuffer<>);
/// <summary>
/// Checks whether or not the input type is a <see cref="ReadOnlyBuffer{T}"/> value
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a <see cref="ReadOnlyBuffer{T}"/> instance</returns>
[Pure]
public static bool IsReadOnlyBufferType(Type type) => type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(ReadOnlyBuffer<>);
/// <summary>
/// Checks whether or not a given <see cref="Type"/> is an HLSL known type
/// </summary>
+9 -2
ファイルの表示
@@ -12,10 +12,15 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields
/// </summary>
public bool IsConstantBuffer { get; } = true;
/// <summary>
/// Gets whether or not this constant buffer actually contains a single, explicit variable
/// </summary>
public bool IsSingleValue { get; }
/// <summary>
/// Gets the index of the current constant buffer field
/// </summary>
public int ConstantBufferIndex { get; set; }
public int ConstantBufferIndex { get; }
/// <summary>
/// Creates a new <see cref="ConstantBufferFieldInfo"/> instance with the specified parameters
@@ -23,9 +28,11 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields
/// <param name="fieldType">The type of the current field</param>
/// <param name="fieldName">The name of the current field</param>
/// <param name="bufferIndex">The index of the current constant buffer field</param>
public ConstantBufferFieldInfo(string fieldType, string fieldName, int bufferIndex) : base(fieldType, fieldName)
/// <param name="singleValue">Whether or not this constant buffer actually contains a single, explicit variable</param>
public ConstantBufferFieldInfo(string fieldType, string fieldName, int bufferIndex, bool singleValue) : base(fieldType, fieldName)
{
ConstantBufferIndex = bufferIndex;
IsSingleValue = singleValue;
}
}
}
+2 -1
ファイルの表示
@@ -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
/// <param name="info">The input <see cref="ShaderInfo"/> instance with the shader information</param>
/// <returns>The source code for the new HLSL shader</returns>
[Pure]
public string Render(ShaderInfo info) => Nustache.Core.Render.StringToString(Template, info);
public string Render(ShaderInfo info) => StaticStubbleRenderer.Render(Template, info);
}
}
+1 -1
ファイルの表示
@@ -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}}
+1 -1
ファイルの表示
@@ -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);
}
+11 -2
ファイルの表示
@@ -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
}
}
/// <summary>
/// A <see cref="Regex"/> uused to preprocess the entry point declaration for both lambda expressions and local methods
/// </summary>
private static readonly Regex LambdaMethodDeclarationRegex = new Regex(@"^(private|internal) void <\w+>[\w_|]+(?=\()", RegexOptions.Compiled);
/// <summary>
/// Decompiles a target method and returns its <see cref="SyntaxTree"/> and <see cref="SemanticModel"/> info
/// </summary>
@@ -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
+21 -6
ファイルの表示
@@ -59,9 +59,9 @@ namespace ComputeSharp.Shaders.Translation
public RootParameter[] RootParameters { get; private set; }
/// <summary>
/// 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
/// </summary>
public IReadOnlyList<GraphicsResource> ReadWriteBuffers { get; private set; }
public IReadOnlyList<GraphicsResource> Buffers { get; private set; }
private readonly List<FieldInfoBase> _FieldsInfo = new List<FieldInfoBase>();
@@ -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<DescriptorRange> descriptorRanges = new List<DescriptorRange>();
List<GraphicsResource> readWriteBuffers = new List<GraphicsResource>();
List<GraphicsResource> buffers = new List<GraphicsResource>();
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;
}
/// <summary>
@@ -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<ConstructorDeclarationSyntax>().First();
MethodDeclarationSyntax methodNode = root.ChildNodes().OfType<MethodDeclarationSyntax>().First();
ThreadsIdsVariableName = methodNode.ParameterList.Parameters.First().Identifier.Text;
MethodBody = methodNode.Body.ToFullString();
+13
ファイルの表示
@@ -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}
+18
ファイルの表示
@@ -4,6 +4,17 @@
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
<Version>1.0.0-alpha+85bfe4f636407cb9f41ce1c8856c662b634399f0</Version>
<Authors>Sergio Pedri</Authors>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<Description>A .NET Standard 2.0 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders</Description>
<Copyright>Copyright (c) 2019 Sergio Pedri</Copyright>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageProjectUrl>https://github.com/Sergio0694/ComputeSharp</PackageProjectUrl>
<RepositoryUrl>https://github.com/Sergio0694/ComputeSharp</RepositoryUrl>
<PackageTags>dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu</PackageTags>
<PackageIconUrl>https://i.imgur.com/oo8dA0q.png</PackageIconUrl>
</PropertyGroup>
<ItemGroup>
@@ -17,4 +28,11 @@
<ProjectReference Include="..\ComputeSharp.Shaders\ComputeSharp.Shaders.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="..\..\LICENSE">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
</ItemGroup>
</Project>
+32 -2
ファイルの表示
@@ -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
/// </summary>
public static class Gpu
{
/// <summary>
/// Gets whether or not the <see cref="Gpu"/> APIs can be used on the current machine (ie. if there is at least a supported GPU device)
/// </summary>
public static bool IsSupported { get; } = (_Devices = DeviceHelper.QueryAllSupportedDevices()).Any();
private static GraphicsDevice _Default;
/// <summary>
/// Gets the default <see cref="GraphicsDevice"/> instance for the current machine
/// </summary>
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);
}
}
/// <summary>
/// Enumerates all the available <see cref="GraphicsDevice"/> objects on the current machine
/// </summary>
/// <returns>A sequence of supported <see cref="GraphicsDevice"/> objects that can be used to run compute shaders</returns>
[Pure]
public static IEnumerable<GraphicsDevice> EnumerateDevices() => _Devices.Select(device => new GraphicsDevice(device.Device, device.Description));
// The loaded collection of supported devices
private static IReadOnlyList<(Device Device, AdapterDescription Description)> _Devices;
}
}
+95
ファイルの表示
@@ -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<float> 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<float> 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<float> sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(array);
using ReadWriteBuffer<float> 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<float> sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(array);
using ReadWriteBuffer<float> 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<float> sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(array);
using ReadOnlyBuffer<float> 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<float> sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(array);
using ReadOnlyBuffer<float> 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));
}
}
}
+19
ファイルの表示
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="MSTest.TestAdapter" Version="1.4.0" />
<PackageReference Include="MSTest.TestFramework" Version="1.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
</ItemGroup>
</Project>
+39
ファイルの表示
@@ -0,0 +1,39 @@
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace ComputeSharp.NetCore.Tests.Extensions
{
/// <summary>
/// An helper <see langword="class"/> with methods to process fixed-size buffers
/// </summary>
public static class SpanExtensions
{
/// <summary>
/// The maximum threshold to validate two <see langword="float"/> values as being equal
/// </summary>
private const float FloatThreshold = 0.00001f;
/// <summary>
/// Checks whether or not the two input <see cref="Span{T}"/> instances have the same content
/// </summary>
/// <param name="a">The first <see cref="Span{T}"/> to check</param>
/// <param name="b">The second <see cref="Span{T}"/> to check</param>
[Pure]
public static bool ContentEquals(this Span<float> a, Span<float> 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;
}
}
}
+42
ファイルの表示
@@ -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<NotSupportedException>(() => Gpu.Default);
}
[TestMethod]
public void RunShaderOnAllDevices()
{
foreach (GraphicsDevice gpu in Gpu.EnumerateDevices())
{
using (ReadWriteBuffer<float> buffer = gpu.AllocateReadWriteBuffer<float>(100))
{
Action<ThreadIds> 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();
}
}
}
}
+19
ファイルの表示
@@ -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<ThreadIds> action = id => { };
Assert.ThrowsException<InvalidOperationException>(() => Gpu.Default.For(10, action));
}
}
}
+3
ファイルの表示
@@ -0,0 +1,3 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
[assembly: DoNotParallelize]
+100
ファイルの表示
@@ -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<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> 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<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(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<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(4);
Action<ThreadIds> 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<float> input = Gpu.Default.AllocateReadWriteBuffer(source);
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(source.Length);
Action<ThreadIds> 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<float> input = Gpu.Default.AllocateReadOnlyBuffer(source);
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(source.Length);
Action<ThreadIds> action = id => buffer[id.X] = input[id.X];
Gpu.Default.For(source.Length, action);
float[] result = buffer.GetData();
Assert.IsTrue(result.AsSpan().ContentEquals(source));
}
}
}
+58
ファイルの表示
@@ -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<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(100);
Action<ThreadIds> 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<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(100);
Action<ThreadIds> 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<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1000);
Action<ThreadIds> 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));
}
}
}