diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md index 497432fa..fadd3bb7 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -49,7 +49,6 @@ CMPS0039 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Ser CMPS0040 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0041 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0042 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0043 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0044 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0045 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0046 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index e761b882..084ae35b 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -586,22 +586,6 @@ partial class DiagnosticDescriptors description: "A shader type cannot implement more than one shader interface.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); - /// - /// Gets a for a dynamic shader annotated as an embedded bytecode. - /// - /// Format: "The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)". - /// - /// - public static readonly DiagnosticDescriptor EmbeddedBytecodeWithDynamicShader = new DiagnosticDescriptor( - id: "CMPS0043", - title: "Embedded bytecode for dynamic shader", - messageFormat: "The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)", - category: "ComputeSharp.Shaders", - defaultSeverity: DiagnosticSeverity.Error, - isEnabledByDefault: true, - description: "A shader type cannot be precompiled if it captures one or more delegate values.", - helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); - /// /// Gets a for an embedded bytecode shader with invalid thread ids values. /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index 19e1d07f..54d2ab01 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using System.Collections.Immutable; using System.Text; using ComputeSharp.__Internals; @@ -88,15 +87,9 @@ partial class IShaderGenerator using ImmutableArrayBuilder statements = new(); StringBuilder textBuilder = new(); - int capturedDelegates = 0; int prologueStatements = 0; int sizeHint = 64; - void AppendLF() - { - _ = textBuilder.Append('\n'); - } - void AppendLine(string text) { _ = textBuilder.Append(text); @@ -132,67 +125,6 @@ partial class IShaderGenerator } } - // Declare the hashsets to track imported members and types from delegates, if needed - if (!hlslSourceInfo.Delegates.IsEmpty) - { - void DeclareMapping(int index, string name, IEnumerable items) - { - // global::System.Collections.Generic.HashSet = new(); - statements.Insert(index, - LocalDeclarationStatement(VariableDeclaration( - GenericName(Identifier("global::System.Collections.Generic.HashSet")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword)))) - .AddVariables( - VariableDeclarator(Identifier(name)) - .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))); - - prologueStatements++; - - // .Add(""); - foreach (string item in items) - { - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(name), - IdentifierName("Add"))) - .AddArgumentListArguments(Argument( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))))); - - prologueStatements++; - } - } - - DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes); - DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants); - DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures); - - // Go through all existing delegate fields, if any - foreach (string fieldName in hlslSourceInfo.Delegates) - { - // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, ""); - statements.Add( - LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}")) - .AddVariables( - VariableDeclarator(Identifier($"__{fieldName}Attribute")) - .WithInitializer( - EqualsValueClause( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"), - IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) - .AddArgumentListArguments( - Argument(IdentifierName(fieldName)), - Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); - - capturedDelegates++; - prologueStatements++; - } - } - // Header and thread ids AppendLine(hlslSourceInfo.HeaderAndThreadsX); AppendParsedStatement("builder.Append(threadsX);"); @@ -204,68 +136,15 @@ partial class IShaderGenerator // Define declarations AppendLine(hlslSourceInfo.Defines); - // Defines from captured delegates - foreach (string fieldName in hlslSourceInfo.Delegates) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);"); - } - // Static fields and declared types AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes); - // Declared types from captured delegates - foreach (string fieldName in hlslSourceInfo.Delegates) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); - } - // Captured variables AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations); - // Forward declarations from captured delegates - foreach (string fieldName in hlslSourceInfo.Delegates) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);"); - } - - // Remove all forward declarations from methods that are embedded into the shader. - // This is necessary to avoid duplicate definitions from methods from delegates. - if (capturedDelegates > 0) - { - // .Add(""); - foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures) - { - FlushText(); - - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("__methodNames"), - IdentifierName("Remove"))) - .AddArgumentListArguments(Argument( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration)))))); - } - } - // Captured methods AppendLine(hlslSourceInfo.CapturedMethods); - // Captured methods from captured delegates - foreach (string fieldName in hlslSourceInfo.Delegates) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);"); - } - - // Captured delegate methods - foreach (string fieldName in hlslSourceInfo.Delegates) - { - AppendLF(); - AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");"); - AppendLF(); - } - // Entry point AppendLine(hlslSourceInfo.EntryPoint); diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index fbadb447..6d888905 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -62,7 +62,6 @@ partial class IShaderGenerator bool isComputeShader = pixelShaderSymbol is null; string? implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); (ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, ImmutableArray<(string Name, string HlslType)> valueFields) = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes, isComputeShader); - ImmutableArray delegateInstanceFields = GetDispatchId.GetInfo(structDeclarationSymbol); ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers = GetSharedBuffers(diagnostics, structDeclarationSymbol, discoveredTypes); (string entryPoint, ImmutableArray<(string Signature, string Definition)> processedMethods, bool isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, isComputeShader); (string, string)? implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); @@ -78,7 +77,6 @@ partial class IShaderGenerator declaredTypes, resourceFields, valueFields, - delegateInstanceFields, staticFields, sharedBuffers, processedMethods, @@ -544,7 +542,6 @@ partial class IShaderGenerator /// The sequence of declared types used by the shader. /// The sequence of resource instance fields for the current shader. /// The sequence of value instance fields for the current shader. - /// The sequence of delegate fields for the current shader. /// The sequence of static fields referenced by the shader. /// The sequence of shared buffers declared by the shader. /// The sequence of processed methods used by the shader. @@ -558,7 +555,6 @@ partial class IShaderGenerator ImmutableArray<(string Name, string Definition)> declaredTypes, ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, ImmutableArray<(string Name, string HlslType)> valueFields, - ImmutableArray delegateInstanceFields, ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers, ImmutableArray<(string Signature, string Definition)> processedMethods, @@ -768,8 +764,7 @@ partial class IShaderGenerator isSamplerUsed, declaredTypes.Select(static t => t.Name).ToImmutableArray(), definedConstants.Select(static c => c.Name).ToImmutableArray(), - processedMethods.Select(static m => m.Signature).ToImmutableArray(), - delegateInstanceFields); + processedMethods.Select(static m => m.Signature).ToImmutableArray()); } /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs deleted file mode 100644 index 59e59acd..00000000 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using ComputeSharp.__Internals; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 - -namespace ComputeSharp.SourceGenerators; - -/// -partial class IShaderGenerator -{ - /// - partial class GetDispatchId - { - /// - /// Creates a instance for the GetDispatchId method. - /// - /// The names of all instance fields within the current shader type. - /// The resulting instance for the GetDispatchId method. - public static MethodDeclarationSyntax GetSyntax(ImmutableArray delegateFieldNames) - { - // This code produces a method declaration as follows: - // - // readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId() - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.IntKeyword)), - Identifier("GetDispatchId")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithBody(GetShaderHashCodeBody(delegateFieldNames)); - } - - /// - /// Gets a instance with the logic to compute the hashcode of a given shader type. - /// - /// The names of all instance fields within the current shader type. - /// The instance to hash the input shader. - private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames) - { - if (delegateFieldNames.Length == 0) - { - // return 0; - return - Block(ReturnStatement( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))); - } - - List blockStatements = new(4) - { - // global::System.HashCode hashCode = default; - LocalDeclarationStatement( - VariableDeclaration(IdentifierName("global::System.HashCode")) - .AddVariables( - VariableDeclarator(Identifier("hashCode")) - .WithInitializer(EqualsValueClause( - LiteralExpression( - SyntaxKind.DefaultLiteralExpression, - Token(SyntaxKind.DefaultKeyword)))))) - }; - - foreach (string fieldName in delegateFieldNames) - { - // hashCode.Add(delegateField.Method); - blockStatements.Add(ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("hashCode"), - IdentifierName("Add"))) - .AddArgumentListArguments(Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(fieldName), - IdentifierName("Method")))))); - } - - // return hashCode.ToHashCode(); - blockStatements.Add(ReturnStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("hashCode"), - IdentifierName("ToHashCode"))))); - - return Block(blockStatements); - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs deleted file mode 100644 index 8485f16a..00000000 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Collections.Immutable; -using System.Linq; -using Microsoft.CodeAnalysis; - -namespace ComputeSharp.SourceGenerators; - -/// -partial class IShaderGenerator -{ - /// - /// A helper with all logic to generate the GetDispatchId method. - /// - private static partial class GetDispatchId - { - /// - /// Extracts the names of all instance fields of a type. - /// - /// The input instance to process. - /// The names of all instance fields within . - public static ImmutableArray GetInfo(INamedTypeSymbol structDeclarationSymbol) - { - return - structDeclarationSymbol - .GetMembers() - .OfType() - .Where(static member => member is { Type: INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }, IsImplicitlyDeclared: false }) - .Select(static member => member.Name) - .ToImmutableArray(); - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs index 18489595..56ea8dab 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs @@ -36,13 +36,11 @@ partial class IShaderGenerator /// /// The collection of produced instances. /// The input instance to process. - /// Indicates whether or not the shader is dynamic (ie. captures delegates). /// Indicates whether or not dynamic shaders are supported. /// The thread ids for the precompiled shader, if available. public static ThreadIdsInfo GetInfo( ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, - bool isDynamicShader, bool supportsDynamicShaders) { // Try to get the attribute that controls shader precompilation (has to be present when ComputeSharp.Dynamic is not referenced) @@ -107,14 +105,6 @@ partial class IShaderGenerator threadsZ = explicitThreadsZ; } - // If the current shader is dynamic, emit a diagnostic error - if (isDynamicShader) - { - diagnostics.Add(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol); - - return new(true, 0, 0, 0); - } - // Ensure the bytecode generation is disabled if any errors are present. This step is done last to ensure that // all available diagnostics are still emitted correctly before reaching this point, instead of being disabled. if (diagnostics.Count > 0) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 280a1d1e..2594f0a6 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -56,11 +56,6 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator using ImmutableArrayBuilder diagnostics = new(); - // GetDispatchId() info - ImmutableArray dispatchIdInfo = GetDispatchId.GetInfo(typeSymbol); - - token.ThrowIfCancellationRequested(); - // LoadDispatchData() info ImmutableArray fieldInfos = LoadDispatchData.GetInfo( diagnostics, @@ -93,14 +88,12 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator ThreadIdsInfo threadIds = LoadBytecode.GetInfo( diagnostics, typeSymbol, - !hlslSourceInfo.Delegates.IsEmpty, IsDynamicCompilationSupported(context.SemanticModel.Compilation)); token.ThrowIfCancellationRequested(); return new ShaderInfo( Hierarchy: HierarchyInfo.From(typeSymbol), - DispatchId: new DispatchIdInfo(dispatchIdInfo), DispatchData: new DispatchDataInfo( shaderType, fieldInfos, @@ -118,20 +111,6 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator shaderInfoWithErrors .Select(static (item, _) => item.Diagnostcs)); - // Get the GetDispatchId() info (hierarchy and dispatch id info) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchIdInfo DispatchId)> dispatchIdInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.DispatchId)); - - // Generate the GetDispatchId() methods - context.RegisterSourceOutput(dispatchIdInfo, static (context, item) => - { - MethodDeclarationSyntax getDispatchIdMethod = GetDispatchId.GetSyntax(item.DispatchId.Delegates); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getDispatchIdMethod, addSkipLocalsInitAttribute: false); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetDispatchId)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - // Get the LoadDispatchData() info (hierarchy and dispatch data info) IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo DispatchData)> dispatchDataInfo = shaderInfoWithErrors diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs deleted file mode 100644 index 1b47c460..00000000 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs +++ /dev/null @@ -1,9 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.SourceGenerators.Models; - -/// -/// A model representing gathered info on a shader dispatch id. -/// -/// The list of delegate field names for the shader. -internal sealed record DispatchIdInfo(EquatableArray Delegates); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs index e115d2ed..eb418c38 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs @@ -18,7 +18,6 @@ namespace ComputeSharp.SourceGenerators.Models; /// The names of declared types. /// The names of defined constants. /// The signatures for captured methods. -/// The list of delegate fields. internal sealed record HlslShaderSourceInfo( string HeaderAndThreadsX, string ThreadsY, @@ -32,5 +31,4 @@ internal sealed record HlslShaderSourceInfo( bool IsSamplerUsed, EquatableArray DefinedTypes, EquatableArray DefinedConstants, - EquatableArray MethodSignatures, - EquatableArray Delegates); \ No newline at end of file + EquatableArray MethodSignatures); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs index 70a7ebfc..27cd2efc 100644 --- a/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs @@ -7,7 +7,6 @@ namespace ComputeSharp.SourceGenerators.Models; /// A model representing all necessary info for a full generation pass for a shader. /// /// The hierarchy info for the shader type. -/// The gathered dispatch id for the shader type. /// The gathered shader dispatch data. /// The gathered shader dispatch metadata. /// The processed HLSL source for the shader. @@ -15,7 +14,6 @@ namespace ComputeSharp.SourceGenerators.Models; /// The discovered diagnostics, if any. internal sealed record ShaderInfo( HierarchyInfo Hierarchy, - DispatchIdInfo DispatchId, DispatchDataInfo DispatchData, DispatchMetadataInfo DispatchMetadata, HlslShaderSourceInfo HlslShaderSource, diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs index be0cc8af..35878d67 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs @@ -10,14 +10,6 @@ namespace ComputeSharp.__Internals; [Obsolete("This interface is not intended to be used directly by user code")] public interface IShader { - /// - /// Gets a unique dispatch identifier for the shader. - /// - /// The unique dispatch identifier for the shader. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be used directly by user code")] - int GetDispatchId(); - /// /// Loads the dispatch data for the shader. /// diff --git a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs index fc4a80fe..cb618e53 100644 --- a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs @@ -35,7 +35,7 @@ internal static class PipelineDataLoader /// The instance for a given shader. public static unsafe PipelineData GetPipelineData(GraphicsDevice device, int threadsX, int threadsY, int threadsZ, ref T shader) { - ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, threadsZ); + ShaderKey key = new(threadsX, threadsY, threadsZ); lock (ShadersCache) { diff --git a/src/ComputeSharp/Shaders/Models/ShaderKey.cs b/src/ComputeSharp/Shaders/Models/ShaderKey.cs index 695630c9..7b80aff3 100644 --- a/src/ComputeSharp/Shaders/Models/ShaderKey.cs +++ b/src/ComputeSharp/Shaders/Models/ShaderKey.cs @@ -8,11 +8,6 @@ namespace ComputeSharp.Shaders.Models; /// internal readonly struct ShaderKey : IEquatable { - /// - /// The hashcode of the current shader type. - /// - private readonly int id; - /// /// The number of iterations to run on the X axis. /// @@ -31,14 +26,12 @@ internal readonly struct ShaderKey : IEquatable /// /// Creates a new instance with the specified parameters. /// - /// The hashcode of the current shader type. /// The number of iterations to run on the X axis. /// The number of iterations to run on the Y axis. /// The number of iterations to run on the Z axis. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ShaderKey(int id, int threadsX, int threadsY, int threadsZ) + public ShaderKey(int threadsX, int threadsY, int threadsZ) { - this.id = id; this.threadsX = threadsX; this.threadsY = threadsY; this.threadsZ = threadsZ; @@ -49,7 +42,6 @@ internal readonly struct ShaderKey : IEquatable public bool Equals(ShaderKey other) { return - this.id == other.id && this.threadsX == other.threadsX && this.threadsY == other.threadsY && this.threadsZ == other.threadsZ; @@ -65,6 +57,6 @@ internal readonly struct ShaderKey : IEquatable [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { - return HashCode.Combine(this.id, this.threadsX, this.threadsY, this.threadsZ); + return HashCode.Combine(this.threadsX, this.threadsY, this.threadsZ); } } \ No newline at end of file diff --git a/tests/ComputeSharp.Tests.GlobalStatements/ComputeSharp.Tests.GlobalStatements.csproj b/tests/ComputeSharp.Tests.GlobalStatements/ComputeSharp.Tests.GlobalStatements.csproj index 5dd86a9c..dfc22942 100644 --- a/tests/ComputeSharp.Tests.GlobalStatements/ComputeSharp.Tests.GlobalStatements.csproj +++ b/tests/ComputeSharp.Tests.GlobalStatements/ComputeSharp.Tests.GlobalStatements.csproj @@ -10,7 +10,6 @@ - diff --git a/tests/ComputeSharp.Tests.GlobalStatements/Program.cs b/tests/ComputeSharp.Tests.GlobalStatements/Program.cs index 9991f2ec..33a9c0a1 100644 --- a/tests/ComputeSharp.Tests.GlobalStatements/Program.cs +++ b/tests/ComputeSharp.Tests.GlobalStatements/Program.cs @@ -5,11 +5,11 @@ float[] numbers = Enumerable.Range(0, 128).Select(i => (float)i).ToArray(); using GraphicsDevice device = GraphicsDevice.GetDefault(); using ReadWriteBuffer buffer = device.AllocateReadWriteBuffer(numbers); -device.For(buffer.Length, new ApplyFunctionShader(buffer, AddHalf)); +device.For(buffer.Length, new ApplyFunctionShader(buffer)); foreach (ref float number in numbers.AsSpan()) { - number = AddHalf(number); + number = ApplyFunctionShader.AddHalf(number); } float[] result = buffer.ToArray(); @@ -21,18 +21,19 @@ if (!numbers.SequenceEqual(result)) Console.WriteLine("Test passed successfully!"); -// See https://github.com/Sergio0694/ComputeSharp/issues/374 -[ShaderMethod] -static float AddHalf(float input) => input + 0.5f; - [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct ApplyFunctionShader : IComputeShader { private readonly ReadWriteBuffer sourceTexture; - private readonly Func func; + + public static float AddHalf(float input) + { + return input + 0.5f; + } public void Execute() { - this.sourceTexture[ThreadIds.X] = this.func(this.sourceTexture[ThreadIds.X]); + this.sourceTexture[ThreadIds.X] = AddHalf(this.sourceTexture[ThreadIds.X]); } } \ No newline at end of file diff --git a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs deleted file mode 100644 index a4dcdcd5..00000000 --- a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using ComputeSharp.__Internals; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -#pragma warning disable CS0618 - -namespace ComputeSharp.Tests.Internals; - -[TestClass] -[TestCategory("ShaderHashCode")] -public partial class ShaderHashCodeTests -{ - public partial struct Shader1 : IComputeShader - { - public float A; - public ReadWriteBuffer B; - - public void Execute() - { - this.B[0] = this.A; - } - } - - [TestMethod] - public void ShaderWithNoCapturedDelegates() - { - float value = 10; - using ReadWriteBuffer buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(1); - - Shader1 shader1 = new() { A = value, B = buffer }; - - int hash1 = ((IShader)shader1).GetDispatchId(); - int hash2 = ((IShader)shader1).GetDispatchId(); - - Assert.IsTrue(hash1 == hash2); - - Shader1 shader2 = new() { A = value, B = buffer }; - - int hash3 = ((IShader)shader2).GetDispatchId(); - - Assert.IsTrue(hash1 == hash3); - } - - public partial struct Shader2 : IComputeShader - { - public float A; - public ReadWriteBuffer B; - public Func F; - - public void Execute() - { - this.B[0] = this.F(this.A); - } - } - - [TestMethod] - public void ShaderWithCapturedDelegates() - { - Func f = static x => x * x; - - using ReadWriteBuffer buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(1); - - Shader2 shader1 = new() { A = 1, B = buffer, F = f }; - - int hash1 = ((IShader)shader1).GetDispatchId(); - int hash2 = ((IShader)shader1).GetDispatchId(); - - Assert.IsTrue(hash1 == hash2); - - f = static x => x + 1; - - Shader2 shader2 = new() { A = 1, B = buffer, F = f }; - - int hash3 = ((IShader)shader2).GetDispatchId(); - - Assert.IsFalse(hash1 == hash3); - } -} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs index 18c30552..9352326b 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs @@ -1481,41 +1481,6 @@ public class DiagnosticsTests VerifyGeneratedDiagnostics(source, "CMPS0042", "CMPS0047"); } - [TestMethod] - public void EmbeddedBytecodeWithDynamicShader() - { - const string source = """ - using System; - using ComputeSharp; - - namespace ComputeSharp - { - public interface IComputeShader { } - public class ReadWriteBuffer { } - public class EmbeddedBytecodeAttribute : Attribute - { - public EmbeddedBytecodeAttribute(int threadsX, int threadsY, int threadsZ) { } - } - } - - namespace MyFancyApp.Sample - { - [EmbeddedBytecode(8, 8, 1)] - public struct MyShader : IComputeShader - { - public ReadWriteBuffer buffer; - public Action action; - - public void Execute() - { - } - } - } - """; - - VerifyGeneratedDiagnostics(source, "CMPS0043"); - } - [TestMethod] [DataRow(-1, 1, 1)] [DataRow(1, -1, 1)] diff --git a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs deleted file mode 100644 index 91bad97b..00000000 --- a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs +++ /dev/null @@ -1,251 +0,0 @@ -using System; -using ComputeSharp.Tests.Attributes; -using ComputeSharp.Tests.Extensions; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -#pragma warning disable IDE0062 - -namespace ComputeSharp.Tests; - -[TestClass] -[TestCategory("Metaprogramming")] -public partial class MetaprogrammingTests -{ - [AutoConstructor] - internal readonly partial struct ActivationWithDelegateShader : IComputeShader - { - public readonly ReadWriteBuffer buffer; - public readonly Func activation; - - public void Execute() - { - this.buffer[ThreadIds.X] = this.activation(ThreadIds.X); - } - } - - public static class Activations - { - [ShaderMethod] - public static int Square(int x) - { - return x * x; - } - - [ShaderMethod] - public static int AddOne(int x) - { - return x + 1; - } - - // Missing attribute - public static int Identity(int x) - { - return x; - } - - [ShaderMethod] - public static int FunctionWithConstants(int x) - { - return (int)(x + FourAndAHalf); - } - - [ShaderMethod] - public static Position FunctionWithTypes(int x) - { - Point point = default; - point.A = x; - point.B = x * x; - - Position position = default; - position.X = point.A; - position.Y = point.B; - - return position; - } - - public struct Point - { - public int A; - public int B; - } - - [ShaderMethod] - public static int FunctionWithLocalFunctionAndStaticMethod(int x) - { - static int AddTwo(int x) => x + 2; - - return Square(3 + AddOne(x) + AddTwo(x)); - } - } - - [CombinatorialTestMethod] - [AllDevices] - public unsafe void ActivationWithDelegate(Device device) - { - using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); - - device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Square)); - - int[] result = buffer.ToArray(); - - for (int i = 0; i < 100; i++) - { - Assert.AreEqual(result[i], Activations.Square(i)); - } - - device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.AddOne)); - - result = buffer.ToArray(); - - for (int i = 0; i < 100; i++) - { - Assert.AreEqual(result[i], Activations.AddOne(i)); - } - } - - [CombinatorialTestMethod] - [AllDevices] - [ExpectedException(typeof(ArgumentException))] - public unsafe void DelegateWithMissingAttributeOnMethod(Device device) - { - using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); - - device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Identity)); - } - - [CombinatorialTestMethod] - [AllDevices] - [ExpectedException(typeof(ArgumentException))] - public unsafe void DelegateWrappingNonStaticMethod(Device device) - { - using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); - - [ShaderMethod] - int Dummy(int x) => x; - - device.Get().For(100, new ActivationWithDelegateShader(buffer, Dummy)); - } - - [AutoConstructor] - internal readonly partial struct ActivationWithMultipleDelegatesShader : IComputeShader - { - public readonly ReadWriteBuffer buffer; - public readonly Func f1; - public readonly Func f2; - - public void Execute() - { - this.buffer[ThreadIds.X] = this.f2(this.f1(ThreadIds.X)); - } - } - - [CombinatorialTestMethod] - [AllDevices] - public unsafe void ActivationWithMultipleDelegates(Device device) - { - using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); - - device.Get().For(100, new ActivationWithMultipleDelegatesShader(buffer, Activations.Square, Activations.AddOne)); - - int[] result = buffer.ToArray(); - - for (int i = 0; i < 100; i++) - { - Assert.AreEqual(result[i], Activations.AddOne(Activations.Square(i))); - } - } - - public const float FourAndAHalf = 4.5f; - public const int MagicNumber = 42; - - [AutoConstructor] - internal readonly partial struct DelegateWithConstantsShader : IComputeShader - { - public readonly ReadWriteBuffer buffer; - public readonly Func activation; - - public void Execute() - { - this.buffer[ThreadIds.X] = MagicNumber + this.activation(ThreadIds.X); - } - } - - [CombinatorialTestMethod] - [AllDevices] - public unsafe void DelegateWithConstants(Device device) - { - using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); - - device.Get().For(100, new DelegateWithConstantsShader(buffer, Activations.FunctionWithConstants)); - - int[] result = buffer.ToArray(); - - for (int i = 0; i < 100; i++) - { - Assert.AreEqual(result[i], MagicNumber + Activations.FunctionWithConstants(i)); - } - } - - public struct Position - { - public int X; - public int Y; - } - - [AutoConstructor] - internal readonly partial struct DelegateWithTypesShader : IComputeShader - { - public readonly ReadWriteBuffer buffer; - public readonly Func activation; - - public void Execute() - { - this.buffer[ThreadIds.X] = this.activation(ThreadIds.X); - } - } - - [CombinatorialTestMethod] - [AllDevices] - public unsafe void DelegateWithTypes(Device device) - { - using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); - - device.Get().For(100, new DelegateWithTypesShader(buffer, Activations.FunctionWithTypes)); - - Position[] result = buffer.ToArray(); - - for (int i = 0; i < 100; i++) - { - Assert.AreEqual(result[i].X, Activations.FunctionWithTypes(i).X); - Assert.AreEqual(result[i].Y, Activations.FunctionWithTypes(i).Y); - } - } - - [AutoConstructor] - internal readonly partial struct DelegateWithLocalFunctionsAndStaticMethodsShader : IComputeShader - { - public readonly ReadWriteBuffer buffer; - public readonly Func activation; - - public void Execute() - { - this.buffer[ThreadIds.X] = Activations.AddOne(ThreadIds.X) + this.activation(ThreadIds.X); - } - } - - [CombinatorialTestMethod] - [AllDevices] - public unsafe void DelegateWithLocalFunctionsAndStaticMethods(Device device) - { - using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); - - device.Get().For(100, new DelegateWithLocalFunctionsAndStaticMethodsShader(buffer, Activations.FunctionWithLocalFunctionAndStaticMethod)); - - int[] result = buffer.ToArray(); - - for (int i = 0; i < 100; i++) - { - Assert.AreEqual(result[i], Activations.AddOne(i) + Activations.FunctionWithLocalFunctionAndStaticMethod(i)); - } - } -} \ No newline at end of file