From 3db275a157002d0084cca2630ffdf6c40a6dd381 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 13 Oct 2023 01:13:53 +0200 Subject: [PATCH 1/6] Remove IShader.GetDispatchId() infrastructure --- .../AnalyzerReleases.Shipped.md | 1 - .../Diagnostics/DiagnosticDescriptors.cs | 16 -- ...ator.CreateBuildHlslSourceMethod.Syntax.cs | 121 --------- ...erGenerator.CreateBuildHlslSourceMethod.cs | 7 +- ...erator.CreateGetDispatchIdMethod.Syntax.cs | 97 ------- ...aderGenerator.CreateGetDispatchIdMethod.cs | 31 --- ...haderGenerator.CreateLoadBytecodeMethod.cs | 10 - .../IShaderGenerator.cs | 21 -- .../Models/DispatchIdInfo.cs | 9 - .../Models/HlslShaderSourceInfo.cs | 4 +- .../Models/ShaderInfo.cs | 2 - .../Core/Interfaces/__Internals/IShader.cs | 8 - .../Shaders/Loading/PipelineDataLoader{T}.cs | 2 +- src/ComputeSharp/Shaders/Models/ShaderKey.cs | 12 +- ...ComputeSharp.Tests.GlobalStatements.csproj | 1 - .../Program.cs | 17 +- .../ShaderHashCodeTests.cs | 78 ------ .../DiagnosticsTests.cs | 35 --- .../MetaprogrammingTests.cs | 251 ------------------ 19 files changed, 14 insertions(+), 709 deletions(-) delete mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs delete mode 100644 src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs delete mode 100644 tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs delete mode 100644 tests/ComputeSharp.Tests/MetaprogrammingTests.cs 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 From 490226aa4d4251b3d4878ff264f06ec7d35b9270 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 13 Oct 2023 11:09:20 +0200 Subject: [PATCH 2/6] Disable dynamic shader compilation support --- .../Blas/BlasHelpers.cs | 1 + .../ComputeSharp.Benchmark.csproj | 1 - .../Dispatching/DispatchingBenchmark.cs | 1 + .../ComputeSharp.ImageProcessing.csproj | 1 - .../HlslBokehBlurProcessor{TPixel}.cs | 4 +++ .../HlslGaussianBlurProcessor{TPixel}.cs | 2 ++ .../ComputeSharp.Sample.FSharp.Shaders.csproj | 1 - .../MultiplyByTwo.cs | 1 + .../ComputeSharp.Sample.FSharp.fsproj | 1 - .../ComputeSharp.Sample.csproj | 1 - samples/ComputeSharp.Sample/Program.cs | 1 + .../ComputeSharp.SwapChain.Cli.csproj | 1 - .../ColorfulInfinity.cs | 2 -- .../ContouredLayers.cs | 2 -- .../ExtrudedTruchetPattern.cs | 2 -- .../FourColorGradient.cs | 2 -- .../FractalTiling.cs | 2 -- .../HelloWorld.cs | 2 -- .../MengerJourney.cs | 2 -- .../Octagrams.cs | 2 -- .../ProteanClouds.cs | 2 -- .../PyramidPattern.cs | 2 -- .../TerracedHills.cs | 2 -- .../TriangleGridContouring.cs | 2 -- .../TwoTiledTruchet.cs | 2 -- .../ComputeSharp.SwapChain.WinUI.csproj | 1 - .../ComputeSharp.SwapChain.csproj | 1 - ...ator.CreateBuildHlslSourceMethod.Syntax.cs | 4 +-- .../IShaderGenerator.Helpers.cs | 11 -------- .../IShaderGenerator.cs | 4 +-- tests/ComputeSharp.Dynamic.NuGet/Program.cs | 13 +++++++--- .../ShaderDataLoaderTests.cs | 7 ++++++ .../DynamicNativeLibrariesResolverTests.cs | 2 +- .../PixNativeLibrariesResolverTests.cs | 2 +- tests/ComputeSharp.Tests/BufferTests.cs | 4 +++ .../ComputeSharp.Tests/ComputeContextTests.cs | 12 +++++++++ tests/ComputeSharp.Tests/DispatchTests.cs | 9 +++++++ tests/ComputeSharp.Tests/IPixelShaderTests.cs | 1 + .../ComputeSharp.Tests/InitializationTests.cs | 1 + .../ResourceDimensionsTests.g.cs | 25 ++++++++++++++++++- .../ResourceDimensionsTests.tt | 3 ++- .../ComputeSharp.Tests/ShaderCompilerTests.cs | 17 +++++++++++++ .../ComputeSharp.Tests/ShaderMembersTests.cs | 4 +++ .../ComputeSharp.Tests/ShaderRewriterTests.cs | 12 +++++++++ .../Shaders/Compute/ColorfulInfinity.cs | 1 + .../Shaders/Compute/ContouredLayers.cs | 1 + .../Shaders/Compute/ExtrudedTruchetPattern.cs | 1 + .../Shaders/Compute/FourColorGradient.cs | 1 + .../Shaders/Compute/FractalTiling.cs | 1 + .../Shaders/Compute/HelloWorld.cs | 1 + .../Shaders/Compute/MengerJourney.cs | 1 + .../Shaders/Compute/Octagrams.cs | 1 + .../Shaders/Compute/ProteanClouds.cs | 1 + .../Shaders/Compute/PyramidPattern.cs | 1 + .../Shaders/Compute/TerracedHills.cs | 1 + .../Shaders/Compute/TriangleGridContouring.cs | 1 + .../Shaders/Compute/TwoTiledTruchet.cs | 1 + .../Texture1DTests.Pixels.cs | 1 + .../Texture1DTests.Pixels.g.cs | 9 ++++++- .../Texture1DTests.Pixels.tt | 3 ++- tests/ComputeSharp.Tests/Texture1DTests.cs | 2 ++ .../Texture2DTests.Pixels.cs | 2 ++ .../Texture2DTests.Pixels.g.cs | 9 ++++++- .../Texture2DTests.Pixels.tt | 3 ++- tests/ComputeSharp.Tests/Texture2DTests.cs | 2 ++ .../Texture3DTests.Pixels.g.cs | 9 ++++++- .../Texture3DTests.Pixels.tt | 3 ++- tests/ComputeSharp.Tests/Texture3DTests.cs | 2 ++ 68 files changed, 169 insertions(+), 64 deletions(-) diff --git a/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs b/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs index a2d94d21..7f092b09 100644 --- a/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs +++ b/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs @@ -81,6 +81,7 @@ internal static partial class BlasHelpers /// Kernel for . /// [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] public readonly partial struct FullyConnectedForwardKernel : IComputeShader { private readonly int n; diff --git a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj index a1795f40..7cd14f1c 100644 --- a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj +++ b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj @@ -28,7 +28,6 @@ - \ No newline at end of file diff --git a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs index a3ec85a8..5c477a7a 100644 --- a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs @@ -109,6 +109,7 @@ public partial class DispatchingBenchmark : IDisposable } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct TestShader : IComputeShader { private readonly ReadWriteBuffer buffer; diff --git a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj index 1670863e..dcbc7cad 100644 --- a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj +++ b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj @@ -19,7 +19,6 @@ - diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index cb4a3949..6c8d9fc8 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -314,6 +314,7 @@ public sealed partial class HlslBokehBlurProcessor /// Kernel for the vertical convolution pass. /// [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct VerticalConvolutionProcessor : IComputeShader { private readonly IReadWriteNormalizedTexture2D source; @@ -351,6 +352,7 @@ public sealed partial class HlslBokehBlurProcessor /// Kernel for the horizontal convolution pass. /// [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader { private readonly float z; @@ -390,6 +392,7 @@ public sealed partial class HlslBokehBlurProcessor /// Kernel for the gamma highlight pass. /// [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct GammaHighlightProcessor : IComputeShader { private readonly IReadWriteNormalizedTexture2D source; @@ -414,6 +417,7 @@ public sealed partial class HlslBokehBlurProcessor /// Kernel for the inverse gamma highlight pass. /// [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader { private readonly ReadWriteTexture2D source; diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index e24a82a2..d35ac808 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -118,6 +118,7 @@ public sealed partial class HlslGaussianBlurProcessor /// Kernel for the vertical convolution pass. /// [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct VerticalConvolutionProcessor : IComputeShader { private readonly IReadWriteNormalizedTexture2D source; @@ -150,6 +151,7 @@ public sealed partial class HlslGaussianBlurProcessor /// Kernel for the horizontal convolution pass. /// [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader { private readonly IReadWriteNormalizedTexture2D source; diff --git a/samples/ComputeSharp.Sample.FSharp.Shaders/ComputeSharp.Sample.FSharp.Shaders.csproj b/samples/ComputeSharp.Sample.FSharp.Shaders/ComputeSharp.Sample.FSharp.Shaders.csproj index 220912b1..3cda0b7d 100644 --- a/samples/ComputeSharp.Sample.FSharp.Shaders/ComputeSharp.Sample.FSharp.Shaders.csproj +++ b/samples/ComputeSharp.Sample.FSharp.Shaders/ComputeSharp.Sample.FSharp.Shaders.csproj @@ -8,7 +8,6 @@ - diff --git a/samples/ComputeSharp.Sample.FSharp.Shaders/MultiplyByTwo.cs b/samples/ComputeSharp.Sample.FSharp.Shaders/MultiplyByTwo.cs index 3b9e6f98..ac8d99a2 100644 --- a/samples/ComputeSharp.Sample.FSharp.Shaders/MultiplyByTwo.cs +++ b/samples/ComputeSharp.Sample.FSharp.Shaders/MultiplyByTwo.cs @@ -4,6 +4,7 @@ namespace ComputeSharp.Sample.FSharp.Shaders; /// A sample shader thaat just multiplies items in a buffer by two. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct MultiplyByTwo : IComputeShader { private readonly ReadWriteBuffer buffer; diff --git a/samples/ComputeSharp.Sample.FSharp/ComputeSharp.Sample.FSharp.fsproj b/samples/ComputeSharp.Sample.FSharp/ComputeSharp.Sample.FSharp.fsproj index b4da66d3..8a0392e9 100644 --- a/samples/ComputeSharp.Sample.FSharp/ComputeSharp.Sample.FSharp.fsproj +++ b/samples/ComputeSharp.Sample.FSharp/ComputeSharp.Sample.FSharp.fsproj @@ -19,7 +19,6 @@ - diff --git a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj b/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj index 884e0a6e..2ab6faf3 100644 --- a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj +++ b/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj @@ -10,7 +10,6 @@ - diff --git a/samples/ComputeSharp.Sample/Program.cs b/samples/ComputeSharp.Sample/Program.cs index 21e050fa..761aecc4 100644 --- a/samples/ComputeSharp.Sample/Program.cs +++ b/samples/ComputeSharp.Sample/Program.cs @@ -24,6 +24,7 @@ Formatting.PrintMatrix(array, 10, 10, "AFTER"); /// The sample kernel that multiples all items by two. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct MultiplyByTwo : IComputeShader { private readonly ReadWriteBuffer buffer; diff --git a/samples/ComputeSharp.SwapChain.Cli/ComputeSharp.SwapChain.Cli.csproj b/samples/ComputeSharp.SwapChain.Cli/ComputeSharp.SwapChain.Cli.csproj index 299c5aa6..9274944d 100644 --- a/samples/ComputeSharp.SwapChain.Cli/ComputeSharp.SwapChain.Cli.csproj +++ b/samples/ComputeSharp.SwapChain.Cli/ComputeSharp.SwapChain.Cli.csproj @@ -10,7 +10,6 @@ WinExe net7.0 x64;ARM64 - $(DefineConstants);SAMPLE_APP $(NoWarn);CA1416 computesharp.cli diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/ColorfulInfinity.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/ColorfulInfinity.cs index 932b1ffc..224ba76f 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/ColorfulInfinity.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/ColorfulInfinity.cs @@ -7,9 +7,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct ColorfulInfinity : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/ContouredLayers.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/ContouredLayers.cs index aaa46d77..99b50e94 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/ContouredLayers.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/ContouredLayers.cs @@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// Created by Shane. /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct ContouredLayers : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/ExtrudedTruchetPattern.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/ExtrudedTruchetPattern.cs index 888530d8..ceea8dce 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/ExtrudedTruchetPattern.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/ExtrudedTruchetPattern.cs @@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// Created by Shane. /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct ExtrudedTruchetPattern : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/FourColorGradient.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/FourColorGradient.cs index dc14ebe5..92bff991 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/FourColorGradient.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/FourColorGradient.cs @@ -7,9 +7,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct FourColorGradient : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/FractalTiling.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/FractalTiling.cs index 5b7b8d56..4478d2dc 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/FractalTiling.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/FractalTiling.cs @@ -7,9 +7,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct FractalTiling : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/HelloWorld.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/HelloWorld.cs index 1fa112b7..192ec941 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/HelloWorld.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/HelloWorld.cs @@ -5,9 +5,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// Ported from . /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct HelloWorld : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/MengerJourney.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/MengerJourney.cs index d3727452..958726ae 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/MengerJourney.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/MengerJourney.cs @@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// Created by Syntopia. /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct MengerJourney : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/Octagrams.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/Octagrams.cs index b9ed0603..3190d925 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/Octagrams.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/Octagrams.cs @@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// Created by whisky_shusuky. /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct Octagrams : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/ProteanClouds.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/ProteanClouds.cs index 33b358bc..ef98690e 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/ProteanClouds.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/ProteanClouds.cs @@ -7,9 +7,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct ProteanClouds : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/PyramidPattern.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/PyramidPattern.cs index ce8988f3..5ffc2fa2 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/PyramidPattern.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/PyramidPattern.cs @@ -7,9 +7,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// Created by Shane. /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct PyramidPattern : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/TerracedHills.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/TerracedHills.cs index 7cf960b8..1d8ab189 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/TerracedHills.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/TerracedHills.cs @@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// Created by Shane. /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct TerracedHills : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/TriangleGridContouring.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/TriangleGridContouring.cs index 4486624e..60e1af58 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/TriangleGridContouring.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/TriangleGridContouring.cs @@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// Created by Shane. /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct TriangleGridContouring : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/TwoTiledTruchet.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/TwoTiledTruchet.cs index b7855082..3e44c208 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/TwoTiledTruchet.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/TwoTiledTruchet.cs @@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders; /// Created by Shane. /// [AutoConstructor] -#if SAMPLE_APP [EmbeddedBytecode(DispatchAxis.XY)] -#endif internal readonly partial struct TwoTiledTruchet : IPixelShader { /// diff --git a/samples/ComputeSharp.SwapChain.WinUI/ComputeSharp.SwapChain.WinUI.csproj b/samples/ComputeSharp.SwapChain.WinUI/ComputeSharp.SwapChain.WinUI.csproj index ddd61735..e789e5ba 100644 --- a/samples/ComputeSharp.SwapChain.WinUI/ComputeSharp.SwapChain.WinUI.csproj +++ b/samples/ComputeSharp.SwapChain.WinUI/ComputeSharp.SwapChain.WinUI.csproj @@ -10,7 +10,6 @@ win10-$(Platform).pubxml true true - $(DefineConstants);SAMPLE_APP diff --git a/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj b/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj index 2694547c..fc340cf9 100644 --- a/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj +++ b/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj @@ -3,7 +3,6 @@ Exe net6.0 x64;ARM64 - $(DefineConstants);SAMPLE_APP $(NoWarn);CA1416;IDE0210 diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index 54d2ab01..e41f96a7 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -28,9 +28,7 @@ partial class IShaderGenerator public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, bool supportsDynamicShaders, int hierarchyDepth) { // Generate the necessary body statements depending on whether dynamic shaders are supported - ImmutableArray bodyStatements = supportsDynamicShaders - ? GenerateRenderMethodBody(hlslSourceInfo, hierarchyDepth) - : GenerateEmptyMethodBody(); + ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo, hierarchyDepth); // This code produces a method declaration as follows: // diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs index 0fa64a96..465269b7 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Linq; using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; @@ -45,16 +44,6 @@ partial class IShaderGenerator return null; } - /// - /// Checks whether dynamic shaders are supported in a given compilation. - /// - /// The instance currently in use. - /// Whether dynamic shaders are supported in the input compilation. - private static bool IsDynamicCompilationSupported(Compilation compilation) - { - return compilation.ReferencedAssemblyNames.Any(static identity => identity.Name is "ComputeSharp.Dynamic"); - } - /// /// Creates a instance wrapping the given method. /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 2594f0a6..20698149 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -25,7 +25,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Check whether or not dynamic shaders are supported IncrementalValueProvider supportsDynamicShaders = context.CompilationProvider - .Select(static (compilation, _) => IsDynamicCompilationSupported(compilation)); + .Select(static (compilation, _) => false); // Discover all shader types and extract all the necessary info from each of them IncrementalValuesProvider shaderInfoWithErrors = @@ -88,7 +88,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator ThreadIdsInfo threadIds = LoadBytecode.GetInfo( diagnostics, typeSymbol, - IsDynamicCompilationSupported(context.SemanticModel.Compilation)); + false); token.ThrowIfCancellationRequested(); diff --git a/tests/ComputeSharp.Dynamic.NuGet/Program.cs b/tests/ComputeSharp.Dynamic.NuGet/Program.cs index 32dccd17..8a1cb76c 100644 --- a/tests/ComputeSharp.Dynamic.NuGet/Program.cs +++ b/tests/ComputeSharp.Dynamic.NuGet/Program.cs @@ -1,13 +1,10 @@ using System.Diagnostics; using System.Linq; -#if NET6_0_OR_GREATER using System.Runtime.Versioning; -#endif using ComputeSharp; +using ComputeSharp.Interop; -#if NET6_0_OR_GREATER [assembly: SupportedOSPlatform("windows6.2")] -#endif float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray(); @@ -26,10 +23,18 @@ for (int i = 0; i < array.Length; i++) Trace.Assert(result[i] == array[i] * 2); } +// Also get the shader info (this requires DXC to be present) +ShaderInfo shaderInfo = ReflectionServices.GetShaderInfo(); + +// Validate a couple properties as a sanity check +Trace.Assert(shaderInfo.HlslSource is { Length: > 0 }); +Trace.Assert(shaderInfo.BoundResourceCount == 2); + /// /// A sample kernel that requires dynamic compilation, as it's not precompiled. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct MultiplyByTwo : IComputeShader { public readonly ReadWriteBuffer buffer; diff --git a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs index 766f597d..847a95c8 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs @@ -11,6 +11,7 @@ namespace ComputeSharp.Tests.Internals; public partial class ShaderDataLoaderTests { [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public partial struct CapturedResourceShader : IComputeShader { public ReadWriteBuffer _; @@ -39,6 +40,7 @@ public partial class ShaderDataLoaderTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public partial struct MultipleResourcesAndPrimitivesShader : IComputeShader { public ReadWriteBuffer _0; @@ -76,6 +78,7 @@ public partial class ShaderDataLoaderTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public partial struct ScalarAndVectorTypesShader : IComputeShader { public ReadWriteBuffer _; @@ -127,6 +130,7 @@ public partial class ShaderDataLoaderTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public partial struct ScalarVectorAndMatrixTypesShader : IComputeShader { public ReadWriteBuffer _; @@ -213,6 +217,7 @@ public partial class ShaderDataLoaderTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public partial struct FlatCustomTypeShader : IComputeShader { public ReadWriteBuffer _0; @@ -305,6 +310,7 @@ public partial class ShaderDataLoaderTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public partial struct NestedCustomTypesShader : IComputeShader { public ReadWriteBuffer _0; @@ -397,6 +403,7 @@ public partial class ShaderDataLoaderTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public partial struct AmbiguousNamesShader : IComputeShader { public ReadWriteBuffer a; diff --git a/tests/ComputeSharp.Tests.NativeLibrariesResolver/DynamicNativeLibrariesResolverTests.cs b/tests/ComputeSharp.Tests.NativeLibrariesResolver/DynamicNativeLibrariesResolverTests.cs index 9f31da5e..539562d0 100644 --- a/tests/ComputeSharp.Tests.NativeLibrariesResolver/DynamicNativeLibrariesResolverTests.cs +++ b/tests/ComputeSharp.Tests.NativeLibrariesResolver/DynamicNativeLibrariesResolverTests.cs @@ -26,7 +26,7 @@ public class DynamicNativeLibrariesResolverTests : NativeLibrariesResolverTestsB } string coreProjectPath = Path.Combine(path, "src", "ComputeSharp.Core", "ComputeSharp.Core.csproj"); - string projectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.csproj"); + string projectPath = Path.Combine(path, "src", "ComputeSharp", "ComputeSharp.csproj"); string dynamicProjectPath = Path.Combine(path, "src", "ComputeSharp.Dynamic", "ComputeSharp.Dynamic.csproj"); Process.Start("dotnet", $"pack {coreProjectPath} -c Release").WaitForExit(); diff --git a/tests/ComputeSharp.Tests.NativeLibrariesResolver/PixNativeLibrariesResolverTests.cs b/tests/ComputeSharp.Tests.NativeLibrariesResolver/PixNativeLibrariesResolverTests.cs index 42d1a734..c44e8061 100644 --- a/tests/ComputeSharp.Tests.NativeLibrariesResolver/PixNativeLibrariesResolverTests.cs +++ b/tests/ComputeSharp.Tests.NativeLibrariesResolver/PixNativeLibrariesResolverTests.cs @@ -26,7 +26,7 @@ public class PixNativeLibrariesResolverTests : NativeLibrariesResolverTestsBase } string coreProjectPath = Path.Combine(path, "src", "ComputeSharp.Core", "ComputeSharp.Core.csproj"); - string projectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.csproj"); + string projectPath = Path.Combine(path, "src", "ComputeSharp", "ComputeSharp.csproj"); string pixProjectPath = Path.Combine(path, "src", "ComputeSharp.Pix", "ComputeSharp.Pix.csproj"); // Run dotnet pack and on the packaging projects, to ensure the local NuGet packages are available diff --git a/tests/ComputeSharp.Tests/BufferTests.cs b/tests/ComputeSharp.Tests/BufferTests.cs index 7de26fd0..6d6c3dcd 100644 --- a/tests/ComputeSharp.Tests/BufferTests.cs +++ b/tests/ComputeSharp.Tests/BufferTests.cs @@ -278,6 +278,7 @@ public partial class BufferTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ConstantBufferKernel : IComputeShader { public readonly ConstantBuffer source; @@ -306,6 +307,7 @@ public partial class BufferTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadOnlyBufferKernel : IComputeShader { public readonly ReadOnlyBuffer source; @@ -334,6 +336,7 @@ public partial class BufferTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteBufferKernel : IComputeShader { public readonly ReadWriteBuffer source; @@ -369,6 +372,7 @@ public partial class BufferTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct DoublePrecisionSupportShader : IComputeShader { public readonly ReadWriteBuffer buffer; diff --git a/tests/ComputeSharp.Tests/ComputeContextTests.cs b/tests/ComputeSharp.Tests/ComputeContextTests.cs index 78ce0ab5..07f12e49 100644 --- a/tests/ComputeSharp.Tests/ComputeContextTests.cs +++ b/tests/ComputeSharp.Tests/ComputeContextTests.cs @@ -1294,6 +1294,7 @@ public partial class ComputeContextTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct OffsetComputeShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -1307,6 +1308,7 @@ public partial class ComputeContextTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct ClearPixelShader : IPixelShader { /// @@ -1317,6 +1319,7 @@ public partial class ComputeContextTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct ColorPixelShader : IPixelShader { public readonly float4 color; @@ -1329,6 +1332,7 @@ public partial class ComputeContextTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct LinearSampling2DPixelShader : IPixelShader { public readonly IReadOnlyTexture2D source; @@ -1341,6 +1345,7 @@ public partial class ComputeContextTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct LinearSampling3DComputeShader : IComputeShader { public readonly IReadOnlyTexture3D source; @@ -1359,6 +1364,7 @@ public partial class ComputeContextTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct LinearSamplingFromNormalized2DPixelShader : IPixelShader { public readonly IReadOnlyNormalizedTexture2D source; @@ -1371,6 +1377,7 @@ public partial class ComputeContextTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct CopyToOutputPixelShader : IPixelShader { public readonly IReadOnlyNormalizedTexture2D source; @@ -1383,6 +1390,7 @@ public partial class ComputeContextTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct InvertPixelShader : IPixelShader { public readonly IReadWriteNormalizedTexture2D source; @@ -1395,6 +1403,7 @@ public partial class ComputeContextTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct LinearSamplingFromNormalized3DComputeShader : IComputeShader { public readonly IReadOnlyNormalizedTexture3D source; @@ -1413,6 +1422,7 @@ public partial class ComputeContextTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct Dotted2DPixelShader : IComputeShader { public readonly IReadWriteNormalizedTexture2D source; @@ -1441,6 +1451,7 @@ public partial class ComputeContextTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct Dotted3DPixelShader : IComputeShader { public readonly IReadWriteNormalizedTexture3D source; @@ -1469,6 +1480,7 @@ public partial class ComputeContextTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct ConvertToNonNormalized2DShader : IComputeShader { public readonly IReadOnlyNormalizedTexture2D source; diff --git a/tests/ComputeSharp.Tests/DispatchTests.cs b/tests/ComputeSharp.Tests/DispatchTests.cs index 7e93e0a4..e551fb06 100644 --- a/tests/ComputeSharp.Tests/DispatchTests.cs +++ b/tests/ComputeSharp.Tests/DispatchTests.cs @@ -57,6 +57,7 @@ public partial class DispatchTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct ThreadIdsShader : IComputeShader { public readonly ReadWriteTexture3D buffer; @@ -111,6 +112,7 @@ public partial class DispatchTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct ThreadIdsNormalizedShader : IComputeShader { public readonly ReadWriteTexture3D buffer; @@ -172,6 +174,7 @@ public partial class DispatchTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct GroupIdsShader : IComputeShader { public readonly ReadWriteTexture3D buffer; @@ -202,6 +205,7 @@ public partial class DispatchTests } [AutoConstructor] + [EmbeddedBytecode(4, 15, 7)] internal readonly partial struct GroupSizeShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -234,6 +238,7 @@ public partial class DispatchTests } [AutoConstructor] + [EmbeddedBytecode(32, 1, 1)] internal readonly partial struct GridIdsShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -265,6 +270,7 @@ public partial class DispatchTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct DispatchSizeShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -304,6 +310,7 @@ public partial class DispatchTests } } + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct DispatchPixelShader : IPixelShader { public float4 Execute() @@ -333,6 +340,7 @@ public partial class DispatchTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct FixedGroupSharedPixelShader : IComputeShader { private readonly ReadWriteBuffer buffer; @@ -376,6 +384,7 @@ public partial class DispatchTests } [AutoConstructor] + [EmbeddedBytecode(32, 1, 1)] internal readonly partial struct DynamicGroupSharedPixelShader : IComputeShader { private readonly ReadWriteBuffer buffer; diff --git a/tests/ComputeSharp.Tests/IPixelShaderTests.cs b/tests/ComputeSharp.Tests/IPixelShaderTests.cs index 0c2c60cc..f81606a4 100644 --- a/tests/ComputeSharp.Tests/IPixelShaderTests.cs +++ b/tests/ComputeSharp.Tests/IPixelShaderTests.cs @@ -35,6 +35,7 @@ public partial class IPixelShaderTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct EarlyReturnShader : IPixelShader { public float4 Execute() diff --git a/tests/ComputeSharp.Tests/InitializationTests.cs b/tests/ComputeSharp.Tests/InitializationTests.cs index 5e3332dc..005502f9 100644 --- a/tests/ComputeSharp.Tests/InitializationTests.cs +++ b/tests/ComputeSharp.Tests/InitializationTests.cs @@ -73,6 +73,7 @@ public partial class InitializationTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct SampleShader : IComputeShader { public readonly ReadWriteBuffer buffer; diff --git a/tests/ComputeSharp.Tests/ResourceDimensionsTests.g.cs b/tests/ComputeSharp.Tests/ResourceDimensionsTests.g.cs index f6d3e5ec..426325ff 100644 --- a/tests/ComputeSharp.Tests/ResourceDimensionsTests.g.cs +++ b/tests/ComputeSharp.Tests/ResourceDimensionsTests.g.cs @@ -1,4 +1,4 @@ -using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -29,6 +29,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadOnlyBuffer_T1_AsReadOnlyBufferShader : IComputeShader { public readonly ReadOnlyBuffer source; @@ -61,6 +62,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteBuffer_T1_AsReadWriteBufferShader : IComputeShader { public readonly ReadWriteBuffer source; @@ -93,6 +95,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadOnlyTexture1D_T1_AsReadOnlyTexture1DShader : IComputeShader { public readonly ReadOnlyTexture1D source; @@ -125,6 +128,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture1D_T1_AsReadWriteTexture1DShader : IComputeShader { public readonly ReadWriteTexture1D source; @@ -161,6 +165,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture1D_T1_AsIReadOnlyTexture1DShader : IComputeShader { public readonly IReadOnlyTexture1D source; @@ -193,6 +198,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadOnlyTexture1D_T2_AsReadOnlyTexture1DShader : IComputeShader { public readonly ReadOnlyTexture1D source; @@ -225,6 +231,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadOnlyTexture1D_T2_AsIReadOnlyNormalizedTexture1DShader : IComputeShader { public readonly IReadOnlyNormalizedTexture1D source; @@ -257,6 +264,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture1D_T2_AsReadWriteTexture1DShader : IComputeShader { public readonly ReadWriteTexture1D source; @@ -289,6 +297,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture1D_T2_AsIReadWriteNormalizedTexture1DShader : IComputeShader { public readonly IReadWriteNormalizedTexture1D source; @@ -321,6 +330,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadOnlyTexture2D_T1_AsReadOnlyTexture2DShader : IComputeShader { public readonly ReadOnlyTexture2D source; @@ -354,6 +364,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture2D_T1_AsReadWriteTexture2DShader : IComputeShader { public readonly ReadWriteTexture2D source; @@ -391,6 +402,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture2D_T1_AsIReadOnlyTexture2DShader : IComputeShader { public readonly IReadOnlyTexture2D source; @@ -424,6 +436,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadOnlyTexture2D_T2_AsReadOnlyTexture2DShader : IComputeShader { public readonly ReadOnlyTexture2D source; @@ -457,6 +470,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadOnlyTexture2D_T2_AsIReadOnlyNormalizedTexture2DShader : IComputeShader { public readonly IReadOnlyNormalizedTexture2D source; @@ -490,6 +504,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture2D_T2_AsReadWriteTexture2DShader : IComputeShader { public readonly ReadWriteTexture2D source; @@ -523,6 +538,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture2D_T2_AsIReadWriteNormalizedTexture2DShader : IComputeShader { public readonly IReadWriteNormalizedTexture2D source; @@ -556,6 +572,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadOnlyTexture3D_T1_AsReadOnlyTexture3DShader : IComputeShader { public readonly ReadOnlyTexture3D source; @@ -590,6 +607,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture3D_T1_AsReadWriteTexture3DShader : IComputeShader { public readonly ReadWriteTexture3D source; @@ -628,6 +646,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture3D_T1_AsIReadOnlyTexture3DShader : IComputeShader { public readonly IReadOnlyTexture3D source; @@ -662,6 +681,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadOnlyTexture3D_T2_AsReadOnlyTexture3DShader : IComputeShader { public readonly ReadOnlyTexture3D source; @@ -696,6 +716,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadOnlyTexture3D_T2_AsIReadOnlyNormalizedTexture3DShader : IComputeShader { public readonly IReadOnlyNormalizedTexture3D source; @@ -730,6 +751,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture3D_T2_AsReadWriteTexture3DShader : IComputeShader { public readonly ReadWriteTexture3D source; @@ -764,6 +786,7 @@ public partial class ResourceDimensionsTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture3D_T2_AsIReadWriteNormalizedTexture3DShader : IComputeShader { public readonly IReadWriteNormalizedTexture3D source; diff --git a/tests/ComputeSharp.Tests/ResourceDimensionsTests.tt b/tests/ComputeSharp.Tests/ResourceDimensionsTests.tt index a315d0d5..b39c5b09 100644 --- a/tests/ComputeSharp.Tests/ResourceDimensionsTests.tt +++ b/tests/ComputeSharp.Tests/ResourceDimensionsTests.tt @@ -1,4 +1,4 @@ -<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ template debug="false" hostspecific="false" language="C#" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text.RegularExpressions" #> @@ -132,6 +132,7 @@ foreach (var pair in typesMap) } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct <#=testMethodName#>Shader : IComputeShader { public readonly <#=shaderResourceType#> source; diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index d17c8344..34ee62e0 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -18,6 +18,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct ReservedKeywordsShader : IComputeShader { public readonly ReadWriteBuffer row_major; @@ -53,6 +54,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct ReservedKeywordsInCustomTypesShader : IComputeShader { public readonly ReadWriteBuffer row_major; @@ -80,6 +82,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct ReservedKeywordsFromHlslTypesAndBuiltInValuesShader : IComputeShader { public readonly ReadWriteBuffer fragmentKeyword; @@ -158,6 +161,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct SpecialTypeAsReturnTypeShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -179,6 +183,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct LocalFunctionInExternalMethodsShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -210,6 +215,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct CapturedNestedStructTypeShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -229,6 +235,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct ExternalStructTypeShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -250,6 +257,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct OutOfOrderMethodsShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -285,6 +293,7 @@ namespace ComputeSharp.Tests Assert.AreEqual(info.BoundResourceCount, 2u); } + [EmbeddedBytecode(DispatchAxis.XY)] public readonly partial struct StatelessPixelShader : IPixelShader { /// @@ -295,6 +304,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct LoopWithVarCounterShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -324,6 +334,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct DoublePrecisionSupportShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -343,6 +354,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct FieldAccessWithThisExpressionShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -369,6 +381,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ComputeShaderWithInheritedShaderInterfaceShader : IMyBaseShader { int IMyBaseShader.A => 42; @@ -402,6 +415,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct PixelShaderWithInheritedShaderInterfaceShader : IMyBaseShader { int IMyBaseShader.A => 42; @@ -450,6 +464,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct StructInstanceMethodsShader : IComputeShader { public readonly MyStructTypeA a; @@ -483,6 +498,7 @@ namespace ComputeSharp.Tests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct PixelShaderWithScopedParameterInMethodsShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -520,6 +536,7 @@ namespace ExternalNamespace public partial class ShaderCompilerTestsInExternalNamespace { [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct UserDefinedTypeShader : IComputeShader { public readonly ReadWriteBuffer buffer; diff --git a/tests/ComputeSharp.Tests/ShaderMembersTests.cs b/tests/ComputeSharp.Tests/ShaderMembersTests.cs index 17708f73..b48a2840 100644 --- a/tests/ComputeSharp.Tests/ShaderMembersTests.cs +++ b/tests/ComputeSharp.Tests/ShaderMembersTests.cs @@ -31,6 +31,7 @@ public partial class ShaderMembersTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct StaticConstantsShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -70,6 +71,7 @@ public partial class ShaderMembersTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct GlobalVariableShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -104,6 +106,7 @@ public partial class ShaderMembersTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct BoolInstanceFieldsShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -167,6 +170,7 @@ public partial class ShaderMembersTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct BoolInstanceFieldInCustomStructShader : IComputeShader { public readonly ReadWriteBuffer buffer; diff --git a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs index 1037d14e..034bfaf8 100644 --- a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs +++ b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs @@ -52,6 +52,7 @@ public partial class ShaderRewriterTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct NanAndInfiniteShader : IComputeShader { public readonly ReadWriteBuffer buffer1; @@ -112,6 +113,7 @@ public partial class ShaderRewriterTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ModAndComparisonOperatorsShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -173,6 +175,7 @@ public partial class ShaderRewriterTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct BitwiseOperatorsShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -225,6 +228,7 @@ public partial class ShaderRewriterTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct BooleanOperatorsShader : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -274,6 +278,7 @@ public partial class ShaderRewriterTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ToBooleanConversionIntrinsicsShader : IComputeShader { public readonly ReadOnlyBuffer buffer1; @@ -357,6 +362,7 @@ public partial class ShaderRewriterTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct FromBooleanConversionIntrinsicsShader : IComputeShader { public readonly ReadOnlyBuffer source; @@ -439,6 +445,7 @@ public partial class ShaderRewriterTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ConstantsInShaderConstantFieldsShader : IComputeShader { public const float rot_angle = (float)(137.2 / 180.0 * Math.PI); @@ -516,6 +523,7 @@ public partial class ShaderRewriterTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct DoubleConstantsInShaderConstantFieldsShader : IComputeShader { public const float DoubleToFloatConstant = (float)(1 / 255.0); @@ -622,6 +630,7 @@ public partial class ShaderRewriterTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct GlslStyleMulOperatorsShader : IComputeShader { public readonly ReadOnlyBuffer source1; @@ -762,6 +771,7 @@ public partial class ShaderRewriterTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct CustomStructTypeShader : IComputeShader { public readonly ReadWriteBuffer source; @@ -799,6 +809,7 @@ public partial class ShaderRewriterTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct MiscHlslIntrinsicsShader : IComputeShader { public readonly ReadWriteBuffer buffer1; @@ -841,6 +852,7 @@ public partial class ShaderRewriterTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadonlyModifierInMethodsShader : IComputeShader { private readonly ReadWriteBuffer buffer; diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/ColorfulInfinity.cs b/tests/ComputeSharp.Tests/Shaders/Compute/ColorfulInfinity.cs index 74e2c88d..07a6b4f5 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/ColorfulInfinity.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/ColorfulInfinity.cs @@ -9,6 +9,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct ColorfulInfinity : IComputeShader { /// diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/ContouredLayers.cs b/tests/ComputeSharp.Tests/Shaders/Compute/ContouredLayers.cs index b47e909d..267b42c7 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/ContouredLayers.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/ContouredLayers.cs @@ -8,6 +8,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// Created by Shane. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct ContouredLayers : IComputeShader { /// diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/ExtrudedTruchetPattern.cs b/tests/ComputeSharp.Tests/Shaders/Compute/ExtrudedTruchetPattern.cs index 7ef2f2b5..d6fc5a22 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/ExtrudedTruchetPattern.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/ExtrudedTruchetPattern.cs @@ -8,6 +8,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// Created by Shane. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct ExtrudedTruchetPattern : IComputeShader { /// diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/FourColorGradient.cs b/tests/ComputeSharp.Tests/Shaders/Compute/FourColorGradient.cs index 4a88ee95..781c3977 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/FourColorGradient.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/FourColorGradient.cs @@ -9,6 +9,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct FourColorGradient : IComputeShader { /// diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/FractalTiling.cs b/tests/ComputeSharp.Tests/Shaders/Compute/FractalTiling.cs index a1a79924..63b95527 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/FractalTiling.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/FractalTiling.cs @@ -9,6 +9,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct FractalTiling : IComputeShader { /// diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/HelloWorld.cs b/tests/ComputeSharp.Tests/Shaders/Compute/HelloWorld.cs index bd58fde3..5b0a6bad 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/HelloWorld.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/HelloWorld.cs @@ -7,6 +7,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// Ported from . /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct HelloWorld : IPixelShader { /// diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/MengerJourney.cs b/tests/ComputeSharp.Tests/Shaders/Compute/MengerJourney.cs index 13d6cc1b..eddb7030 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/MengerJourney.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/MengerJourney.cs @@ -8,6 +8,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// Created by Syntopia. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct MengerJourney : IComputeShader { /// diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/Octagrams.cs b/tests/ComputeSharp.Tests/Shaders/Compute/Octagrams.cs index 5c4b9141..6d82537d 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/Octagrams.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/Octagrams.cs @@ -8,6 +8,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// Created by whisky_shusuky. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct Octagrams : IComputeShader { /// diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/ProteanClouds.cs b/tests/ComputeSharp.Tests/Shaders/Compute/ProteanClouds.cs index 81091c26..837d8c33 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/ProteanClouds.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/ProteanClouds.cs @@ -9,6 +9,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct ProteanClouds : IComputeShader { /// diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/PyramidPattern.cs b/tests/ComputeSharp.Tests/Shaders/Compute/PyramidPattern.cs index 97b689a7..dd78a284 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/PyramidPattern.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/PyramidPattern.cs @@ -9,6 +9,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// Created by Shane. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct PyramidPattern : IComputeShader { /// diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/TerracedHills.cs b/tests/ComputeSharp.Tests/Shaders/Compute/TerracedHills.cs index 50bb13bd..4b70114c 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/TerracedHills.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/TerracedHills.cs @@ -6,6 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// Created by Shane. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct TerracedHills : IComputeShader { /// diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs b/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs index 74f9d9a8..64df5c0f 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs @@ -8,6 +8,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// Created by Shane. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct TriangleGridContouring : IComputeShader { /// diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/TwoTiledTruchet.cs b/tests/ComputeSharp.Tests/Shaders/Compute/TwoTiledTruchet.cs index 142da84e..ae6ee711 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/TwoTiledTruchet.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/TwoTiledTruchet.cs @@ -8,6 +8,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute; /// Created by Shane. /// [AutoConstructor] +[EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct TwoTiledTruchet : IComputeShader { /// diff --git a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.cs index 522f8af8..014dec14 100644 --- a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.cs @@ -89,6 +89,7 @@ partial class Texture1DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] public readonly partial struct SamplingComputeShader : IComputeShader { public readonly IReadOnlyNormalizedTexture1D source; diff --git a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.g.cs b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.g.cs index a2971a09..4a791f90 100644 --- a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.g.cs +++ b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.g.cs @@ -1,4 +1,4 @@ -using System; +using System; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; @@ -69,6 +69,7 @@ partial class Texture1DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct Shader_Unorm_Bgra32_Float4 : IComputeShader { public readonly ReadOnlyTexture1D source; @@ -81,6 +82,7 @@ partial class Texture1DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct Shader_Unorm_R16_float : IComputeShader { public readonly ReadOnlyTexture1D source; @@ -93,6 +95,7 @@ partial class Texture1DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct Shader_Unorm_R8_float : IComputeShader { public readonly ReadOnlyTexture1D source; @@ -105,6 +108,7 @@ partial class Texture1DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct Shader_Unorm_Rg16_Float2 : IComputeShader { public readonly ReadOnlyTexture1D source; @@ -117,6 +121,7 @@ partial class Texture1DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct Shader_Unorm_Rg32_Float2 : IComputeShader { public readonly ReadOnlyTexture1D source; @@ -129,6 +134,7 @@ partial class Texture1DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct Shader_Unorm_Rgba32_Float4 : IComputeShader { public readonly ReadOnlyTexture1D source; @@ -141,6 +147,7 @@ partial class Texture1DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct Shader_Unorm_Rgba64_Float4 : IComputeShader { public readonly ReadOnlyTexture1D source; diff --git a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.tt b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.tt index 29e2195d..10c63aeb 100644 --- a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.tt +++ b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.tt @@ -1,4 +1,4 @@ -<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ template debug="false" hostspecific="false" language="C#" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> @@ -65,6 +65,7 @@ foreach (var (t, tPixel) in EnumerateTypes()) #> [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct Shader_Unorm_<#=t#>_<#=tPixel#> : IComputeShader { public readonly ReadOnlyTexture1D<<#=t#>, <#=tPixel#>> source; diff --git a/tests/ComputeSharp.Tests/Texture1DTests.cs b/tests/ComputeSharp.Tests/Texture1DTests.cs index 21468a7c..ef323c0b 100644 --- a/tests/ComputeSharp.Tests/Texture1DTests.cs +++ b/tests/ComputeSharp.Tests/Texture1DTests.cs @@ -363,6 +363,7 @@ public partial class Texture1DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadOnlyTexture1DKernel : IComputeShader { public readonly ReadOnlyTexture1D source; @@ -393,6 +394,7 @@ public partial class Texture1DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] internal readonly partial struct ReadWriteTexture1DKernel : IComputeShader { public readonly ReadWriteTexture1D source; diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs index 5fe9fec1..f204cb24 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs @@ -72,6 +72,7 @@ partial class Texture2DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] public readonly partial struct SamplingComputeShader : IComputeShader { public readonly IReadOnlyNormalizedTexture2D source; @@ -105,6 +106,7 @@ partial class Texture2DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] public readonly partial struct SamplingPixelShader : IPixelShader { public readonly IReadOnlyNormalizedTexture2D texture; diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs index b0815b9f..51fd801e 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs @@ -1,4 +1,4 @@ -using System; +using System; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; @@ -69,6 +69,7 @@ partial class Texture2DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct Shader_Unorm_Bgra32_Float4 : IComputeShader { public readonly ReadOnlyTexture2D source; @@ -81,6 +82,7 @@ partial class Texture2DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct Shader_Unorm_R16_float : IComputeShader { public readonly ReadOnlyTexture2D source; @@ -93,6 +95,7 @@ partial class Texture2DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct Shader_Unorm_R8_float : IComputeShader { public readonly ReadOnlyTexture2D source; @@ -105,6 +108,7 @@ partial class Texture2DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct Shader_Unorm_Rg16_Float2 : IComputeShader { public readonly ReadOnlyTexture2D source; @@ -117,6 +121,7 @@ partial class Texture2DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct Shader_Unorm_Rg32_Float2 : IComputeShader { public readonly ReadOnlyTexture2D source; @@ -129,6 +134,7 @@ partial class Texture2DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct Shader_Unorm_Rgba32_Float4 : IComputeShader { public readonly ReadOnlyTexture2D source; @@ -141,6 +147,7 @@ partial class Texture2DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct Shader_Unorm_Rgba64_Float4 : IComputeShader { public readonly ReadOnlyTexture2D source; diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt index da622b25..f5577e31 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt @@ -1,4 +1,4 @@ -<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ template debug="false" hostspecific="false" language="C#" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> @@ -65,6 +65,7 @@ foreach (var (t, tPixel) in EnumerateTypes()) #> [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct Shader_Unorm_<#=t#>_<#=tPixel#> : IComputeShader { public readonly ReadOnlyTexture2D<<#=t#>, <#=tPixel#>> source; diff --git a/tests/ComputeSharp.Tests/Texture2DTests.cs b/tests/ComputeSharp.Tests/Texture2DTests.cs index a9dec703..5cf79486 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.cs @@ -428,6 +428,7 @@ public partial class Texture2DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct ReadOnlyTexture2DKernel : IComputeShader { public readonly ReadOnlyTexture2D source; @@ -458,6 +459,7 @@ public partial class Texture2DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] internal readonly partial struct ReadWriteTexture2DKernel : IComputeShader { public readonly ReadWriteTexture2D source; diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs index 5f3c08b7..f2601e67 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs @@ -1,4 +1,4 @@ -using System; +using System; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; @@ -69,6 +69,7 @@ partial class Texture3DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct Shader_Unorm_Bgra32_Float4 : IComputeShader { public readonly ReadOnlyTexture3D source; @@ -81,6 +82,7 @@ partial class Texture3DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct Shader_Unorm_R16_float : IComputeShader { public readonly ReadOnlyTexture3D source; @@ -93,6 +95,7 @@ partial class Texture3DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct Shader_Unorm_R8_float : IComputeShader { public readonly ReadOnlyTexture3D source; @@ -105,6 +108,7 @@ partial class Texture3DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct Shader_Unorm_Rg16_Float2 : IComputeShader { public readonly ReadOnlyTexture3D source; @@ -117,6 +121,7 @@ partial class Texture3DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct Shader_Unorm_Rg32_Float2 : IComputeShader { public readonly ReadOnlyTexture3D source; @@ -129,6 +134,7 @@ partial class Texture3DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct Shader_Unorm_Rgba32_Float4 : IComputeShader { public readonly ReadOnlyTexture3D source; @@ -141,6 +147,7 @@ partial class Texture3DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct Shader_Unorm_Rgba64_Float4 : IComputeShader { public readonly ReadOnlyTexture3D source; diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt index 003696f7..f18c826b 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt @@ -1,4 +1,4 @@ -<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ template debug="false" hostspecific="false" language="C#" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> @@ -65,6 +65,7 @@ foreach (var (t, tPixel) in EnumerateTypes()) #> [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct Shader_Unorm_<#=t#>_<#=tPixel#> : IComputeShader { public readonly ReadOnlyTexture3D<<#=t#>, <#=tPixel#>> source; diff --git a/tests/ComputeSharp.Tests/Texture3DTests.cs b/tests/ComputeSharp.Tests/Texture3DTests.cs index 62c4f4e7..faa111a4 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.cs +++ b/tests/ComputeSharp.Tests/Texture3DTests.cs @@ -533,6 +533,7 @@ public partial class Texture3DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct ReadOnlyTexture3DKernel : IComputeShader { public readonly ReadOnlyTexture3D source; @@ -563,6 +564,7 @@ public partial class Texture3DTests } [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct ReadWriteTexture3DKernel : IComputeShader { public readonly ReadWriteTexture3D source; From 2e020a1524cdb215b6905648f0a068eedafd2faa Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 13 Oct 2023 11:22:11 +0200 Subject: [PATCH 3/6] Remove checks for dynamic shader in source generator --- .../Translation/__Internals/ShaderCompiler.cs | 38 --------- ...ator.CreateBuildHlslSourceMethod.Syntax.cs | 3 +- ...nerator.CreateLoadBytecodeMethod.Syntax.cs | 84 ++----------------- .../IShaderGenerator.cs | 27 +++--- .../Interfaces/__Internals/IBytecodeLoader.cs | 8 -- .../Dispatching/ShaderBytecodeLoader.cs | 14 +--- 6 files changed, 19 insertions(+), 155 deletions(-) delete mode 100644 src/ComputeSharp.Dynamic/Shaders/Translation/__Internals/ShaderCompiler.cs diff --git a/src/ComputeSharp.Dynamic/Shaders/Translation/__Internals/ShaderCompiler.cs b/src/ComputeSharp.Dynamic/Shaders/Translation/__Internals/ShaderCompiler.cs deleted file mode 100644 index 709314f8..00000000 --- a/src/ComputeSharp.Dynamic/Shaders/Translation/__Internals/ShaderCompiler.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.ComponentModel; -using System.Runtime.CompilerServices; -using TerraFX.Interop.DirectX; -using TerraFX.Interop.Windows; - -namespace ComputeSharp.__Internals; - -/// -/// A that uses the DXC APIs to compile compute shaders. -/// -[EditorBrowsable(EditorBrowsableState.Never)] -[Obsolete("This type is not intended to be used directly by user code")] -public static class ShaderCompiler -{ - /// - /// Compiles a new HLSL shader from the input source code. - /// - /// The type of bytecode loader being used. - /// The type of shader being dispatched. - /// The instance to use to load the bytecode. - /// The number of threads in each thread group for the X axis. - /// The number of threads in each thread group for the Y axis. - /// The number of threads in each thread group for the Z axis. - /// The input instance representing the compute shader to run. - public static unsafe void LoadDynamicBytecode(ref TLoader loader, int threadsX, int threadsY, int threadsZ, in T shader) - where TLoader : struct, IBytecodeLoader - where T : struct, IShader - { - Unsafe.AsRef(in shader).BuildHlslSource(out ArrayPoolStringBuilder builder, threadsX, threadsY, threadsZ); - - using ComPtr dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(builder.WrittenSpan); - - builder.Dispose(); - - loader.LoadDynamicBytecode((IntPtr)dxcBlobBytecode.Get()); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index e41f96a7..610a3f83 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -22,10 +22,9 @@ partial class IShaderGenerator /// Creates a instance for the BuildHlslSource method. /// /// The input instance to use. - /// Indicates whether or not dynamic shaders are supported. /// The depth of the hierarchy for this type (used to calculate the right indentation). /// The resulting instance for the BuildHlslSource method. - public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, bool supportsDynamicShaders, int hierarchyDepth) + public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth) { // Generate the necessary body statements depending on whether dynamic shaders are supported ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo, hierarchyDepth); diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 81b8bd06..9538ffb4 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -23,12 +23,11 @@ partial class IShaderGenerator /// Creates a instance for the TryGetBytecode method. /// /// The input instance. - /// Indicates whether or not dynamic shaders are supported. /// An opaque instance to transform the final tree into text. /// The resulting instance for the BuildHlslSource method. - public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, bool supportsDynamicShaders, out Func fixup) + public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup) { - BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, supportsDynamicShaders, out string? bytecodeLiterals); + BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals); if (bytecodeLiterals is not null) { @@ -66,25 +65,16 @@ partial class IShaderGenerator /// Gets a instance with the logic to try to get a compiled shader bytecode. /// /// The input instance. - /// Indicates whether or not dynamic shaders are supported. /// The resulting bytecode literals to insert into the final source code. /// The instance trying to retrieve the precompiled shader. - private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, bool supportsDynamicShaders, out string? bytecodeLiterals) + private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals) { if (bytecodeInfo.Bytecode.IsEmpty) { bytecodeLiterals = null; - if (supportsDynamicShaders) - { - // Return the dynamic compilation path - return Block(GetDynamicCompilationStatement()); - } - else - { - // Faulting path - return Block(GetDynamicCompilationFaultingBlock()); - } + // Faulting path + return Block(); } bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan()); @@ -142,70 +132,8 @@ partial class IShaderGenerator IdentifierName("LoadEmbeddedBytecode"))) .AddArgumentListArguments(Argument(IdentifierName("bytecode")))))); - // If dynamic shaders are supported, return the combined block - if (supportsDynamicShaders) - { - return Block(embeddedBranch.WithElse(ElseClause(Block(GetDynamicCompilationStatement())))); - } - // If there is no dynamic shader support, add the faulting path after the branch - return Block(embeddedBranch.WithElse(ElseClause(Block(GetDynamicCompilationFaultingBlock())))); - } - - /// - /// The cached tree of dynamic statements. - /// - private static StatementSyntax? dynamicStatement; - - /// - /// Returns the instance to create a new dynamic shader. - /// - /// The instance to create a new dynamic shader. - private static StatementSyntax GetDynamicCompilationStatement() - { - // This code produces a method declaration as follows: - // - // ComputeSharp.__Internals.ShaderCompiler.LoadDynamicBytecode(ref loader, threadsX, threadsY, threadsZ, in this); - return dynamicStatement ??= - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("ComputeSharp.__Internals.ShaderCompiler"), - IdentifierName("LoadDynamicBytecode"))) - .AddArgumentListArguments( - Argument(IdentifierName("loader")).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)), - Argument(IdentifierName("threadsX")), - Argument(IdentifierName("threadsY")), - Argument(IdentifierName("threadsZ")), - Argument(ThisExpression()).WithRefKindKeyword(Token(SyntaxKind.InKeyword)))); - } - - /// - /// The cached tree of dynamic fault statement. - /// - private static ExpressionStatementSyntax? dynamicFaultStatement; - - /// - /// Returns a instances to perform a faulting call to LoadDynamicBytecode(IntPtr). - /// - /// A instances to perform a faulting call to LoadDynamicBytecode(IntPtr). - private static ExpressionStatementSyntax GetDynamicCompilationFaultingBlock() - { - // This code produces a faulting call as follows: - // - // loader.LoadDynamicBytecode(default); - return dynamicFaultStatement ??= - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadDynamicBytecode"))) - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.DefaultLiteralExpression, - Token(SyntaxKind.DefaultKeyword))))); + return Block(embeddedBranch.WithElse(ElseClause(Block()))); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 20698149..29d98041 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -22,11 +22,6 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator /// public void Initialize(IncrementalGeneratorInitializationContext context) { - // Check whether or not dynamic shaders are supported - IncrementalValueProvider supportsDynamicShaders = - context.CompilationProvider - .Select(static (compilation, _) => false); - // Discover all shader types and extract all the necessary info from each of them IncrementalValuesProvider shaderInfoWithErrors = context.SyntaxProvider @@ -130,18 +125,17 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator }); // Get the BuildHlslSource info (hierarchy, HLSL source and parsing options) - IncrementalValuesProvider<((HierarchyInfo Hierarchy, HlslShaderSourceInfo HlslShaderSource) Left, bool SupportsDynamicShaders)> hlslSourceInfo = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo HlslShaderSource)> hlslSourceInfo = shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource)) - .Combine(supportsDynamicShaders); + .Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource)); // Generate the BuildHlslSource() methods context.RegisterSourceOutput(hlslSourceInfo, static (context, item) => { - MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Left.HlslShaderSource, item.SupportsDynamicShaders, item.Left.Hierarchy.Hierarchy.Length); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, addSkipLocalsInitAttribute: true); + MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.HlslShaderSource, item.Hierarchy.Hierarchy.Length); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, buildHlslStringMethod, addSkipLocalsInitAttribute: true); - context.AddSource($"{item.Left.Hierarchy.FullyQualifiedMetadataName}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); // Get the LoadDispatchMetadata() info (hierarchy and dispatch metadata info) @@ -198,19 +192,18 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator context.ReportDiagnostics(embeddedBytecodeDiagnostics); // Get the TryGetBytecode() info (hierarchy and compiled bytecode) - IncrementalValuesProvider<((HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode) Info, bool SupportsDynamicShaders)> embeddedBytecodeInfo = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode)> embeddedBytecodeInfo = embeddedBytecodeWithErrors - .Select(static (item, token) => (item.Hierarchy, item.EmbeddedBytecode)) - .Combine(supportsDynamicShaders); + .Select(static (item, token) => (item.Hierarchy, item.EmbeddedBytecode)); // Generate the TryGetBytecode() methods context.RegisterSourceOutput(embeddedBytecodeInfo, static (context, item) => { - MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.Info.EmbeddedBytecode, item.SupportsDynamicShaders, out Func fixup); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, tryGetBytecodeMethod, addSkipLocalsInitAttribute: false); + MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.EmbeddedBytecode, out Func fixup); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, tryGetBytecodeMethod, addSkipLocalsInitAttribute: false); SourceText text = fixup(compilationUnit); - context.AddSource($"{item.Info.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", text); + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", text); }); } } \ No newline at end of file diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs index e3dbc4b3..7521536c 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs @@ -10,14 +10,6 @@ namespace ComputeSharp.__Internals; [Obsolete("This interface is not intended to be used directly by user code")] public interface IBytecodeLoader { - /// - /// Loads a dynamic shader bytecode. - /// - /// An opaque handle to the shader bytecode. - /// Thrown if the shader has already been initialized. - /// Thrown if is (indicating an unsupported configuration). - void LoadDynamicBytecode(IntPtr handle); - /// /// Loads the embedded shader bytecode for the shader being dispatched. /// diff --git a/src/ComputeSharp/Shaders/Dispatching/ShaderBytecodeLoader.cs b/src/ComputeSharp/Shaders/Dispatching/ShaderBytecodeLoader.cs index 345473de..c9a60a5b 100644 --- a/src/ComputeSharp/Shaders/Dispatching/ShaderBytecodeLoader.cs +++ b/src/ComputeSharp/Shaders/Dispatching/ShaderBytecodeLoader.cs @@ -2,7 +2,6 @@ using System; using System.Runtime.CompilerServices; using ComputeSharp.__Internals; using ComputeSharp.Shaders.Models; -using TerraFX.Interop.DirectX; #pragma warning disable CS0618 @@ -22,24 +21,15 @@ internal struct ShaderBytecodeLoader : IBytecodeLoader /// Gets the current cached shader instance. /// /// The current instance. - /// Thrown if the shader has not been initialized. + /// Thrown if the HLSL bytecode is not available. [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly ICachedShader GetCachedShader() { - default(InvalidOperationException).ThrowIf(this.cachedShader is null); + default(NotSupportedException).ThrowIf(this.cachedShader is null); return this.cachedShader; } - /// - public unsafe void LoadDynamicBytecode(IntPtr handle) - { - default(InvalidOperationException).ThrowIf(this.cachedShader is not null); - default(NotSupportedException).ThrowIf(handle == IntPtr.Zero); - - this.cachedShader = new ICachedShader.Dynamic((IDxcBlob*)handle); - } - /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public void LoadEmbeddedBytecode(ReadOnlySpan bytecode) From 249c708466f4ba3b55d778640c2419aca53f6dd5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 13 Oct 2023 11:27:31 +0200 Subject: [PATCH 4/6] Remove [ShaderMethod] support and infrastructure --- .../Extensions/MethodInfoExtensions.cs | 39 ---- .../Attributes/ShaderMethodAttribute.cs | 21 -- ...derMethodSourceAttribute.HlslGeneration.cs | 93 --------- .../ShaderMethodSourceAttribute.cs | 113 ----------- .../ComputeSharp.SourceGenerators.csproj | 3 - .../Helpers/SyntaxFactoryHelper.cs | 41 ---- ...erGenerator.CreateBuildHlslSourceMethod.cs | 4 +- .../Models/HlslMethodSourceInfo.cs | 18 -- .../Models/ShaderMethodInfo.cs | 11 - .../ShaderMethodSourceGenerator.cs | 190 ------------------ 10 files changed, 2 insertions(+), 531 deletions(-) delete mode 100644 src/ComputeSharp.Dynamic/Attributes/Extensions/MethodInfoExtensions.cs delete mode 100644 src/ComputeSharp.Dynamic/Attributes/ShaderMethodAttribute.cs delete mode 100644 src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs delete mode 100644 src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.cs delete mode 100644 src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs delete mode 100644 src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs delete mode 100644 src/ComputeSharp.SourceGenerators/Models/ShaderMethodInfo.cs delete mode 100644 src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs diff --git a/src/ComputeSharp.Dynamic/Attributes/Extensions/MethodInfoExtensions.cs b/src/ComputeSharp.Dynamic/Attributes/Extensions/MethodInfoExtensions.cs deleted file mode 100644 index 17279abd..00000000 --- a/src/ComputeSharp.Dynamic/Attributes/Extensions/MethodInfoExtensions.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Linq; -using System.Reflection; -using System.Text.RegularExpressions; - -namespace ComputeSharp.Extensions; - -/// -/// A that provides extension methods for the type. -/// -internal static class MethodInfoExtensions -{ - /// - /// Gets a fully qualified name for the input method, including parameters. - /// - /// The input instance. - /// A fully qualified name for , including parameters. - public static string GetFullyQualifiedName(this MethodInfo method) - { - string parameters = string.Join(", ", method.GetParameters().Select(static p => p.ParameterType.FullName)); - - // Fixup the method name for static local functions in global statements. This only needs to - // be done when the method is in a type with fully qualified name "Program", as that's the only - // case where it might happen. If the declaring type has a name, it can't be that for sure. - (string declaringType, string methodName) = (method.DeclaringType!.FullName!, method.Name) switch - { - ("Program", var name) => ("Program", Regex.Replace(name, @"<
\$>g__(\w+)\|\d+_\d+", static m => m.Groups[1].Value)), - (var type, var name) => (type, name) - }; - - if (method.IsGenericMethod) - { - string arguments = string.Join(", ", method.GetGenericArguments().Select(static t => t.FullName)); - - return $"{declaringType}.{methodName}<{arguments}>({parameters})"; - } - - return $"{declaringType}.{methodName}({parameters})"; - } -} \ No newline at end of file diff --git a/src/ComputeSharp.Dynamic/Attributes/ShaderMethodAttribute.cs b/src/ComputeSharp.Dynamic/Attributes/ShaderMethodAttribute.cs deleted file mode 100644 index 84a5afbd..00000000 --- a/src/ComputeSharp.Dynamic/Attributes/ShaderMethodAttribute.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.ComponentModel; - -namespace ComputeSharp; - -/// -/// An attribute that indicates that a method will be indirectly used in a compute shader. -/// This method is necessary for methods that are captured and used within a given shader -/// through a field (of some custom type). In order to be processed -/// correctly, wrapped methods need to have this attribute manually applied to them. -/// Methods also need to be static, though this can only be tested at runtime. -/// -[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] -[EditorBrowsable(EditorBrowsableState.Never)] -[Obsolete( - "This API (and shader metaprogramming in general) is being removed in a future version of ComputeSharp. " + - "If you're relying on this functionality, consider manually implementing different shader variants. " + - "It is possible to still reuse code by moving it to helper methods that are used by multiple shaders.")] -public sealed class ShaderMethodAttribute : Attribute -{ -} \ No newline at end of file diff --git a/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs b/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs deleted file mode 100644 index 2bc68b06..00000000 --- a/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace ComputeSharp.__Internals; - -/// -partial class ShaderMethodSourceAttribute : Attribute -{ - /// - /// Appends the mapped source code for the current method. - /// - /// The target instance to write to. - /// The mapping of already discovered constant names. - public void AppendConstants(ref ArrayPoolStringBuilder builder, HashSet mapping) - { - foreach (KeyValuePair constant in this.constants) - { - if (mapping.Add(constant.Key)) - { - builder.Append('\n'); - builder.Append("#define "); - builder.Append(constant.Key); - builder.Append(' '); - builder.Append(constant.Value); - builder.Append('\n'); - } - } - } - - /// - /// Appends the discovered types for the current method. - /// - /// The target instance to write to. - /// The mapping of already discovered type names. - public void AppendTypes(ref ArrayPoolStringBuilder builder, HashSet mapping) - { - foreach (KeyValuePair type in this.types) - { - if (mapping.Add(type.Key)) - { - builder.Append('\n'); - builder.Append(type.Value); - builder.Append('\n'); - } - } - } - - /// - /// Appends the discovered forward declarations for the current method. - /// - /// The target instance to write to. - /// The mapping of already discovered type names. - public void AppendForwardDeclarations(ref ArrayPoolStringBuilder builder, HashSet mapping) - { - foreach (KeyValuePair method in this.methods) - { - if (mapping.Add(method.Key)) - { - builder.Append('\n'); - builder.Append(method.Key); - builder.Append('\n'); - } - } - } - - /// - /// Appends the discovered methods for the current method. - /// - /// The target instance to write to. - /// The mapping of already discovered type names. - public void AppendMethods(ref ArrayPoolStringBuilder builder, HashSet mapping) - { - foreach (KeyValuePair method in this.methods) - { - if (mapping.Remove(method.Key)) - { - builder.Append('\n'); - builder.Append(method.Value); - builder.Append('\n'); - } - } - } - - /// - /// Appends the mapped source code for the current method. - /// - /// The target instance to write to. - /// The name to bind the method to. - public void AppendMappedInvokeMethod(ref ArrayPoolStringBuilder builder, string name) - { - builder.Append(this.invokeMethod.Replace(InvokeMethodIdentifier, name)); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.cs deleted file mode 100644 index 74c0b631..00000000 --- a/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Reflection; -using ComputeSharp.Extensions; - -#pragma warning disable IDE0052 - -namespace ComputeSharp.__Internals; - -/// -/// An attribute that contains info on a processed shader method that can be executed within a shader. -/// Instances of this attribute are generated from method annotated with . -/// -/// This attribute is not meant to be directly used by applications using ComputeSharp. -[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] -[EditorBrowsable(EditorBrowsableState.Never)] -[Obsolete("This attribute is not intended to be used directly by user code")] -public sealed partial class ShaderMethodSourceAttribute : Attribute -{ - /// - /// The identifier for the invoke method, for late binding. - /// - internal const string InvokeMethodIdentifier = "____"; - - /// - /// The fully qualified name of the current method. - /// - private readonly string methodName; - - /// - /// The source code for the target entry point method. - /// - private readonly string invokeMethod; - - /// - /// The collection of custom types. - /// - private readonly Dictionary types; - - /// - /// The collection of processed methods. - /// - private readonly Dictionary methods; - - /// - /// The collection of discovered constants. - /// - private readonly Dictionary constants; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The fully qualified name of the current method. - /// The source code for the target entry point method. - /// The collection of custom types. - /// The collection of processed methods. - /// The collection of discovered constants. - public ShaderMethodSourceAttribute(string methodName, string invokeMethod, object[] types, object[] methods, object[] constants) - { - this.methodName = methodName; - this.invokeMethod = invokeMethod; - this.types = types.Cast().ToDictionary(static c => c[0], static c => c[1]); - this.methods = methods.Cast().ToDictionary(static c => c[0], static c => c[1]); - this.constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); - } - - /// - /// Gets the associated instance for a specified delegate. - /// - /// The input instance to get info for. - /// The name of the shader field containing . - /// The associated instance for the given delegate. - public static ShaderMethodSourceAttribute GetForDelegate(Delegate function, string name) - { - if (!function.Method.IsStatic) - { - return ThrowArgumentExceptionForNonStaticMethod(name); - } - - IEnumerable attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes(); - string methodName = function.Method.GetFullyQualifiedName(); - - foreach (ShaderMethodSourceAttribute attribute in attributes) - { - if (attribute.methodName.Equals(methodName)) - { - return attribute; - } - } - - return ThrowArgumentExceptionForMissingShaderMethodAttribute(name); - } - - /// - /// Throws an when a given is not static. - /// - /// The name of the shader field containing the invalid method. - private static ShaderMethodSourceAttribute ThrowArgumentExceptionForNonStaticMethod(string name) - { - throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a non static method (only static methods are supported for captured delegates).", name); - } - - /// - /// Throws an when a given doesn't have applied to it. - /// - /// The name of the shader field containing the invalid method. - private static ShaderMethodSourceAttribute ThrowArgumentExceptionForMissingShaderMethodAttribute(string name) - { - throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a method without the [ShaderMethod] attribute applied to it.", name); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 4e026855..ae2b90c9 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -57,9 +57,6 @@ - - - diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs deleted file mode 100644 index 166c6579..00000000 --- a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -namespace ComputeSharp.SourceGenerators.Helpers; - -/// -/// A class containing additional factory methods for constructing syntax nodes, tokens and trivia. -/// -internal static class SyntaxFactoryHelper -{ - /// - /// Creates an [] array expression with the nested groups in the input sequence. - /// - /// That it, it applies the following transformation: - /// - /// { ("K1", "V1"), ("K2", "V2") } => new object[] { new string[] { "K1", "V1" }, new string[] { "K2", "V2" } } - /// - /// - /// - /// The input sequence of groups. - /// An instance with the described contents. - public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B)> groups) - { - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(groups.Select(static group => - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)), - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B))))).ToArray())); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index 6d888905..adffa7b0 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -421,7 +421,7 @@ partial class IShaderGenerator /// /// The collection of discovered constant definitions. /// A sequence of discovered constants to declare in the shader. - internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) + private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) { using ImmutableArrayBuilder<(string, string)> builder = new(); @@ -444,7 +444,7 @@ partial class IShaderGenerator /// The sequence of discovered custom types. /// The collection of discovered instance methods for custom struct types. /// A sequence of custom type definitions to add to the shader source. - internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( + private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( ImmutableArrayBuilder diagnostics, ISymbol sourceSymbol, IEnumerable types, diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs deleted file mode 100644 index 78b83804..00000000 --- a/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs +++ /dev/null @@ -1,18 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.SourceGenerators.Models; - -/// -/// A model for extracted info on a processed HLSL method. -/// -/// The metadata name for the method. -/// The meethod entry point. -/// The discovered declared types. -/// The discovered defined constants. -/// The dependent captured methods. -internal sealed record HlslMethodSourceInfo( - string MetadataName, - string EntryPoint, - EquatableArray<(string Name, string Definition)> DefinedTypes, - EquatableArray<(string Name, string Value)> DefinedConstants, - EquatableArray<(string Signature, string Definition)> DependentMethods); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderMethodInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderMethodInfo.cs deleted file mode 100644 index f2745cc3..00000000 --- a/src/ComputeSharp.SourceGenerators/Models/ShaderMethodInfo.cs +++ /dev/null @@ -1,11 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Models; - -namespace ComputeSharp.SourceGenerators.Models; - -/// -/// A model representing all necessary info for a full generation pass for a shader method. -/// -/// The processed HLSL source for the shader method. -/// The discovered diagnostics, if any. -internal sealed record ShaderMethodInfo(HlslMethodSourceInfo HlslMethodSource, EquatableArray Diagnostcs); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs deleted file mode 100644 index 1a97cf1f..00000000 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ /dev/null @@ -1,190 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using System.Text; -using ComputeSharp.__Internals; -using ComputeSharp.SourceGeneration.Extensions; -using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Models; -using ComputeSharp.SourceGeneration.SyntaxRewriters; -using ComputeSharp.SourceGenerators.Models; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 - -namespace ComputeSharp.SourceGenerators; - -/// -/// A source generator for processing static methods referenced from compute shaders. -/// -[Generator(LanguageNames.CSharp)] -public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator -{ - /// - public void Initialize(IncrementalGeneratorInitializationContext context) - { - // Get all declared methods (including global function declarations) with the [ShaderMethod] attribute, and their info - IncrementalValuesProvider methodInfoWithErrors = - context.SyntaxProvider - .ForAttributeWithMetadataName( - typeof(ShaderMethodAttribute).FullName, - static (node, _) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } or LocalFunctionStatementSyntax { Parent: GlobalStatementSyntax { Parent: CompilationUnitSyntax } }, - static (context, token) => - { - HlslMethodSourceInfo hlslMethodSourceInfo = Execute.GetData( - context.SemanticModel.Compilation, - (CSharpSyntaxNode)context.TargetNode, - (IMethodSymbol)context.TargetSymbol, - out ImmutableArray diagnostics); - - return new ShaderMethodInfo(hlslMethodSourceInfo, diagnostics); - }); - - // Output the diagnostics, if any - context.ReportDiagnostics( - methodInfoWithErrors - .Select(static (item, _) => item.Diagnostcs)); - - // Generate the [ShaderMethodSource] attributes - context.RegisterSourceOutput(methodInfoWithErrors, static (context, item) => - { - CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item.HlslMethodSource); - string filename = item.HlslMethodSource.MetadataName.Replace('`', '-').Replace('+', '.'); - - context.AddSource($"{filename}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - } - - /// - /// A helper with all logic to generate the attribute declarations. - /// - private static class Execute - { - /// - /// Processes a given target method. - /// - /// The input object currently in use. - /// The or node to process. - /// The instance for the current method. - /// The resulting diagnostics from the processing operation. - public static HlslMethodSourceInfo GetData( - Compilation compilation, - CSharpSyntaxNode methodDeclaration, - IMethodSymbol methodSymbol, - out ImmutableArray diagnostics) - { - using ImmutableArrayBuilder builder = new(); - - // We need to sets to track all discovered custom types and static methods - HashSet discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); - Dictionary instanceMethods = new(SymbolEqualityComparer.Default); // Unused in this generator - - // Explore the syntax tree and extract the processed info - SemanticModelProvider semanticModel = new(compilation); - (string entryPoint, ImmutableArray<(string Signature, string Definition)> dependentMethods) = GetProcessedMethods(builder, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions); - ImmutableArray<(string Name, string Definition)> definedTypes = IShaderGenerator.BuildHlslSource.GetDeclaredTypes(builder, methodSymbol, discoveredTypes, instanceMethods); - ImmutableArray<(string Name, string Value)> definedConstants = IShaderGenerator.BuildHlslSource.GetDefinedConstants(constantDefinitions); - - diagnostics = builder.ToImmutable(); - - return new( - methodSymbol.GetFullyQualifiedMetadataName(includeParameters: true), - entryPoint, - definedTypes, - definedConstants, - dependentMethods); - } - - /// - /// Gets a sequence of processed methods from a target method declaration. - /// - /// The collection of produced instances. - /// The or instance for the current method. - /// The instance for the method to process. - /// The collection of currently discovered types. - /// The collection of discovered constant definitions. - /// A sequence of processed methods in (main method and all captured methods). - private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods( - ImmutableArrayBuilder diagnostics, - CSharpSyntaxNode methodDeclaration, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary constantDefinitions) - { - Dictionary staticMethods = new(SymbolEqualityComparer.Default); - Dictionary instanceMethods = new(SymbolEqualityComparer.Default); - - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, diagnostics); - - // Process the possible syntax nodes - SyntaxNode visitedMethod = methodDeclaration switch - { - MethodDeclarationSyntax methodDeclarationSyntax => shaderSourceRewriter.Visit(methodDeclarationSyntax)!.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)), - LocalFunctionStatementSyntax functionStatementSyntax => shaderSourceRewriter.Visit(functionStatementSyntax)!.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)), - _ => throw new ArgumentException("Invalid method declaration syntax node type.") - }; - - // Rewrite the method syntax tree - string targetMethod = visitedMethod - .WithoutTrivia() - .NormalizeWhitespace(eol: "\n") - .ToFullString(); - - using ImmutableArrayBuilder<(string, string)> methods = new(); - - // Emit the extracted local functions - foreach (KeyValuePair localFunction in shaderSourceRewriter.LocalFunctions) - { - methods.Add(( - localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); - } - - // Emit the discovered static methods - foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) - { - methods.Add(( - staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); - } - - return (targetMethod, methods.ToImmutable()); - } - - /// - /// Creates a instance with the processed attribute. - /// - /// The input instance to use. - public static CompilationUnitSyntax GetSyntax(HlslMethodSourceInfo methodSourceInfo) - { - // This produces an assembly attribute declaration as follows: - // - // // - // #pragma warning disable - // [assembly: global::ComputeSharp.ShaderMethodSourceAttribute()] - return - CompilationUnit().AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.MetadataName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.EntryPoint))), - AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedTypes)), - AttributeArgument(NestedArrayExpression(methodSourceInfo.DependentMethods)), - AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedConstants))))) - .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) - .WithOpenBracketToken(Token(TriviaList( - Comment("// "), - Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), - SyntaxKind.OpenBracketToken, - TriviaList())) - .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) - .NormalizeWhitespace(eol: "\n"); - } - } -} \ No newline at end of file From 8e0aa437bc7f2459d31008971b6126a74c2ca33e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 13 Oct 2023 11:46:18 +0200 Subject: [PATCH 5/6] Always generate hardcoded HLSL source --- ...ator.CreateBuildHlslSourceMethod.Syntax.cs | 79 +++---------------- ...erGenerator.CreateBuildHlslSourceMethod.cs | 72 ++++------------- ...haderGenerator.CreateLoadBytecodeMethod.cs | 5 +- .../IShaderGenerator.cs | 24 +++--- .../Models/HlslShaderSourceInfo.cs | 30 +------ 5 files changed, 43 insertions(+), 167 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index 610a3f83..c1e55e3c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -1,5 +1,4 @@ using System.Collections.Immutable; -using System.Text; using ComputeSharp.__Internals; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; @@ -83,73 +82,8 @@ partial class IShaderGenerator { using ImmutableArrayBuilder statements = new(); - StringBuilder textBuilder = new(); - int prologueStatements = 0; - int sizeHint = 64; - - void AppendLine(string text) - { - _ = textBuilder.Append(text); - } - - void AppendParsedStatement(string text) - { - FlushText(); - - statements.Add(ParseStatement(text)); - } - - void FlushText() - { - if (textBuilder.Length > 0) - { - string hlslSource = textBuilder.ToString(); - - _ = textBuilder.Append(hlslSource); - - sizeHint += textBuilder.Length; - - // The indentation level is the current depth + 2 (the method, and the return expression) - SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSource, hierarchyDepth + 2); - - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression))))); - - _ = textBuilder.Clear(); - } - } - - // Header and thread ids - AppendLine(hlslSourceInfo.HeaderAndThreadsX); - AppendParsedStatement("builder.Append(threadsX);"); - AppendLine(hlslSourceInfo.ThreadsY); - AppendParsedStatement("builder.Append(threadsY);"); - AppendLine(hlslSourceInfo.ThreadsZ); - AppendParsedStatement("builder.Append(threadsZ);"); - - // Define declarations - AppendLine(hlslSourceInfo.Defines); - - // Static fields and declared types - AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes); - - // Captured variables - AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations); - - // Captured methods - AppendLine(hlslSourceInfo.CapturedMethods); - - // Entry point - AppendLine(hlslSourceInfo.EntryPoint); - - FlushText(); - // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(); - statements.Insert( - prologueStatements, + statements.Add( ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, @@ -162,7 +96,16 @@ partial class IShaderGenerator .AddArgumentListArguments( Argument(LiteralExpression( SyntaxKind.NumericLiteralExpression, - Literal(sizeHint))))))); + Literal(hlslSourceInfo.HlslSource.Length))))))); + + // The indentation level is the current depth + 2 (the method, and the return expression) + SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSourceInfo.HlslSource, hierarchyDepth + 2); + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression))))); return statements.ToImmutable(); } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index adffa7b0..80ab5c6c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -15,8 +15,6 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -#pragma warning disable CS0618 - namespace ComputeSharp.SourceGenerators; /// @@ -34,12 +32,16 @@ partial class IShaderGenerator /// The input object currently in use. /// The node to process. /// The for . + /// The info on the shader thread count size to use. + /// Indicates whether the current shader uses an implicit texture. /// The resulting info on the processed shader. public static HlslShaderSourceInfo GetInfo( ImmutableArrayBuilder diagnostics, Compilation compilation, StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol) + INamedTypeSymbol structDeclarationSymbol, + ThreadIdsInfo threadIds, + out bool isImplicitTextureUsed) { // Detect invalid properties DetectAndReportInvalidPropertyDeclarations(diagnostics, structDeclarationSymbol); @@ -71,8 +73,12 @@ partial class IShaderGenerator ImmutableArray<(string Name, string Definition)> declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods); ImmutableArray<(string Name, string Value)> definedConstants = GetDefinedConstants(constantDefinitions); + // Check whether an implicit texture is used in the shader + isImplicitTextureUsed = implicitTextureType is not null; + // Get the HLSL source data with the intermediate info return GetHlslSourceInfo( + threadIds, definedConstants, declaredTypes, resourceFields, @@ -538,6 +544,7 @@ partial class IShaderGenerator /// /// Produces the series of statements to build the current HLSL source. /// + /// The info on the shader thread count size to use. /// The sequence of defined constants for the shader. /// The sequence of declared types used by the shader. /// The sequence of resource instance fields for the current shader. @@ -551,6 +558,7 @@ partial class IShaderGenerator /// The body of the entry point of the shader. /// The series of statements to build the HLSL source to compile to execute the current shader. private static HlslShaderSourceInfo GetHlslSourceInfo( + ThreadIdsInfo threadIds, ImmutableArray<(string Name, string Value)> definedConstants, ImmutableArray<(string Name, string Definition)> declaredTypes, ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, @@ -606,20 +614,11 @@ partial class IShaderGenerator // Group size constants AppendLF(); AppendLine("#define __GroupSize__get_X "); - - string headerAndThreadsX = FlushText(); - - AppendLF(); + AppendLineAndLF(threadIds.X.ToString()); AppendLine("#define __GroupSize__get_Y "); - - string threadsY = FlushText(); - - AppendLF(); + AppendLineAndLF(threadIds.Y.ToString()); AppendLine("#define __GroupSize__get_Z "); - - string threadsZ = FlushText(); - - AppendLF(); + AppendLineAndLF(threadIds.Z.ToString()); // Define declarations foreach ((string name, string value) in definedConstants) @@ -627,8 +626,6 @@ partial class IShaderGenerator AppendLineAndLF($"#define {name} {value}"); } - string defines = FlushText(); - // Static fields if (staticFields.Any()) { @@ -654,8 +651,6 @@ partial class IShaderGenerator AppendLineAndLF(typeDefinition); } - string staticFieldsAndDeclaredTypes = FlushText(); - // Captured variables AppendLF(); AppendLineAndLF("cbuffer _ : register(b0)"); @@ -733,8 +728,6 @@ partial class IShaderGenerator AppendLineAndLF(forwardDeclaration); } - string capturedFieldsAndResourcesAndForwardDeclarations = FlushText(); - // Captured methods foreach ((string _, string method) in processedMethods) { @@ -742,47 +735,14 @@ partial class IShaderGenerator AppendLineAndLF(method); } - string capturedMethods = FlushText(); - // Entry point AppendLF(); AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); AppendLineAndLF(executeMethod); - string entryPoint = FlushText(); + string hlslSource = FlushText(); - return new( - headerAndThreadsX, - threadsY, - threadsZ, - defines, - staticFieldsAndDeclaredTypes, - capturedFieldsAndResourcesAndForwardDeclarations, - capturedMethods, - entryPoint, - implicitTextureType, - isSamplerUsed, - declaredTypes.Select(static t => t.Name).ToImmutableArray(), - definedConstants.Select(static c => c.Name).ToImmutableArray(), - processedMethods.Select(static m => m.Signature).ToImmutableArray()); - } - - /// - /// Produces the non dynamic HLSL source (concatenating all generated HLSL source chunks). - /// - /// The input instance to use. - /// The non dynamic HLSL source code. - public static string GetNonDynamicHlslSource(HlslShaderSourceInfo hlslSourceInfo) - { - return - hlslSourceInfo.HeaderAndThreadsX + "" + - hlslSourceInfo.ThreadsY + "" + - hlslSourceInfo.ThreadsZ + "" + - hlslSourceInfo.Defines + - hlslSourceInfo.StaticFieldsAndDeclaredTypes + - hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations + - hlslSourceInfo.CapturedMethods + - hlslSourceInfo.EntryPoint; + return new(hlslSource, isSamplerUsed); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs index 56ea8dab..1a29c02b 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs @@ -47,10 +47,7 @@ partial class IShaderGenerator if (!structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName(typeof(EmbeddedBytecodeAttribute).FullName, out AttributeData? attribute)) { // Emit the diagnostics if dynamic shaders are not supported - if (!supportsDynamicShaders) - { - diagnostics.Add(MissingEmbeddedBytecodeAttributeWhenDynamicShaderCompilationIsNotSupported, structDeclarationSymbol, structDeclarationSymbol); - } + diagnostics.Add(MissingEmbeddedBytecodeAttributeWhenDynamicShaderCompilationIsNotSupported, structDeclarationSymbol, structDeclarationSymbol); return new(true, 0, 0, 0); } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 29d98041..ed27be1b 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -61,32 +61,34 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator token.ThrowIfCancellationRequested(); + // TryGetBytecode() info + ThreadIdsInfo threadIds = LoadBytecode.GetInfo( + diagnostics, + typeSymbol, + false); + + token.ThrowIfCancellationRequested(); + // BuildHlslSource() info HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo( diagnostics, context.SemanticModel.Compilation, typeDeclaration, - typeSymbol); + typeSymbol, + threadIds, + out bool isImplicitTextureUsed); token.ThrowIfCancellationRequested(); // GetDispatchMetadata() info DispatchMetadataInfo dispatchMetadataInfo = LoadDispatchMetadata.GetInfo( root32BitConstantCount, - hlslSourceInfo.ImplicitTextureType is not null, + isImplicitTextureUsed, hlslSourceInfo.IsSamplerUsed, fieldInfos); token.ThrowIfCancellationRequested(); - // TryGetBytecode() info - ThreadIdsInfo threadIds = LoadBytecode.GetInfo( - diagnostics, - typeSymbol, - false); - - token.ThrowIfCancellationRequested(); - return new ShaderInfo( Hierarchy: HierarchyInfo.From(typeSymbol), DispatchData: new DispatchDataInfo( @@ -155,7 +157,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Transform the raw HLSL source to compile (this step aggregates the HLSL source to ensure compilation is only done for actual HLSL changes) IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo = shaderInfoWithErrors - .Select(static (item, token) => (item.Hierarchy, BuildHlslSource.GetNonDynamicHlslSource(item.HlslShaderSource), item.ThreadIds)); + .Select(static (item, token) => (item.Hierarchy, item.HlslShaderSource.HlslSource, item.ThreadIds)); // Compile the requested shader bytecodes IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs index eb418c38..e0220a50 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs @@ -1,34 +1,8 @@ -using ComputeSharp.SourceGeneration.Helpers; - namespace ComputeSharp.SourceGenerators.Models; /// /// A model for extracted info on a processed HLSL shader. /// -/// The shader generated header and threadsX count declaration. -/// The threadsY count declaration. -/// The threadsZ count declaration. -/// The define statements, if any. -/// The static fields and declared types, if any. -/// The captured fields, and method forward declarations. -/// The captured method implementations. -/// The shader entry point. -/// The type of the implicit texture type, if any. +/// The HLSL source for the shader. /// Whether or not the static sampler is used. -/// The names of declared types. -/// The names of defined constants. -/// The signatures for captured methods. -internal sealed record HlslShaderSourceInfo( - string HeaderAndThreadsX, - string ThreadsY, - string ThreadsZ, - string Defines, - string StaticFieldsAndDeclaredTypes, - string CapturedFieldsAndResourcesAndForwardDeclarations, - string CapturedMethods, - string EntryPoint, - string? ImplicitTextureType, - bool IsSamplerUsed, - EquatableArray DefinedTypes, - EquatableArray DefinedConstants, - EquatableArray MethodSignatures); \ No newline at end of file +internal sealed record HlslShaderSourceInfo(string HlslSource, bool IsSamplerUsed); \ No newline at end of file From d797f1477192183c63d28dab2584bd9a36ed17d4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 13 Oct 2023 12:06:42 +0200 Subject: [PATCH 6/6] Remove unnecessary ArrayPoolStringBuilder type --- .../Shaders/Interop/ReflectionServices.cs | 8 +- ...ator.CreateBuildHlslSourceMethod.Syntax.cs | 77 +-------- .../Core/Interfaces/__Internals/IShader.cs | 7 +- .../__Internals/ArrayPoolStringBuilder.cs | 163 ------------------ 4 files changed, 13 insertions(+), 242 deletions(-) delete mode 100644 src/ComputeSharp/Shaders/Dispatching/__Internals/ArrayPoolStringBuilder.cs diff --git a/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs b/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs index 8b8e0ced..b31d8c38 100644 --- a/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs +++ b/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs @@ -104,11 +104,9 @@ public static class ReflectionServices private static unsafe ShaderInfo GetNonGenericShaderInfo(in T shader) where T : struct, IShader { - Unsafe.AsRef(in shader).BuildHlslSource(out ArrayPoolStringBuilder shaderSource, 1, 1, 1); + Unsafe.AsRef(in shader).BuildHlslSource(out string hlslSource); - using ComPtr dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(shaderSource.WrittenSpan); - - shaderSource.Dispose(); + using ComPtr dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(hlslSource); using ComPtr dxcUtils = default; @@ -134,7 +132,7 @@ public static class ReflectionServices return new( CompilerVersion: new string(d3D12ShaderDescription.Creator), - HlslSource: shaderSource.WrittenSpan.ToString(), + HlslSource: hlslSource, ConstantBufferCount: d3D12ShaderDescription.ConstantBuffers, BoundResourceCount: d3D12ShaderDescription.BoundResources, InstructionCount: d3D12ShaderDescription.InstructionCount, diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index c1e55e3c..cf9d323a 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -1,4 +1,3 @@ -using System.Collections.Immutable; using ComputeSharp.__Internals; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; @@ -25,14 +24,14 @@ partial class IShaderGenerator /// The resulting instance for the BuildHlslSource method. public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth) { - // Generate the necessary body statements depending on whether dynamic shaders are supported - ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo, hierarchyDepth); + // The indentation level is the current depth + 2 (the method, and the return expression) + SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSourceInfo.HlslSource, hierarchyDepth + 2); // This code produces a method declaration as follows: // - // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) + // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out string hlslSource) // { - // + // hlslSource = ; // } return MethodDeclaration( @@ -41,73 +40,13 @@ partial class IShaderGenerator .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) .AddParameterListParameters( - Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")), - Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .WithBody(Block(bodyStatements)); - } - - /// - /// Produces the series of statements for the empty fallback method. - /// - /// A series of statements for when dynamic shaders are not supported. - private static ImmutableArray GenerateEmptyMethodBody() - { - // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(0); - return - ImmutableArray.Create( + Parameter(Identifier("hlslSource")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(PredefinedType(Token(SyntaxKind.StringKeyword)))) + .WithBody(Block( ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, - IdentifierName("builder"), - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"), - IdentifierName("Create"))) - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0))))))); - } - - /// - /// Produces the series of statements to build the current HLSL source. - /// - /// The input instance to use. - /// The depth of the hierarchy for this type (used to calculate the right indentation). - /// The series of statements to build the HLSL source to compile to execute the current shader. - private static ImmutableArray GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth) - { - using ImmutableArrayBuilder statements = new(); - - // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(); - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("builder"), - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"), - IdentifierName("Create"))) - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(hlslSourceInfo.HlslSource.Length))))))); - - // The indentation level is the current depth + 2 (the method, and the return expression) - SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSourceInfo.HlslSource, hierarchyDepth + 2); - - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression))))); - - return statements.ToImmutable(); + IdentifierName("hlslSource"), + LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression))))); } } } \ No newline at end of file diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs index 35878d67..d39d9234 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs @@ -38,13 +38,10 @@ public interface IShader /// /// Builds the HLSL source code for the current shader instance. /// - /// The resulting instance containing the HLSL source. - /// The number of threads in each thread group for the X axis. - /// The number of threads in each thread group for the Y axis. - /// The number of threads in each thread group for the Z axis. + /// The resulting HLSL source. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be called directly by user code")] - void BuildHlslSource(out ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ); + void BuildHlslSource(out string hlslSource); /// /// Loads the bytecode for the current shader. diff --git a/src/ComputeSharp/Shaders/Dispatching/__Internals/ArrayPoolStringBuilder.cs b/src/ComputeSharp/Shaders/Dispatching/__Internals/ArrayPoolStringBuilder.cs deleted file mode 100644 index cb503640..00000000 --- a/src/ComputeSharp/Shaders/Dispatching/__Internals/ArrayPoolStringBuilder.cs +++ /dev/null @@ -1,163 +0,0 @@ -using System; -using System.Buffers; -using System.ComponentModel; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; - -namespace ComputeSharp.__Internals; - -/// -/// A helper type that implements a pooled buffer writer for values. -/// -[EditorBrowsable(EditorBrowsableState.Never)] -[Obsolete("This type is not intended to be used directly by user code")] -[DebuggerTypeProxy(typeof(DebugView))] -public ref struct ArrayPoolStringBuilder -{ - /// - /// The underlying array. - /// - private char[] array; - - /// - /// The starting offset within . - /// - private int index; - - /// - /// Creates a new instance ready to use. - /// - /// The size hint for the internal buffer to allocate. - /// A new instance with default values. - public static ArrayPoolStringBuilder Create(int sizeHint) - { - ArrayPoolStringBuilder builder; - - builder.array = ArrayPool.Shared.Rent(sizeHint); - builder.index = 0; - - return builder; - } - - /// - /// Gets the data written to the underlying buffer so far, as a . - /// - [UnscopedRef] - public readonly ReadOnlySpan WrittenSpan - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => new(this.array, 0, this.index); - } - - /// - /// Appends the input character to the current buffer. - /// - /// The input character to write. - public void Append(char value) - { - EnsureCapacity(1); - - this.array[this.index++] = value; - } - - /// - /// Appends the input sequence of characters to the current buffer. - /// - /// The input characters to write. - public void Append(string value) - { - EnsureCapacity(value.Length); - -#if NET6_0_OR_GREATER - value.CopyTo(this.array.AsSpan(this.index)); -#else - value.AsSpan().CopyTo(this.array.AsSpan(this.index)); -#endif - - this.index += value.Length; - } - - /// - /// Appends the text representation of the input value to the current buffer. - /// - /// The input value to write. - public void Append(int value) - { -#if NET6_0_OR_GREATER - int charsWritten; - - while (!value.TryFormat(this.array.AsSpan(this.index), out charsWritten)) - { - EnsureCapacity(10); - } - - this.index += charsWritten; -#else - Append(value.ToString()); -#endif - } - - /// - /// Ensures that has enough free space to contain a given number of new items. - /// - /// The minimum number of items to ensure space for in . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void EnsureCapacity(int requestedSize) - { - if (requestedSize > this.array.Length - this.index) - { - ResizeBuffer(requestedSize); - } - } - - /// - /// Resizes to ensure it can fit the specified number of new items. - /// - /// The minimum number of items to ensure space for in . - [MethodImpl(MethodImplOptions.NoInlining)] - private void ResizeBuffer(int sizeHint) - { - int minimumSize = this.index + sizeHint; - - // Rent a new array with the specified size, and copy as many items from the current array - // as possible to the new array. This mirrors the behavior of the Array.Resize API from - // the BCL: if the new size is greater than the length of the current array, copy all the - // items from the original array into the new one. Otherwise, copy as many items as possible, - // until the new array is completely filled, and ignore the remaining items in the first array. - char[] newArray = ArrayPool.Shared.Rent(minimumSize); - int itemsToCopy = Math.Min(this.array.Length, minimumSize); - - Array.Copy(this.array, 0, newArray, 0, itemsToCopy); - - ArrayPool.Shared.Return(this.array); - - this.array = newArray; - } - - /// - public readonly void Dispose() - { - ArrayPool.Shared.Return(this.array); - } - - /// - /// A debug proxy used for displaying debug info. - /// - internal sealed class DebugView - { - /// - /// Initializes a new instance of the class with the specified parameters. - /// - /// The input instance to display. - public DebugView(ArrayPoolStringBuilder builder) - { - Text = builder.WrittenSpan.ToString(); - } - - /// - /// Gets the text to display for the current instance. - /// - public string Text { get; } - } -} \ No newline at end of file