Merge pull request #615 from Sergio0694/dev/thread-ids

Tweak IShader, add HlslBytecode and [NumThreads] properties
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-10-14 09:53:07 +02:00
コミット 8a4e63fcec
18ファイル変更
+314 -442

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

+2 -18
ファイルの表示
@@ -249,24 +249,8 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene
using (writer.WriteBlock())
{
// Add the System directives first, in the correct order
foreach (string usingDirective in usingDirectives.AsEnumerable().Where(static name => name.StartsWith("global::System")).OrderBy(static name => name))
{
writer.WriteLine($"using {usingDirective};");
}
// Add the other directives, also sorted in the correct order
foreach (string usingDirective in usingDirectives.AsEnumerable().Where(static name => !name.StartsWith("global::System")).OrderBy(static name => name))
{
writer.WriteLine($"using {usingDirective};");
}
foreach (IndentedTextWriter.Callback<D2D1ShaderInfo> callback in additionalTypes.WrittenSpan)
{
writer.WriteLine();
callback(item, writer);
}
writer.WriteSortedUsingDirectives(usingDirectives.AsEnumerable());
writer.WriteLineSeparatedMembers(additionalTypes.WrittenSpan, (callback, writer) => callback(item, writer));
}
}
+26
ファイルの表示
@@ -1,4 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using ComputeSharp.SourceGeneration.Helpers;
@@ -40,6 +42,30 @@ internal static class IndentedTextWriterExtensions
}
}
/// <summary>
/// Writes a sequence of using directives, sorted correctly.
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="usingDirectives">The sequence of using directives to write.</param>
public static void WriteSortedUsingDirectives(this IndentedTextWriter writer, IEnumerable<string> usingDirectives)
{
// Add the System directives first, in the correct order
foreach (string usingDirective in usingDirectives.Where(static name => name.StartsWith("global::System")).OrderBy(static name => name))
{
writer.WriteLine($"using {usingDirective};");
}
// Add the other directives, also sorted in the correct order
foreach (string usingDirective in usingDirectives.Where(static name => !name.StartsWith("global::System")).OrderBy(static name => name))
{
writer.WriteLine($"using {usingDirective};");
}
// Leave a trailing blank line if at least one using directive has been written.
// This is so that any members will correctly have a leading blank line before.
writer.WriteLineIf(usingDirectives.Any());
}
/// <summary>
/// Writes a new line into the target writer depending on an input condition.
/// </summary>
+124 -14
ファイルの表示
@@ -12,38 +12,148 @@ partial class IShaderGenerator
partial class LoadBytecode
{
/// <summary>
/// Writes the <c>LoadBytecode</c> method.
/// Writes the <c>HlslBytecode</c> property.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
public static void WriteHlslBytecodeSyntax(ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadBytecode<TLoader>(ref TLoader loader, int threadsX, int threadsY, int threadsZ)");
writer.Write($"readonly global::System.ReadOnlyMemory<byte> global::ComputeSharp.__Internals.IShader.HlslBytecode => ");
using (writer.WriteBlock())
// Just like with the D2D1 generator, only return the MemoryManager<T> if we do have HLSL bytecode
if (info.HlslInfo is not HlslBytecodeInfo.Success)
{
// If there is no HLSL bytecode, there's nothing left to do
if (info.HlslInfo is not HlslBytecodeInfo.Success success)
{
return;
}
writer.WriteLine("default;");
}
else
{
writer.WriteLine("global::ComputeSharp.Generated.HlslBytecodeMemoryManager.Instance.Memory;");
}
}
// Check that the [numthreads] values match
writer.WriteLine($"if (threadsX == {info.ThreadsX} && threadsY == {info.ThreadsY} && threadsZ == {info.ThreadsZ})");
/// <summary>
/// Registers a callback to generate an additional type, if needed.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void RegisterAdditionalTypeSyntax(
ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> usingDirectives)
{
// If there is no bytecode, no memory manager is needed
if (info.HlslInfo is not HlslBytecodeInfo.Success)
{
return;
}
usingDirectives.Add("global::System");
usingDirectives.Add("global::System.Buffers");
usingDirectives.Add("global::System.CodeDom.Compiler");
usingDirectives.Add("global::System.Diagnostics");
usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
usingDirectives.Add("global::System.Runtime.CompilerServices");
usingDirectives.Add("global::System.Runtime.InteropServices");
// Declare the HlslBytecodeMemoryManager custom memory manager type
static void Callback(ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine($$"""/// <summary>""");
writer.WriteLine($$"""/// <see cref="MemoryManager{T}"/> implementation to get the HLSL bytecode.""");
writer.WriteLine($$"""/// </summary>""");
writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false);
writer.WriteLine($$"""file sealed class HlslBytecodeMemoryManager : MemoryManager<byte>""");
using (writer.WriteBlock())
{
writer.Write("global::System.ReadOnlySpan<byte> bytecode = new byte[] { ");
// Static singleton instance (to avoid the static constructor, just like with the input types)
writer.WriteLine($$"""/// <summary>The singleton <see cref="HlslBytecodeMemoryManager"/> instance to use.</summary>""");
writer.WriteLine($$"""public static readonly HlslBytecodeMemoryManager Instance = new();""");
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(success.Bytecode.AsSpan(), writer);
// RVA field (with the compiled HLSL bytecode, on a single line)
writer.WriteLine();
writer.WriteLine("/// <summary>The RVA data with the HLSL bytecode.</summary>");
writer.Write("private static ReadOnlySpan<byte> Data => new byte[] { ");
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(((HlslBytecodeInfo.Success)info.HlslInfo).Bytecode.AsSpan(), writer);
writer.WriteLine(" };");
writer.WriteLine();
writer.WriteLine("loader.LoadEmbeddedBytecode(bytecode);");
// Add the remaining members for the memory manager
writer.WriteLine("""
/// <inheritdoc/>
public override unsafe Span<byte> GetSpan()
{
return new(Unsafe.AsPointer(ref MemoryMarshal.GetReference(Data)), Data.Length);
}
/// <inheritdoc/>
public override Memory<byte> Memory
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => CreateMemory(Data.Length);
}
/// <inheritdoc/>
public override unsafe MemoryHandle Pin(int elementIndex)
{
return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
}
/// <inheritdoc/>
public override void Unpin()
{
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
}
""", isMultiline: true);
}
}
callbacks.Add(Callback);
}
/// <summary>
/// Writes the <c>ThreadsX</c> property.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteThreadsXSyntax(ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine($"readonly int global::ComputeSharp.__Internals.IShader.ThreadsX => {info.ThreadsX};");
}
/// <summary>
/// Writes the <c>ThreadsY</c> property.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteThreadsYSyntax(ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine($"readonly int global::ComputeSharp.__Internals.IShader.ThreadsY => {info.ThreadsY};");
}
/// <summary>
/// Writes the <c>ThreadsZ</c> property.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteThreadsZSyntax(ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine($"readonly int global::ComputeSharp.__Internals.IShader.ThreadsZ => {info.ThreadsZ};");
}
}
}
+22 -1
ファイルの表示
@@ -145,10 +145,18 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
{
using ImmutableArrayBuilder<IndentedTextWriter.Callback<ShaderInfo>> declaredMembers = new();
declaredMembers.Add(LoadBytecode.WriteThreadsXSyntax);
declaredMembers.Add(LoadBytecode.WriteThreadsYSyntax);
declaredMembers.Add(LoadBytecode.WriteThreadsZSyntax);
declaredMembers.Add(LoadBytecode.WriteHlslBytecodeSyntax);
declaredMembers.Add(LoadDispatchData.WriteSyntax);
declaredMembers.Add(LoadDispatchMetadata.WriteSyntax);
declaredMembers.Add(BuildHlslSource.WriteSyntax);
declaredMembers.Add(LoadBytecode.WriteSyntax);
using ImmutableArrayBuilder<IndentedTextWriter.Callback<ShaderInfo>> additionalTypes = new();
using ImmutableHashSetBuilder<string> usingDirectives = new();
LoadBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
using IndentedTextWriter writer = new();
@@ -158,6 +166,19 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
baseTypes: ReadOnlySpan<string>.Empty,
memberCallbacks: declaredMembers.WrittenSpan);
// Append any additional types as well
if (additionalTypes.Count > 0)
{
writer.WriteLine();
writer.WriteLine("namespace ComputeSharp.Generated");
using (writer.WriteBlock())
{
writer.WriteSortedUsingDirectives(usingDirectives.AsEnumerable());
writer.WriteLineSeparatedMembers(additionalTypes.WrittenSpan, (callback, writer) => callback(item, writer));
}
}
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString());
});
}
-19
ファイルの表示
@@ -1,19 +0,0 @@
using System;
using System.ComponentModel;
namespace ComputeSharp.__Internals;
/// <summary>
/// A base <see langword="interface"/> representing a bytecode loader for a shader being dispatched.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This interface is not intended to be used directly by user code")]
public interface IBytecodeLoader
{
/// <summary>
/// Loads the embedded shader bytecode for the shader being dispatched.
/// </summary>
/// <param name="bytecode">The shader bytecode.</param>
/// <exception cref="InvalidOperationException">Thrown if the shader has already been initialized.</exception>
void LoadEmbeddedBytecode(ReadOnlySpan<byte> bytecode);
}
+20 -14
ファイルの表示
@@ -10,6 +10,26 @@ namespace ComputeSharp.__Internals;
[Obsolete("This interface is not intended to be used directly by user code")]
public interface IShader
{
/// <summary>
/// The number of threads in each thread group for the X axis.
/// </summary>
int ThreadsX { get; }
/// <summary>
/// The number of threads in each thread group for the Y axis.
/// </summary>
int ThreadsY { get; }
/// <summary>
/// The number of threads in each thread group for the Z axis.
/// </summary>
int ThreadsZ { get; }
/// <summary>
/// Gets the HLSL bytecode for the current shader.
/// </summary>
ReadOnlyMemory<byte> HlslBytecode { get; }
/// <summary>
/// Loads the dispatch data for the shader.
/// </summary>
@@ -42,18 +62,4 @@ public interface IShader
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
void BuildHlslSource(out string hlslSource);
/// <summary>
/// Loads the bytecode for the current shader.
/// </summary>
/// <typeparam name="TLoader">The type of bytecode loader being used.</typeparam>
/// <param name="loader">The <typeparamref name="TLoader"/> instance to use to load the bytecode.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <exception cref="NotSupportedException">Thrown if the bytecode required runtime compilation and it wasn't supported on the current configuration.</exception>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be used directly by user code")]
void LoadBytecode<TLoader>(ref TLoader loader, int threadsX, int threadsY, int threadsZ)
where TLoader : struct, IBytecodeLoader;
}
-22
ファイルの表示
@@ -63,28 +63,6 @@ public static partial class GraphicsDeviceExtensions
context.Run(x, y, z, ref Unsafe.AsRef(in shader));
}
/// <summary>
/// Runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(this GraphicsDevice device, int x, int y, int z, int threadsX, int threadsY, int threadsZ, in T shader)
where T : struct, IComputeShader
{
default(ArgumentNullException).ThrowIfNull(device);
using ComputeContext context = device.CreateComputeContext();
context.Run(x, y, z, threadsX, threadsY, threadsZ, ref Unsafe.AsRef(in shader));
}
/// <summary>
/// Runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
+1 -1
ファイルの表示
@@ -8,7 +8,7 @@ using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Graphics.Helpers;
using ComputeSharp.Interop;
using ComputeSharp.Interop.Allocation;
using ComputeSharp.Shaders.Models;
using ComputeSharp.Shaders.Loading;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE;
+10 -42
ファイルの表示
@@ -7,7 +7,6 @@ using ComputeSharp.Graphics.Commands;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Shaders.Dispatching;
using ComputeSharp.Shaders.Loading;
using ComputeSharp.Shaders.Models;
using TerraFX.Interop.DirectX;
#pragma warning disable CS0618
@@ -127,7 +126,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
where T : struct, IComputeShader
{
Run(x, 1, 1, 64, 1, 1, ref shader);
Run(x, 1, 1, ref shader);
}
/// <summary>
@@ -140,21 +139,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
where T : struct, IComputeShader
{
Run(x, y, 1, 8, 8, 1, ref shader);
}
/// <summary>
/// Runs the input shader with the specified parameters.
/// </summary>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
internal readonly unsafe void Run<T>(int x, int y, int z, ref T shader)
where T : struct, IComputeShader
{
Run(x, y, z, 4, 4, 4, ref shader);
Run(x, y, 1, ref shader);
}
/// <summary>
@@ -164,38 +149,24 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
internal readonly unsafe void Run<T>(
int x,
int y,
int z,
int threadsX,
int threadsY,
int threadsZ,
ref T shader)
internal readonly unsafe void Run<T>(int x, int y, int z, ref T shader)
where T : struct, IComputeShader
{
default(InvalidOperationException).ThrowIf(this.device is null);
default(ArgumentOutOfRangeException).ThrowIfNegativeOrZero(x);
default(ArgumentOutOfRangeException).ThrowIfNegativeOrZero(y);
default(ArgumentOutOfRangeException).ThrowIfNegativeOrZero(z);
default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(threadsX, 1, 1024);
default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(threadsY, 1, 1024);
default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(threadsZ, 1, 64);
default(ArgumentOutOfRangeException).ThrowIfGreaterThan(threadsX * threadsY * threadsZ, 1024, "threadsXYZ");
int groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1);
int groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1);
int groupsZ = Math.DivRem(z, threadsZ, out int modZ) + (modZ == 0 ? 0 : 1);
int groupsX = Math.DivRem(x, shader.ThreadsX, out int modX) + (modX == 0 ? 0 : 1);
int groupsY = Math.DivRem(y, shader.ThreadsY, out int modY) + (modY == 0 ? 0 : 1);
int groupsZ = Math.DivRem(z, shader.ThreadsZ, out int modZ) + (modZ == 0 ? 0 : 1);
default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(groupsX, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION);
default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(groupsY, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX));
default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(groupsZ, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX));
PipelineData pipelineData = PipelineDataLoader<T>.GetPipelineData(this.device, threadsX, threadsY, threadsZ, ref shader);
PipelineData pipelineData = PipelineDataLoader<T>.GetPipelineData(this.device);
ref CommandList commandList = ref GetCommandList(pipelineData.D3D12PipelineState);
@@ -223,16 +194,13 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
int x = texture.Width;
int y = texture.Height;
const int threadsX = 8;
const int threadsY = 8;
const int threadsZ = 1;
int groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1);
int groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1);
int groupsX = Math.DivRem(x, shader.ThreadsX, out int modX) + (modX == 0 ? 0 : 1);
int groupsY = Math.DivRem(y, shader.ThreadsY, out int modY) + (modY == 0 ? 0 : 1);
default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(groupsX, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION);
default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(groupsY, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX));
PipelineData pipelineData = PipelineDataLoader<T>.GetPipelineData(this.device, threadsX, threadsY, threadsZ, ref shader);
PipelineData pipelineData = PipelineDataLoader<T>.GetPipelineData(this.device);
ref CommandList commandList = ref GetCommandList(pipelineData.D3D12PipelineState);
-41
ファイルの表示
@@ -1,41 +0,0 @@
using System;
using System.Runtime.CompilerServices;
using ComputeSharp.__Internals;
using ComputeSharp.Shaders.Models;
#pragma warning disable CS0618
namespace ComputeSharp.Shaders.Dispatching;
/// <summary>
/// A bytecode loader for compute shaders.
/// </summary>
internal struct ShaderBytecodeLoader : IBytecodeLoader
{
/// <summary>
/// The current cached shader instance.
/// </summary>
private ICachedShader? cachedShader;
/// <summary>
/// Gets the current cached shader instance.
/// </summary>
/// <returns>The current <see cref="ICachedShader"/> instance.</returns>
/// <exception cref="NotSupportedException">Thrown if the HLSL bytecode is not available.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ICachedShader GetCachedShader()
{
default(NotSupportedException).ThrowIf(this.cachedShader is null);
return this.cachedShader;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void LoadEmbeddedBytecode(ReadOnlySpan<byte> bytecode)
{
default(InvalidOperationException).ThrowIf(this.cachedShader is not null);
this.cachedShader = new ICachedShader.Embedded(bytecode);
}
}
-18
ファイルの表示
@@ -520,24 +520,6 @@ public static class ComputeContextExtensions
context.Run(x, y, z, ref Unsafe.AsRef(in shader));
}
/// <summary>
/// Runs the input shader on a target <see cref="ComputeContext"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(this in ComputeContext context, int x, int y, int z, int threadsX, int threadsY, int threadsZ, in T shader)
where T : struct, IComputeShader
{
context.Run(x, y, z, threadsX, threadsY, threadsZ, ref Unsafe.AsRef(in shader));
}
/// <summary>
/// Runs the input shader on a target <see cref="ComputeContext"/> instance, with the specified parameters.
/// </summary>
@@ -2,7 +2,7 @@ using ComputeSharp.Interop;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
namespace ComputeSharp.Shaders.Models;
namespace ComputeSharp.Shaders.Loading;
/// <summary>
/// A <see langword="class"/> representing a custom pipeline state for a compute operation.
+26 -58
ファイルの表示
@@ -1,12 +1,10 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using ComputeSharp.Shaders.Dispatching;
using ComputeSharp.Shaders.Extensions;
using ComputeSharp.__Internals;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using ComputeSharp.Shaders.Models;
#pragma warning disable CS0618
@@ -20,86 +18,56 @@ internal static class PipelineDataLoader<T>
where T : struct, IShader
{
/// <summary>
/// The mapping used to cache and reuse compiled shaders.
/// The map of cached <see cref="PipelineData"/> instances for each GPU in use.
/// </summary>
private static readonly Dictionary<ShaderKey, ICachedShader> ShadersCache = new();
private static readonly ConditionalWeakTable<GraphicsDevice, PipelineData> CachedPipelines = new();
/// <summary>
/// Gets the <see cref="PipelineData"/> instance for a given shader.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
/// <returns>The <see cref="PipelineData"/> instance for a given shader.</returns>
public static unsafe PipelineData GetPipelineData(GraphicsDevice device, int threadsX, int threadsY, int threadsZ, ref T shader)
public static PipelineData GetPipelineData(GraphicsDevice device)
{
ShaderKey key = new(threadsX, threadsY, threadsZ);
lock (ShadersCache)
{
// Get or preload the shader
if (!ShadersCache.TryGetValue(key, out ICachedShader? shaderData))
{
LoadShader(threadsX, threadsY, threadsZ, ref shader, out shaderData);
// Cache for later use
ShadersCache.Add(key, shaderData);
}
// Create the reusable pipeline state
if (!shaderData.CachedPipelines.TryGetValue(device, out PipelineData? pipelineData))
{
CreatePipelineData(device, shaderData, out pipelineData);
}
return pipelineData;
}
}
/// <summary>
/// Loads a shader with the specified parameters.
/// </summary>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
/// <param name="shaderData">The <see cref="ICachedShader"/> instance to return with the cached shader data.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe void LoadShader(int threadsX, int threadsY, int threadsZ, ref T shader, out ICachedShader shaderData)
{
ShaderBytecodeLoader bytecodeLoader = default;
shader.LoadBytecode(ref bytecodeLoader, threadsX, threadsY, threadsZ);
shaderData = bytecodeLoader.GetCachedShader();
return CachedPipelines.GetValue(device, CreatePipelineData);
}
/// <summary>
/// Creates and caches a <see cref="PipelineData"/> instance for a given shader.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="shaderData">The <see cref="ICachedShader"/> instance with the data on the loaded shader.</param>
/// <param name="pipelineData">The resulting <see cref="PipelineData"/> instance to use to run the shader.</param>
/// <returns>The resulting <see cref="PipelineData"/> instance to use to run the shader.</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe void CreatePipelineData(GraphicsDevice device, ICachedShader shaderData, out PipelineData pipelineData)
private static unsafe PipelineData CreatePipelineData(GraphicsDevice device)
{
using ComPtr<ID3D12RootSignature> d3D12RootSignature = default;
PipelineData pipelineData;
ShaderDispatchMetadataLoader metadataLoader = new(device.D3D12Device);
using (ComPtr<ID3D12RootSignature> d3D12RootSignature = default)
{
ShaderDispatchMetadataLoader metadataLoader = new(device.D3D12Device);
Unsafe.SkipInit(out T shader);
Unsafe.SkipInit(out T shader);
shader.LoadDispatchMetadata(ref metadataLoader, out *(IntPtr*)&d3D12RootSignature);
shader.LoadDispatchMetadata(ref metadataLoader, out *(IntPtr*)&d3D12RootSignature);
using ComPtr<ID3D12PipelineState> d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.D3D12ShaderBytecode);
ReadOnlyMemory<byte> hlslBytecode = shader.HlslBytecode;
pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get());
fixed (byte* hlslBytecodePtr = hlslBytecode.Span)
{
D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new(hlslBytecodePtr, (nuint)hlslBytecode.Length);
shaderData.CachedPipelines.Add(device, pipelineData);
using ComPtr<ID3D12PipelineState> d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), d3D12ShaderBytecode);
pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get());
}
}
// Add the pipeline to the cache for this type
CachedPipelines.Add(device, pipelineData);
// Register the newly created pipeline data to enable early disposal
device.RegisterPipelineData(pipelineData);
return pipelineData;
}
}
-96
ファイルの表示
@@ -1,96 +0,0 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Interop;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
namespace ComputeSharp.Shaders.Models;
/// <summary>
/// An interface that contains info on a cached shader.
/// </summary>
internal interface ICachedShader
{
/// <summary>
/// Gets the map of cached <see cref="PipelineData"/> instances for each GPU in use.
/// </summary>
ConditionalWeakTable<GraphicsDevice, PipelineData> CachedPipelines { get; }
/// <summary>
/// Gets a <see cref="D3D12_SHADER_BYTECODE"/> value pointing shader bytecode to use.
/// </summary>
D3D12_SHADER_BYTECODE D3D12ShaderBytecode { get; }
/// <summary>
/// An <see cref="ICachedShader"/> implementation for an embedded shader.
/// </summary>
public sealed unsafe class Embedded : ICachedShader
{
/// <summary>
/// The bytecode buffer, if a precompiled shader is used.
/// </summary>
private readonly byte* precompiledBytecodeBuffer;
/// <summary>
/// The buffer size for <see cref="precompiledBytecodeBuffer"/>, if present.
/// </summary>
private readonly uint precompiledBytecodeSize;
/// <summary>
/// Creates a new <see cref="Embedded"/> instance with the specified parameters.
/// </summary>
/// <param name="precompiledBytecode">The shader bytecode buffer to wrap.</param>
/// <remarks>
/// It is assumed that <paramref name="precompiledBytecode"/> is a static binary block in the <c>.text</c> segment of the
/// PE file, which is what Roslyn generates when directly assigning a new array to a <see cref="ReadOnlySpan{T}"/>. As such,
/// the underlying buffer is assumed to be pinned, and it will not be properly tracked for GC compactions. If an invalid
/// buffer is passed and its contents are moved, the behavior is undefined (access violations will most definitely occurr).
/// </remarks>
public Embedded(ReadOnlySpan<byte> precompiledBytecode)
{
this.precompiledBytecodeBuffer = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(precompiledBytecode));
this.precompiledBytecodeSize = (uint)precompiledBytecode.Length;
}
/// <inheritdoc/>
public ConditionalWeakTable<GraphicsDevice, PipelineData> CachedPipelines { get; } = new();
/// <inheritdoc/>
public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new(this.precompiledBytecodeBuffer, this.precompiledBytecodeSize);
}
/// <summary>
/// An <see cref="ICachedShader"/> implementation for a dynamically compiled shader.
/// </summary>
public sealed unsafe class Dynamic : ReferenceTrackedObject, ICachedShader
{
/// <summary>
/// The <see cref="IDxcBlob"/> instance currently in use.
/// </summary>
private ComPtr<IDxcBlob> dxcBlobBytecode;
/// <summary>
/// Creates a new <see cref="Dynamic"/> instance with the specified parameters.
/// </summary>
/// <param name="dxcBlobBytecode">The <see cref="IDxcBlob"/> bytecode instance to wrap.</param>
public Dynamic(IDxcBlob* dxcBlobBytecode)
{
using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease();
this.dxcBlobBytecode = new ComPtr<IDxcBlob>(dxcBlobBytecode);
}
/// <inheritdoc/>
public ConditionalWeakTable<GraphicsDevice, PipelineData> CachedPipelines { get; } = new();
/// <inheritdoc/>
public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new((ID3DBlob*)this.dxcBlobBytecode.Get());
/// <inheritdoc/>
protected override void DangerousOnDispose()
{
this.dxcBlobBytecode.Dispose();
}
}
}
-62
ファイルの表示
@@ -1,62 +0,0 @@
using System;
using System.Runtime.CompilerServices;
namespace ComputeSharp.Shaders.Models;
/// <summary>
/// A <see langword="struct"/> representing a key for a given shader.
/// </summary>
internal readonly struct ShaderKey : IEquatable<ShaderKey>
{
/// <summary>
/// The number of iterations to run on the X axis.
/// </summary>
private readonly int threadsX;
/// <summary>
/// The number of iterations to run on the Y axis.
/// </summary>
private readonly int threadsY;
/// <summary>
/// The number of iterations to run on the Z axis.
/// </summary>
private readonly int threadsZ;
/// <summary>
/// Creates a new <see cref="ShaderKey"/> instance with the specified parameters.
/// </summary>
/// <param name="threadsX">The number of iterations to run on the X axis.</param>
/// <param name="threadsY">The number of iterations to run on the Y axis.</param>
/// <param name="threadsZ">The number of iterations to run on the Z axis.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ShaderKey(int threadsX, int threadsY, int threadsZ)
{
this.threadsX = threadsX;
this.threadsY = threadsY;
this.threadsZ = threadsZ;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(ShaderKey other)
{
return
this.threadsX == other.threadsX &&
this.threadsY == other.threadsY &&
this.threadsZ == other.threadsZ;
}
/// <inheritdoc/>
public override bool Equals(object? obj)
{
return obj is ShaderKey other && Equals(other);
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
return HashCode.Combine(this.threadsX, this.threadsY, this.threadsZ);
}
}
+1 -11
ファイルの表示
@@ -18,7 +18,7 @@ public partial class DispatchTests
using ReadWriteBuffer<float> buffer = device.Get().AllocateReadWriteBuffer(array);
device.Get().For(128, 1, 1, 32, 1, 1, new ComputeShader(buffer, 2.0f));
device.Get().For(128, 1, 1, new ComputeShader(buffer, 2.0f));
float[] result = buffer.ToArray();
@@ -30,16 +30,6 @@ public partial class DispatchTests
CollectionAssert.AreEqual(result, array);
}
[CombinatorialTestMethod]
[AllDevices]
[ExpectedException(typeof(NotSupportedException))]
public void ComputeShader_Test_Fail(Device device)
{
using ReadWriteBuffer<float> buffer = device.Get().AllocateReadWriteBuffer<float>(128);
device.Get().For(128, 1, 1, 64, 1, 1, new ComputeShader(buffer, 2.0f));
}
[AutoConstructor]
[EmbeddedBytecode(32, 1, 1)]
internal readonly partial struct ComputeShader : IComputeShader
+4 -24
ファイルの表示
@@ -131,7 +131,7 @@ public partial class DispatchTests
{
using ReadWriteTexture3D<int4> buffer = device.Get().AllocateReadWriteTexture3D<int4>(50, 50, 50);
device.Get().For(buffer.Width, buffer.Height, buffer.Depth, 4, 4, 4, new GroupIdsShader(buffer));
device.Get().For(buffer.Width, buffer.Height, buffer.Depth, new GroupIdsShader(buffer));
int4[,,] data = buffer.ToArray();
int* value = stackalloc int[4];
@@ -153,26 +153,6 @@ public partial class DispatchTests
}
}
[CombinatorialTestMethod]
[AllDevices]
[Data(0, 8, 8)]
[Data(8, 0, 8)]
[Data(8, 8, 0)]
[Data(1025, 8, 8)]
[Data(8, 2000, 8)]
[Data(8, 8, 70)]
[Data(8, -1, 8)]
[Data(8, 15, 16)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void Verify_GroupIds_OutOfRange(Device device, int x, int y, int z)
{
using ReadWriteTexture3D<int4> buffer = device.Get().AllocateReadWriteTexture3D<int4>(50, 50, 50);
device.Get().For(buffer.Width, buffer.Height, buffer.Depth, x, y, z, new GroupIdsShader(buffer));
Assert.Fail();
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct GroupIdsShader : IComputeShader
@@ -192,7 +172,7 @@ public partial class DispatchTests
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(32);
device.Get().For(1, 1, 1, 4, 15, 7, new GroupSizeShader(buffer));
device.Get().For(1, 1, 1, new GroupSizeShader(buffer));
int[] data = buffer.ToArray();
@@ -227,7 +207,7 @@ public partial class DispatchTests
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(256);
device.Get().For(256, 1, 1, 32, 1, 1, new GridIdsShader(buffer));
device.Get().For(256, 1, 1, new GridIdsShader(buffer));
int[] data = buffer.ToArray();
@@ -373,7 +353,7 @@ public partial class DispatchTests
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(32);
device.Get().For(64, 1, 1, 32, 1, 1, new DynamicGroupSharedPixelShader(buffer));
device.Get().For(64, 1, 1, new DynamicGroupSharedPixelShader(buffer));
int[] result = buffer.ToArray();
+77
ファイルの表示
@@ -0,0 +1,77 @@
using ComputeSharp.__Internals;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests;
[TestClass]
[TestCategory("ThreadGroupSize")]
public partial class ThreadGroupSizeTests
{
[TestMethod]
public unsafe void Verify_ThreadGroupSize()
{
Assert.AreEqual(64, ((IShader)default(DispatchXShader)).ThreadsX);
Assert.AreEqual(1, ((IShader)default(DispatchXShader)).ThreadsY);
Assert.AreEqual(1, ((IShader)default(DispatchXShader)).ThreadsZ);
Assert.AreEqual(8, ((IShader)default(DispatchXYShader)).ThreadsX);
Assert.AreEqual(8, ((IShader)default(DispatchXYShader)).ThreadsY);
Assert.AreEqual(1, ((IShader)default(DispatchXYShader)).ThreadsZ);
Assert.AreEqual(4, ((IShader)default(DispatchXYZShader)).ThreadsX);
Assert.AreEqual(4, ((IShader)default(DispatchXYZShader)).ThreadsY);
Assert.AreEqual(4, ((IShader)default(DispatchXYZShader)).ThreadsZ);
Assert.AreEqual(11, ((IShader)default(DispatchCustomShader)).ThreadsX);
Assert.AreEqual(14, ((IShader)default(DispatchCustomShader)).ThreadsY);
Assert.AreEqual(6, ((IShader)default(DispatchCustomShader)).ThreadsZ);
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct DispatchXShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public void Execute()
{
this.buffer[ThreadIds.X] = 0;
}
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct DispatchXYShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public void Execute()
{
this.buffer[ThreadIds.X] = 0;
}
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct DispatchXYZShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public void Execute()
{
this.buffer[ThreadIds.X] = 0;
}
}
[AutoConstructor]
[EmbeddedBytecode(11, 14, 6)]
internal readonly partial struct DispatchCustomShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public void Execute()
{
this.buffer[ThreadIds.X] = 0;
}
}
}