diff --git a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs index b7584b81..cc46fd43 100644 --- a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using System.Collections.Immutable; +using System.Collections.Immutable; using System.Linq; using System.Text; using ComputeSharp.Core.SourceGenerators.Models; @@ -31,11 +30,11 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator symbol.GetAttributes().Any(static a => a.AttributeClass?.ToDisplayString() == typeof(AutoConstructorAttribute).FullName))!; // Get the type hierarchy and fields info - IncrementalValuesProvider<(HierarchyInfo Left, ImmutableArray Right)> constructorInfo = + IncrementalValuesProvider<(HierarchyInfo Left, ConstructorInfo Right)> constructorInfo = structDeclarations - .Select(static (item, token) => (Hierarchy: HierarchyInfo.From(item), Parameters: Ctor.GetData(item))) - .Where(static item => !item.Parameters.IsEmpty) - .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default.ForImmutableArray()); + .Select(static (item, token) => (Hierarchy: HierarchyInfo.From(item), Info: Ctor.GetData(item))) + .Where(static item => !item.Info.Parameters.IsEmpty) + .WithComparers(HierarchyInfo.Comparer.Default, ConstructorInfo.Comparer.Default); // Generate the constructors context.RegisterSourceOutput(constructorInfo, static (context, item) => @@ -55,23 +54,46 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator /// Gets the sequence of items for all fields in the input type. /// /// The being inspected. - /// The sequence of items for all fields in . - public static ImmutableArray GetData(INamedTypeSymbol structDeclarationSymbol) + /// The instance for . + public static ConstructorInfo GetData(INamedTypeSymbol structDeclarationSymbol) { - return ( - from fieldSymbol in structDeclarationSymbol.GetMembers().OfType() - where fieldSymbol is { IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false } - let typeName = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) - select new ParameterInfo(typeName, fieldSymbol.Name)).ToImmutableArray(); + ImmutableArray.Builder parameters = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder defaulted = ImmutableArray.CreateBuilder(); + + foreach (IFieldSymbol fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + // Skip fields that are not instance ones (and also ignore generated fields and fixed size buffers) + if (fieldSymbol is not { IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false }) + { + continue; + } + + // Check whether the field is annotated to have a special behavior + if (fieldSymbol.Type.TryGetAttributeWithFullMetadataName("ComputeSharp.AutoConstructorBehaviorAttribute", out AttributeData? usageData) && + usageData!.ConstructorArguments is { Length: 1 } arguments && + arguments[0].Value is (int)AutoConstructorBehavior.IgnoreAndSetToDefault) + { + defaulted.Add(fieldSymbol.Name); + } + else + { + // Track the field normally + string typeName = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + + parameters.Add(new ParameterInfo(typeName, fieldSymbol.Name)); + } + } + + return new(parameters.ToImmutableArray(), defaulted.ToImmutableArray()); } /// /// Gets the instance for a given type and sequence of parameters. /// /// The type hierarchy info. - /// The sequence of parameters to initialize. + /// The instance with the info for the constructor to generate. /// A instance for a specified type. - public static CompilationUnitSyntax GetSyntax(HierarchyInfo hierarchyInfo, ImmutableArray parameters) + public static CompilationUnitSyntax GetSyntax(HierarchyInfo hierarchyInfo, ConstructorInfo constructorInfo) { // Create the constructor declaration for the type. This will // produce a constructor with simple initialization of all variables: @@ -82,15 +104,20 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator // this.b = b; // this.c = c; // ... + // this.ignored1 = default; + // this.ignored2 = default; + // this.ignored3 = default; + // ... // } ConstructorDeclarationSyntax constructorDeclaration = ConstructorDeclaration(hierarchyInfo.Hierarchy[0].QualifiedName) .AddModifiers(Token(SyntaxKind.PublicKeyword)) - .AddParameterListParameters(parameters.Select(field => Parameter(Identifier(field.Name)).WithType(IdentifierName(field.Type))).ToArray()) - .AddBodyStatements(parameters.Select(field => ParseStatement($"this.{field.Name} = {field.Name};")).ToArray()); + .AddParameterListParameters(constructorInfo.Parameters.Select(field => Parameter(Identifier(field.Name)).WithType(IdentifierName(field.Type))).ToArray()) + .AddBodyStatements(constructorInfo.Parameters.Select(field => ParseStatement($"this.{field.Name} = {field.Name};")).ToArray()) + .AddBodyStatements(constructorInfo.DefaultedFields.Select(field => ParseStatement($"this.{field} = default;")).ToArray()); // Add the unsafe modifier, if needed - if (parameters.Any(static param => param.Type.Contains("*"))) + if (constructorInfo.Parameters.Any(static param => param.Type.Contains("*"))) { constructorDeclaration = constructorDeclaration.AddModifiers(Token(SyntaxKind.UnsafeKeyword)); } diff --git a/src/ComputeSharp.Core.SourceGenerators/ComputeSharp.Core.SourceGenerators.csproj b/src/ComputeSharp.Core.SourceGenerators/ComputeSharp.Core.SourceGenerators.csproj index 17c0c1bd..4c8fc75c 100644 --- a/src/ComputeSharp.Core.SourceGenerators/ComputeSharp.Core.SourceGenerators.csproj +++ b/src/ComputeSharp.Core.SourceGenerators/ComputeSharp.Core.SourceGenerators.csproj @@ -16,6 +16,8 @@ and to match members based on full name, so the types being in the generator assembly are not an issue.--> + + diff --git a/src/ComputeSharp.Core.SourceGenerators/Models/ConstructorInfo.cs b/src/ComputeSharp.Core.SourceGenerators/Models/ConstructorInfo.cs new file mode 100644 index 00000000..684014b0 --- /dev/null +++ b/src/ComputeSharp.Core.SourceGenerators/Models/ConstructorInfo.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; + +namespace ComputeSharp.Core.SourceGenerators.Models; + +/// +/// A model containiing information on a constructor to generate. +/// +/// The values for the constructor. +/// The names of ignored fields that should be defaulted. +internal sealed record ConstructorInfo(ImmutableArray Parameters, ImmutableArray DefaultedFields) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, ConstructorInfo obj) + { + hashCode.AddRange(obj.Parameters); + hashCode.AddRange(obj.DefaultedFields); + } + + /// + protected override bool AreEqual(ConstructorInfo x, ConstructorInfo y) + { + return + x.Parameters.SequenceEqual(y.Parameters) && + x.DefaultedFields.SequenceEqual(y.DefaultedFields); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.Core/Attributes/Internals/AutoConstructorBehavior.cs b/src/ComputeSharp.Core/Attributes/Internals/AutoConstructorBehavior.cs new file mode 100644 index 00000000..0690f9f7 --- /dev/null +++ b/src/ComputeSharp.Core/Attributes/Internals/AutoConstructorBehavior.cs @@ -0,0 +1,12 @@ +namespace ComputeSharp; + +/// +/// Indicates the behavior of fields annotated with . +/// +internal enum AutoConstructorBehavior +{ + /// + /// Causes to ignore fields and set their values to . + /// + IgnoreAndSetToDefault +} diff --git a/src/ComputeSharp.Core/Attributes/Internals/AutoConstructorBehaviorAttribute.cs b/src/ComputeSharp.Core/Attributes/Internals/AutoConstructorBehaviorAttribute.cs new file mode 100644 index 00000000..f25456c6 --- /dev/null +++ b/src/ComputeSharp.Core/Attributes/Internals/AutoConstructorBehaviorAttribute.cs @@ -0,0 +1,24 @@ +using System; + +namespace ComputeSharp; + +/// +/// An attribute that indicates that a target shader type should get an automatic constructor for all fields. +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] +internal sealed class AutoConstructorBehaviorAttribute : Attribute +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The value for the current instance. + public AutoConstructorBehaviorAttribute(AutoConstructorBehavior behavior) + { + Behavior = behavior; + } + + /// + /// Gets the value for the current instance. + /// + public AutoConstructorBehavior Behavior { get; } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md index 7bd22acc..e6f78fde 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md @@ -52,3 +52,8 @@ CMPSD2D0042 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github CMPSD2D0043 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0044 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0045 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0046 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0047 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0048 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0049 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0050 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj index 84a806b7..37fac13b 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj @@ -82,6 +82,7 @@ + diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index a546df0a..e3b47f1e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -547,7 +547,7 @@ internal static class DiagnosticDescriptors /// public static readonly DiagnosticDescriptor OutOfRangeInputIndex = new DiagnosticDescriptor( id: "CMPSD2D0039", - title: "Our of range D2D1 shader input indices", + title: "Out of range D2D1 shader input indices", messageFormat: "The D2D1 shader of type {0} is using some out of range input indices", category: "ComputeSharp.D2D1.Shaders", defaultSeverity: DiagnosticSeverity.Error, @@ -595,7 +595,7 @@ internal static class DiagnosticDescriptors /// public static readonly DiagnosticDescriptor OutOfRangeInputDescriptionIndex = new DiagnosticDescriptor( id: "CMPSD2D0042", - title: "Our of range D2D1 shader input description indices", + title: "Out of range D2D1 shader input description indices", messageFormat: "The D2D1 shader of type {0} is using some out of range input description indices", category: "ComputeSharp.D2D1.Shaders", defaultSeverity: DiagnosticSeverity.Error, @@ -636,18 +636,98 @@ internal static class DiagnosticDescriptors helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// - /// Gets a for when the [D2DRequiresPosition] attribute is missing. + /// Gets a for when the [D2DRequiresScenePosition] attribute is missing. /// - /// Format: "The D2D1 shader of type {0} is using D2D1 APIs that require the [D2DRequiresPosition] attribute to be used (that is, D2D1.GetScenePosition() and D2D1.SampleInputAtPosition(int, float2)), but the shader type is not annotated accordingly". + /// Format: "The D2D1 shader of type {0} is using D2D1 APIs that require the [D2DRequiresScenePosition] attribute to be used (that is, D2D1.GetScenePosition() and D2D1.SampleInputAtPosition(int, float2)), but the shader type is not annotated accordingly". /// /// - public static readonly DiagnosticDescriptor MissingD2DRequiresPositionAttribute = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor MissingD2DRequiresScenePositionAttribute = new DiagnosticDescriptor( id: "CMPSD2D0045", - title: "Missing [D2DRequiresPosition] attribute", - messageFormat: "The D2D1 shader of type {0} is using D2D1 APIs that require the [D2DRequiresPosition] attribute to be used (that is, D2D.GetScenePosition() and D2D.SampleInputAtPosition(int, float2)), but the shader type is not annotated accordingly", + title: "Missing [D2DRequiresScenePosition] attribute", + messageFormat: "The D2D1 shader of type {0} is using D2D1 APIs that require the [D2DRequiresScenePosition] attribute to be used (that is, D2D.GetScenePosition() and D2D.SampleInputAtPosition(int, float2)), but the shader type is not annotated accordingly", category: "ComputeSharp.D2D1.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "A D2D1 shader using functionality that needs position info (ie. when [D2DRequiresPosition] is used, which is mandatory when calling either D2D.GetScenePosition() or D2D.SampleInputAtPosition(int, float2)) needs to be annotated accordingly.", + description: "A D2D1 shader using functionality that needs position info (ie. when [D2DRequiresScenePosition] is used, which is mandatory when calling either D2D.GetScenePosition() or D2D.SampleInputAtPosition(int, float2)) needs to be annotated accordingly.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a shader with an out of range resource texture index (or more). + /// + /// Format: "The D2D1 shader of type {0} is using some out of range resource texture indices". + /// + /// + public static readonly DiagnosticDescriptor ResourceTextureIndexOverlappingWithInputIndex = new DiagnosticDescriptor( + id: "CMPSD2D0046", + title: "D2D1 shader resource texture indices overlapping input indices", + messageFormat: "The D2D1 shader of type {0} is using some resource texture indices that overlap with the shader input indices", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A D2D1 shader must have all the indices of its resource textures in the valid range (between the input count and 16, exclusive).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a shader with an out of range resource texture index (or more). + /// + /// Format: "The D2D1 shader of type {0} is using some out of range resource texture indices". + /// + /// + public static readonly DiagnosticDescriptor OutOfRangeResourceTextureIndex = new DiagnosticDescriptor( + id: "CMPSD2D0047", + title: "Out of range D2D1 shader resource texture indices", + messageFormat: "The D2D1 shader of type {0} is using some out of range resource texture indices", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A D2D1 shader must have all the indices of its resource textures in the valid range (between the input count and 16, exclusive).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for repeated indices for D2D resource texture indices. + /// + /// Format: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DResourceTextureIndex] attributes". + /// + /// + public static readonly DiagnosticDescriptor RepeatedD2DResourceTextureIndices = new DiagnosticDescriptor( + id: "CMPSD2D0048", + title: "Repeated D2D1 shader resource texture indices", + messageFormat: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DResourceTextureIndex] attributes", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A D2D1 shader must only have unique indices for all of its [D2DResourceTextureIndex] attributes.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid use of [D2DResourceTextureIndex]. + /// + /// Format: "The field \"{0}\" (in type {1}) is using [D2DResourceTextureIndex] incorrectly (the attribute can only be used on D2D1 resource texture types, but the field is of type {2})". + /// + /// + public static readonly DiagnosticDescriptor InvalidD2DResourceTextureIndexAttributeUse = new DiagnosticDescriptor( + id: "CMPSD2D0049", + title: "Invalid [D2DResourceTextureIndex] use", + messageFormat: "The field \"{0}\" (in type {1}) is using [D2DResourceTextureIndex] incorrectly (the attribute can only be used on D2D1 resource texture types, but the field is of type {2})", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A field is using [D2DResourceTextureIndex] incorrectly (the attribute can only be used on D2D1 resource texture types).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a missing [D2DResourceTextureIndex]. + /// + /// Format: "The field \"{0}\" (in type {1}) is of a D2D1 resource texture type but is missing the [D2DResourceTextureIndex] attribute". + /// + /// + public static readonly DiagnosticDescriptor MissingD2DResourceTextureIndexAttribute = new DiagnosticDescriptor( + id: "CMPSD2D0050", + title: "Missing [D2DResourceTextureIndex] attribute", + messageFormat: "The field \"{0}\" (in type {1}) is of a D2D1 resource texture type but is missing the [D2DResourceTextureIndex] attribute", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "All fields of a D2D1 resource texture type must be annotated using the [D2DResourceTextureIndex] attribute.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs index 1f454394..49c433df 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -53,11 +53,18 @@ partial class ID2D1ShaderGenerator Dictionary staticMethods = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + // Extract information on all captured fields + GetInstanceFields( + diagnostics, + structDeclarationSymbol, + discoveredTypes, + out ImmutableArray<(string Name, string HlslType)> valueFields, + out ImmutableArray<(string Name, string HlslType, int Index)> resourceTextureFields); + // Explore the syntax tree and extract the processed info var semanticModelProvider = new SemanticModelProvider(compilation); - var valueFields = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes); - var (entryPoint, processedMethods) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, out bool methodsNeedD2D1RequiresPosition); - var staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions, out bool fieldsNeedD2D1RequiresPosition); + var (entryPoint, processedMethods) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, out bool methodsNeedD2D1RequiresScenePosition); + var staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions, out bool fieldsNeedD2D1RequiresScenePosition); // Process the discovered types and constants var declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes); @@ -67,13 +74,14 @@ partial class ID2D1ShaderGenerator bool requiresScenePosition = GetD2DRequiresScenePositionInfo(structDeclarationSymbol); // Emit diagnostics for incorrect scene position uses - ReportInvalidD2DRequiresPositionUse(diagnostics, structDeclarationSymbol, requiresScenePosition, methodsNeedD2D1RequiresPosition || fieldsNeedD2D1RequiresPosition); + ReportInvalidD2DRequiresScenePositionUse(diagnostics, structDeclarationSymbol, requiresScenePosition, methodsNeedD2D1RequiresScenePosition || fieldsNeedD2D1RequiresScenePosition); // Get the HLSL source return GetHlslSource( definedConstants, declaredTypes, valueFields, + resourceTextureFields, staticFields, processedMethods, entryPoint, @@ -89,13 +97,17 @@ partial class ID2D1ShaderGenerator /// The collection of produced instances. /// The input instance to process. /// The collection of currently discovered types. - /// A sequence of captured fields in . - private static ImmutableArray<(string Name, string HlslType)> GetInstanceFields( + /// The sequence of captured fields in . + /// The sequence of captured resource textures in . + private static void GetInstanceFields( ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, - ICollection types) + ICollection types, + out ImmutableArray<(string Name, string HlslType)> valueFields, + out ImmutableArray<(string Name, string HlslType, int Index)> resourceTextureFields) { ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>(); + ImmutableArray<(string, string, int)>.Builder resourceTextures = ImmutableArray.CreateBuilder<(string, string, int)>(); foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -117,10 +129,25 @@ partial class ID2D1ShaderGenerator _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - // Allowed fields must be unmanaged values - if (typeSymbol.IsUnmanagedType) + // Handle resource textures as a special case + if (HlslKnownTypes.IsResourceTextureType(metadataName)) { - // Track the type if it's a custom struct + int index = 0; + + // If [D2DResourceTextureIndex] is present, get the resource texture index. + // This generator doesn't need to emit diagnostics, as that's handled separately + // by the logic handling the info gathering for LoadResourceTextureDescriptions. + if (fieldSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute", out AttributeData? attributeData)) + { + _ = attributeData!.TryGetConstructorArgument(0, out index); + } + + resourceTextures.Add((mapping ?? fieldSymbol.Name, typeName, index)); + } + else if (typeSymbol.IsUnmanagedType) + { + // Allowed fields must be unmanaged values. + // Also, track the type if it's a custom struct. if (!HlslKnownTypes.IsKnownHlslType(metadataName)) { types.Add(typeSymbol); @@ -134,7 +161,8 @@ partial class ID2D1ShaderGenerator } } - return values.ToImmutable(); + valueFields = values.ToImmutable(); + resourceTextureFields = resourceTextures.ToImmutable(); } /// @@ -146,7 +174,7 @@ partial class ID2D1ShaderGenerator /// The type symbol for the shader type. /// The collection of currently discovered types. /// The collection of discovered constant definitions. - /// Whether or not the shader needs the [D2DRequiresPosition] annotation. + /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// A sequence of static constant fields in . private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( ImmutableArray.Builder diagnostics, @@ -155,11 +183,11 @@ partial class ID2D1ShaderGenerator INamedTypeSymbol structDeclarationSymbol, ICollection discoveredTypes, IDictionary constantDefinitions, - out bool needsD2D1RequiresPosition) + out bool needsD2D1RequiresScenePosition) { ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>(); - needsD2D1RequiresPosition = false; + needsD2D1RequiresScenePosition = false; foreach (var fieldDeclaration in structDeclaration.Members.OfType()) { @@ -197,7 +225,7 @@ partial class ID2D1ShaderGenerator string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString(); - needsD2D1RequiresPosition |= staticFieldRewriter.NeedsD2DRequiresPositionAttribute; + needsD2D1RequiresScenePosition |= staticFieldRewriter.NeedsD2DRequiresScenePositionAttribute; builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment)); } @@ -216,7 +244,7 @@ partial class ID2D1ShaderGenerator /// The collection of currently discovered types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. - /// Whether or not the shader needs the [D2DRequiresPosition] annotation. + /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// A sequence of processed methods in , and the entry point. private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods) GetProcessedMethods( ImmutableArray.Builder diagnostics, @@ -226,7 +254,7 @@ partial class ID2D1ShaderGenerator ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions, - out bool needsD2D1RequiresPosition) + out bool needsD2D1RequiresScenePosition) { // Find all declared methods in the type ImmutableArray methodDeclarations = ( @@ -237,7 +265,7 @@ partial class ID2D1ShaderGenerator string? entryPoint = null; ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(); - needsD2D1RequiresPosition = false; + needsD2D1RequiresScenePosition = false; foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { @@ -267,7 +295,7 @@ partial class ID2D1ShaderGenerator MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); // Update the position requirement - needsD2D1RequiresPosition |= shaderSourceRewriter.NeedsD2DRequiresPositionAttribute; + needsD2D1RequiresScenePosition |= shaderSourceRewriter.NeedsD2DRequiresScenePositionAttribute; // Emit the extracted local functions first foreach (var localFunction in shaderSourceRewriter.LocalFunctions) @@ -412,13 +440,13 @@ partial class ID2D1ShaderGenerator } /// - /// Reports diagnostics for invalid uses of [D2DRequiresPosition] in a shader. + /// Reports diagnostics for invalid uses of [D2DRequiresScenePosition] in a shader. /// /// The collection of produced instances. /// The input instance to process. /// Whether the shader type is declaring the need for scene position. /// Whether the shader is using APIs that rely on scene position. - private static void ReportInvalidD2DRequiresPositionUse( + private static void ReportInvalidD2DRequiresScenePositionUse( ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, bool requiresScenePosition, @@ -426,7 +454,7 @@ partial class ID2D1ShaderGenerator { if (!requiresScenePosition && usesPositionDependentMethods) { - diagnostics.Add(MissingD2DRequiresPositionAttribute, structDeclarationSymbol, structDeclarationSymbol); + diagnostics.Add(MissingD2DRequiresScenePositionAttribute, structDeclarationSymbol, structDeclarationSymbol); } } @@ -446,6 +474,7 @@ partial class ID2D1ShaderGenerator /// The sequence of defined constants for the shader. /// The sequence of declared types used by the shader. /// The sequence of value instance fields for the current shader. + /// The sequence of captured resource textures for the current shader. /// The sequence of static fields referenced by the shader. /// The sequence of processed methods used by the shader. /// The body of the entry point of the shader. @@ -458,6 +487,7 @@ partial class ID2D1ShaderGenerator ImmutableArray<(string Name, string Value)> definedConstants, ImmutableArray<(string Name, string Definition)> declaredTypes, ImmutableArray<(string Name, string HlslType)> valueFields, + ImmutableArray<(string Name, string HlslType, int Index)> resourceTextureFields, ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, ImmutableArray<(string Signature, string Definition)> processedMethods, string executeMethod, @@ -556,6 +586,15 @@ partial class ID2D1ShaderGenerator } } + // Resource textures + foreach (var (fieldName, fieldType, index) in resourceTextureFields) + { + AppendLF(); + + AppendLineAndLF($"{fieldType} {fieldName} : register(t{index});"); + AppendLineAndLF($"SamplerState __sampler__{fieldName} : register(s{index});"); + } + // Forward declarations foreach (var (forwardDeclaration, _) in processedMethods) { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 0a88badb..d777fdc5 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -42,7 +42,7 @@ partial class ID2D1ShaderGenerator /// /// The array of values for all captured fields. /// The size of the shader constant buffer. - /// The sequence of instances to load shader dispatch data. + /// The sequence of instances to load the shader dispatch data. private static ImmutableArray GetDispatchDataLoadingStatements(ImmutableArray fieldInfos, int constantBufferSizeInBytes) { // If there are no fields, just load an empty buffer diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs index 8d4ae132..3a568749 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs @@ -41,7 +41,7 @@ partial class ID2D1ShaderGenerator /// Gets a sequence of statements to load the input descriptions for a given shader. /// /// The array of values for all available input descriptions. - /// The sequence of instances to load shader dispatch data. + /// The sequence of instances to load the input descriptions data. private static ImmutableArray GetInputDescriptionsLoadingStatements(ImmutableArray inputDescriptions) { // If there are no input descriptions available, just load an empty buffer @@ -127,7 +127,7 @@ partial class ID2D1ShaderGenerator AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset + 8}))"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)inputDescription.LevelOfDetail))))); + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(inputDescription.LevelOfDetail))))); offset += sizeof(int) * 3; } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs index 05000c74..f110aae9 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs @@ -57,7 +57,7 @@ partial class ID2D1ShaderGenerator inputDescriptions = ImmutableArray.Empty; - // Validate the input count (ignore if invalid, this will be validated by the HLSL source generator) + // Validate the input count (ignore if invalid, this will be validated by GetInputType() generator) if (inputCount is not (>= 0 and <= 8)) { goto End; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs new file mode 100644 index 00000000..82bac704 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs @@ -0,0 +1,139 @@ +using System.Collections.Immutable; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + private static partial class LoadResourceTextureDescriptions + { + /// + /// Creates a instance for the LoadResourceTextureDescriptions method. + /// + /// The resource texture descriptions info gathered for the current shader. + /// The resulting instance for the LoadResourceTextureDescriptions method. + public static MethodDeclarationSyntax GetSyntax(ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadResourceTextureDescriptions(ref TLoader loader) + // { + // + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(LoadResourceTextureDescriptions))) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) + .AddParameterListParameters(Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader"))) + .WithBody(Block(GetInputDescriptionsLoadingStatements(resourceTextureDescriptionsInfo.ResourceTextureDescriptions))); + } + + /// + /// Gets a sequence of statements to load the resource texture descriptions for a given shader. + /// + /// The array of values for all available resource texture descriptions. + /// The sequence of instances to load the resource texture descriptions data. + private static ImmutableArray GetInputDescriptionsLoadingStatements(ImmutableArray resourceTextureDescriptionsInfo) + { + // If there are no resource texture descriptions available, just load an empty buffer + if (resourceTextureDescriptionsInfo.IsEmpty) + { + // loader.LoadResourceTextureDescriptions(default); + return + ImmutableArray.Create( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadResourceTextureDescriptions"))) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword)))))); + } + + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + + // The size of the buffer with the resource texture descriptions is the number of resurce textures descriptions, + // times the size of each input description, which is a struct containing two int-sized fields (index and rank). + int resourceTextureDescriptionSizeInBytes = resourceTextureDescriptionsInfo.Length * sizeof(int) * 2; + + // global::System.Span data = stackalloc byte[]; + statements.Insert(0, + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("data")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceTextureDescriptionSizeInBytes))))))))))); + + // ref byte r0 = ref data[0]; + statements.Insert(1, + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("data")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + int offset = 0; + + // Generate loading statements for each resource texture description + foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptionsInfo) + { + // Write the index of the current resource texture description: + // + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) = ; + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset}))"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)resourceTextureDescription.Index))))); + + // Write the rank of the current resource texture description: + // + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint) + 4)) = ; + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset + 4}))"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)resourceTextureDescription.Rank))))); + + offset += sizeof(int) * 2; + } + + // loader.LoadInputDescriptions(data); + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadResourceTextureDescriptions"))) + .AddArgumentListArguments(Argument(IdentifierName("data"))))); + + return statements.ToImmutable(); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs new file mode 100644 index 00000000..80be7b41 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs @@ -0,0 +1,135 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Mappings; +using Microsoft.CodeAnalysis; +using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + /// A helper with all logic to generate the LoadResourceTextureDescriptions method. + /// + private static partial class LoadResourceTextureDescriptions + { + /// + /// Extracts the resource texture descriptions for the current shader. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The number of inputs for the shader. + /// The produced resource texture descriptions for the shader. + public static void GetInfo( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + int inputCount, + out ImmutableArray resourceTextureDescriptions) + { + ImmutableArray<(int? Index, int Rank)>.Builder resourceTextureInfos = ImmutableArray.CreateBuilder<(int?, int)>(); + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + // Only look for fields of a named type symbol (diagnostics is emitted by the HLSL rewriter if it's not the case). + // We're only looking for instance fields of unmanaged types in this case (as resource textures are structs). + if (fieldSymbol is not { IsStatic: false, Type: INamedTypeSymbol { IsUnmanagedType: true } typeSymbol }) + { + continue; + } + + string metadataName = typeSymbol.GetFullMetadataName(); + + // Check that the field is a resource texture type (if not, it will be processed by the HLSL rewriter too) + if (HlslKnownTypes.IsResourceTextureType(metadataName)) + { + // The type name will be ComputeSharp.D2D1.D2D1ResourceTexture1D or the 2D/3D versions + int rank = int.Parse(metadataName.Substring(metadataName.Length - 2, 1)); + int? index = null; + + // Get the index from the [D2DResourceTextureIndex] attribute over the field + if (fieldSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute", out AttributeData? attributeData)) + { + // If the constructor argument isn't available, it means the code is invalid. Just do nothing then, as the + // user will have to fix that to get the code to compile anyway. This way the generator won't crash too. + if (attributeData!.TryGetConstructorArgument(0, out int resourceIndex)) + { + index = resourceIndex; + } + } + else + { + // If the attribute is missing, emit a diagnostic + diagnostics.Add(MissingD2DResourceTextureIndexAttribute, fieldSymbol, fieldSymbol.Name, structDeclarationSymbol); + } + + resourceTextureInfos.Add((index, rank)); + } + } + + // Extract the resource texture descriptions for the rest of the pipeline + resourceTextureDescriptions = resourceTextureInfos.Select(static info => new ResourceTextureDescription((uint)(info.Index ?? 0), (uint)info.Rank)).ToImmutableArray(); + + // If the input count is invalid, do nothing and avoid emitting potentially incorrect + // diagnostics based on the resource texture indices with respect to the input count. + // The GetInputType() generator has already emitted diagnostic for this error, so this + // generator can just wait for users to go back and fix that issue before proceeding. + if (inputCount is not (>= 0 and <= 8)) + { + return; + } + + // Validate that the resource texture indices don't overlap with the shader inputs + if (resourceTextureInfos.Any(info => info.Index < inputCount)) + { + diagnostics.Add(ResourceTextureIndexOverlappingWithInputIndex, structDeclarationSymbol, structDeclarationSymbol); + + return; + } + + // Validate that no resource texture has an index greater than or equal to 16 + if (resourceTextureInfos.Any(info => info.Index >= 16)) + { + diagnostics.Add(OutOfRangeResourceTextureIndex, structDeclarationSymbol, structDeclarationSymbol); + + return; + } + + HashSet resourceTextureIndices = new(resourceTextureInfos.Where(info => info.Index.HasValue).Select(info => info.Index!.Value)); + + // All input description indices must be unique + if (resourceTextureIndices.Count != resourceTextureInfos.Count) + { + diagnostics.Add(RepeatedD2DResourceTextureIndices, structDeclarationSymbol, structDeclarationSymbol); + } + } + + /// + /// Gets the diagnostics for a field with invalid [D2DResourceTextureIndex] attribute use, if that is the case. + /// + /// The input instance to process. + /// The resulting instance for , if needed. + public static Diagnostic? GetDiagnosticForFieldWithInvalidD2DResourceTextureIndexAttribute(IFieldSymbol fieldSymbol) + { + if (fieldSymbol.HasAttributeWithFullyQualifiedName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute")) + { + string metadataName = fieldSymbol.Type.GetFullMetadataName(); + + if (!HlslKnownTypes.IsResourceTextureType(metadataName)) + { + return Diagnostic.Create( + InvalidD2DResourceTextureIndexAttributeUse, + fieldSymbol.Locations.FirstOrDefault(), + fieldSymbol.Name, + fieldSymbol.ContainingType, + fieldSymbol.Type); + } + } + + return null; + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 41f73ce5..87076d30 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -51,9 +51,9 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator .Where(static item => IsD2D1PixelShaderType(item.Left.Symbol, item.Right)) .Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol))); - // Get the dispatch data, input types, HLSL source and embedded bytecode info. This info is computed - // on the same step as parts are shared in following sub-branches in the incremental generator pipeline. - IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, HlslShaderSourceInfo Source, ImmutableArray Diagnostics)> shaderInfoWithErrors = + // Get the dispatch data, input types, resource texture descriptions, HLSL source and embedded bytecode info. This info + // is computed on the same step as parts are shared in following sub-branches in the incremental generator pipeline. + IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, HlslShaderSourceInfo Source, ImmutableArray Diagnostics)> shaderInfoWithErrors = shaderDeclarations .Combine(context.CompilationProvider) .Select(static (item, token) => @@ -81,6 +81,15 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator InputTypesInfo inputTypesInfo = new(inputTypes); + // Get the resource texture info for LoadResourceTextureDescriptions() + LoadResourceTextureDescriptions.GetInfo( + diagnostics, + item.Left.Symbol, + inputCount, + out ImmutableArray resourceTextureDescriptions); + + ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo = new(resourceTextureDescriptions); + // Get HLSL source for BuildHlslSource() string hlslSource = BuildHlslSource.GetHlslSource( diagnostics, @@ -111,6 +120,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator item.Left.Hierarchy, dispatchDataInfo, inputTypesInfo, + resourceTextureDescriptionsInfo, sourceInfo, diagnostics.ToImmutableArray()); }); @@ -128,10 +138,10 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.ReportDiagnostics(d2DCompileOptionsAtAssemblyLevelErrors.Select(static (item, token) => item)); // Filter all items to enable caching at a coarse level, and remove diagnostics - IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, HlslShaderSourceInfo Source)> shaderInfo = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, HlslShaderSourceInfo Source)> shaderInfo = shaderInfoWithErrors - .Select(static (item, token) => (item.Hierarchy, item.Dispatch, item.InputTypes, item.Source)) - .WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default, InputTypesInfo.Comparer.Default, EqualityComparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.Dispatch, item.InputTypes, item.ResourceTextureDescriptions, item.Source)) + .WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default, InputTypesInfo.Comparer.Default, ResourceTextureDescriptionsInfo.Comparer.Default, EqualityComparer.Default); // Filter items to enable caching for the input count methods IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo = @@ -163,6 +173,21 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetInputType)}", compilationUnit.GetText(Encoding.UTF8)); }); + // Get a filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, ResourceTextureDescriptionsInfo ResourceTextureDescriptions)> resourceTextureDescriptionsInfo = + shaderInfo + .Select(static (item, token) => (item.Hierarchy, item.ResourceTextureDescriptions)) + .WithComparers(HierarchyInfo.Comparer.Default, ResourceTextureDescriptionsInfo.Comparer.Default); + + // Generate the LoadResourceTextureDescriptions() methods + context.RegisterSourceOutput(resourceTextureDescriptionsInfo.Combine(canUseSkipLocalsInit), static (context, item) => + { + MethodDeclarationSyntax getInputTypeMethod = LoadResourceTextureDescriptions.GetSyntax(item.Left.ResourceTextureDescriptions); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false); + + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadResourceTextureDescriptions)}", compilationUnit.GetText(Encoding.UTF8)); + }); + // Get a filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch)> dispatchDataInfo = shaderInfo @@ -355,5 +380,18 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetPixelOptions)}", compilationUnit.GetText(Encoding.UTF8)); }); + + // Get all diagnostics for invalid [D2DResourceTextureIndex] uses + IncrementalValuesProvider invalidD2DResourceTextureIndexUseErrors = + context.SyntaxProvider + .CreateSyntaxProvider( + static (node, _) => node is FieldDeclarationSyntax { AttributeLists.Count: > 0 }, + static (context, _) => ((FieldDeclarationSyntax)context.Node).Declaration.Variables.Select(v => (IFieldSymbol)context.SemanticModel.GetDeclaredSymbol(v)!)) + .SelectMany(static (item, _) => item) + .Select(static (item, token) => LoadResourceTextureDescriptions.GetDiagnosticForFieldWithInvalidD2DResourceTextureIndexAttribute(item)) + .Where(static diagnostic => diagnostic is not null)!; + + // Output the diagnostics + context.ReportDiagnostics(invalidD2DResourceTextureIndexUseErrors); } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownMethods.cs b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownMethods.cs index 5c502afc..2968f79c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownMethods.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownMethods.cs @@ -12,11 +12,11 @@ partial class HlslKnownMethods { /// /// Checks whether or not a method name (previous matched with - /// needs the [D2DRequiresPosition] annotation on its containing shader in order to be used. + /// needs the [D2DRequiresScenePosition] annotation on its containing shader in order to be used. /// /// The fully qualified metadata name. - /// Whether the method needs the [D2DRequiresPosition] annotation. - public static bool NeedsD2DRequiresPositionAttribute(string name) + /// Whether the method needs the [D2DRequiresScenePosition] annotation. + public static bool NeedsD2DRequiresScenePositionAttribute(string name) { return name is "ComputeSharp.D2D1.D2D.GetScenePosition" or "ComputeSharp.D2D1.D2D.SampleInputAtPosition"; } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownProperties.cs b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownProperties.cs new file mode 100644 index 00000000..7b70b8f1 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownProperties.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; + +namespace ComputeSharp.SourceGeneration.Mappings; + +/// +partial class HlslKnownProperties +{ + /// + private static partial IReadOnlyDictionary BuildKnownResourceIndexers() + { + return new Dictionary + { + [$"ComputeSharp.D2D1.D2D1ResourceTexture2D.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.D2D1.D2D1ResourceTexture3D.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" + }; + } + + /// + private static partial IReadOnlyDictionary BuildKnownResourceSamplers() + { + return new Dictionary + { + [$"ComputeSharp.D2D1.D2D1ResourceTexture1D.this[{typeof(float).FullName}]"] = null, + [$"ComputeSharp.D2D1.D2D1ResourceTexture2D.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", + [$"ComputeSharp.D2D1.D2D1ResourceTexture2D.this[{typeof(Float2).FullName}]"] = null, + [$"ComputeSharp.D2D1.D2D1ResourceTexture3D.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", + [$"ComputeSharp.D2D1.D2D1ResourceTexture3D.this[{typeof(Float3).FullName}]"] = null + }; + } + + /// + private static partial IReadOnlyDictionary BuildKnownSizeAccessors() + { + return new Dictionary + { + ["ComputeSharp.D2D1.D2D1ResourceTexture1D.Width"] = (1, 0), + ["ComputeSharp.D2D1.D2D1ResourceTexture2D.Width"] = (2, 0), + ["ComputeSharp.D2D1.D2D1ResourceTexture2D.Height"] = (2, 1), + ["ComputeSharp.D2D1.D2D1ResourceTexture3D.Width"] = (3, 0), + ["ComputeSharp.D2D1.D2D1ResourceTexture3D.Height"] = (3, 1), + ["ComputeSharp.D2D1.D2D1ResourceTexture3D.Depth"] = (3, 2) + }; + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownTypes.cs index 33dc9cbe..b25b41dc 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -1,4 +1,5 @@ -using ComputeSharp.SourceGeneration.Extensions; +using System; +using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; namespace ComputeSharp.SourceGeneration.Mappings; @@ -6,11 +7,39 @@ namespace ComputeSharp.SourceGeneration.Mappings; /// partial class HlslKnownTypes { + /// + /// Checks whether or not a given type name matches a resource texture type. + /// + /// The input type name to check. + /// Whether or not represents a readonly typed resource type. + public static bool IsResourceTextureType(string typeName) + { + return typeName switch + { + "ComputeSharp.D2D1.D2D1ResourceTexture1D" or + "ComputeSharp.D2D1.D2D1ResourceTexture2D" or + "ComputeSharp.D2D1.D2D1ResourceTexture3D" => true, + _ => false + }; + } + /// public static partial string GetMappedName(INamedTypeSymbol typeSymbol) { string typeName = typeSymbol.GetFullMetadataName(); + // Special case for resource texture types + if (IsResourceTextureType(typeName)) + { + return typeName switch + { + "ComputeSharp.D2D1.D2D1ResourceTexture1D" => "Texture1D", + "ComputeSharp.D2D1.D2D1ResourceTexture2D" => "Texture2D", + "ComputeSharp.D2D1.D2D1ResourceTexture3D" => "Texture3D", + _ => throw new ArgumentException() + }; + } + // The captured field is of an HLSL primitive type if (KnownHlslTypes.TryGetValue(typeName, out string? mappedType)) { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs index 29d20cc9..c92757ab 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs @@ -3,7 +3,7 @@ /// /// A model representing an input description for a shader. /// -/// The index of the input resource the description if for. +/// The index of the input resource the description is for. /// The input filter to use. /// The level of detail to use. internal sealed record InputDescription(uint Index, D2D1Filter Filter, int LevelOfDetail); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs index 3ac7001b..81869b59 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs @@ -8,7 +8,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// /// A model representing gathered input descriptions for a shader. /// -/// The input types for a given shader. +/// The input descriptions for a given shader. internal sealed record InputDescriptionsInfo(ImmutableArray InputDescriptions) { /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescription.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescription.cs new file mode 100644 index 00000000..63f0d842 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescription.cs @@ -0,0 +1,8 @@ +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing a resource texture description for a shader. +/// +/// The index of the resource texture resource the description is for. +/// The rank of the resource texture. +internal sealed record ResourceTextureDescription(uint Index, uint Rank); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs new file mode 100644 index 00000000..b5a174d5 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; + +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing gathered resource texture descriptions for a shader. +/// +/// The resource textures for the current shader. +internal sealed record ResourceTextureDescriptionsInfo(ImmutableArray ResourceTextureDescriptions) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, ResourceTextureDescriptionsInfo obj) + { + hashCode.AddRange(obj.ResourceTextureDescriptions); + } + + /// + protected override bool AreEqual(ResourceTextureDescriptionsInfo x, ResourceTextureDescriptionsInfo y) + { + return x.ResourceTextureDescriptions.SequenceEqual(y.ResourceTextureDescriptions); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index 26f9c756..f76c7843 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -66,9 +66,9 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter } /// - /// Gets whether or not the shader needs the [D2DRequiresPosition] attribute. + /// Gets whether or not the shader needs the [D2DRequiresScenePosition] attribute. /// - public bool NeedsD2DRequiresPositionAttribute { get; protected set; } + public bool NeedsD2DRequiresScenePositionAttribute { get; protected set; } /// public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) @@ -247,6 +247,40 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter { string propertyName = operation.Property.GetFullMetadataName(); + // Rewrite texture resource indices taking individual indices a vector argument, as per HLSL spec. + // For instance: texture[ThreadIds.X, ThreadIds.Y] will be rewritten as texture[int2(ThreadIds.X, ThreadIds.Y)]. + if (HlslKnownProperties.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping)) + { + var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments)); + + return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index)))); + } + + // Rewrite texture resource sampled accesses, if needed + if (HlslKnownProperties.TryGetMappedResourceSamplerAccessType(propertyName, out mapping)) + { + // Get the syntax for the argument syntax transformation as described above + ArgumentSyntax coordinateSyntax = mapping switch + { + not null => Argument(InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments))), + null => updatedNode.ArgumentList.Arguments[0] + }; + + string fieldName = (operation.Instance as IFieldReferenceOperation)?.Member.Name ?? ""; + + _ = HlslKnownKeywords.TryGetMappedName(fieldName, out string? mapped); + + // Transform an indexer syntax into a sampling call with the implicit static linear sampler. + // For instance: texture[uv] will be rewritten as texture.Sample(__sampler__texture, uv). + return + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + updatedNode.Expression, + IdentifierName("Sample"))) + .AddArgumentListArguments(Argument(IdentifierName($"__sampler__{mapped ?? fieldName}")), coordinateSyntax); + } + // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01. if (HlslKnownProperties.IsKnownMatrixIndexer(propertyName)) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 31f325a4..a45647db 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -264,6 +264,56 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter false => updatedNode.WithName(IdentifierName(mapping!)) }; } + + // If the current member access is an access to any of the size properties in the available + // resource types (either buffer or texture types), then rewrite the subtree to transform the + // property access into an invocation of an autogenerated static helper method to get the target + // dimension for the buffer in use. The helper method is added to the list of static helpers. + if (operation is IPropertyReferenceOperation propertyOperation && + HlslKnownProperties.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) + { + IMethodSymbol key = propertyOperation.Property.GetMethod!; + + if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax)) + { + INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.For(node).GetTypeInfo(node.Expression).Type!; + string resourceName = HlslKnownTypes.GetMappedName(resourceType); + + // Create a static method to get a specified dimension for a target resource type. + // The method will automatically create the necessary number of temporary variables + // depending on the rank of the input resource (eg. 2 for Texture2D resources). + // For instance, this code will generate the following tree for Texture2D.Width: + // + // static int __get_Dimension0(Texture2D texture) + // { + // uint _0, _1; + // texture.GetDimensions(_0, _1); + // + // return _0; + // } + methodSyntax = + MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") + .AddModifiers(Token(SyntaxKind.StaticKeyword)) + .AddParameterListParameters( + Parameter(Identifier("resource")) + .WithType(IdentifierName(resourceName))) + .WithBody(Block( + LocalDeclarationStatement( + VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), + ExpressionStatement( + InvocationExpression(MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("resource"), + IdentifierName("GetDimensions"))) + .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), + ReturnStatement(IdentifierName("_" + axis)))); + + this.staticMethods.Add(key, methodSyntax); + } + + return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression)); + } } return updatedNode; @@ -285,10 +335,10 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter // For instance: Math.Abs(expr) => abs(expr). if (HlslKnownMethods.TryGetMappedName(metadataName, out string? mapping)) { - // Track whether the method needs [D2DRequiresPosition] - if (HlslKnownMethods.NeedsD2DRequiresPositionAttribute(metadataName)) + // Track whether the method needs [D2DRequiresScenePosition] + if (HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName)) { - NeedsD2DRequiresPositionAttribute = true; + NeedsD2DRequiresScenePositionAttribute = true; } return updatedNode.WithExpression(ParseExpression(mapping!)); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs index f4ae8d82..91f5ea3c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs @@ -99,9 +99,9 @@ internal sealed class StaticFieldRewriter : HlslSourceRewriter // Rewrite HLSL intrinsic methods if (HlslKnownMethods.TryGetMappedName(metadataName, out string? mapping)) { - if (HlslKnownMethods.NeedsD2DRequiresPositionAttribute(metadataName)) + if (HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName)) { - NeedsD2DRequiresPositionAttribute = true; + NeedsD2DRequiresScenePositionAttribute = true; } return updatedNode.WithExpression(ParseExpression(mapping!)); diff --git a/src/ComputeSharp.D2D1/Attributes/D2DOutputBuffer.cs b/src/ComputeSharp.D2D1/Attributes/D2DOutputBufferAttribute.cs similarity index 100% rename from src/ComputeSharp.D2D1/Attributes/D2DOutputBuffer.cs rename to src/ComputeSharp.D2D1/Attributes/D2DOutputBufferAttribute.cs diff --git a/src/ComputeSharp.D2D1/Attributes/D2DPixelOptions.cs b/src/ComputeSharp.D2D1/Attributes/D2DPixelOptionsAttribute.cs similarity index 100% rename from src/ComputeSharp.D2D1/Attributes/D2DPixelOptions.cs rename to src/ComputeSharp.D2D1/Attributes/D2DPixelOptionsAttribute.cs diff --git a/src/ComputeSharp.D2D1/Attributes/D2DResourceTextureIndexAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DResourceTextureIndexAttribute.cs new file mode 100644 index 00000000..1bf4938e --- /dev/null +++ b/src/ComputeSharp.D2D1/Attributes/D2DResourceTextureIndexAttribute.cs @@ -0,0 +1,28 @@ +using System; + +namespace ComputeSharp.D2D1; + +/// +/// An attribute for resource fields in a D2D1 shader indicating the index of the D2D1 resource texture. +/// This is needed to bind an input resource in a shader to the correct input. Using this attribute is mandatory. +/// +/// +/// For more info, see . +/// +[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] +public sealed class D2DResourceTextureIndexAttribute : Attribute +{ + /// + /// Creates a new instance of the type with the specified arguments. + /// + /// The index of the annotated resource field. + public D2DResourceTextureIndexAttribute(int index) + { + Index = index; + } + + /// + /// Gets the index of the annotated resource field. + /// + public int Index { get; } +} diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1ResourceTextureDescriptionsLoader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1ResourceTextureDescriptionsLoader.cs new file mode 100644 index 00000000..76b0014e --- /dev/null +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1ResourceTextureDescriptionsLoader.cs @@ -0,0 +1,18 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.D2D1.__Internals; + +/// +/// A base representing a loader for resource texture descriptions in a D2D1 shader. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +[Obsolete("This interface is not intended to be used directly by user code")] +public interface ID2D1ResourceTextureDescriptionsLoader +{ + /// + /// Loads the available resource texture descriptions for the shader. + /// + /// The sequence of serialized resource texture descriptions. + void LoadResourceTextureDescriptions(ReadOnlySpan data); +} diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs index cfc6814f..554b138c 100644 --- a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs @@ -55,6 +55,16 @@ public interface ID2D1Shader void LoadInputDescriptions(ref TLoader loader) where TLoader : struct, ID2D1InputDescriptionsLoader; + /// + /// Loads the resource texture descriptions for the shader, if any. + /// + /// The type of resource texture descriptions loader being used. + /// The instance to use to load the resource texture descriptions. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be used directly by user code")] + void LoadResourceTextureDescriptions(ref TLoader loader) + where TLoader : struct, ID2D1ResourceTextureDescriptionsLoader; + /// /// Gets the output buffer precision and depth for the shader. /// diff --git a/src/ComputeSharp.D2D1/Resources/D2D1ResourceTexture1D.cs b/src/ComputeSharp.D2D1/Resources/D2D1ResourceTexture1D.cs new file mode 100644 index 00000000..33b49698 --- /dev/null +++ b/src/ComputeSharp.D2D1/Resources/D2D1ResourceTexture1D.cs @@ -0,0 +1,31 @@ +using ComputeSharp.Exceptions; + +namespace ComputeSharp.D2D1; + +/// +/// A representing a readonly 1D texture stored on GPU memory. +/// This can be used from D2D1 pixel shaders to be able to pass arbitrary inputs to them. +/// +[AutoConstructorBehavior(AutoConstructorBehavior.IgnoreAndSetToDefault)] +public readonly struct D2D1ResourceTexture1D +{ + /// + /// Gets the width of the current texture. + /// + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public int Width => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture1D)}.{nameof(Width)}"); + + /// + /// Gets a single value from the current readonly texture. + /// + /// The horizontal offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref readonly Float4 this[int x] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}[{typeof(int)}]"); + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The horizontal normalized offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref readonly Float4 this[float u] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}[{typeof(float)}]"); +} diff --git a/src/ComputeSharp.D2D1/Resources/D2D1ResourceTexture2D.cs b/src/ComputeSharp.D2D1/Resources/D2D1ResourceTexture2D.cs new file mode 100644 index 00000000..c35bfbbb --- /dev/null +++ b/src/ComputeSharp.D2D1/Resources/D2D1ResourceTexture2D.cs @@ -0,0 +1,53 @@ +using ComputeSharp.Exceptions; + +namespace ComputeSharp.D2D1; + +/// +/// A representing a readonly 2D texture stored on GPU memory. +/// This can be used from D2D1 pixel shaders to be able to pass arbitrary inputs to them. +/// +[AutoConstructorBehavior(AutoConstructorBehavior.IgnoreAndSetToDefault)] +public readonly struct D2D1ResourceTexture2D +{ + /// + /// Gets the width of the current texture. + /// + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public int Width => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}.{nameof(Width)}"); + + /// + /// Gets the height of the current texture. + /// + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public int Height => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}.{nameof(Height)}"); + + /// + /// Gets a single value from the current readonly texture. + /// + /// The horizontal offset of the value to get. + /// The vertical offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref readonly Float4 this[int x, int y] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}[{typeof(int)}, {typeof(int)}]"); + + /// + /// Gets a single value from the current readonly texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref readonly Float4 this[Int2 xy] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}[{typeof(Int2)}]"); + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The horizontal normalized offset of the value to get. + /// The vertical normalized offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref readonly Float4 this[float u, float v] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}[{typeof(float)}, {typeof(float)}]"); + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The normalized coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref readonly Float4 this[Float2 uv] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}[{typeof(Float2)}]"); +} diff --git a/src/ComputeSharp.D2D1/Resources/D2D1ResourceTexture3D.cs b/src/ComputeSharp.D2D1/Resources/D2D1ResourceTexture3D.cs new file mode 100644 index 00000000..ff927558 --- /dev/null +++ b/src/ComputeSharp.D2D1/Resources/D2D1ResourceTexture3D.cs @@ -0,0 +1,61 @@ +using ComputeSharp.Exceptions; + +namespace ComputeSharp.D2D1; + +/// +/// A representing a readonly 3D texture stored on GPU memory. +/// This can be used from D2D1 pixel shaders to be able to pass arbitrary inputs to them. +/// +[AutoConstructorBehavior(AutoConstructorBehavior.IgnoreAndSetToDefault)] +public readonly struct D2D1ResourceTexture3D +{ + /// + /// Gets the width of the current texture. + /// + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public int Width => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}.{nameof(Width)}"); + + /// + /// Gets the height of the current texture. + /// + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public int Height => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}.{nameof(Height)}"); + + /// + /// Gets the depth of the current texture. + /// + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public int Depth => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}.{nameof(Depth)}"); + + /// + /// Gets a single value from the current readonly texture. + /// + /// The horizontal offset of the value to get. + /// The vertical offset of the value to get. + /// The depthwise offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref readonly Float4 this[int x, int y, int z] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}[{typeof(int)}, {typeof(int)}, {typeof(int)}]"); + + /// + /// Gets a single value from the current readonly texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref readonly Float4 this[Int3 xyz] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}[{typeof(Int3)}]"); + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The horizontal normalized offset of the value to get. + /// The vertical normalized offset of the value to get. + /// The depthwise offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref readonly Float4 this[float u, float v, float w] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}[{typeof(float)}, {typeof(float)}, {typeof(float)}]"); + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The normalized coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref readonly Float4 this[Float3 uvw] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}[{typeof(Float3)}]"); +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs index 9c1c04c9..51c7c47a 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs @@ -1,6 +1,4 @@ -using System; - -namespace ComputeSharp.D2D1.Interop; +namespace ComputeSharp.D2D1.Interop; /// /// A type containing info on a description for a given D2D1 pixel shader input resource. diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs index 3679a1f7..83149d16 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs @@ -214,6 +214,23 @@ public static class D2D1PixelShader return inputDescriptionsLoader.GetResultingInputDescriptions(); } + /// + /// Gets the available resource texture descriptions for a D2D1 pixel shader. + /// + /// The type of D2D1 pixel shader to get the resource texture descriptions for. + /// A with the available resource texture descriptions for the shader. + public static ReadOnlyMemory GetResourceTextureDescriptions() + where T : unmanaged, ID2D1PixelShader + { + D2D1ByteArrayResourceTextureDescriptionsLoader resourceTextureDescriptionsLoader = default; + + Unsafe.SkipInit(out T shader); + + shader.LoadResourceTextureDescriptions(ref resourceTextureDescriptionsLoader); + + return resourceTextureDescriptionsLoader.GetResultingResourceTextureDescriptions(); + } + /// /// Gets the buffer precision for the output buffer of a D2D1 pixel shader. /// diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs new file mode 100644 index 00000000..8ed7c690 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs @@ -0,0 +1,28 @@ +namespace ComputeSharp.D2D1.Interop; + +/// +/// A type containing info on a description for a given D2D1 pixel shader resource resource. +/// +public readonly struct D2D1ResourceTextureDescription +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The index of the resource texture the description belongs to. + /// The rank of the resource texture the description belongs to. + internal D2D1ResourceTextureDescription(int index, int rank) + { + Index = index; + Rank = rank; + } + + /// + /// Gets the index of the resource texture the description belongs to. + /// + public int Index { get; } + + /// + /// Gets the rank of the resource texture the description belongs to. + /// + public int Rank { get; } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1BufferSizeDispatchDataLoader.cs b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1BufferSizeDispatchDataLoader.cs index 98a95f83..b18fcc4e 100644 --- a/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1BufferSizeDispatchDataLoader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1BufferSizeDispatchDataLoader.cs @@ -22,7 +22,7 @@ internal unsafe struct D2D1BufferSizeDispatchDataLoader : ID2D1DispatchDataLoade /// /// The size of the constant buffer. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int GetConstantBufferSize() + private int GetConstantBufferSize() { return this.size; } diff --git a/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayInputDescriptionsLoader.cs b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayInputDescriptionsLoader.cs index 7c871f1b..dffefa81 100644 --- a/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayInputDescriptionsLoader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayInputDescriptionsLoader.cs @@ -3,7 +3,6 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.Interop; -using TerraFX.Interop.DirectX; #pragma warning disable CS0618 @@ -15,7 +14,7 @@ namespace ComputeSharp.D2D1.Shaders.Loaders; internal struct D2D1ByteArrayInputDescriptionsLoader : ID2D1InputDescriptionsLoader { /// - /// The object in use. + /// The resulting array. /// private D2D1InputDescription[]? inputDescriptions; diff --git a/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayResourceTextureDescriptionsLoader.cs b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayResourceTextureDescriptionsLoader.cs new file mode 100644 index 00000000..1a375e82 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayResourceTextureDescriptionsLoader.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.Interop; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Shaders.Loaders; + +/// +/// A resource texture descriptions loader for D2D1 pixel shaders. +/// +internal struct D2D1ByteArrayResourceTextureDescriptionsLoader : ID2D1ResourceTextureDescriptionsLoader +{ + /// + /// The resulting array. + /// + private D2D1ResourceTextureDescription[]? resourceTextureDescriptions; + + /// + /// Gets the resulting resource texture descriptions. + /// + /// A array with the available resource texture descriptions. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public D2D1ResourceTextureDescription[] GetResultingResourceTextureDescriptions() + { + return this.resourceTextureDescriptions!; + } + + /// + void ID2D1ResourceTextureDescriptionsLoader.LoadResourceTextureDescriptions(ReadOnlySpan data) + { + this.resourceTextureDescriptions = MemoryMarshal.Cast(data).ToArray(); + } +} diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownProperties.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownProperties.cs index c39af7a0..059e970e 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownProperties.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownProperties.cs @@ -209,6 +209,39 @@ internal static partial class HlslKnownProperties select $"{typeof(MatrixIndex).FullName}.{name}").ToImmutableHashSet(); } + /// + /// The mapping of supported known indexers to HLSL resource type names. + /// + private static readonly IReadOnlyDictionary KnownResourceIndexers = BuildKnownResourceIndexers(); + + /// + /// Builds the mapping of supported known indexers to HLSL resource type names. + /// + /// The mapping of supported known indexers to HLSL resource type names. + private static partial IReadOnlyDictionary BuildKnownResourceIndexers(); + + /// + /// The mapping of supported known samplers to HLSL resource type names. + /// + private static readonly IReadOnlyDictionary KnownResourceSamplers = BuildKnownResourceSamplers(); + + /// + /// Builds the mapping of supported known samplers to HLSL resource type names. + /// + /// The mapping of supported known samplers to HLSL resource type names. + private static partial IReadOnlyDictionary BuildKnownResourceSamplers(); + + /// + /// The mapping of supported known size accessors for HLSL resource types. + /// + private static readonly IReadOnlyDictionary KnownSizeAccessors = BuildKnownSizeAccessors(); + + /// + /// Builds the mapping of supported known size accessors for HLSL resource types. + /// + /// The mapping of supported known size accessors for HLSL resource types. + private static partial IReadOnlyDictionary BuildKnownSizeAccessors(); + /// /// Checks whether or not a given property fullname matches a matrix swizzled indexer. /// @@ -239,4 +272,47 @@ internal static partial class HlslKnownProperties { return KnownProperties.TryGetValue(name, out mapped); } + + /// + /// Tries to get the mapped HLSL-compatible indexer resource type name for the input indexer name. + /// + /// The input fully qualified indexer name. + /// The mapped type name, if one is found. + /// The HLSL-compatible type name that can be used in an HLSL shader for the given indexer. + public static bool TryGetMappedResourceIndexerTypeName(string name, out string? mapped) + { + return KnownResourceIndexers.TryGetValue(name, out mapped); + } + + /// + /// Tries to get the mapped HLSL-compatible sampler resource type name for the input indexer name. + /// + /// The input fully qualified indexer name. + /// The mapped type name, if one is found. + /// The HLSL-compatible type name that can be used in an HLSL shader for the given sampler. + public static bool TryGetMappedResourceSamplerAccessType(string name, out string? mapped) + { + return KnownResourceSamplers.TryGetValue(name, out mapped); + } + + /// + /// Tries to get the mapped rank and axis for a given indexer name. + /// + /// The input fully qualified indexer name. + /// The resulting indexer rank, if found. + /// The resulting indexer axis, if found. + /// Whether or not a rank and axis could be resolved by the input indexer name. + public static bool TryGetAccessorRankAndAxis(string name, out int rank, out int axis) + { + if (KnownSizeAccessors.TryGetValue(name, out var info)) + { + (rank, axis) = info; + + return true; + } + + (rank, axis) = default((int, int)); + + return false; + } } diff --git a/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs index 37436b1c..0130f215 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs @@ -8,6 +8,29 @@ namespace ComputeSharp.SourceGeneration.Extensions; /// internal static class AttributeDataExtensions { + /// + /// Tries to get a constructor argument at a given index from the input instance. + /// + /// The type of constructor argument to retrieve. + /// The target instance to get the argument from. + /// The index of the argument to try to retrieve. + /// The resulting argument, if it was found. + /// Whether or not an argument of type at position was found. + public static bool TryGetConstructorArgument(this AttributeData attributeData, int index, out T? result) + { + if (attributeData.ConstructorArguments.Length >= index + 1 && + attributeData.ConstructorArguments[index].Value is T argument) + { + result = argument; + + return true; + } + + result = default; + + return false; + } + /// /// Tries to get a given named argument value from an instance, if present. /// diff --git a/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs index d12cb721..906998f8 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs @@ -134,6 +134,27 @@ internal static class ISymbolExtensions return symbol.GetFullMetadataName().Replace('`', '-').Replace('+', '.'); } + /// + /// Checks whether or not a given symbol has an attribute with the specified full name. + /// + /// The input instance to check. + /// The attribute name to look for. + /// Whether or not has an attribute with the specified name. + public static bool HasAttributeWithFullyQualifiedName(this ISymbol symbol, string name) + { + ImmutableArray attributes = symbol.GetAttributes(); + + foreach (AttributeData attribute in attributes) + { + if (attribute.AttributeClass?.HasFullyQualifiedName(name) == true) + { + return true; + } + } + + return false; + } + /// /// Tries to get an attribute with the specified full metadata name. /// diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs index f7a26034..a338cc34 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs @@ -69,6 +69,32 @@ internal static class IncrementalValuesProviderExtensions return source.WithComparer(new Comparer(comparer1, comparer2, comparer3, comparer4)); } + /// + /// Creates a new instance with a gven pair of comparers. + /// + /// The type of first items in each tuple. + /// The type of second items in each tuple. + /// The type of third items in each tuple. + /// The type of fourth items in each tuple. + /// The type of fourth items in each tuple. + /// The input instance. + /// An instance for items. + /// An instance for items. + /// An instance for items. + /// An instance for items. + /// An instance for items. + /// An with the specified comparers applied to each item. + public static IncrementalValuesProvider<(T1, T2, T3, T4, T5)> WithComparers( + this IncrementalValuesProvider<(T1, T2, T3, T4, T5)> source, + IEqualityComparer comparer1, + IEqualityComparer comparer2, + IEqualityComparer comparer3, + IEqualityComparer comparer4, + IEqualityComparer comparer5) + { + return source.WithComparer(new Comparer(comparer1, comparer2, comparer3, comparer4, comparer5)); + } + /// /// An implementation for a value tuple. /// @@ -224,4 +250,74 @@ internal static class IncrementalValuesProviderExtensions this.comparer4.GetHashCode(obj.Item4)); } } + + /// + /// An implementation for a value tuple. + /// + public sealed class Comparer : IEqualityComparer<(T1, T2, T3, T4, T5)> + { + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer1; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer2; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer3; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer4; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer5; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The comparer. + /// The comparer. + /// The comparer. + /// The comparer. + /// The comparer. + public Comparer(IEqualityComparer comparer1, IEqualityComparer comparer2, IEqualityComparer comparer3, IEqualityComparer comparer4, IEqualityComparer comparer5) + { + this.comparer1 = comparer1; + this.comparer2 = comparer2; + this.comparer3 = comparer3; + this.comparer4 = comparer4; + this.comparer5 = comparer5; + } + + /// + public bool Equals((T1, T2, T3, T4, T5) x, (T1, T2, T3, T4, T5) y) + { + return + this.comparer1.Equals(x.Item1, y.Item1) && + this.comparer2.Equals(x.Item2, y.Item2) && + this.comparer3.Equals(x.Item3, y.Item3) && + this.comparer4.Equals(x.Item4, y.Item4) && + this.comparer5.Equals(x.Item5, y.Item5); + } + + /// + public int GetHashCode((T1, T2, T3, T4, T5) obj) + { + return HashCode.Combine( + this.comparer1.GetHashCode(obj.Item1), + this.comparer2.GetHashCode(obj.Item2), + this.comparer3.GetHashCode(obj.Item3), + this.comparer4.GetHashCode(obj.Item4), + this.comparer5.GetHashCode(obj.Item5)); + } + } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownProperties.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownProperties.cs index 6baf91aa..114e23e9 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownProperties.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownProperties.cs @@ -8,75 +8,78 @@ namespace ComputeSharp.SourceGeneration.Mappings; /// partial class HlslKnownProperties { - /// - /// The mapping of supported known indexers to HLSL resource type names. - /// - private static readonly IReadOnlyDictionary KnownResourceIndexers = new Dictionary + /// + private static partial IReadOnlyDictionary BuildKnownResourceIndexers() { - [$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.ReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.IReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.IReadWriteNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.IReadWriteNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" - }; + return new Dictionary + { + [$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.ReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.IReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.IReadWriteNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.IReadWriteNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" + }; + } - /// - /// The mapping of supported known samplers to HLSL resource type names. - /// - private static readonly IReadOnlyDictionary KnownResourceSamplers = new Dictionary + /// + private static partial IReadOnlyDictionary BuildKnownResourceSamplers() { - [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", - [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(Float2).FullName}]"] = null, - [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", - [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float2).FullName}]"] = null, - [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", - [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(Float2).FullName}]"] = null, - [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", - [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(Float3).FullName}]"] = null, - [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", - [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(Float3).FullName}]"] = null, - [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", - [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(Float3).FullName}]"] = null - }; + return new Dictionary + { + [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", + [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(Float2).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float2).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", + [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(Float2).FullName}]"] = null, + [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", + [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(Float3).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", + [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(Float3).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", + [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(Float3).FullName}]"] = null + }; + } - /// - /// The mapping of supported known size accessors for HLSL resource types. - /// - private static readonly IReadOnlyDictionary KnownSizeAccessors = new Dictionary + /// + private static partial IReadOnlyDictionary BuildKnownSizeAccessors() { - ["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0), - ["ComputeSharp.Resources.Texture2D`1.Width"] = (2, 0), - ["ComputeSharp.Resources.Texture2D`1.Height"] = (2, 1), - ["ComputeSharp.Resources.Texture3D`1.Width"] = (3, 0), - ["ComputeSharp.Resources.Texture3D`1.Height"] = (3, 1), - ["ComputeSharp.Resources.Texture3D`1.Depth"] = (3, 2), - ["ComputeSharp.IReadOnlyTexture2D`1.Width"] = (2, 0), - ["ComputeSharp.IReadOnlyTexture2D`1.Height"] = (2, 1), - ["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0), - ["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1), - ["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2), - ["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Width"] = (2, 0), - ["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Height"] = (2, 1), - ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Width"] = (3, 0), - ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Height"] = (3, 1), - ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Depth"] = (3, 2), - ["ComputeSharp.IReadWriteNormalizedTexture2D`1.Width"] = (2, 0), - ["ComputeSharp.IReadWriteNormalizedTexture2D`1.Height"] = (2, 1), - ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Width"] = (3, 0), - ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Height"] = (3, 1), - ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Depth"] = (3, 2) - }; + return new Dictionary + { + ["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0), + ["ComputeSharp.Resources.Texture2D`1.Width"] = (2, 0), + ["ComputeSharp.Resources.Texture2D`1.Height"] = (2, 1), + ["ComputeSharp.Resources.Texture3D`1.Width"] = (3, 0), + ["ComputeSharp.Resources.Texture3D`1.Height"] = (3, 1), + ["ComputeSharp.Resources.Texture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadOnlyTexture2D`1.Width"] = (2, 0), + ["ComputeSharp.IReadOnlyTexture2D`1.Height"] = (2, 1), + ["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0), + ["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1), + ["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Width"] = (2, 0), + ["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Height"] = (2, 1), + ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Width"] = (3, 0), + ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Height"] = (3, 1), + ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadWriteNormalizedTexture2D`1.Width"] = (2, 0), + ["ComputeSharp.IReadWriteNormalizedTexture2D`1.Height"] = (2, 1), + ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Width"] = (3, 0), + ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Height"] = (3, 1), + ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Depth"] = (3, 2) + }; + } /// static partial void AddKnownProperties(IDictionary knownProperties) @@ -175,47 +178,4 @@ partial class HlslKnownProperties } } } - - /// - /// Tries to get the mapped HLSL-compatible indexer resource type name for the input indexer name. - /// - /// The input fully qualified indexer name. - /// The mapped type name, if one is found. - /// The HLSL-compatible type name that can be used in an HLSL shader for the given indexer. - public static bool TryGetMappedResourceIndexerTypeName(string name, out string? mapped) - { - return KnownResourceIndexers.TryGetValue(name, out mapped); - } - - /// - /// Tries to get the mapped HLSL-compatible sampler resource type name for the input indexer name. - /// - /// The input fully qualified indexer name. - /// The mapped type name, if one is found. - /// The HLSL-compatible type name that can be used in an HLSL shader for the given sampler. - public static bool TryGetMappedResourceSamplerAccessType(string name, out string? mapped) - { - return KnownResourceSamplers.TryGetValue(name, out mapped); - } - - /// - /// Tries to get the mapped rank and axis for a given indexer name. - /// - /// The input fully qualified indexer name. - /// The resulting indexer rank, if found. - /// The resulting indexer axis, if found. - /// Whether or not a rank and axis could be resolved by the input indexer name. - public static bool TryGetAccessorRankAndAxis(string name, out int rank, out int axis) - { - if (KnownSizeAccessors.TryGetValue(name, out var info)) - { - (rank, axis) = info; - - return true; - } - - (rank, axis) = default((int, int)); - - return false; - } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 109e1b16..0018c6dc 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -41,7 +41,7 @@ partial class HlslKnownTypes "ComputeSharp.ConstantBuffer`1" or "ComputeSharp.ReadOnlyBuffer`1" or "ComputeSharp.ReadWriteBuffer`1" => true, - _ => false, + _ => false }; } @@ -63,7 +63,7 @@ partial class HlslKnownTypes "ComputeSharp.IReadOnlyTexture3D`1" => true, "ComputeSharp.IReadOnlyNormalizedTexture2D`1" or "ComputeSharp.IReadOnlyNormalizedTexture3D`1" => true, - _ => false, + _ => false }; } @@ -83,7 +83,7 @@ partial class HlslKnownTypes "ComputeSharp.ReadWriteTexture3D`2" or "ComputeSharp.IReadWriteNormalizedTexture2D`1" or "ComputeSharp.IReadWriteNormalizedTexture3D`1" => true, - _ => false, + _ => false }; } @@ -113,7 +113,7 @@ partial class HlslKnownTypes "ComputeSharp.IReadWriteNormalizedTexture2D`1" or "ComputeSharp.IReadOnlyNormalizedTexture3D`1" or "ComputeSharp.IReadWriteNormalizedTexture3D`1" => true, - _ => false, + _ => false }; } diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs index a3dad56d..074483ce 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs @@ -169,6 +169,73 @@ public partial class D2D1PixelShaderTests } } + [TestMethod] + public unsafe void GetResourceTextureDescriptions_Empty() + { + Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0); + + Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0); + } + + [TestMethod] + public unsafe void GetResourceTextureDescriptions_Custom() + { + ReadOnlyMemory resourceTextureDescriptions = D2D1PixelShader.GetResourceTextureDescriptions(); + + Assert.AreEqual(resourceTextureDescriptions.Length, 3); + + ReadOnlySpan span = resourceTextureDescriptions.Span; + + Assert.AreEqual(span[0].Index, 5); + Assert.AreEqual(span[0].Rank, 1); + + Assert.AreEqual(span[1].Index, 6); + Assert.AreEqual(span[1].Rank, 2); + + Assert.AreEqual(span[2].Index, 7); + Assert.AreEqual(span[2].Rank, 3); + } + + [D2DInputCount(4)] + [D2DInputSimple(0)] + [D2DInputSimple(2)] + [D2DInputComplex(1)] + [D2DInputComplex(3)] + [AutoConstructor] + partial struct ShaderWithResourceTextures : ID2D1PixelShader + { + float number; + + [D2DResourceTextureIndex(5)] + D2D1ResourceTexture1D myTexture1; + + [D2DResourceTextureIndex(6)] + D2D1ResourceTexture2D myTexture2; + + [D2DResourceTextureIndex(7)] + D2D1ResourceTexture3D myTexture3; + + public Float4 Execute() + { + float4 pixel1 = myTexture1[0]; + float4 pixel2 = myTexture1[0.4f]; + float4 pixel3 = myTexture2[0, 1]; + float4 pixel4 = myTexture2[0.4f, 0.3f]; + float4 pixel5 = myTexture3[0, 1, 2]; + float4 pixel6 = myTexture3[0.4f, 0.5f, 0.6f]; + + return 0; + } + } + [TestMethod] public unsafe void GetBytecode_FromEmbeddedBytecode() {