diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
index 0530ae6d..3e2dcc6f 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
+++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
@@ -29,6 +29,7 @@
+
diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs
index e582b220..e90839c0 100644
--- a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs
+++ b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs
@@ -22,7 +22,7 @@ namespace ComputeSharp.SourceGenerators.Helpers
///
///
/// The input sequence of instances.
- /// An instance with the described contents.
+ /// An instance with the described contents.
[Pure]
public static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable values)
{
@@ -44,7 +44,7 @@ namespace ComputeSharp.SourceGenerators.Helpers
///
///
/// The input sequence of groups.
- /// An instance with the described contents.
+ /// An instance with the described contents.
[Pure]
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable> groups)
{
@@ -71,7 +71,7 @@ namespace ComputeSharp.SourceGenerators.Helpers
///
///
/// The input sequence of groups.
- /// An instance with the described contents.
+ /// An instance with the described contents.
[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()));
}
+
+ ///
+ /// Creates a []? array expression from the given tuple instance.
+ ///
+ /// That it, it applies the following transformation:
+ ///
+ /// null => null
+ /// ("S1", "S2") => new string[] { "S1", "S2" }
+ ///
+ ///
+ ///
+ /// The input tuple instance.
+ /// An instance with the described contents.
+ [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(OmittedArraySizeExpression()))))
+ .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
+ .AddExpressions(
+ LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.First)),
+ LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.Second))));
+ }
}
}
diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs
index a16456be..b426151e 100644
--- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs
+++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs
@@ -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) }))
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
}
diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs
index c8ae8f9c..2e58a0cb 100644
--- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs
+++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs
@@ -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) }))
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
}
diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs
index 7b3ad917..a4d2182b 100644
--- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs
+++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs
@@ -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) }))
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
}
diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs
index 597434d3..7fa30393 100644
--- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs
@@ -75,9 +75,12 @@ namespace ComputeSharp.SourceGenerators
Dictionary 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) });
+ 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
/// The current generator context in use.
/// The input instance to process.
/// The collection of currently discovered types.
+ /// Indicates whether or not represents a compute shader.
/// A sequence of captured fields in .
[Pure]
private static IEnumerable> GetProcessedFields(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
- ICollection types)
+ ICollection 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
/// The collection of currently discovered types.
/// The set of discovered and processed static methods.
/// The collection of discovered constant definitions.
+ /// Indicates whether or not represents a compute shader.
/// A sequence of processed methods in , and the entry point.
[Pure]
private static (string EntryPoint, IEnumerable Methods, IEnumerable Declarations) GetProcessedMethods(
@@ -312,7 +320,8 @@ namespace ComputeSharp.SourceGenerators
SemanticModelProvider semanticModel,
ICollection discoveredTypes,
IDictionary staticMethods,
- IDictionary constantDefinitions)
+ IDictionary constantDefinitions,
+ bool isComputeShader)
{
// Find all declared methods in the type
ImmutableArray 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.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();
}
diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs
index 812040df..1c7a0751 100644
--- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs
+++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs
@@ -265,6 +265,26 @@ namespace ComputeSharp.SourceGenerators.Mappings
return typeName.ToHlslIdentifierName();
}
+ ///
+ /// Gets the mapped HLSL-compatible type name for the output texture of a pixel shader.
+ ///
+ /// The pixel shader type to map.
+ /// The HLSL-compatible type name that can be used in an HLSL shader.
+ [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";
+ }
+
///
/// Gets the mapped HLSL-compatible type name for the input element type symbol.
///
diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs
index 0c9febca..d363b9ca 100644
--- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs
+++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs
@@ -15,13 +15,20 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
///
private readonly ShaderSourceRewriter shaderSourceRewriter;
+ ///
+ /// Indicates whether or not the method belongs to a compute shader.
+ ///
+ private readonly bool isComputeShader;
+
///
/// Creates a new instance with the specified parameters.
///
/// The instance used to process the input tree.
- public ExecuteMethodRewriter(ShaderSourceRewriter shaderSourceRewriter)
+ /// Indicates whether or not the method belongs to a compute shader.
+ public ExecuteMethodRewriter(ShaderSourceRewriter shaderSourceRewriter, bool isComputeShader)
{
this.shaderSourceRewriter = shaderSourceRewriter;
+ this.isComputeShader = isComputeShader;
}
///
@@ -56,11 +63,42 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return updatedNode;
}
+ ///
+ public override SyntaxNode? VisitReturnStatement(ReturnStatementSyntax node)
+ {
+ var updatedNode = (ReturnStatementSyntax)base.VisitReturnStatement(node)!;
+
+ if (this.isComputeShader)
+ {
+ return updatedNode;
+ }
+
+ // __outputTexture[ThreadIds.xy] = ;
+ return
+ ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ElementAccessExpression(IdentifierName("__outputTexture"))
+ .AddArgumentListArguments(
+ Argument(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("ThreadIds"),
+ IdentifierName("xy")))),
+ updatedNode.Expression!));
+ }
+
///
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:
diff --git a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs
index 22f05618..169f78cb 100644
--- a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs
+++ b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs
@@ -22,6 +22,7 @@ namespace ComputeSharp.__Internals
///
/// The type of the current shader.
/// The collection of custom types.
+ /// The implicit texture field info, if present.
/// The mapped collection of shader fields.
/// The forward declarations for static methods.
/// The source code for the method.
@@ -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().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2]));
ForwardDeclarations = forwardDeclarations;
ExecuteMethod = executeMethod;
@@ -61,6 +64,11 @@ namespace ComputeSharp.__Internals
///
internal IReadOnlyCollection Types { get; }
+ ///
+ /// Gets the mapping for the implicit texture field, if the shader is a pixel shader.
+ ///
+ internal (string Name, string Type)? ImplicitTextureField { get; }
+
///
/// Gets the mapping of field names.
///
diff --git a/src/ComputeSharp/Core/Interfaces/IPixelShader{TPixel}.cs b/src/ComputeSharp/Core/Interfaces/IPixelShader{TPixel}.cs
new file mode 100644
index 00000000..d89d6187
--- /dev/null
+++ b/src/ComputeSharp/Core/Interfaces/IPixelShader{TPixel}.cs
@@ -0,0 +1,15 @@
+namespace ComputeSharp
+{
+ ///
+ /// An representing a pixel shader.
+ ///
+ public interface IPixelShader
+ where TPixel : unmanaged
+ {
+ ///
+ /// Executes the current pixel shader.
+ ///
+ /// The pixel value for the current invocation.
+ TPixel Execute();
+ }
+}
diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs
index 834b2bab..57592daf 100644
--- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs
+++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs
@@ -1131,5 +1131,34 @@ namespace ComputeSharp
{
ShaderRunner.Run(device, x, y, z, threadsX, threadsY, threadsZ, in shader);
}
+
+ ///
+ /// Compiles and runs the input shader on a target instance, with the specified parameters.
+ ///
+ /// The type of pixel shader to run.
+ /// The type of pixels being processed by the shader.
+ /// The to use to run the shader.
+ /// The target texture to apply the pixel shader to.
+ public static void ForEach(this GraphicsDevice device, IReadWriteTexture2D texture)
+ where T : struct, IPixelShader
+ where TPixel : unmanaged
+ {
+ ShaderRunner.Run(device, texture, default);
+ }
+
+ ///
+ /// Compiles and runs the input shader on a target instance, with the specified parameters.
+ ///
+ /// The type of pixel shader to run.
+ /// The type of pixels being processed by the shader.
+ /// The to use to run the shader.
+ /// The target texture to apply the pixel shader to.
+ /// The input instance representing the pixel shader to run.
+ public static void ForEach(this GraphicsDevice device, IReadWriteTexture2D texture, in T shader)
+ where T : struct, IPixelShader
+ where TPixel : unmanaged
+ {
+ ShaderRunner.Run(device, texture, in shader);
+ }
}
}
diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs
index eb03e3ff..c01dd702 100644
--- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs
+++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs
@@ -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
{
///
@@ -20,7 +23,7 @@ namespace ComputeSharp.Shaders
///
/// The type of compute shader to run.
internal static class ShaderRunner
- where T : struct, IComputeShader
+ where T : struct
{
///
/// The mapping used to cache and reuse compiled shaders.
@@ -175,6 +178,86 @@ namespace ComputeSharp.Shaders
commandList.ExecuteAndWaitForCompletion();
}
+ ///
+ /// Compiles and runs the input shader on a target instance, with the specified parameters.
+ ///
+ /// The to use to run the shader.
+ /// The target texture to invoke the pixel shader upon.
+ /// The input instance representing the pixel shader to run.
+ public static unsafe void Run(GraphicsDevice device, IReadWriteTexture2D 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 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 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();
+ }
+
///
/// Loads a shader with the specified parameters.
///
diff --git a/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs b/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs
index da4de180..39558fb1 100644
--- a/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs
+++ b/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs
@@ -9,7 +9,7 @@ namespace ComputeSharp.Shaders.Translation.Models
///
/// The type of compute shader in use.
internal readonly struct CachedShader
- where T : struct, IComputeShader
+ where T : struct
{
///
/// The instance with the shader metadata.
diff --git a/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs
index d6139881..2304eba6 100644
--- a/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs
+++ b/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs
@@ -15,7 +15,7 @@ namespace ComputeSharp.Shaders.Translation
///
/// The type of compute shader currently in use.
private static class TypeInfo
- where T : struct, IComputeShader
+ where T : struct
{
///
/// 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(in T shader)
- where T : struct, IComputeShader
+ where T : struct
{
int hash = TypeInfo.Id;
@@ -70,6 +70,6 @@ namespace ComputeSharp.Shaders.Translation
/// The compute shader instance to use to compute the final hash value.
/// The final hash value for the input closure.
private delegate int Hasher(int hash, in T shader)
- where T : struct, IComputeShader;
+ where T : struct;
}
}
diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs
index 745f53b0..c410988e 100644
--- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs
+++ b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs
@@ -19,7 +19,7 @@ namespace ComputeSharp.Shaders.Translation
///
/// The type of compute shader currently in use.
internal sealed partial class ShaderLoader : IShaderLoader
- where T : struct, IComputeShader
+ where T : struct
{
///
/// The associated instance for the current shader type.
@@ -181,6 +181,23 @@ namespace ComputeSharp.Shaders.Translation
List 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)
{