From 54d7cb53e2fab848ffad06b64313ca9ccfe1da26 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 8 May 2022 14:17:55 +0200 Subject: [PATCH 1/6] Add D2D1 input description types --- .../ComputeSharp.D2D1.SourceGenerators.csproj | 1 + .../D2DInputDescriptionAttribute.cs | 41 +++++++++++++ .../Attributes/Enums/D2D1Filter.cs | 57 +++++++++++++++++++ .../ID2D1InputDescriptionsLoader.cs | 18 ++++++ .../Interfaces/__Internals/ID2D1Shader.cs | 10 ++++ .../Shaders/Interop/D2D1InputDescription.cs | 41 +++++++++++++ .../um/d2d1effectauthor/D2D1_FILTER.cs | 21 +++++++ .../TerraFX.Interop.Windows.D2D1.projitems | 1 + 8 files changed, 190 insertions(+) create mode 100644 src/ComputeSharp.D2D1/Attributes/D2DInputDescriptionAttribute.cs create mode 100644 src/ComputeSharp.D2D1/Attributes/Enums/D2D1Filter.cs create mode 100644 src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1InputDescriptionsLoader.cs create mode 100644 src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs create mode 100644 src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_FILTER.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj index 3ca380e3..2716303d 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj @@ -77,6 +77,7 @@ + diff --git a/src/ComputeSharp.D2D1/Attributes/D2DInputDescriptionAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DInputDescriptionAttribute.cs new file mode 100644 index 00000000..8bafd59e --- /dev/null +++ b/src/ComputeSharp.D2D1/Attributes/D2DInputDescriptionAttribute.cs @@ -0,0 +1,41 @@ +using System; + +namespace ComputeSharp.D2D1; + +/// +/// An attribute for a D2D1 shader indicating the description of a given input resource. +/// This attribute is optional, and not using it will cause no description to be declared. +/// +/// +/// This attribute exposes the options that can be set via D2D1_INPUT_DESCRIPTION. +/// For more info, see . +/// +[AttributeUsage(AttributeTargets.Struct, AllowMultiple = true)] +public sealed class D2DInputDescriptionAttribute : Attribute +{ + /// + /// Creates a new instance of the type with the specified arguments. + /// + /// The index of the resource to declare the description for. + /// The type of filter to apply to the input texture. + public D2DInputDescriptionAttribute(int index, D2D1Filter filter) + { + Index = index; + Filter = filter; + } + + /// + /// Gets the index of the resource to declare the description for. + /// + public int Index { get; } + + /// + /// Gets the type of filter to apply to the input texture. + /// + public D2D1Filter Filter { get; } + + /// + /// Gets the mip level to retrieve from the upstream transform, if specified. + /// + public int LevelOfDetail { get; init; } +} diff --git a/src/ComputeSharp.D2D1/Attributes/Enums/D2D1Filter.cs b/src/ComputeSharp.D2D1/Attributes/Enums/D2D1Filter.cs new file mode 100644 index 00000000..29a6b9fa --- /dev/null +++ b/src/ComputeSharp.D2D1/Attributes/Enums/D2D1Filter.cs @@ -0,0 +1,57 @@ +using static TerraFX.Interop.DirectX.D2D1_FILTER; + +namespace ComputeSharp.D2D1; + +/// +/// Represents the filtering mode that a transform may select to use on input textures. +/// +/// +/// This type exposes the available values in . +/// +public enum D2D1Filter +{ + /// + /// Use point sampling for minification, magnification, and mip-level sampling. + /// + MinMagMipPoint = (int)D2D1_FILTER_MIN_MAG_MIP_POINT, + + /// + /// Use point sampling for minification and magnification, use linear interpolation for mip-level sampling. + /// + MinMagPointMipLinear = (int)D2D1_FILTER_MIN_MAG_POINT_MIP_LINEAR, + + /// + /// Use point sampling for minification, use linear interpolation for magnification, use point sampling for mip-level sampling. + /// + MinPointMagLinearMipPoint = (int)D2D1_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT, + + /// + /// Use point sampling for minification, use linear interpolation for magnification and mip-level sampling. + /// + MinPointMagMipLinear = (int)D2D1_FILTER_MIN_POINT_MAG_MIP_LINEAR, + + /// + /// Use linear interpolation for minification, use point sampling for magnification and mip-level sampling. + /// + MinLinearMagMipPoint = (int)D2D1_FILTER_MIN_LINEAR_MAG_MIP_POINT, + + /// + /// Use linear interpolation for minification, use point sampling for magnification, use linear interpolation for mip-level sampling. + /// + MinLinearMagPointMinLinear = (int)D2D1_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR, + + /// + /// Use linear interpolation for minification and magnification, use point sampling for mip-level sampling. + /// + MinMagLinearMipPoint = (int)D2D1_FILTER_MIN_MAG_LINEAR_MIP_POINT, + + /// + /// Use linear interpolation for minification, magnification, and mip-level sampling. + /// + MinMagMipLinear = (int)D2D1_FILTER_MIN_MAG_MIP_LINEAR, + + /// + /// Use anisotropic interpolation for minification, magnification, and mip-level sampling. + /// + Anisotropic = (int)D2D1_FILTER_ANISOTROPIC +} diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1InputDescriptionsLoader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1InputDescriptionsLoader.cs new file mode 100644 index 00000000..b5ebd493 --- /dev/null +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1InputDescriptionsLoader.cs @@ -0,0 +1,18 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.D2D1.__Internals; + +/// +/// A base representing a loader for input descriptions in a D2D1 shader. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +[Obsolete("This interface is not intended to be used directly by user code")] +public interface ID2D1InputDescriptionsLoader +{ + /// + /// Loads the available input descriptions for the shader. + /// + /// The sequence of serialized input descriptions. + void LoadInputDescriptions(ReadOnlySpan data); +} diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs index 035d7b52..11cd5ae3 100644 --- a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs @@ -37,6 +37,16 @@ public interface ID2D1Shader [Obsolete("This method is not intended to be used directly by user code")] uint GetInputType(uint index); + /// + /// Loads the input descriptions for the shader, if any. + /// + /// The type of input descriptions loader being used. + /// The instance to use to load the input descriptions. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be used directly by user code")] + void LoadInputDescriptions(ref TLoader loader) + where TLoader : struct, ID2D1InputDescriptionsLoader; + /// /// Gets the output buffer precision and depth for the shader. /// diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs new file mode 100644 index 00000000..4566f288 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs @@ -0,0 +1,41 @@ +using System; + +namespace ComputeSharp.D2D1.Interop; + +/// +/// A type containing info on a description for a given D2D1 pixel shader input resource. +/// +/// +/// This type exposes the values that can be set via ID2D1RenderInfo::SetInputDescription. +/// For more info, see . +/// +public readonly struct D2D1InputDescription +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The index of the resource the description belongs to. + /// The type of filter to apply to the input texture. + /// The mip level to retrieve from the upstream transform, if specified. + internal D2D1InputDescription(int index, D2D1Filter filter, int levelOfDetail) + { + Index = index; + Filter = filter; + LevelOfDetail = levelOfDetail; + } + + /// + /// Gets the index of the resource the description belongs to. + /// + public int Index { get; } + + /// + /// Gets the type of filter to apply to the input texture. + /// + public D2D1Filter Filter { get; } + + /// + /// Gets the mip level to retrieve from the upstream transform, if specified. + /// + public int LevelOfDetail { get; } +} diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_FILTER.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_FILTER.cs new file mode 100644 index 00000000..7f6d604c --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_FILTER.cs @@ -0,0 +1,21 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.DirectX +{ + internal enum D2D1_FILTER : uint + { + D2D1_FILTER_MIN_MAG_MIP_POINT = 0x00, + D2D1_FILTER_MIN_MAG_POINT_MIP_LINEAR = 0x01, + D2D1_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x04, + D2D1_FILTER_MIN_POINT_MAG_MIP_LINEAR = 0x05, + D2D1_FILTER_MIN_LINEAR_MAG_MIP_POINT = 0x10, + D2D1_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11, + D2D1_FILTER_MIN_MAG_LINEAR_MIP_POINT = 0x14, + D2D1_FILTER_MIN_MAG_MIP_LINEAR = 0x15, + D2D1_FILTER_ANISOTROPIC = 0x55, + D2D1_FILTER_FORCE_DWORD = 0xffffffff + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems index 70a7135d..da6f98fe 100644 --- a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems +++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems @@ -11,6 +11,7 @@ + From 3b760f02d45017c4cfb021f9fe371b3d7fb226be Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 8 May 2022 15:39:40 +0200 Subject: [PATCH 2/6] Enable generation for ID2D1Shader.LoadInputDescriptions API --- .../AnalyzerReleases.Shipped.md | 2 + .../ComputeSharp.D2D1.SourceGenerators.csproj | 1 + .../Diagnostics/DiagnosticDescriptors.cs | 32 ++++ ...haderGenerator.CreateGetInputTypeMethod.cs | 2 +- ...reateLoadInputDescriptionsMethod.Syntax.cs | 148 ++++++++++++++++++ ...rator.CreateLoadInputDescriptionsMethod.cs | 90 +++++++++++ .../ID2D1ShaderGenerator.cs | 36 +++++ .../Models/InputDescription.cs | 9 ++ .../Models/InputDescriptionsInfo.cs | 31 ++++ .../ComputeSharp.SourceGeneration.projitems | 1 + .../Extensions/AttributeDataExtensions.cs | 35 +++++ 11 files changed, 386 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs create mode 100644 src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md index 6cbb9ede..89d1c79e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md @@ -48,3 +48,5 @@ CMPSD2D0038 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github CMPSD2D0039 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0040 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0041 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0042 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0043 | 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 2716303d..878c9c54 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj @@ -67,6 +67,7 @@ + diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 1ad3ab02..9a54a56e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -586,4 +586,36 @@ internal static class DiagnosticDescriptors isEnabledByDefault: true, description: "D2D1 shaders can only use supported types (some .NET primitives and vector types, HLSL primitive, vector and matrix types, and custom types containing these types can be used).", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a shader with an out of range input description index (or more). + /// + /// Format: "The D2D1 shader of type {0} is using some out of range input description indices". + /// + /// + public static readonly DiagnosticDescriptor OutOfRangeInputDescriptionIndex = new DiagnosticDescriptor( + id: "CMPSD2D0042", + title: "Our 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, + isEnabledByDefault: true, + description: "A D2D1 shader must have all the indices of its input descriptions in the valid range (between 0 and the number of declared inputs).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for repeated indices for D2D input descriptions. + /// + /// Format: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputDescription] attributes". + /// + /// + public static readonly DiagnosticDescriptor RepeatedD2DInputDescriptionIndices = new DiagnosticDescriptor( + id: "CMPSD2D0043", + title: "Repeated D2D1 shader input description indices", + messageFormat: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputDescription] attributes", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A D2D1 shader must only have unique indices for all of its [D2DInputDescription] attributes.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs index f4798fdf..5c45d3a8 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs @@ -19,12 +19,12 @@ partial class ID2D1ShaderGenerator /// /// Extracts the input info for the current shader. /// - /// The collection of produced instances. /// The input instance to process. /// The number of shader inputs to declare. /// The indicess of the simple shader inputs. /// The indices of the complex shader inputs. /// The combined and serialized input types for each available input. + /// The collection of produced instances. public static void GetInfo( INamedTypeSymbol structDeclarationSymbol, out int inputCount, diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs new file mode 100644 index 00000000..8d4ae132 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs @@ -0,0 +1,148 @@ +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 LoadInputDescriptions + { + /// + /// Creates a instance for the LoadInputDescriptions method. + /// + /// The input descriptions info gathered for the current shader. + /// The resulting instance for the LoadInputDescriptions method. + public static MethodDeclarationSyntax GetSyntax(InputDescriptionsInfo inputDescriptionsInfo) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadInputDescriptions(ref TLoader loader) + // { + // + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(LoadInputDescriptions))) + .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(inputDescriptionsInfo.InputDescriptions))); + } + + /// + /// 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. + private static ImmutableArray GetInputDescriptionsLoadingStatements(ImmutableArray inputDescriptions) + { + // If there are no input descriptions available, just load an empty buffer + if (inputDescriptions.IsEmpty) + { + // loader.LoadInputDescriptions(default); + return + ImmutableArray.Create( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadInputDescriptions"))) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword)))))); + } + + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + + // The size of the buffer with the input descriptions is the number of input descriptions, times the size of each + // input description, which is a struct containing three int-sized fields (index, filter, and level of detail). + int inputDescriptionSizeInBytes = inputDescriptions.Length * sizeof(int) * 3; + + // 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(inputDescriptionSizeInBytes))))))))))); + + // 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 input description + foreach (InputDescription inputDescription in inputDescriptions) + { + // Write the index of the current input 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)inputDescription.Index))))); + + // Write the filter of the current input 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)inputDescription.Filter))))); + + // Write the level of detail of the current input description: + // + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint) + 8)) = ; + statements.Add(ExpressionStatement( + 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))))); + + offset += sizeof(int) * 3; + } + + // loader.LoadInputDescriptions(data); + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadInputDescriptions"))) + .AddArgumentListArguments(Argument(IdentifierName("data"))))); + + return statements.ToImmutable(); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs new file mode 100644 index 00000000..44f3fc46 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +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 LoadInputDescriptions method. + /// + private static partial class LoadInputDescriptions + { + /// + /// Extracts the input descriptions for the current shader. + /// + /// The input instance to process. + /// The produced input descriptions for the shader. + /// The collection of produced instances. + public static void GetInfo( + INamedTypeSymbol structDeclarationSymbol, + out ImmutableArray inputDescriptions, + out ImmutableArray diagnostics) + { + int inputCount = 0; + ImmutableArray.Builder inputDescriptionsBuilder = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder diagnosticsBuilder = ImmutableArray.CreateBuilder(); + + foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes()) + { + switch (attributeData.AttributeClass?.GetFullMetadataName()) + { + case "ComputeSharp.D2D1.D2DInputCountAttribute": + inputCount = (int)attributeData.ConstructorArguments[0].Value!; + break; + case "ComputeSharp.D2D1.D2DInputDescriptionAttribute": + if (attributeData.ConstructorArguments.Length == 2) + { + int index = (int)attributeData.ConstructorArguments[0].Value!; + D2D1Filter filter = (D2D1Filter)attributeData.ConstructorArguments[1].Value!; + + _ = attributeData.TryGetNamedArgument("LevelOfDetail", out int levelOfDetail); + + inputDescriptionsBuilder.Add(new InputDescription((uint)index, filter, levelOfDetail)); + } + break; + default: + break; + } + } + + inputDescriptions = ImmutableArray.Empty; + + // Validate the input count (ignore if invalid, this will be validated by the HLSL source generator) + if (inputCount is not (>= 0 and <= 8)) + { + goto End; + } + + // All simple indices must be in range + if (inputDescriptionsBuilder.Any(description => description.Index >= inputCount)) + { + diagnosticsBuilder.Add(OutOfRangeInputDescriptionIndex, structDeclarationSymbol, structDeclarationSymbol); + + goto End; + } + + HashSet inputDescriptionIndices = new(inputDescriptionsBuilder.Select(description => description.Index)); + + // All input description indices must be unique + if (inputDescriptionIndices.Count != inputDescriptionsBuilder.Count) + { + diagnosticsBuilder.Add(RepeatedD2DInputDescriptionIndices, structDeclarationSymbol, structDeclarationSymbol); + + goto End; + } + + inputDescriptions = inputDescriptionsBuilder.ToImmutable(); + + End: + diagnostics = diagnosticsBuilder.ToImmutable(); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index a972cbf5..b3314ae2 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -269,5 +269,41 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetOutputBuffer)}", compilationUnit.ToFullString()); }); + + // Get the input description data, which can also be computed separately from all other generation steps. + IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result Info)> inputDescriptionsInfoWithErrors = + shaderDeclarations + .Select(static (item, token) => + { + // LoadInputDescriptions() info + LoadInputDescriptions.GetInfo( + item.Symbol, + out ImmutableArray inputDescriptions, + out ImmutableArray diagnostics); + + token.ThrowIfCancellationRequested(); + + InputDescriptionsInfo inputDescriptionsInfo = new(inputDescriptions); + + return (item.Hierarchy, new Result(inputDescriptionsInfo, diagnostics)); + }); + + // Output the diagnostics + context.ReportDiagnostics(inputDescriptionsInfoWithErrors.Select(static (item, token) => item.Info.Errors)); + + // Get the filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputDescriptionsInfo Info)> inputDescriptionsInfo = + inputDescriptionsInfoWithErrors + .Select(static (item, token) => (item.Hierarchy, item.Info.Value)) + .WithComparers(HierarchyInfo.Comparer.Default, InputDescriptionsInfo.Comparer.Default); + + // Generate the LoadInputDescriptions() methods + context.RegisterSourceOutput(inputDescriptionsInfo.Combine(canUseSkipLocalsInit), static (context, item) => + { + MethodDeclarationSyntax loadInputDescriptionsMethod = LoadInputDescriptions.GetSyntax(item.Left.Info); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadInputDescriptionsMethod, item.Right); + + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadInputDescriptions)}", compilationUnit.ToFullString()); + }); } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs new file mode 100644 index 00000000..29d20cc9 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs @@ -0,0 +1,9 @@ +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing an input description for a shader. +/// +/// The index of the input resource the description if 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 new file mode 100644 index 00000000..3ac7001b --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.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 input descriptions for a shader. +/// +/// The input types for a given shader. +internal sealed record InputDescriptionsInfo(ImmutableArray InputDescriptions) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, InputDescriptionsInfo obj) + { + hashCode.AddRange(obj.InputDescriptions); + } + + /// + protected override bool AreEqual(InputDescriptionsInfo x, InputDescriptionsInfo y) + { + return x.InputDescriptions.SequenceEqual(y.InputDescriptions); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index 30b2bcf1..948079f9 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -9,6 +9,7 @@ ComputeSharp.SourceGeneration + diff --git a/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs new file mode 100644 index 00000000..37436b1c --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGeneration.Extensions; + +/// +/// Extension methods for the type. +/// +internal static class AttributeDataExtensions +{ + /// + /// Tries to get a given named argument value from an instance, if present. + /// + /// The type of argument to check. + /// The target instance to check. + /// The name of the argument to check. + /// The resulting argument value, if present. + /// Whether or not contains an argument named with a valid value. + public static bool TryGetNamedArgument(this AttributeData attributeData, string name, out T? value) + { + foreach (KeyValuePair properties in attributeData.NamedArguments) + { + if (properties.Key == name) + { + value = (T?)properties.Value.Value; + + return true; + } + } + + value = default; + + return false; + } +} From 7a5386a55e2642a1daf5e8bdb85f171c98dface0 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 8 May 2022 15:51:27 +0200 Subject: [PATCH 3/6] Add D2D1PixelShader.GetInputDescriptions API --- .../Shaders/Interop/D2D1PixelShader.cs | 19 +++++++++- .../Shaders/Interop/D2D1PixelShaderEffect.cs | 2 +- .../Shaders/Interop/D2D1ReflectionServices.cs | 2 +- .../D2D1ByteArrayDispatchDataLoader.cs | 6 +-- .../D2D1ByteArrayInputDescriptionsLoader.cs | 37 +++++++++++++++++++ .../D2D1DrawInfoDispatchDataLoader.cs | 4 +- .../D2D1EffectDispatchDataLoader.cs | 4 +- .../D2D1ShaderBytecodeLoader.cs | 7 ++-- 8 files changed, 68 insertions(+), 13 deletions(-) rename src/ComputeSharp.D2D1/Shaders/{Dispatching => Loaders}/D2D1ByteArrayDispatchDataLoader.cs (82%) create mode 100644 src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayInputDescriptionsLoader.cs rename src/ComputeSharp.D2D1/Shaders/{Dispatching => Loaders}/D2D1DrawInfoDispatchDataLoader.cs (90%) rename src/ComputeSharp.D2D1/Shaders/{Dispatching => Loaders}/D2D1EffectDispatchDataLoader.cs (91%) rename src/ComputeSharp.D2D1/Shaders/{Dispatching => Loaders}/D2D1ShaderBytecodeLoader.cs (91%) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs index 1082ba7a..b0ec5b48 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs @@ -1,8 +1,8 @@ using System; using System.Runtime.CompilerServices; using ComputeSharp.D2D1.Helpers; -using ComputeSharp.D2D1.Shaders.Dispatching; using ComputeSharp.D2D1.Shaders.Interop.Buffers; +using ComputeSharp.D2D1.Shaders.Loaders; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -113,6 +113,23 @@ public static class D2D1PixelShader return (D2D1PixelShaderInputType)shader.GetInputType((uint)index); } + /// + /// Gets the available input descriptions for a D2D1 pixel shader. + /// + /// The type of D2D1 pixel shader to get the input descriptions for. + /// A with the available input descriptions for the shader. + public static ReadOnlyMemory GetInputDescriptions() + where T : unmanaged, ID2D1PixelShader + { + D2D1ByteArrayInputDescriptionsLoader inputDescriptionsLoader = default; + + Unsafe.SkipInit(out T shader); + + shader.LoadInputDescriptions(ref inputDescriptionsLoader); + + return inputDescriptionsLoader.GetResultingInputDescriptions(); + } + /// /// Gets the buffer precision for the output buffer of a D2D1 pixel shader. /// diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs index 3600b928..3c1c813e 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -8,8 +8,8 @@ using System.Text; using ComputeSharp.D2D1.Extensions; using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop.Effects; -using ComputeSharp.D2D1.Shaders.Dispatching; using ComputeSharp.D2D1.Shaders.Interop.Buffers; +using ComputeSharp.D2D1.Shaders.Loaders; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs index c70d4d1e..f82b577c 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs @@ -2,7 +2,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.D2D1.Extensions; -using ComputeSharp.D2D1.Shaders.Dispatching; +using ComputeSharp.D2D1.Shaders.Loaders; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; diff --git a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayDispatchDataLoader.cs similarity index 82% rename from src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs rename to src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayDispatchDataLoader.cs index 2b00632a..9e2d13b7 100644 --- a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayDispatchDataLoader.cs @@ -6,7 +6,7 @@ using TerraFX.Interop.DirectX; #pragma warning disable CS0618 -namespace ComputeSharp.D2D1.Shaders.Dispatching; +namespace ComputeSharp.D2D1.Shaders.Loaders; /// /// A data loader for D2D1 pixel shaders dispatched via . @@ -14,7 +14,7 @@ namespace ComputeSharp.D2D1.Shaders.Dispatching; internal struct D2D1ByteArrayDispatchDataLoader : ID2D1DispatchDataLoader { /// - /// The object in use. + /// The resulting array with the constant buffer to use. /// private byte[]? data; @@ -29,7 +29,7 @@ internal struct D2D1ByteArrayDispatchDataLoader : ID2D1DispatchDataLoader } /// - public void LoadConstantBuffer(ReadOnlySpan data) + void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan data) { this.data = MemoryMarshal.AsBytes(data).ToArray(); } diff --git a/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayInputDescriptionsLoader.cs b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayInputDescriptionsLoader.cs new file mode 100644 index 00000000..f3a65c2f --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ByteArrayInputDescriptionsLoader.cs @@ -0,0 +1,37 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.Interop; +using TerraFX.Interop.DirectX; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Shaders.Loaders; + +/// +/// An input descriptions loader for D2D1 pixel shaders. +/// +internal struct D2D1ByteArrayInputDescriptionsLoader : ID2D1InputDescriptionsLoader +{ + /// + /// The object in use. + /// + private D2D1InputDescription[]? inputDescriptions; + + /// + /// Gets the resulting input descriptions. + /// + /// A array with the available input descriptions. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public D2D1InputDescription[] GetResultingInputDescriptions() + { + return this.inputDescriptions!; + } + + /// + void ID2D1InputDescriptionsLoader.LoadInputDescriptions(ReadOnlySpan data) + { + this.inputDescriptions = MemoryMarshal.Cast(data).ToArray(); + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1DrawInfoDispatchDataLoader.cs similarity index 90% rename from src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs rename to src/ComputeSharp.D2D1/Shaders/Loaders/D2D1DrawInfoDispatchDataLoader.cs index be47d04c..65142fcd 100644 --- a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1DrawInfoDispatchDataLoader.cs @@ -6,7 +6,7 @@ using TerraFX.Interop.DirectX; #pragma warning disable CS0618 -namespace ComputeSharp.D2D1.Shaders.Dispatching; +namespace ComputeSharp.D2D1.Shaders.Loaders; /// /// A data loader for D2D1 pixel shaders dispatched via . @@ -29,7 +29,7 @@ internal readonly unsafe struct D2D1DrawInfoDispatchDataLoader : ID2D1DispatchDa } /// - public void LoadConstantBuffer(ReadOnlySpan data) + void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan data) { this.d2D1DrawInfo->SetPixelShaderConstantBuffer( buffer: (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data)), diff --git a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1EffectDispatchDataLoader.cs b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1EffectDispatchDataLoader.cs similarity index 91% rename from src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1EffectDispatchDataLoader.cs rename to src/ComputeSharp.D2D1/Shaders/Loaders/D2D1EffectDispatchDataLoader.cs index 69b06622..ce3b0385 100644 --- a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1EffectDispatchDataLoader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1EffectDispatchDataLoader.cs @@ -7,7 +7,7 @@ using TerraFX.Interop.DirectX; #pragma warning disable CS0618 -namespace ComputeSharp.D2D1.Shaders.Dispatching; +namespace ComputeSharp.D2D1.Shaders.Loaders; /// /// A data loader for D2D1 pixel shaders dispatched via . @@ -30,7 +30,7 @@ internal readonly unsafe struct D2D1EffectDispatchDataLoader : ID2D1DispatchData } /// - public void LoadConstantBuffer(ReadOnlySpan data) + void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan data) { if (data.IsEmpty) { diff --git a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ShaderBytecodeLoader.cs similarity index 91% rename from src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs rename to src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ShaderBytecodeLoader.cs index 0d0da779..4db265a3 100644 --- a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ShaderBytecodeLoader.cs @@ -9,7 +9,7 @@ using TerraFX.Interop.Windows; #pragma warning disable CS0618 -namespace ComputeSharp.D2D1.Shaders.Dispatching; +namespace ComputeSharp.D2D1.Shaders.Loaders; /// /// A bytecode loader for D2D1 shaders. @@ -46,7 +46,8 @@ internal unsafe struct D2D1ShaderBytecodeLoader : ID2D1BytecodeLoader } /// - public unsafe void LoadDynamicBytecode(IntPtr handle) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + unsafe void ID2D1BytecodeLoader.LoadDynamicBytecode(IntPtr handle) { if (this.embeddedBytecodePtr is not null || this.d3DBlob.Get() is not null) @@ -64,7 +65,7 @@ internal unsafe struct D2D1ShaderBytecodeLoader : ID2D1BytecodeLoader /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void LoadEmbeddedBytecode(ReadOnlySpan bytecode) + void ID2D1BytecodeLoader.LoadEmbeddedBytecode(ReadOnlySpan bytecode) { if (this.embeddedBytecodePtr is not null || this.d3DBlob.Get() is not null) From ecae463892d8a9fea8e9d1830c40e3114d7c5d8f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 8 May 2022 15:58:39 +0200 Subject: [PATCH 4/6] Add unit tests for input description APIs --- .../D2D1InteropServicesTests.cs | 69 ++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1InteropServicesTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1InteropServicesTests.cs index 3e6d1919..9b9f24c2 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1InteropServicesTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1InteropServicesTests.cs @@ -1,4 +1,5 @@ -using ComputeSharp.D2D1.Interop; +using System; +using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Tests.Effects; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -99,4 +100,70 @@ public partial class D2D1InteropServicesTests return 0; } } + + [TestMethod] + public unsafe void GetInputDescriptions_Empty() + { + Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0); + + Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0); + Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0); + } + + [TestMethod] + public unsafe void GetInputDescriptions_Custom() + { + ReadOnlyMemory inputDescriptions = D2D1PixelShader.GetInputDescriptions(); + + Assert.AreEqual(inputDescriptions.Length, 5); + + ReadOnlySpan span = inputDescriptions.Span; + + Assert.AreEqual(span[0].Index, 0); + Assert.AreEqual(span[0].Filter, D2D1Filter.MinPointMagLinearMipPoint); + Assert.AreEqual(span[0].LevelOfDetail, 0); + + Assert.AreEqual(span[1].Index, 1); + Assert.AreEqual(span[1].Filter, D2D1Filter.Anisotropic); + Assert.AreEqual(span[1].LevelOfDetail, 0); + + Assert.AreEqual(span[2].Index, 2); + Assert.AreEqual(span[2].Filter, D2D1Filter.MinLinearMagPointMinLinear); + Assert.AreEqual(span[2].LevelOfDetail, 4); + + Assert.AreEqual(span[3].Index, 5); + Assert.AreEqual(span[3].Filter, D2D1Filter.MinMagPointMipLinear); + Assert.AreEqual(span[3].LevelOfDetail, 0); + + Assert.AreEqual(span[4].Index, 6); + Assert.AreEqual(span[4].Filter, D2D1Filter.MinPointMagMipLinear); + Assert.AreEqual(span[4].LevelOfDetail, 3); + } + + [D2DInputCount(7)] + [D2DInputSimple(0)] + [D2DInputSimple(2)] + [D2DInputComplex(1)] + [D2DInputComplex(3)] + [D2DInputComplex(5)] + [D2DInputSimple(6)] + [D2DInputDescription(0, D2D1Filter.MinPointMagLinearMipPoint)] + [D2DInputDescription(1, D2D1Filter.Anisotropic)] + [D2DInputDescription(2, D2D1Filter.MinLinearMagPointMinLinear, LevelOfDetail = 4)] + [D2DInputDescription(5, D2D1Filter.MinMagPointMipLinear)] + [D2DInputDescription(6, D2D1Filter.MinPointMagMipLinear, LevelOfDetail = 3)] + partial struct ShaderWithInputDescriptions : ID2D1PixelShader + { + public Float4 Execute() + { + return 0; + } + } } \ No newline at end of file From 69448a8d3471d6d1b86a88447d24610d2a81af9d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 8 May 2022 16:13:04 +0200 Subject: [PATCH 5/6] Enable input descriptions info in D2D1PixelShaderEffect --- .../Effects/PixelShaderEffect.For{T}.cs | 27 ++++++++++++++++--- ...lShaderEffect.ID2D1DrawTransformMethods.cs | 27 ++++++++++++++++++- .../Interop/Effects/PixelShaderEffect.cs | 20 ++++++++++++++ .../D2D1_INPUT_DESCRIPTION.cs | 15 +++++++++++ .../um/d2d1effectauthor/ID2D1DrawInfo.cs | 7 +++++ .../TerraFX.Interop.Windows.D2D1.projitems | 1 + 6 files changed, 93 insertions(+), 4 deletions(-) create mode 100644 src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_INPUT_DESCRIPTION.cs diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs index 576b567b..57addcbc 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs @@ -54,6 +54,16 @@ internal unsafe partial struct PixelShaderEffect /// private static D2D1PixelShaderInputType* inputTypes; + /// + /// The number of available input descriptions. + /// + private static int inputDescriptionCount; + + /// + /// The buffer with the available input descriptions for the shader. + /// + private static D2D1InputDescription* inputDescriptions; + /// /// The shader bytecode. /// @@ -104,8 +114,8 @@ internal unsafe partial struct PixelShaderEffect { // Load all shader properties Guid shaderId = typeof(T).GUID; - ReadOnlyMemory buffer = D2D1PixelShader.LoadBytecode(); - int bytecodeSize = buffer.Length; + ReadOnlyMemory bytecodeInfo = D2D1PixelShader.LoadBytecode(); + int bytecodeSize = bytecodeInfo.Length; byte* bytecode = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), bytecodeSize); D2D1BufferPrecision bufferPrecision = D2D1PixelShader.GetOutputBufferPrecision(); D2D1ChannelDepth channelDepth = D2D1PixelShader.GetOutputBufferChannelDepth(); @@ -119,13 +129,22 @@ internal unsafe partial struct PixelShaderEffect inputTypes[i] = D2D1PixelShader.GetInputType(i); } + // Prepare the input descriptions + ReadOnlyMemory inputDescriptionsInfo = D2D1PixelShader.GetInputDescriptions(); + int inputDescriptionCount = inputDescriptionsInfo.Length; + D2D1InputDescription* inputDescriptions = (D2D1InputDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), inputDescriptionCount); + + inputDescriptionsInfo.Span.CopyTo(new Span(inputDescriptions, inputDescriptionCount)); + // Copy the bytecode to the target buffer - buffer.Span.CopyTo(new Span(bytecode, bytecodeSize)); + bytecodeInfo.Span.CopyTo(new Span(bytecode, bytecodeSize)); // Set the shared state and mark the type as initialized For.shaderId = shaderId; For.inputCount = inputCount; For.inputTypes = inputTypes; + For.inputDescriptionCount = inputDescriptionCount; + For.inputDescriptions = inputDescriptions; For.bytecode = bytecode; For.bytecodeSize = bytecodeSize; For.bufferPrecision = bufferPrecision; @@ -207,6 +226,8 @@ internal unsafe partial struct PixelShaderEffect shaderId, inputCount, inputTypes, + inputDescriptionCount, + inputDescriptions, bytecode, bytecodeSize, bufferPrecision, diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs index fbfbb0c5..9af7e953 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs @@ -331,13 +331,38 @@ partial struct PixelShaderEffect return hresult; } + // If any input descriptions are present, set them + if (@this->inputDescriptionCount > 0) + { + for (int i = 0; i < @this->inputDescriptionCount; i++) + { + ref D2D1InputDescription inputDescription = ref @this->inputDescriptions[i]; + + D2D1_INPUT_DESCRIPTION d2D1InputDescription; + d2D1InputDescription.filter = (D2D1_FILTER)inputDescription.Filter; + d2D1InputDescription.levelOfDetailCount = (uint)inputDescription.LevelOfDetail; + + hresult = drawInfo->SetInputDescription((uint)inputDescription.Index, d2D1InputDescription); + + if (hresult != S.S_OK) + { + return hresult; + } + } + } + // If a custom buffer precision or channel depth is requested, set it if (@this->bufferPrecision != D2D1BufferPrecision.Unknown || @this->channelDepth != D2D1ChannelDepth.Default) { - return drawInfo->SetOutputBuffer( + hresult = drawInfo->SetOutputBuffer( (D2D1_BUFFER_PRECISION)@this->bufferPrecision, (D2D1_CHANNEL_DEPTH)@this->channelDepth); + + if (hresult != S.S_OK) + { + return hresult; + } } return S.S_OK; diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs index af5e1537..e330ab71 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs @@ -161,6 +161,20 @@ internal unsafe partial struct PixelShaderEffect /// private D2D1PixelShaderInputType* inputTypes; + /// + /// The number of available input descriptions. + /// + private int inputDescriptionCount; + + /// + /// The buffer with the available input descriptions for the shader. + /// + /// + /// This buffer is also shared among effect instances, so it should not be released. It is + /// owned by , which will release it when the target type is unloaded. + /// + private D2D1InputDescription* inputDescriptions; + /// /// The shader bytecode. /// @@ -197,6 +211,8 @@ internal unsafe partial struct PixelShaderEffect /// The for the shader. /// The number of inputs for the shader. /// The buffer with the types of inputs for the shader. + /// The number of available input descriptions. + /// The buffer with the available input descriptions for the shader. /// The shader bytecode. /// The size of . /// The buffer precision for the resulting output buffer. @@ -208,6 +224,8 @@ internal unsafe partial struct PixelShaderEffect Guid shaderId, int inputCount, D2D1PixelShaderInputType* inputTypes, + int inputDescriptionCount, + D2D1InputDescription* inputDescriptions, byte* bytecode, int bytecodeSize, D2D1BufferPrecision bufferPrecision, @@ -225,6 +243,8 @@ internal unsafe partial struct PixelShaderEffect @this->shaderId = shaderId; @this->inputCount = inputCount; @this->inputTypes = inputTypes; + @this->inputDescriptionCount = inputDescriptionCount; + @this->inputDescriptions = inputDescriptions; @this->bytecode = bytecode; @this->bytecodeSize = bytecodeSize; @this->bufferPrecision = bufferPrecision; diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_INPUT_DESCRIPTION.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_INPUT_DESCRIPTION.cs new file mode 100644 index 00000000..0da17fd0 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_INPUT_DESCRIPTION.cs @@ -0,0 +1,15 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.DirectX +{ + internal partial struct D2D1_INPUT_DESCRIPTION + { + public D2D1_FILTER filter; + + [NativeTypeName("UINT32")] + public uint levelOfDetailCount; + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawInfo.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawInfo.cs index 76105584..bd4d7036 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawInfo.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawInfo.cs @@ -20,6 +20,13 @@ namespace TerraFX.Interop.DirectX { public void** lpVtbl; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(3)] + public HRESULT SetInputDescription([NativeTypeName("UINT32")] uint inputIndex, D2D1_INPUT_DESCRIPTION inputDescription) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[3]))((ID2D1DrawInfo*)Unsafe.AsPointer(ref this), inputIndex, inputDescription); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(4)] public HRESULT SetOutputBuffer(D2D1_BUFFER_PRECISION bufferPrecision, D2D1_CHANNEL_DEPTH channelDepth) diff --git a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems index da6f98fe..9668e5d7 100644 --- a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems +++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems @@ -14,6 +14,7 @@ + From 7e31359785c65b8d8f875ec7df7801b553141b99 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 8 May 2022 18:44:44 +0200 Subject: [PATCH 6/6] Add user friendly remarks to D2D1Filter --- src/ComputeSharp.D2D1/Attributes/Enums/D2D1Filter.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/ComputeSharp.D2D1/Attributes/Enums/D2D1Filter.cs b/src/ComputeSharp.D2D1/Attributes/Enums/D2D1Filter.cs index 29a6b9fa..986e7e55 100644 --- a/src/ComputeSharp.D2D1/Attributes/Enums/D2D1Filter.cs +++ b/src/ComputeSharp.D2D1/Attributes/Enums/D2D1Filter.cs @@ -6,6 +6,14 @@ namespace ComputeSharp.D2D1; /// Represents the filtering mode that a transform may select to use on input textures. /// /// +/// +/// In most scenarios, or when unsure on what values to use, consider this reference: +/// +/// : point sampling. +/// : linear sampling. +/// +/// Other values can be used when explicit fine grained control is needed on how inputs are sampled. +/// /// This type exposes the available values in . /// public enum D2D1Filter