Merge pull request #9 from Sergio0694/dev
Major code refactoring, initial public APIs implemented
このコミットが含まれているのは:
51ファイル変更
+730
-684
検索条件に一致するファイルはありません
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp3.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+13
-18
@@ -1,11 +1,9 @@
|
||||
using DirectX12GameEngine.Shaders;
|
||||
using System;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using DirectX12GameEngine.Graphics.Buffers;
|
||||
using DirectX12GameEngine.Shaders.Primitives;
|
||||
using Buffer = DirectX12GameEngine.Graphics.Buffers.Buffer;
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.Graphics.Buffers;
|
||||
|
||||
namespace DirectX12ComputeShaderSample
|
||||
namespace NetCoreComputeShaderSample
|
||||
{
|
||||
public class Program
|
||||
{
|
||||
@@ -20,29 +18,26 @@ namespace DirectX12ComputeShaderSample
|
||||
array[i] = i + 1;
|
||||
}
|
||||
|
||||
using Buffer<float> gpuBuffer = Buffer.UnorderedAccess.New(Gpu.Default, array.AsSpan());
|
||||
// Print the initial matrix
|
||||
Console.WriteLine("Before:");
|
||||
PrintMatrix(array, width, height);
|
||||
|
||||
// Variables for closure
|
||||
uint size = (uint)width;
|
||||
var data = gpuBuffer.GetGpuResource();
|
||||
using ReadWriteBuffer<float> gpuBuffer = Gpu.Default.AllocateReadWriteBuffer(array);
|
||||
|
||||
// Shader body
|
||||
Action<ThreadIds> action = id =>
|
||||
{
|
||||
data[id.X + id.Y * size] *= 2;
|
||||
uint offset = id.X + id.Y * (uint)width;
|
||||
gpuBuffer[offset] *= 2;
|
||||
};
|
||||
|
||||
// Run the shader
|
||||
Gpu.Default.For(100, action);
|
||||
|
||||
// Print matrix
|
||||
// Get the data back
|
||||
gpuBuffer.GetData(array);
|
||||
|
||||
Console.WriteLine("Before:");
|
||||
PrintMatrix(array, width, height);
|
||||
|
||||
gpuBuffer.GetData(array.AsSpan());
|
||||
|
||||
Console.WriteLine();
|
||||
// Print the updated matrix
|
||||
Console.WriteLine("After:");
|
||||
PrintMatrix(array, width, height);
|
||||
}
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
using System;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics.Buffers.Abstract
|
||||
namespace ComputeSharp.Graphics.Buffers.Abstract
|
||||
{
|
||||
/// <summary>
|
||||
/// An abstract <see langword="class"/> that represents a graphics resource object
|
||||
@@ -35,12 +35,12 @@ namespace DirectX12GameEngine.Graphics.Buffers.Abstract
|
||||
/// <summary>
|
||||
/// Gets the <see cref="CpuDescriptorHandle"/> instance for the current resource
|
||||
/// </summary>
|
||||
protected internal CpuDescriptorHandle NativeCpuDescriptorHandle { get; protected set; }
|
||||
protected internal CpuDescriptorHandle? NativeCpuDescriptorHandle { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="GpuDescriptorHandle"/> instance for the current resource
|
||||
/// </summary>
|
||||
protected internal GpuDescriptorHandle NativeGpuDescriptorHandle { get; protected set; }
|
||||
protected internal GpuDescriptorHandle? NativeGpuDescriptorHandle { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Maps the current resource to a specified subresource
|
||||
@@ -0,0 +1,175 @@
|
||||
using System;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
using ComputeSharp.Graphics.Helpers;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace ComputeSharp.Graphics.Buffers
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> representing a typed buffer stored on GPU memory
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
|
||||
public class Buffer<T> : GraphicsResource where T : unmanaged
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="Buffer{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="heapType">The heap type for the current buffer</param>
|
||||
protected internal Buffer(GraphicsDevice device, int size, HeapType heapType) : base(device)
|
||||
{
|
||||
Size = size;
|
||||
ElementSizeInBytes = Unsafe.SizeOf<T>();
|
||||
SizeInBytes = Size * ElementSizeInBytes;
|
||||
HeapType = heapType;
|
||||
|
||||
ResourceFlags flags = heapType == HeapType.Default ? ResourceFlags.AllowUnorderedAccess : ResourceFlags.None;
|
||||
ResourceDescription description = ResourceDescription.Buffer(SizeInBytes, flags);
|
||||
ResourceStates resourceStates = heapType switch
|
||||
{
|
||||
HeapType.Upload => ResourceStates.GenericRead,
|
||||
HeapType.Readback => ResourceStates.CopyDestination,
|
||||
_ => ResourceStates.Common
|
||||
};
|
||||
|
||||
NativeResource = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(heapType), HeapFlags.None, description, resourceStates);
|
||||
|
||||
(NativeCpuDescriptorHandle, NativeGpuDescriptorHandle) = heapType switch
|
||||
{
|
||||
HeapType.Default => CreateUnorderedAccessView(),
|
||||
HeapType.Upload => CreateConstantBufferView(),
|
||||
_ => default
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the descriptors for a constant buffer
|
||||
/// </summary>
|
||||
/// <returns>The CPU and GPU handles for a constant buffer</returns>
|
||||
[Pure]
|
||||
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateConstantBufferView()
|
||||
{
|
||||
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
|
||||
|
||||
int constantBufferSize = (SizeInBytes + 255) & ~255;
|
||||
|
||||
ConstantBufferViewDescription description = new ConstantBufferViewDescription
|
||||
{
|
||||
BufferLocation = NativeResource!.GPUVirtualAddress,
|
||||
SizeInBytes = constantBufferSize
|
||||
};
|
||||
|
||||
GraphicsDevice.NativeDevice.CreateConstantBufferView(description, cpuHandle);
|
||||
|
||||
return (cpuHandle, gpuHandle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the descriptors for a read write buffer
|
||||
/// </summary>
|
||||
/// <returns>The CPU and GPU handles for a read write buffer</returns>
|
||||
[Pure]
|
||||
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateUnorderedAccessView()
|
||||
{
|
||||
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
|
||||
|
||||
UnorderedAccessViewDescription description = new UnorderedAccessViewDescription
|
||||
{
|
||||
Format = SharpDX.DXGI.Format.R32_Float,
|
||||
Dimension = UnorderedAccessViewDimension.Buffer,
|
||||
Buffer = { ElementCount = Size }
|
||||
};
|
||||
|
||||
GraphicsDevice.NativeDevice.CreateUnorderedAccessView(NativeResource, null, description, cpuHandle);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using System;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.Graphics;
|
||||
using ComputeSharp.Graphics.Buffers;
|
||||
|
||||
namespace ComputeSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> with extension methods for the <see cref="GraphicsDevice"/> type to allocate buffers
|
||||
/// </summary>
|
||||
public static class BufferExtensions
|
||||
{
|
||||
/// <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="size">The size of the buffer to allocate</param>
|
||||
/// <returns>A zeroed <see cref="ReadWriteBuffer{T}"/> instance of size <paramref name="size"/></returns>
|
||||
[Pure]
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, int size) where T : unmanaged
|
||||
{
|
||||
return new ReadWriteBuffer<T>(device, size);
|
||||
}
|
||||
|
||||
/// <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="array">The input <typeparamref name="T"/> array 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 array</returns>
|
||||
[Pure]
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, T[] array) where T : unmanaged
|
||||
{
|
||||
return device.AllocateReadWriteBuffer(array.AsSpan());
|
||||
}
|
||||
|
||||
/// <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="array">The input 2D <typeparamref name="T"/> array 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 2D array</returns>
|
||||
[Pure]
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, T[,] array) where T : unmanaged
|
||||
{
|
||||
fixed (T* p = array)
|
||||
{
|
||||
Span<T> span = new Span<T>(p, array.Length);
|
||||
return device.AllocateReadWriteBuffer(span);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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="span">The input <see cref="Span{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="Span{T}"/></returns>
|
||||
[Pure]
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, Span<T> span) where T : unmanaged
|
||||
{
|
||||
ReadWriteBuffer<T> buffer = new ReadWriteBuffer<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="array">The input <typeparamref name="T"/> array with the data to copy on the allocated buffer</param>
|
||||
/// <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
|
||||
{
|
||||
return device.AllocateConstantBuffer(array.AsSpan());
|
||||
}
|
||||
|
||||
/// <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="array">The input 2D <typeparamref name="T"/> array with the data to copy on the allocated buffer</param>
|
||||
/// <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
|
||||
{
|
||||
fixed (T* p = array)
|
||||
{
|
||||
Span<T> span = new Span<T>(p, array.Length);
|
||||
return device.AllocateConstantBuffer(span);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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="span">The input <see cref="Span{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="Span{T}"/></returns>
|
||||
[Pure]
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static ReadOnlyBuffer<T> AllocateConstantBuffer<T>(this GraphicsDevice device, Span<T> span) where T : unmanaged
|
||||
{
|
||||
ReadOnlyBuffer<T> buffer = new ReadOnlyBuffer<T>(device, span.Length);
|
||||
buffer.SetData(span);
|
||||
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace ComputeSharp.Graphics.Buffers
|
||||
{
|
||||
/// <summary>
|
||||
/// 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
|
||||
{
|
||||
/// <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) { }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a single <typeparamref name="T"/> value from the current read write buffer
|
||||
/// </summary>
|
||||
/// <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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace ComputeSharp.Graphics.Buffers
|
||||
{
|
||||
/// <summary>
|
||||
/// 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
|
||||
{
|
||||
/// <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) { }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a single <typeparamref name="T"/> value from the current read write buffer
|
||||
/// </summary>
|
||||
/// <param name="i">The index of the value to get or set</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]
|
||||
{
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
using System.Collections.Generic;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
namespace ComputeSharp.Graphics
|
||||
{
|
||||
internal sealed class CommandAllocatorPool : IDisposable
|
||||
{
|
||||
+6
-4
@@ -1,8 +1,8 @@
|
||||
using System;
|
||||
using DirectX12GameEngine.Graphics.Buffers.Abstract;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
namespace ComputeSharp.Graphics
|
||||
{
|
||||
public sealed class CommandList : IDisposable
|
||||
{
|
||||
@@ -110,7 +110,8 @@ namespace DirectX12GameEngine.Graphics
|
||||
|
||||
public void SetGraphicsRootDescriptorTable(int rootParameterIndex, GraphicsResource resource)
|
||||
{
|
||||
SetGraphicsRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle);
|
||||
if (resource.NativeGpuDescriptorHandle == null) throw new InvalidOperationException("Invalid graphics resource GPU descriptor");
|
||||
SetGraphicsRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle.Value);
|
||||
}
|
||||
|
||||
public void SetGraphicsRootDescriptorTable(int rootParameterIndex, GpuDescriptorHandle baseDescriptor)
|
||||
@@ -130,7 +131,8 @@ namespace DirectX12GameEngine.Graphics
|
||||
|
||||
public void SetComputeRootDescriptorTable(int rootParameterIndex, GraphicsResource resource)
|
||||
{
|
||||
SetComputeRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle);
|
||||
if (resource.NativeGpuDescriptorHandle == null) throw new InvalidOperationException("Invalid graphics resource GPU descriptor");
|
||||
SetComputeRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle.Value);
|
||||
}
|
||||
|
||||
public void SetComputeRootDescriptorTable(int rootParameterIndex, GpuDescriptorHandle baseDescriptor)
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
namespace ComputeSharp.Graphics
|
||||
{
|
||||
public sealed class CompiledCommandList
|
||||
{
|
||||
+3
@@ -2,11 +2,14 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>8.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Windows.SDK.Contracts" Version="10.0.18362.2002-preview" />
|
||||
<PackageReference Include="SharpDX.Direct3D12" Version="4.2.1-beta0-gab36f12303" />
|
||||
<PackageReference Include="System.Memory" Version="4.5.3" />
|
||||
<PackageReference Include="System.Numerics.Vectors" Version="4.6.0-preview5.19224.8" />
|
||||
<PackageReference Include="System.Runtime.InteropServices.WindowsRuntime" Version="4.3.0" />
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
using System;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
namespace ComputeSharp.Graphics
|
||||
{
|
||||
internal sealed class DescriptorAllocator : IDisposable
|
||||
{
|
||||
+7
-1
@@ -3,7 +3,7 @@ using System.Threading;
|
||||
using SharpDX.Direct3D;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
namespace ComputeSharp.Graphics
|
||||
{
|
||||
public sealed class GraphicsDevice : IDisposable
|
||||
{
|
||||
@@ -15,6 +15,7 @@ namespace DirectX12GameEngine.Graphics
|
||||
if (enableDebugLayer) DebugInterface.Get().EnableDebugLayer();
|
||||
#endif
|
||||
NativeDevice = new Device(null, FeatureLevel);
|
||||
WavefrontSize = NativeDevice.D3D12Options1.WaveLaneCountMin;
|
||||
|
||||
NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Compute));
|
||||
NativeCopyCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Copy));
|
||||
@@ -40,6 +41,11 @@ namespace DirectX12GameEngine.Graphics
|
||||
CopyCommandList.Close();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width")
|
||||
/// </summary>
|
||||
public int WavefrontSize { get; }
|
||||
|
||||
public CommandList CommandList { get; }
|
||||
|
||||
public CommandList CopyCommandList { get; }
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
namespace ComputeSharp.Graphics
|
||||
{
|
||||
public enum GraphicsHeapType
|
||||
{
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace DirectX12GameEngine.Core.Helpers
|
||||
namespace ComputeSharp.Graphics.Helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> with some helper methods to copy data between memory areas
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
namespace ComputeSharp.Graphics
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> representing a custom pipeline state for a compute operation
|
||||
+2
-7
@@ -18,8 +18,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DirectX12GameEngine.Core\DirectX12GameEngine.Core.csproj" />
|
||||
<ProjectReference Include="..\DirectX12GameEngine.Graphics\DirectX12GameEngine.Graphics.csproj" />
|
||||
<ProjectReference Include="..\ComputeSharp.Graphics\ComputeSharp.Graphics.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -36,11 +35,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="Assets\ShaderTemplate.mustache" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="Assets\ShaderTemplate.mustache">
|
||||
<Content Include="Renderer\Templates\ShaderTemplate.mustache">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
@@ -0,0 +1,67 @@
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using ComputeSharp.Shaders.Mappings;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace ComputeSharp.Shaders.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> with some extension methods for C# syntax nodes
|
||||
/// </summary>
|
||||
public static class SyntaxNodeExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks a <see cref="SyntaxNode"/> value and replaces the value type to be HLSL compatible, if needed
|
||||
/// </summary>
|
||||
/// <typeparam name="TRoot">The type of the input <see cref="SyntaxNode"/> instance</typeparam>
|
||||
/// <param name="node">The input <see cref="SyntaxNode"/> to check and modify if needed</param>
|
||||
/// <param name="type">The <see cref="TypeSyntax"/> to use for the input node</param>
|
||||
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL</returns>
|
||||
[Pure]
|
||||
public static TRoot ReplaceType<TRoot>(this TRoot node, TypeSyntax type) where TRoot : SyntaxNode
|
||||
{
|
||||
string value = HlslKnownTypes.GetMappedName(type.ToString());
|
||||
|
||||
// If the HLSL mapped full type name equals the original type, just return the input node
|
||||
if (value == type.ToString()) return node;
|
||||
|
||||
// Process and return the type name
|
||||
TypeSyntax newType = SyntaxFactory.ParseTypeName(value).WithLeadingTrivia(type.GetLeadingTrivia()).WithTrailingTrivia(type.GetTrailingTrivia());
|
||||
return node.ReplaceNode(type, newType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks a <see cref="MemberAccessExpressionSyntax"/> instance and replaces it to be HLSL compatible, if needed
|
||||
/// </summary>
|
||||
/// <param name="node">The input <see cref="MemberAccessExpressionSyntax"/> to check and modify if needed</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModel"/> to use to load symbols for the input node</param>
|
||||
/// <returns>A <see cref="SyntaxNode"/> instance that is compatible with HLSL</returns>
|
||||
[Pure]
|
||||
public static SyntaxNode ReplaceMember(this MemberAccessExpressionSyntax node, SemanticModel semanticModel)
|
||||
{
|
||||
SymbolInfo containingMemberSymbolInfo = semanticModel.GetSymbolInfo(node.Expression);
|
||||
SymbolInfo memberSymbolInfo = semanticModel.GetSymbolInfo(node.Name);
|
||||
|
||||
ISymbol? memberSymbol = memberSymbolInfo.Symbol ?? memberSymbolInfo.CandidateSymbols.FirstOrDefault();
|
||||
|
||||
// If the input member has no symbol or is not a field, property or method, just return it
|
||||
if (memberSymbol is null ||
|
||||
memberSymbol.Kind != SymbolKind.Field &&
|
||||
memberSymbol.Kind != SymbolKind.Property &&
|
||||
memberSymbol.Kind != SymbolKind.Method)
|
||||
{
|
||||
return node;
|
||||
}
|
||||
|
||||
// Process the input node if it's a known method invocation
|
||||
if (HlslKnownMethods.TryGetMappedName(containingMemberSymbolInfo.Symbol, memberSymbol) is string value)
|
||||
{
|
||||
return SyntaxFactory.IdentifierName(value).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -3,7 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Mappings
|
||||
namespace ComputeSharp.Shaders.Mappings
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains and maps known HLSL method names to common .NET method
|
||||
@@ -30,9 +30,9 @@ namespace DirectX12GameEngine.Shaders.Mappings
|
||||
["System.MathF.PI"] = "3.14159274f",
|
||||
|
||||
// ThreadIds
|
||||
["DirectX12GameEngine.Shaders.Primitives.ThreadIds.X"] = ".x",
|
||||
["DirectX12GameEngine.Shaders.Primitives.ThreadIds.Y"] = ".y",
|
||||
["DirectX12GameEngine.Shaders.Primitives.ThreadIds.Z"] = ".z",
|
||||
["ComputeSharp.ThreadIds.X"] = ".x",
|
||||
["ComputeSharp.ThreadIds.Y"] = ".y",
|
||||
["ComputeSharp.ThreadIds.Z"] = ".z",
|
||||
|
||||
// Vector3
|
||||
["System.Numerics.Vector3.X"] = ".x",
|
||||
+6
-6
@@ -3,9 +3,9 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Numerics;
|
||||
using System.Text.RegularExpressions;
|
||||
using DirectX12GameEngine.Shaders.Primitives;
|
||||
using ComputeSharp.Graphics.Buffers;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Mappings
|
||||
namespace ComputeSharp.Shaders.Mappings
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains and maps known HLSL type names to common .NET types
|
||||
@@ -27,7 +27,7 @@ namespace DirectX12GameEngine.Shaders.Mappings
|
||||
[typeof(Vector4).FullName] = "float4",
|
||||
[typeof(Matrix4x4).FullName] = "float4x4",
|
||||
[typeof(ThreadIds).FullName] = "uint3",
|
||||
[typeof(RWBufferResource<>).FullName] = "RWBuffer"
|
||||
[typeof(ReadWriteBuffer<>).FullName] = "RWBuffer"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
@@ -54,13 +54,13 @@ namespace DirectX12GameEngine.Shaders.Mappings
|
||||
type == typeof(Matrix4x4);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not the input type is a <see cref="RWBufferResource{T}"/> value
|
||||
/// Checks whether or not the input type is a <see cref="ReadWriteBuffer{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="RWBufferResource{T}"/> instance</returns>
|
||||
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a <see cref="ReadWriteBuffer{T}"/> instance</returns>
|
||||
[Pure]
|
||||
public static bool IsReadWriteBufferType(Type type) => type.IsGenericType &&
|
||||
type.GetGenericTypeDefinition() == typeof(RWBufferResource<>);
|
||||
type.GetGenericTypeDefinition() == typeof(ReadWriteBuffer<>);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not a given <see cref="Type"/> is an HLSL known type
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
namespace DirectX12GameEngine.Shaders.Primitives
|
||||
namespace ComputeSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="struct"/> that indicates the ids of a given GPU thread running a compute shader
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
namespace DirectX12GameEngine.Shaders.Renderer.Models.Abstract
|
||||
namespace ComputeSharp.Shaders.Renderer.Models.Fields.Abstract
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains info on a shader field
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
|
||||
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Renderer.Models.Fields
|
||||
namespace ComputeSharp.Shaders.Renderer.Models.Fields
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains info on a constant buffer field
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
|
||||
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Renderer.Models.Fields
|
||||
namespace ComputeSharp.Shaders.Renderer.Models.Fields
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains info on a read write buffer field
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
|
||||
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Renderer.Models.Fields
|
||||
namespace ComputeSharp.Shaders.Renderer.Models.Fields
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains info on a static scalar field
|
||||
+20
-5
@@ -1,9 +1,9 @@
|
||||
using System.Collections.Generic;
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
|
||||
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
|
||||
|
||||
#pragma warning disable CS8618 // Non-nullable field is uninitialized
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Renderer.Models
|
||||
namespace ComputeSharp.Shaders.Renderer.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains info to render a shader source to compile
|
||||
@@ -16,20 +16,35 @@ namespace DirectX12GameEngine.Shaders.Renderer.Models
|
||||
public IReadOnlyList<FieldInfoBase> FieldsList { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of threads in the X group
|
||||
/// Gets or sets the total number of threads to run on the X axis
|
||||
/// </summary>
|
||||
public int ThreadsX { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of threads in the Y group
|
||||
/// Gets or sets the total number of threads to run on the Y axis
|
||||
/// </summary>
|
||||
public int ThreadsY { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of threads in the Z group
|
||||
/// Gets or sets the total number of threads to run on the Z axis
|
||||
/// </summary>
|
||||
public int ThreadsZ { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of threads in the X group
|
||||
/// </summary>
|
||||
public int NumThreadsX { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of threads in the Y group
|
||||
/// </summary>
|
||||
public int NumThreadsY { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of threads in the Z group
|
||||
/// </summary>
|
||||
public int NumThreadsZ { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name for the threads id variable used in the shader
|
||||
/// </summary>
|
||||
+3
-3
@@ -2,9 +2,9 @@
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models;
|
||||
using ComputeSharp.Shaders.Renderer.Models;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Renderer
|
||||
namespace ComputeSharp.Shaders.Renderer
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that uses the mustache templating system to render HLSL shaders
|
||||
@@ -24,7 +24,7 @@ namespace DirectX12GameEngine.Shaders.Renderer
|
||||
string
|
||||
assemblyPath = Assembly.GetExecutingAssembly().Location,
|
||||
assemblyDirectory = Path.GetDirectoryName(assemblyPath) ?? throw new InvalidOperationException("Can't find the assembly directory"),
|
||||
templatePath = Path.Combine(assemblyDirectory, "Assets", "ShaderTemplate.mustache");
|
||||
templatePath = Path.Combine(assemblyDirectory, "Renderer", "Templates", "ShaderTemplate.mustache");
|
||||
Template = File.ReadAllText(templatePath);
|
||||
}
|
||||
|
||||
+6
-1
@@ -18,6 +18,11 @@ cbuffer {{FieldName}}Buffer : register(b{{ConstantBufferIndex}})
|
||||
{{/FieldsList}}
|
||||
{{!Shader entry point}}
|
||||
[Shader("compute")]
|
||||
[NumThreads({{ThreadsX}}, {{ThreadsY}}, {{ThreadsZ}})]
|
||||
[NumThreads({{NumThreadsX}}, {{NumThreadsY}}, {{NumThreadsZ}})]
|
||||
void CSMain(uint3 {{ThreadsIdsVariableName}} : SV_DispatchThreadId)
|
||||
{
|
||||
if ({{ThreadsIdsVariableName}}.x < {{ThreadsX}} &&
|
||||
{{ThreadsIdsVariableName}}.y < {{ThreadsY}} &&
|
||||
{{ThreadsIdsVariableName}}.z < {{ThreadsZ}})
|
||||
{{&ShaderBody}}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using ComputeSharp.Graphics;
|
||||
using ComputeSharp.Shaders.Renderer;
|
||||
using ComputeSharp.Shaders.Renderer.Models;
|
||||
using ComputeSharp.Shaders.Translation;
|
||||
using SharpDX.Direct3D12;
|
||||
using CommandList = ComputeSharp.Graphics.CommandList;
|
||||
using PipelineState = ComputeSharp.Graphics.PipelineState;
|
||||
|
||||
namespace ComputeSharp.Shaders
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> responsible for performing all the necessary operations to compile and run a compute shader
|
||||
/// </summary>
|
||||
public static class ShaderRunner
|
||||
{
|
||||
/// <summary>
|
||||
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
|
||||
/// <param name="x">The number of threads to run on the X axis</param>
|
||||
/// <param name="y">The number of threads to run on the Y axis</param>
|
||||
/// <param name="z">The number of threads to run on the Z axis</param>
|
||||
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
|
||||
public static void Run(GraphicsDevice device, int x, int y, int z, Action<ThreadIds> action)
|
||||
{
|
||||
// Calculate the optimized thread num and group values
|
||||
int
|
||||
threadsX = device.WavefrontSize,
|
||||
threadsY = y > 1 ? device.WavefrontSize : 1,
|
||||
threadsZ = z > 1 ? device.WavefrontSize : 1,
|
||||
groupsX = (x - 1) / device.WavefrontSize + 1,
|
||||
groupsY = (y - 1) / device.WavefrontSize + 1,
|
||||
groupsZ = (z - 1) / device.WavefrontSize + 1;
|
||||
|
||||
// Load the input shader
|
||||
ShaderLoader shaderLoader = ShaderLoader.Load(action);
|
||||
|
||||
// Render the loaded shader
|
||||
ShaderInfo shaderInfo = new ShaderInfo
|
||||
{
|
||||
FieldsList = shaderLoader.FieldsInfo,
|
||||
ThreadsX = x,
|
||||
ThreadsY = y,
|
||||
ThreadsZ = z,
|
||||
NumThreadsX = threadsX,
|
||||
NumThreadsY = threadsY,
|
||||
NumThreadsZ = threadsZ,
|
||||
ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName,
|
||||
ShaderBody = shaderLoader.MethodBody
|
||||
};
|
||||
string shaderSource = ShaderRenderer.Instance.Render(shaderInfo);
|
||||
|
||||
// Compile the loaded shader to HLSL bytecode
|
||||
ShaderBytecode shaderBytecode = ShaderCompiler.Instance.CompileShader(shaderSource);
|
||||
|
||||
// Create the root signature for the pipeline and the pipeline state
|
||||
RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, shaderLoader.RootParameters);
|
||||
RootSignature rootSignature = device.CreateRootSignature(rootSignatureDescription);
|
||||
PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode);
|
||||
|
||||
// Create the commands list
|
||||
using CommandList commandList = new CommandList(device, CommandListType.Compute);
|
||||
commandList.SetPipelineState(pipelineState);
|
||||
|
||||
// Load the captured buffers
|
||||
foreach (var buffer in shaderLoader.ReadWriteBuffers.Select((r, i) => (Resource: r, Index: i)))
|
||||
{
|
||||
commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource);
|
||||
}
|
||||
|
||||
// Dispatch and wait for completion
|
||||
commandList.Dispatch(groupsX, groupsY, groupsZ);
|
||||
commandList.Flush(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-52
@@ -12,7 +12,7 @@ using ICSharpCode.Decompiler.Metadata;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
namespace ComputeSharp.Shaders.Translation
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that is able to decompile arbitrary methods
|
||||
@@ -108,8 +108,8 @@ namespace DirectX12GameEngine.Shaders
|
||||
lock (Lock)
|
||||
{
|
||||
// Get the handle of the input method
|
||||
GetMethodHandle(methodInfo, out string assemblyPath, out EntityHandle methodHandle);
|
||||
|
||||
string assemblyPath = methodInfo.DeclaringType?.Assembly.Location ?? throw new InvalidOperationException();
|
||||
EntityHandle methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException();
|
||||
// Get or create a decompiler for the target assembly, and decompile the method
|
||||
if (!Decompilers.TryGetValue(assemblyPath, out CSharpDecompiler decompiler))
|
||||
{
|
||||
@@ -129,55 +129,6 @@ namespace DirectX12GameEngine.Shaders
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the assembly path and method handle for the input <see cref="MethodInfo"/> instance
|
||||
/// </summary>
|
||||
/// <param name="methodInfo">The input <see cref="MethodInfo"/> to inspect</param>
|
||||
/// <param name="assemblyPath">The path of the assembly containing the input method</param>
|
||||
/// <param name="methodHandle">The handle for the input method</param>
|
||||
private void GetMethodHandle(MethodInfo methodInfo, out string assemblyPath, out EntityHandle methodHandle)
|
||||
{
|
||||
// Try to get the method handle from the assembly of the declaring type
|
||||
Type declaringType = methodInfo.DeclaringType ?? throw new InvalidOperationException("Invalid declaring type");
|
||||
string path = declaringType.Assembly.Location;
|
||||
if (!string.IsNullOrEmpty(path))
|
||||
{
|
||||
assemblyPath = path;
|
||||
methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Try to get the PEFile and type definition for the method declaring type
|
||||
if (!TypeDefinitions.TryGetValue(methodInfo.DeclaringType, out (PEFile PEFile, TypeDefinition TypeDefinition) tuple))
|
||||
{
|
||||
foreach (PEFile peFile in PEFiles)
|
||||
{
|
||||
// If not available, browse through the loaded PEFiles to find the type definition
|
||||
TypeDefinitionHandle typeDefinitionHandle = peFile.Metadata.TypeDefinitions.FirstOrDefault(t => t.GetFullTypeName(peFile.Metadata).ToString() == methodInfo.DeclaringType.FullName);
|
||||
|
||||
if (!typeDefinitionHandle.IsNil)
|
||||
{
|
||||
tuple = (peFile, peFile.Metadata.GetTypeDefinition(typeDefinitionHandle));
|
||||
TypeDefinitions.Add(methodInfo.DeclaringType, tuple);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (tuple.PEFile is null) throw new InvalidOperationException($"Missing PEFile for declaring type {methodInfo.DeclaringType.FullName}");
|
||||
}
|
||||
|
||||
PEFile peFileForMethod = tuple.PEFile;
|
||||
TypeDefinition typeDefinition = tuple.TypeDefinition;
|
||||
|
||||
// Retrieve the assembly path and method handle from the loaded PEFile and metadata
|
||||
assemblyPath = peFileForMethod.FileName;
|
||||
methodHandle = typeDefinition.GetMethods()
|
||||
.Where(m => peFileForMethod.Metadata.StringComparer.Equals(peFileForMethod.Metadata.GetMethodDefinition(m).Name, methodInfo.Name))
|
||||
.First(m => peFileForMethod.Metadata.GetMethodDefinition(m).GetParameters().Count == methodInfo.GetParameters().Length);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="CSharpDecompiler"/> instance targeting a given assembly
|
||||
/// </summary>
|
||||
+1
-1
@@ -3,7 +3,7 @@ using System.Diagnostics.Contracts;
|
||||
using DotNetDxc;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
namespace ComputeSharp.Shaders.Translation
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that uses the <see cref="HlslDxcLib"/> APIs to compile compute shaders
|
||||
+8
-10
@@ -4,18 +4,17 @@ using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
using DirectX12GameEngine.Graphics.Buffers.Abstract;
|
||||
using DirectX12GameEngine.Shaders.Mappings;
|
||||
using DirectX12GameEngine.Shaders.Primitives;
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models.Fields;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
using ComputeSharp.Shaders.Mappings;
|
||||
using ComputeSharp.Shaders.Renderer.Models.Fields;
|
||||
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
#pragma warning disable CS8618 // Non-nullable field is uninitialized
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
namespace ComputeSharp.Shaders.Translation
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> responsible for loading and processing <see cref="Action{T}"/> instances
|
||||
@@ -123,9 +122,7 @@ namespace DirectX12GameEngine.Shaders
|
||||
descriptorRanges.Add(range);
|
||||
|
||||
// Reference to the underlying buffer
|
||||
object readWriteBuffer = fieldInfo.GetValue(ShaderInstance);
|
||||
GraphicsResource resource = (GraphicsResource)fieldType.GetProperty(nameof(RWBufferResource<byte>.Buffer)).GetValue(readWriteBuffer);
|
||||
readWriteBuffers.Add(resource);
|
||||
readWriteBuffers.Add((GraphicsResource)fieldValue);
|
||||
|
||||
string typeName = HlslKnownTypes.GetMappedName(fieldType);
|
||||
processedFieldInfo = new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++);
|
||||
@@ -154,7 +151,7 @@ namespace DirectX12GameEngine.Shaders
|
||||
MethodDecompiler.Instance.GetSyntaxTree(Action.Method, out SyntaxNode root, out SemanticModel semanticModel);
|
||||
|
||||
// Rewrite the shader method (eg. to fix the type declarations)
|
||||
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, true);
|
||||
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel);
|
||||
root = syntaxRewriter.Visit(root);
|
||||
|
||||
// Get the thread ids identifier name and shader method body
|
||||
@@ -164,6 +161,7 @@ namespace DirectX12GameEngine.Shaders
|
||||
|
||||
// Additional preprocessing
|
||||
MethodBody = Regex.Replace(MethodBody, @"\d+[fFdD]", m => m.Value.Replace("f", ""));
|
||||
MethodBody = MethodBody.TrimEnd('\n', '\r', ' ');
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
-46
@@ -1,33 +1,31 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using ComputeSharp.Shaders.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
namespace ComputeSharp.Shaders.Translation
|
||||
{
|
||||
/// <summary>
|
||||
/// A custom <see cref="CSharpSyntaxRewriter"/> <see langword="class"/> that processes C# methods to convert to HLSL
|
||||
/// </summary>
|
||||
public class ShaderSyntaxRewriter : CSharpSyntaxRewriter
|
||||
{
|
||||
private readonly int depth;
|
||||
private readonly bool isTopLevel;
|
||||
private readonly SemanticModel semanticModel;
|
||||
/// <summary>
|
||||
/// The <see cref="Microsoft.CodeAnalysis.SemanticModel"/> instance to use to rewrite the decompiled code
|
||||
/// </summary>
|
||||
private readonly SemanticModel SemanticModel;
|
||||
|
||||
public ShaderSyntaxRewriter(SemanticModel semanticModel, bool isTopLevel = false, int depth = 0)
|
||||
{
|
||||
this.semanticModel = semanticModel;
|
||||
this.isTopLevel = isTopLevel;
|
||||
this.depth = depth;
|
||||
}
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderSyntaxRewriter"/> instance with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="semanticModel"></param>
|
||||
public ShaderSyntaxRewriter(SemanticModel semanticModel) => SemanticModel = semanticModel;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
|
||||
{
|
||||
node = (MethodDeclarationSyntax)base.VisitMethodDeclaration(node);
|
||||
|
||||
if (isTopLevel && depth > 0)
|
||||
{
|
||||
node = node.ReplaceToken(node.Identifier, SyntaxFactory.Identifier($"Base_{depth}_{node.Identifier.ValueText}"));
|
||||
}
|
||||
|
||||
SyntaxTokenList modifiers = new SyntaxTokenList();
|
||||
|
||||
if (node.Modifiers.Any(SyntaxKind.StaticKeyword))
|
||||
@@ -38,6 +36,7 @@ namespace DirectX12GameEngine.Shaders
|
||||
return node.ReplaceType(node.ReturnType).WithModifiers(modifiers);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitParameter(ParameterSyntax node)
|
||||
{
|
||||
node = (ParameterSyntax)base.VisitParameter(node);
|
||||
@@ -47,18 +46,23 @@ namespace DirectX12GameEngine.Shaders
|
||||
return node;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
|
||||
{
|
||||
node = (CastExpressionSyntax)base.VisitCastExpression(node);
|
||||
|
||||
return node.ReplaceType(node.Type);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
|
||||
{
|
||||
node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node);
|
||||
|
||||
return node.ReplaceType(node.Declaration.Type);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
|
||||
{
|
||||
node = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node);
|
||||
@@ -68,48 +72,25 @@ namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
return SyntaxFactory.CastExpression(node.Type, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)));
|
||||
}
|
||||
else
|
||||
{
|
||||
return SyntaxFactory.InvocationExpression(node.Type, node.ArgumentList);
|
||||
}
|
||||
|
||||
return SyntaxFactory.InvocationExpression(node.Type, node.ArgumentList);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node)
|
||||
{
|
||||
node = (DefaultExpressionSyntax)base.VisitDefaultExpression(node);
|
||||
node = node.ReplaceType(node.Type);
|
||||
|
||||
return SyntaxFactory.CastExpression(node.Type, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
|
||||
{
|
||||
node = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node);
|
||||
|
||||
if (node.Expression is BaseExpressionSyntax)
|
||||
{
|
||||
if (isTopLevel)
|
||||
{
|
||||
return SyntaxFactory.IdentifierName($"Base_{depth + 1}_{node.Name}");
|
||||
}
|
||||
else
|
||||
{
|
||||
SymbolInfo memberSymbolInfo = semanticModel.GetSymbolInfo(node.Name);
|
||||
ISymbol? memberSymbol = memberSymbolInfo.Symbol ?? memberSymbolInfo.CandidateSymbols.FirstOrDefault();
|
||||
|
||||
if (memberSymbol != null)
|
||||
{
|
||||
return SyntaxFactory.IdentifierName($"{memberSymbol.ContainingType.Name}::{node.Name}");
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return node.ReplaceMember(semanticModel);
|
||||
}
|
||||
return node.ReplaceMember(SemanticModel);
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-4
@@ -3,13 +3,20 @@ Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.29201.188
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DirectX12GameEngine.Graphics", "DirectX12GameEngine.Graphics\DirectX12GameEngine.Graphics.csproj", "{2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Graphics", "ComputeSharp.Graphics\ComputeSharp.Graphics.csproj", "{2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DirectX12GameEngine.Shaders", "DirectX12GameEngine.Shaders\DirectX12GameEngine.Shaders.csproj", "{23AE6EED-79CD-4ADD-9A85-0148BD957D19}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Shaders", "ComputeSharp.Shaders\ComputeSharp.Shaders.csproj", "{23AE6EED-79CD-4ADD-9A85-0148BD957D19}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DirectX12GameEngine.Core", "DirectX12GameEngine.Core\DirectX12GameEngine.Core.csproj", "{314EB353-E7E3-4146-8111-685CC83EC1DE}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp", "ComputeSharp\ComputeSharp.csproj", "{314EB353-E7E3-4146-8111-685CC83EC1DE}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DirectX12ComputeShaderSample", "DirectX12ComputeShaderSample\DirectX12ComputeShaderSample.csproj", "{7A48A85D-8866-4DED-A404-653ED09BF396}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetCoreComputeShaderSample", "..\samples\NetCoreComputeShaderSample\NetCoreComputeShaderSample.csproj", "{7A48A85D-8866-4DED-A404-653ED09BF396}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_SolutionItems", "_SolutionItems", "{1A9C4108-F61A-4ABE-B5CF-F524521EAE2D}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
..\.gitignore = ..\.gitignore
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@@ -55,6 +62,9 @@ Global
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{7A48A85D-8866-4DED-A404-653ED09BF396} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC}
|
||||
EndGlobalSection
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>8.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Windows.SDK.Contracts" Version="10.0.18362.2002-preview" />
|
||||
<PackageReference Include="System.Memory" Version="4.5.3" />
|
||||
<PackageReference Include="System.Numerics.Vectors" Version="4.6.0-preview5.19224.8" />
|
||||
<PackageReference Include="System.Runtime.InteropServices.WindowsRuntime" Version="4.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ComputeSharp.Shaders\ComputeSharp.Shaders.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using ComputeSharp.Graphics;
|
||||
using ComputeSharp.Shaders;
|
||||
|
||||
namespace ComputeSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains extension methods for the <see cref="GraphicsDevice"/> type, used to run compute shaders
|
||||
/// </summary>
|
||||
public static class GraphicsDeviceExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
|
||||
/// <param name="x">The number of threads to run on the X axis</param>
|
||||
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
|
||||
public static void For(this GraphicsDevice device, int x, Action<ThreadIds> action) => ShaderRunner.Run(device, x, 1, 1, action);
|
||||
|
||||
/// <summary>
|
||||
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
|
||||
/// <param name="x">The number of threads to run on the X axis</param>
|
||||
/// <param name="y">The number of threads to run on the Y axis</param>
|
||||
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
|
||||
public static void For(this GraphicsDevice device, int x, int y, Action<ThreadIds> action) => ShaderRunner.Run(device, x, y, 1, action);
|
||||
|
||||
/// <summary>
|
||||
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
|
||||
/// <param name="x">The number of threads to run on the X axis</param>
|
||||
/// <param name="y">The number of threads to run on the Y axis</param>
|
||||
/// <param name="z">The number of threads to run on the Z axis</param>
|
||||
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
|
||||
public static void For(this GraphicsDevice device, int x, int y, int z, Action<ThreadIds> action) => ShaderRunner.Run(device, x, y, z, action);
|
||||
}
|
||||
}
|
||||
差分なしでファイル名を変更。
差分なしでファイル名を変更。
差分なしでファイル名を変更。
@@ -0,0 +1,17 @@
|
||||
using ComputeSharp.Graphics;
|
||||
|
||||
namespace ComputeSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that acts as an entry-point for all the library APIs, exposing the available GPU devices
|
||||
/// </summary>
|
||||
public static class Gpu
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp3.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DirectX12GameEngine.Graphics\DirectX12GameEngine.Graphics.csproj" />
|
||||
<ProjectReference Include="..\DirectX12GameEngine.Shaders\DirectX12GameEngine.Shaders.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,64 +0,0 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using DirectX12GameEngine.Graphics;
|
||||
using DirectX12GameEngine.Shaders;
|
||||
using DirectX12GameEngine.Shaders.Primitives;
|
||||
using DirectX12GameEngine.Shaders.Renderer;
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models;
|
||||
using SharpDX.Direct3D12;
|
||||
using CommandList = DirectX12GameEngine.Graphics.CommandList;
|
||||
using PipelineState = DirectX12GameEngine.Graphics.PipelineState;
|
||||
using ShaderBytecode = SharpDX.Direct3D12.ShaderBytecode;
|
||||
|
||||
namespace DirectX12ComputeShaderSample
|
||||
{
|
||||
public static class Gpu
|
||||
{
|
||||
private static GraphicsDevice _Default;
|
||||
|
||||
public static GraphicsDevice Default => _Default ??= new GraphicsDevice(true);
|
||||
}
|
||||
|
||||
public static class GraphicsDeviceExtensions
|
||||
{
|
||||
public static void For(this GraphicsDevice device, int n, Action<ThreadIds> action)
|
||||
{
|
||||
// Load the input shader
|
||||
ShaderLoader shaderLoader = ShaderLoader.Load(action);
|
||||
|
||||
// Render the loaded shader
|
||||
ShaderInfo shaderInfo = new ShaderInfo
|
||||
{
|
||||
FieldsList = shaderLoader.FieldsInfo,
|
||||
ThreadsX = n,
|
||||
ThreadsY = 1,
|
||||
ThreadsZ = 1,
|
||||
ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName,
|
||||
ShaderBody = shaderLoader.MethodBody
|
||||
};
|
||||
string shaderSource = ShaderRenderer.Instance.Render(shaderInfo);
|
||||
|
||||
// Compile the loaded shader to HLSL bytecode
|
||||
ShaderBytecode shaderBytecode = ShaderCompiler.Instance.CompileShader(shaderSource);
|
||||
|
||||
// Create the root signature for the pipeline and the pipeline state
|
||||
RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, shaderLoader.RootParameters);
|
||||
RootSignature rootSignature = device.CreateRootSignature(rootSignatureDescription);
|
||||
PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode);
|
||||
|
||||
// Create the commands list
|
||||
using CommandList commandList = new CommandList(device, CommandListType.Compute);
|
||||
commandList.SetPipelineState(pipelineState);
|
||||
|
||||
// Load the captured buffers
|
||||
foreach (var buffer in shaderLoader.ReadWriteBuffers.Select((r, i) => (Resource: r, Index: i)))
|
||||
{
|
||||
commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource);
|
||||
}
|
||||
|
||||
// Dispatch and wait for completion
|
||||
commandList.Dispatch(1, 1, 1);
|
||||
commandList.Flush(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public struct BufferDescription
|
||||
{
|
||||
public BufferDescription(int sizeInBytes, BufferFlags bufferFlags, GraphicsHeapType heapType)
|
||||
{
|
||||
SizeInBytes = sizeInBytes;
|
||||
Flags = bufferFlags;
|
||||
HeapType = heapType;
|
||||
}
|
||||
|
||||
public int SizeInBytes;
|
||||
|
||||
public BufferFlags Flags;
|
||||
|
||||
public GraphicsHeapType HeapType;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
[Flags]
|
||||
public enum BufferFlags
|
||||
{
|
||||
None = 0,
|
||||
ConstantBuffer = 1,
|
||||
IndexBuffer = 2,
|
||||
VertexBuffer = 4,
|
||||
RenderTarget = 8,
|
||||
ShaderResource = 16,
|
||||
UnorderedAccess = 32,
|
||||
StructuredBuffer = 64,
|
||||
RawBuffer = 512,
|
||||
ArgumentBuffer = 1024
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics.Buffers
|
||||
{
|
||||
public partial class Buffer
|
||||
{
|
||||
public static class Constant
|
||||
{
|
||||
public static unsafe Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Upload)
|
||||
{
|
||||
return Buffer.New(device, size, BufferFlags.ConstantBuffer, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, in T data, GraphicsHeapType heapType = GraphicsHeapType.Upload) where T : unmanaged
|
||||
{
|
||||
return Buffer.New(device, data, BufferFlags.ConstantBuffer, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, Span<T> data, GraphicsHeapType heapType = GraphicsHeapType.Upload) where T : unmanaged
|
||||
{
|
||||
return Buffer.New(device, data, BufferFlags.ConstantBuffer, heapType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics.Buffers
|
||||
{
|
||||
public partial class Buffer
|
||||
{
|
||||
public static class UnorderedAccess
|
||||
{
|
||||
public static unsafe Buffers.Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Default)
|
||||
{
|
||||
return Buffers.Buffer.New(device, size, BufferFlags.UnorderedAccess, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, in T data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
return Buffers.Buffer.New(device, data, BufferFlags.UnorderedAccess, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, Span<T> data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
return Buffers.Buffer.New(device, data, BufferFlags.UnorderedAccess, heapType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using DirectX12GameEngine.Core.Helpers;
|
||||
using DirectX12GameEngine.Graphics.Buffers.Abstract;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics.Buffers
|
||||
{
|
||||
public partial class Buffer : GraphicsResource
|
||||
{
|
||||
protected Buffer(GraphicsDevice device) : base(device)
|
||||
{
|
||||
}
|
||||
|
||||
public BufferDescription Description { get; private set; }
|
||||
|
||||
public int SizeInBytes => Description.SizeInBytes;
|
||||
|
||||
public BufferFlags Flags => Description.Flags;
|
||||
|
||||
public GraphicsHeapType Usage => Description.HeapType;
|
||||
|
||||
public int ElementCount { get; protected set; }
|
||||
|
||||
public T[] GetData<T>() where T : unmanaged
|
||||
{
|
||||
T[] data = new T[SizeInBytes / Unsafe.SizeOf<T>()];
|
||||
GetData(data.AsSpan());
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
public unsafe void GetData<T>(ref T data, int offsetInBytes = 0) where T : unmanaged
|
||||
{
|
||||
fixed (T* pointer = &data)
|
||||
{
|
||||
GetData(new Span<T>(pointer, 1), offsetInBytes);
|
||||
}
|
||||
}
|
||||
|
||||
public void GetData<T>(Span<T> data, int offsetInBytes = 0) where T : unmanaged
|
||||
{
|
||||
if (Usage == GraphicsHeapType.Default)
|
||||
{
|
||||
using Buffer<T> readbackBaffer = New<T>(GraphicsDevice, data.Length, BufferFlags.None, GraphicsHeapType.Readback);
|
||||
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
|
||||
|
||||
copyCommandList.CopyBufferRegion(this, offsetInBytes, readbackBaffer, 0, data.Length * Unsafe.SizeOf<T>());
|
||||
copyCommandList.Flush(true);
|
||||
|
||||
readbackBaffer.GetData(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
Map(0);
|
||||
MemoryHelper.Copy(MappedResource + offsetInBytes, data);
|
||||
Unmap(0);
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void SetData<T>(in T data, int offsetInBytes = 0) where T : unmanaged
|
||||
{
|
||||
fixed (T* pointer = &data)
|
||||
{
|
||||
SetData(new Span<T>(pointer, 1), offsetInBytes);
|
||||
}
|
||||
}
|
||||
|
||||
public void SetData<T>(Span<T> data, int offsetInBytes = 0) where T : unmanaged
|
||||
{
|
||||
if (Usage == GraphicsHeapType.Default)
|
||||
{
|
||||
using Buffer<T> uploadBuffer = New(GraphicsDevice, data, BufferFlags.None, GraphicsHeapType.Upload);
|
||||
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
|
||||
|
||||
copyCommandList.CopyBufferRegion(uploadBuffer, 0, this, offsetInBytes, data.Length * Unsafe.SizeOf<T>());
|
||||
copyCommandList.Flush(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
Map(0);
|
||||
MemoryHelper.Copy(data, MappedResource + offsetInBytes);
|
||||
Unmap(0);
|
||||
}
|
||||
}
|
||||
|
||||
public Buffers.Buffer ToReadback()
|
||||
{
|
||||
BufferDescription description = Description;
|
||||
description.HeapType = GraphicsHeapType.Readback;
|
||||
description.Flags = BufferFlags.None;
|
||||
|
||||
return New(GraphicsDevice, description);
|
||||
}
|
||||
|
||||
public static Buffers.Buffer New(GraphicsDevice device, BufferDescription description)
|
||||
{
|
||||
return new Buffers.Buffer(device).InitializeFrom(description);
|
||||
}
|
||||
|
||||
public static Buffers.Buffer New(GraphicsDevice device, int size, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default)
|
||||
{
|
||||
return New(device, new BufferDescription(size, bufferFlags, heapType));
|
||||
}
|
||||
|
||||
public static Buffer<T> New<T>(GraphicsDevice device, int elementCount, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
int bufferSize = elementCount * Unsafe.SizeOf<T>();
|
||||
|
||||
return new Buffer<T>(device, bufferSize, bufferFlags, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, in T data, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
fixed (T* pointer = &data)
|
||||
{
|
||||
return New(device, new Span<T>(pointer, 1), bufferFlags, heapType);
|
||||
}
|
||||
}
|
||||
|
||||
public static Buffer<T> New<T>(GraphicsDevice device, Span<T> data, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
Buffer<T> buffer = New<T>(device, data.Length, bufferFlags, heapType);
|
||||
buffer.SetData(data);
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
protected internal Buffers.Buffer InitializeFrom(BufferDescription description)
|
||||
{
|
||||
ResourceStates resourceStates = ResourceStates.Common;
|
||||
|
||||
if (description.HeapType == GraphicsHeapType.Upload)
|
||||
{
|
||||
resourceStates = ResourceStates.GenericRead;
|
||||
}
|
||||
else if (description.HeapType == GraphicsHeapType.Readback)
|
||||
{
|
||||
resourceStates = ResourceStates.CopyDestination;
|
||||
}
|
||||
|
||||
NativeResource ??= GraphicsDevice.NativeDevice.CreateCommittedResource(
|
||||
new HeapProperties((HeapType)description.HeapType), HeapFlags.None,
|
||||
ConvertToNativeDescription(description), resourceStates);
|
||||
|
||||
Description = description;
|
||||
|
||||
(NativeCpuDescriptorHandle, NativeGpuDescriptorHandle) = description.Flags switch
|
||||
{
|
||||
BufferFlags.ConstantBuffer => CreateConstantBufferView(),
|
||||
BufferFlags.ShaderResource => CreateShaderResourceView(),
|
||||
BufferFlags.UnorderedAccess => CreateUnorderedAccessView(),
|
||||
_ => default
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
private static ResourceDescription ConvertToNativeDescription(BufferDescription description)
|
||||
{
|
||||
int size = description.SizeInBytes;
|
||||
ResourceFlags flags = ResourceFlags.None;
|
||||
|
||||
if (description.Flags.HasFlag(BufferFlags.UnorderedAccess))
|
||||
{
|
||||
flags |= ResourceFlags.AllowUnorderedAccess;
|
||||
//flags |= ResourceFlags.AllowSimultaneousAccess;
|
||||
}
|
||||
|
||||
return ResourceDescription.Buffer(size, flags);
|
||||
}
|
||||
|
||||
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateConstantBufferView()
|
||||
{
|
||||
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
|
||||
|
||||
int constantBufferSize = (SizeInBytes + 255) & ~255;
|
||||
|
||||
ConstantBufferViewDescription cbvDescription = new ConstantBufferViewDescription
|
||||
{
|
||||
BufferLocation = NativeResource.GPUVirtualAddress,
|
||||
SizeInBytes = constantBufferSize
|
||||
};
|
||||
|
||||
GraphicsDevice.NativeDevice.CreateConstantBufferView(cbvDescription, cpuHandle);
|
||||
|
||||
return (cpuHandle, gpuHandle);
|
||||
}
|
||||
|
||||
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateShaderResourceView()
|
||||
{
|
||||
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
|
||||
GraphicsDevice.NativeDevice.CreateShaderResourceView(NativeResource, null, cpuHandle);
|
||||
|
||||
return (cpuHandle, gpuHandle);
|
||||
}
|
||||
|
||||
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateUnorderedAccessView()
|
||||
{
|
||||
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
|
||||
|
||||
var description = new UnorderedAccessViewDescription
|
||||
{
|
||||
Format = SharpDX.DXGI.Format.R32_Float,
|
||||
Dimension = UnorderedAccessViewDimension.Buffer,
|
||||
Buffer =
|
||||
{
|
||||
ElementCount = ElementCount,
|
||||
}
|
||||
};
|
||||
|
||||
GraphicsDevice.NativeDevice.CreateUnorderedAccessView(NativeResource, null, description, cpuHandle);
|
||||
|
||||
return (cpuHandle, gpuHandle);
|
||||
}
|
||||
}
|
||||
|
||||
public class Buffer<T> : Buffers.Buffer where T : unmanaged
|
||||
{
|
||||
protected internal Buffer(GraphicsDevice device, int size, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) : base(device)
|
||||
{
|
||||
ElementSize = Unsafe.SizeOf<T>();
|
||||
ElementCount = size / ElementSize;
|
||||
|
||||
InitializeFrom(new BufferDescription(size, bufferFlags, heapType));
|
||||
}
|
||||
|
||||
public int ElementSize { get; }
|
||||
|
||||
public T[] GetData() => GetData<T>();
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>8.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="SharpDX.Direct3D12" Version="4.2.1-beta0-gab36f12303" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DirectX12GameEngine.Core\DirectX12GameEngine.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,18 +0,0 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
public class ShaderGenerationResult
|
||||
{
|
||||
public ShaderGenerationResult(string shaderSource, string computeShader)
|
||||
{
|
||||
ShaderSource = shaderSource;
|
||||
ComputeShader = computeShader;
|
||||
}
|
||||
|
||||
public string ShaderSource { get; }
|
||||
|
||||
public string ComputeShader { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using DirectX12GameEngine.Graphics.Buffers;
|
||||
using Buffer = System.Buffer;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
public abstract class ShaderResource
|
||||
{
|
||||
}
|
||||
|
||||
public sealed class RWBufferResource<T> : ShaderResource where T : unmanaged
|
||||
{
|
||||
internal RWBufferResource(Buffer<T> buffer) => Buffer = buffer;
|
||||
|
||||
public Buffer<T> Buffer { get; }
|
||||
|
||||
public T this[uint index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
|
||||
}
|
||||
|
||||
public static class RWBufferResourceExtensions
|
||||
{
|
||||
public static RWBufferResource<T> GetGpuResource<T>(this Buffer<T> buffer) where T : unmanaged
|
||||
{
|
||||
return new RWBufferResource<T>(buffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
using System.Linq;
|
||||
using DirectX12GameEngine.Shaders.Mappings;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
public static class SyntaxNodeExtensions
|
||||
{
|
||||
public static TRoot ReplaceType<TRoot>(this TRoot node, TypeSyntax type) where TRoot : SyntaxNode
|
||||
{
|
||||
string value = HlslKnownTypes.GetMappedName(type.ToString());
|
||||
|
||||
if (value == type.ToString())
|
||||
{
|
||||
return node;
|
||||
}
|
||||
else
|
||||
{
|
||||
return node.ReplaceNode(type, SyntaxFactory.ParseTypeName(value).WithLeadingTrivia(type.GetLeadingTrivia()).WithTrailingTrivia(type.GetTrailingTrivia()));
|
||||
}
|
||||
}
|
||||
|
||||
public static SyntaxNode ReplaceMember(this MemberAccessExpressionSyntax node, SemanticModel semanticModel)
|
||||
{
|
||||
SymbolInfo containingMemberSymbolInfo = semanticModel.GetSymbolInfo(node.Expression);
|
||||
SymbolInfo memberSymbolInfo = semanticModel.GetSymbolInfo(node.Name);
|
||||
|
||||
ISymbol? memberSymbol = memberSymbolInfo.Symbol ?? memberSymbolInfo.CandidateSymbols.FirstOrDefault();
|
||||
|
||||
if (memberSymbol is null || (memberSymbol.Kind != SymbolKind.Field && memberSymbol.Kind != SymbolKind.Property && memberSymbol.Kind != SymbolKind.Method))
|
||||
{
|
||||
return node;
|
||||
}
|
||||
|
||||
if (HlslKnownMethods.TryGetMappedName(containingMemberSymbolInfo.Symbol, memberSymbol) is string value)
|
||||
{
|
||||
return SyntaxFactory.IdentifierName(value).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする