Introduced IPixelShader<TPixel> interface, initial working support
このコミットが含まれているのは:
1 親
0a0f51bd5f
コミット
49d73b675f
15ファイル変更
+285
-23
検索条件に一致するファイルはありません
@@ -29,6 +29,7 @@
|
||||
<Compile Include="..\ComputeSharp\Core\Extensions\MethodInfoExtensions.cs" Link="Core\Extensions\MethodInfoExtensions.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Helpers\AlignmentHelper.cs" Link="Core\Helpers\AlignmentHelper.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Interfaces\IComputeShader.cs" Link="Core\Interfaces\IComputeShader.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Interfaces\IPixelShader{TPixel}.cs" Link="Core\Interfaces\IPixelShader{TPixel}.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Intrinsics\Attributes\HlslIntrinsicNameAttribute.cs" Link="Core\Intrinsics\Attributes\HlslIntrinsicNameAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Intrinsics\Hlsl.cs" Link="Core\Intrinsics\Hlsl.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Intrinsics\Hlsl.g.cs" Link="Core\Intrinsics\Hlsl.g.cs" />
|
||||
|
||||
@@ -22,7 +22,7 @@ namespace ComputeSharp.SourceGenerators.Helpers
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="values">The input sequence of <see cref="string"/> instances.</param>
|
||||
/// <returns>An <see cref="ArrayCreationExpression"/> instance with the described contents.</returns>
|
||||
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
|
||||
[Pure]
|
||||
public static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable<string> values)
|
||||
{
|
||||
@@ -44,7 +44,7 @@ namespace ComputeSharp.SourceGenerators.Helpers
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="values">The input sequence of <see cref="string"/> groups.</param>
|
||||
/// <returns>An <see cref="ArrayCreationExpression"/> instance with the described contents.</returns>
|
||||
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
|
||||
[Pure]
|
||||
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<IEnumerable<string?>> groups)
|
||||
{
|
||||
@@ -71,7 +71,7 @@ namespace ComputeSharp.SourceGenerators.Helpers
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="values">The input sequence of <see cref="string"/> groups.</param>
|
||||
/// <returns>An <see cref="ArrayCreationExpression"/> instance with the described contents.</returns>
|
||||
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
|
||||
[Pure]
|
||||
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B, int? C)> groups)
|
||||
{
|
||||
@@ -92,5 +92,35 @@ namespace ComputeSharp.SourceGenerators.Helpers
|
||||
? LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(i))
|
||||
: LiteralExpression(SyntaxKind.NullLiteralExpression)))).ToArray()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="string"/>[]? array expression from the given tuple instance.
|
||||
/// <para>
|
||||
/// That it, it applies the following transformation:
|
||||
/// <code>
|
||||
/// null => null
|
||||
/// ("S1", "S2") => new string[] { "S1", "S2" }
|
||||
/// </code>
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="values">The input tuple instance.</param>
|
||||
/// <returns>An <see cref="ExpressionSyntax"/> instance with the described contents.</returns>
|
||||
[Pure]
|
||||
public static ExpressionSyntax ArrayExpression((string First, string Second)? values)
|
||||
{
|
||||
if (values is null)
|
||||
{
|
||||
return LiteralExpression(SyntaxKind.NullLiteralExpression);
|
||||
}
|
||||
|
||||
return
|
||||
ArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
|
||||
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
|
||||
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
|
||||
.AddExpressions(
|
||||
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.First)),
|
||||
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.Second))));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,9 @@ namespace ComputeSharp.SourceGenerators
|
||||
{
|
||||
if (context.Node is StructDeclarationSyntax structDeclaration &&
|
||||
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
|
||||
structSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader)))
|
||||
structSymbol.Interfaces.Any(static interfaceSymbol =>
|
||||
interfaceSymbol.Name == nameof(IComputeShader) ||
|
||||
interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) }))
|
||||
{
|
||||
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
|
||||
}
|
||||
|
||||
@@ -29,7 +29,9 @@ namespace ComputeSharp.SourceGenerators
|
||||
{
|
||||
if (context.Node is StructDeclarationSyntax structDeclaration &&
|
||||
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
|
||||
structSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader)))
|
||||
structSymbol.Interfaces.Any(static interfaceSymbol =>
|
||||
interfaceSymbol.Name == nameof(IComputeShader) ||
|
||||
interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) }))
|
||||
{
|
||||
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
|
||||
}
|
||||
|
||||
@@ -29,7 +29,9 @@ namespace ComputeSharp.SourceGenerators
|
||||
{
|
||||
if (context.Node is StructDeclarationSyntax structDeclaration &&
|
||||
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
|
||||
structSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader)))
|
||||
structSymbol.Interfaces.Any(static interfaceSymbol =>
|
||||
interfaceSymbol.Name == nameof(IComputeShader) ||
|
||||
interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) }))
|
||||
{
|
||||
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
|
||||
}
|
||||
|
||||
@@ -75,9 +75,12 @@ namespace ComputeSharp.SourceGenerators
|
||||
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
|
||||
|
||||
// Explore the syntax tree and extract the processed info
|
||||
var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes).ToArray();
|
||||
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
|
||||
var isComputeShader = pixelShaderSymbol is null;
|
||||
var implicitTextureField = isComputeShader ? default((string, string)?) : (HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!), "__outputTexture");
|
||||
var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray();
|
||||
var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
|
||||
var (entryPoint, processedMethods, forwardDeclarations) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
|
||||
var (entryPoint, processedMethods, forwardDeclarations) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader);
|
||||
var processedTypes = GetProcessedTypes(discoveredTypes).ToArray();
|
||||
var processedConstants = GetProcessedConstants(constantDefinitions);
|
||||
var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
|
||||
@@ -90,6 +93,7 @@ namespace ComputeSharp.SourceGenerators
|
||||
Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments(
|
||||
AttributeArgument(TypeOfExpression(IdentifierName(structDeclarationSymbol.ToDisplayString()))),
|
||||
AttributeArgument(ArrayExpression(processedTypes)),
|
||||
AttributeArgument(ArrayExpression(implicitTextureField)),
|
||||
AttributeArgument(NestedArrayExpression(processedMembers)),
|
||||
AttributeArgument(ArrayExpression(forwardDeclarations)),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))),
|
||||
@@ -112,12 +116,14 @@ namespace ComputeSharp.SourceGenerators
|
||||
/// <param name="context">The current generator context in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="types">The collection of currently discovered types.</param>
|
||||
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
|
||||
/// <returns>A sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</returns>
|
||||
[Pure]
|
||||
private static IEnumerable<IEnumerable<string>> GetProcessedFields(
|
||||
GeneratorExecutionContext context,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
ICollection<INamedTypeSymbol> types)
|
||||
ICollection<INamedTypeSymbol> types,
|
||||
bool isComputeShader)
|
||||
{
|
||||
bool hlslResourceFound = false;
|
||||
|
||||
@@ -176,7 +182,8 @@ namespace ComputeSharp.SourceGenerators
|
||||
yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName };
|
||||
}
|
||||
|
||||
if (!hlslResourceFound)
|
||||
// If the shader is a compute one (so no implicit output texture), it has to contain at least one resource
|
||||
if (!hlslResourceFound && isComputeShader)
|
||||
{
|
||||
context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol);
|
||||
}
|
||||
@@ -303,6 +310,7 @@ namespace ComputeSharp.SourceGenerators
|
||||
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
|
||||
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
|
||||
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
|
||||
[Pure]
|
||||
private static (string EntryPoint, IEnumerable<string> Methods, IEnumerable<string> Declarations) GetProcessedMethods(
|
||||
@@ -312,7 +320,8 @@ namespace ComputeSharp.SourceGenerators
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions)
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
bool isComputeShader)
|
||||
{
|
||||
// Find all declared methods in the type
|
||||
ImmutableArray<MethodDeclarationSyntax> methodDeclarations = (
|
||||
@@ -328,10 +337,16 @@ namespace ComputeSharp.SourceGenerators
|
||||
{
|
||||
IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!;
|
||||
bool isShaderEntryPoint =
|
||||
methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) &&
|
||||
methodDeclarationSymbol.ReturnsVoid &&
|
||||
methodDeclarationSymbol.TypeParameters.Length == 0 &&
|
||||
methodDeclarationSymbol.Parameters.Length == 0;
|
||||
(isComputeShader &&
|
||||
methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) &&
|
||||
methodDeclarationSymbol.ReturnsVoid &&
|
||||
methodDeclarationSymbol.TypeParameters.Length == 0 &&
|
||||
methodDeclarationSymbol.Parameters.Length == 0) ||
|
||||
(!isComputeShader &&
|
||||
methodDeclarationSymbol.Name == nameof(IPixelShader<byte>.Execute) &&
|
||||
methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type
|
||||
methodDeclarationSymbol.TypeParameters.Length == 0 &&
|
||||
methodDeclarationSymbol.Parameters.Length == 0);
|
||||
|
||||
// Create the source rewriter for the current method
|
||||
ShaderSourceRewriter shaderSourceRewriter = new(
|
||||
@@ -356,7 +371,7 @@ namespace ComputeSharp.SourceGenerators
|
||||
// If the method is the shader entry point, do additional processing
|
||||
if (isShaderEntryPoint)
|
||||
{
|
||||
processedMethod = new ExecuteMethodRewriter(shaderSourceRewriter).Visit(processedMethod)!;
|
||||
processedMethod = new ExecuteMethodRewriter(shaderSourceRewriter, isComputeShader).Visit(processedMethod)!;
|
||||
|
||||
entryPoint = processedMethod.NormalizeWhitespace().ToFullString();
|
||||
}
|
||||
|
||||
@@ -265,6 +265,26 @@ namespace ComputeSharp.SourceGenerators.Mappings
|
||||
return typeName.ToHlslIdentifierName();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapped HLSL-compatible type name for the output texture of a pixel shader.
|
||||
/// </summary>
|
||||
/// <param name="typeSymbol">The pixel shader type to map.</param>
|
||||
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
|
||||
[Pure]
|
||||
public static string GetMappedNameForPixelShaderType(INamedTypeSymbol typeSymbol)
|
||||
{
|
||||
string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments.First()).GetFullMetadataName();
|
||||
|
||||
// If the current type is a custom type, format it as needed
|
||||
if (!KnownHlslTypes.TryGetValue(genericArgumentName, out string? mappedElementType))
|
||||
{
|
||||
mappedElementType = genericArgumentName.ToHlslIdentifierName();
|
||||
}
|
||||
|
||||
// Construct the HLSL type name
|
||||
return $"RWTexture2D<unorm {mappedElementType}>";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapped HLSL-compatible type name for the input element type symbol.
|
||||
/// </summary>
|
||||
|
||||
@@ -15,13 +15,20 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
|
||||
/// </summary>
|
||||
private readonly ShaderSourceRewriter shaderSourceRewriter;
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether or not the method belongs to a compute shader.
|
||||
/// </summary>
|
||||
private readonly bool isComputeShader;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ExecuteMethodRewriter"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="shaderSourceRewriter">The <see cref="ShaderSourceRewriter"/> instance used to process the input tree.</param>
|
||||
public ExecuteMethodRewriter(ShaderSourceRewriter shaderSourceRewriter)
|
||||
/// <param name="isComputeShader">Indicates whether or not the method belongs to a compute shader.</param>
|
||||
public ExecuteMethodRewriter(ShaderSourceRewriter shaderSourceRewriter, bool isComputeShader)
|
||||
{
|
||||
this.shaderSourceRewriter = shaderSourceRewriter;
|
||||
this.isComputeShader = isComputeShader;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
|
||||
@@ -56,11 +63,42 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitReturnStatement(ReturnStatementSyntax node)
|
||||
{
|
||||
var updatedNode = (ReturnStatementSyntax)base.VisitReturnStatement(node)!;
|
||||
|
||||
if (this.isComputeShader)
|
||||
{
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
// __outputTexture[ThreadIds.xy] = <RETURN_EXPRESSION>;
|
||||
return
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ElementAccessExpression(IdentifierName("__outputTexture"))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("ThreadIds"),
|
||||
IdentifierName("xy")))),
|
||||
updatedNode.Expression!));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node)
|
||||
{
|
||||
var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList());
|
||||
|
||||
// Change the return type if the current shader is a pixel shader
|
||||
if (!this.isComputeShader)
|
||||
{
|
||||
updatedNode = updatedNode.WithReturnType(PredefinedType(Token(SyntaxKind.VoidKeyword)));
|
||||
}
|
||||
|
||||
// When we're rewriting the main compute shader method, we need to insert a range
|
||||
// check to ensure that invocation outside of the requested range are discarded.
|
||||
// The following snippet creates this prologue before the user provided body:
|
||||
|
||||
@@ -22,6 +22,7 @@ namespace ComputeSharp.__Internals
|
||||
/// </summary>
|
||||
/// <param name="shaderType">The type of the current shader.</param>
|
||||
/// <param name="types">The collection of custom types.</param>
|
||||
/// <param name="implicitTextureField">The implicit texture field info, if present.</param>
|
||||
/// <param name="fields">The mapped collection of shader fields.</param>
|
||||
/// <param name="forwardDeclarations">The forward declarations for static methods.</param>
|
||||
/// <param name="executeMethod">The source code for the <see cref="IComputeShader.Execute"/> method.</param>
|
||||
@@ -32,6 +33,7 @@ namespace ComputeSharp.__Internals
|
||||
public IComputeShaderSourceAttribute(
|
||||
Type shaderType,
|
||||
string[] types,
|
||||
string[]? implicitTextureField,
|
||||
object[] fields,
|
||||
string[] forwardDeclarations,
|
||||
string executeMethod,
|
||||
@@ -42,6 +44,7 @@ namespace ComputeSharp.__Internals
|
||||
{
|
||||
ShaderType = shaderType;
|
||||
Types = types;
|
||||
ImplicitTextureField = implicitTextureField is null ? null : (implicitTextureField[0], implicitTextureField[1]);
|
||||
Fields = fields.Cast<string[]>().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2]));
|
||||
ForwardDeclarations = forwardDeclarations;
|
||||
ExecuteMethod = executeMethod;
|
||||
@@ -61,6 +64,11 @@ namespace ComputeSharp.__Internals
|
||||
/// </summary>
|
||||
internal IReadOnlyCollection<string> Types { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapping for the implicit texture field, if the shader is a pixel shader.
|
||||
/// </summary>
|
||||
internal (string Name, string Type)? ImplicitTextureField { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapping of field names.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace ComputeSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// An <see langword="interface"/> representing a pixel shader.
|
||||
/// </summary>
|
||||
public interface IPixelShader<TPixel>
|
||||
where TPixel : unmanaged
|
||||
{
|
||||
/// <summary>
|
||||
/// Executes the current pixel shader.
|
||||
/// </summary>
|
||||
/// <returns>The pixel value for the current invocation.</returns>
|
||||
TPixel Execute();
|
||||
}
|
||||
}
|
||||
@@ -1131,5 +1131,34 @@ namespace ComputeSharp
|
||||
{
|
||||
ShaderRunner<T>.Run(device, x, y, z, threadsX, threadsY, threadsZ, in shader);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of pixel shader to run.</typeparam>
|
||||
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
|
||||
/// <param name="texture">The target texture to apply the pixel shader to.</param>
|
||||
public static void ForEach<T, TPixel>(this GraphicsDevice device, IReadWriteTexture2D<TPixel> texture)
|
||||
where T : struct, IPixelShader<TPixel>
|
||||
where TPixel : unmanaged
|
||||
{
|
||||
ShaderRunner<T>.Run(device, texture, default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of pixel shader to run.</typeparam>
|
||||
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
|
||||
/// <param name="texture">The target texture to apply the pixel shader to.</param>
|
||||
/// <param name="shader">The input <typeparamref name="T"/> instance representing the pixel shader to run.</param>
|
||||
public static void ForEach<T, TPixel>(this GraphicsDevice device, IReadWriteTexture2D<TPixel> texture, in T shader)
|
||||
where T : struct, IPixelShader<TPixel>
|
||||
where TPixel : unmanaged
|
||||
{
|
||||
ShaderRunner<T>.Run(device, texture, in shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,14 @@ using ComputeSharp.Shaders.Renderer;
|
||||
using ComputeSharp.Shaders.Translation;
|
||||
using ComputeSharp.Shaders.Translation.Interop;
|
||||
using ComputeSharp.Shaders.Translation.Models;
|
||||
using ComputeSharp.__Internals;
|
||||
using Microsoft.Toolkit.Diagnostics;
|
||||
using TerraFX.Interop;
|
||||
using FX = TerraFX.Interop.Windows;
|
||||
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.Shaders
|
||||
{
|
||||
/// <summary>
|
||||
@@ -20,7 +23,7 @@ namespace ComputeSharp.Shaders
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of compute shader to run.</typeparam>
|
||||
internal static class ShaderRunner<T>
|
||||
where T : struct, IComputeShader
|
||||
where T : struct
|
||||
{
|
||||
/// <summary>
|
||||
/// The mapping used to cache and reuse compiled shaders.
|
||||
@@ -175,6 +178,86 @@ namespace ComputeSharp.Shaders
|
||||
commandList.ExecuteAndWaitForCompletion();
|
||||
}
|
||||
|
||||
/// <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="texture">The target texture to invoke the pixel shader upon.</param>
|
||||
/// <param name="shader">The input <typeparamref name="T"/> instance representing the pixel shader to run.</param>
|
||||
public static unsafe void Run<TPixel>(GraphicsDevice device, IReadWriteTexture2D<TPixel> texture, in T shader)
|
||||
where TPixel : unmanaged
|
||||
{
|
||||
device.ThrowIfDisposed();
|
||||
|
||||
// Calculate the dispatch values
|
||||
int
|
||||
x = texture.Width,
|
||||
y = texture.Height,
|
||||
z = 1,
|
||||
threadsX = 8,
|
||||
threadsY = 8,
|
||||
threadsZ = 1,
|
||||
groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1),
|
||||
groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1),
|
||||
groupsZ = Math.DivRem(z, threadsZ, out int modZ) + (modZ == 0 ? 0 : 1);
|
||||
|
||||
Guard.IsBetweenOrEqualTo(groupsX, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX));
|
||||
Guard.IsBetweenOrEqualTo(groupsY, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX));
|
||||
Guard.IsBetweenOrEqualTo(groupsZ, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX));
|
||||
|
||||
// Create the shader key
|
||||
ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(in shader), threadsX, threadsY, threadsZ);
|
||||
CachedShader<T> shaderData;
|
||||
PipelineData? pipelineData;
|
||||
|
||||
lock (ShadersCache)
|
||||
{
|
||||
// Get or preload the shader
|
||||
if (!ShadersCache.TryGetValue(key, out shaderData))
|
||||
{
|
||||
LoadShader(threadsX, threadsY, threadsZ, in shader, out shaderData);
|
||||
|
||||
// Cache for later use
|
||||
ShadersCache.Add(key, shaderData);
|
||||
}
|
||||
|
||||
// Create the reusable pipeline state
|
||||
if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineData))
|
||||
{
|
||||
CreatePipelineData(device, shaderData, out pipelineData);
|
||||
}
|
||||
}
|
||||
|
||||
// Create the commands list and set the pipeline state
|
||||
using CommandList commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE);
|
||||
|
||||
commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature);
|
||||
commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineData.D3D12PipelineState);
|
||||
|
||||
// Extract the dispatch data for the shader invocation
|
||||
using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in shader, x, y, z);
|
||||
|
||||
// Initialize the loop targets and the captured values
|
||||
commandList.D3D12GraphicsCommandList->SetComputeRoot32BitConstants(dispatchData.Variables);
|
||||
|
||||
// Load the implicit output texture
|
||||
commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable(
|
||||
1,
|
||||
((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuDescriptorHandle(device));
|
||||
|
||||
ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> resources = dispatchData.Resources;
|
||||
|
||||
for (int i = 1; i < resources.Length; i++)
|
||||
{
|
||||
// Load the captured buffers
|
||||
commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable((uint)i + 2, resources[i]);
|
||||
}
|
||||
|
||||
// Dispatch and wait for completion
|
||||
commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, (uint)groupsZ);
|
||||
commandList.ExecuteAndWaitForCompletion();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads a shader with the specified parameters.
|
||||
/// </summary>
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace ComputeSharp.Shaders.Translation.Models
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of compute shader in use.</typeparam>
|
||||
internal readonly struct CachedShader<T>
|
||||
where T : struct, IComputeShader
|
||||
where T : struct
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="ShaderLoader{T}"/> instance with the shader metadata.
|
||||
|
||||
@@ -15,7 +15,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
|
||||
private static class TypeInfo<T>
|
||||
where T : struct, IComputeShader
|
||||
where T : struct
|
||||
{
|
||||
/// <summary>
|
||||
/// The id of the compute shader type in use.
|
||||
@@ -51,7 +51,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
[Pure]
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetHashCode<T>(in T shader)
|
||||
where T : struct, IComputeShader
|
||||
where T : struct
|
||||
{
|
||||
int hash = TypeInfo<T>.Id;
|
||||
|
||||
@@ -70,6 +70,6 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// <param name="shader">The compute shader instance to use to compute the final hash value.</param>
|
||||
/// <returns>The final hash value for the input closure.</returns>
|
||||
private delegate int Hasher<T>(int hash, in T shader)
|
||||
where T : struct, IComputeShader;
|
||||
where T : struct;
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
|
||||
internal sealed partial class ShaderLoader<T> : IShaderLoader
|
||||
where T : struct, IComputeShader
|
||||
where T : struct
|
||||
{
|
||||
/// <summary>
|
||||
/// The associated <see cref="IComputeShaderSourceAttribute"/> instance for the current shader type.
|
||||
@@ -181,6 +181,23 @@ namespace ComputeSharp.Shaders.Translation
|
||||
|
||||
List<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges1 = new();
|
||||
|
||||
// Add the implicit texture descriptor if the shader is a pixel shader
|
||||
foreach (Type interfaceType in typeof(T).GetInterfaces())
|
||||
{
|
||||
if (interfaceType.IsGenericType &&
|
||||
interfaceType.GetGenericTypeDefinition() == typeof(IPixelShader<>))
|
||||
{
|
||||
d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount));
|
||||
|
||||
(string hlslType, string hlslName) = Attribute.ImplicitTextureField!.Value;
|
||||
|
||||
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++));
|
||||
this.totalResourceCount++;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Inspect the captured fields
|
||||
foreach (FieldInfo fieldInfo in shaderFields)
|
||||
{
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする