diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md index 2678d236..f0709b41 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md @@ -58,3 +58,9 @@ CMPSD2D0048 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github CMPSD2D0049 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0050 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0051 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0052 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0053 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0054 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0055 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0056 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0057 | 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 ec2e545f..2af1c50f 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj @@ -64,6 +64,7 @@ + @@ -71,11 +72,12 @@ - + + diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs new file mode 100644 index 00000000..93ef05c5 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs @@ -0,0 +1,104 @@ +using System; +using System.Linq; +using System.Text; +using ComputeSharp.D2D1.SourceGenerators.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class D2DPixelShaderSourceGenerator +{ + /// + partial class Execute + { + /// + /// Creates a instance for the TryGetBytecode method. + /// + /// The input bytecode info. + /// An opaque instance to transform the final tree into text. + /// The resulting instance for the target method. + public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeMethodInfo bytecodeInfo, out Func fixup) + { + // Get the TypeSyntax for the return type (either ReadOnlySpan, or an invalid one). + // This is done so that if the user picks an invalid type, the code is still generated, + // just returning default, so that proper diagnostic can be generated, without also + // having hard to understand compiler errors due to the mismatched return type here. + TypeSyntax returnType = bytecodeInfo.InvalidReturnType is string invalidReturnType + ? IdentifierName(invalidReturnType) + : GenericName(Identifier("global::System.ReadOnlySpan")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))); + + BlockSyntax methodBlock; + + if (bytecodeInfo.Bytecode.IsDefaultOrEmpty) + { + // This code generates the following block: + // + // { + // return default; + // } + methodBlock = + Block(ReturnStatement( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword)))); + + fixup = tree => tree.GetText(Encoding.UTF8); + } + else + { + // This code generates the following block: + // + // { + // return new byte[] { __EMBEDDED_SHADER_BYTECODE }; + // } + // + // As in the ID2D1Shader generator, the __EMBEDDED_SHADER_BYTECODE identifier will be replaced with the bytecode + // after the full string for the syntax tree has been generated, to avoid every literal going through a token. + methodBlock = + Block( + ReturnStatement( + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer( + InitializerExpression( + SyntaxKind.ArrayInitializerExpression, + SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))); + + string bytecodeLiterals = ID2D1ShaderGenerator.LoadBytecode.BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan()); + + // Prepare the fixup function + fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8); + } + + // This code produces a branch as follows: + // + // /// + // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] + // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + // () + // + return + MethodDeclaration(returnType, Identifier(bytecodeInfo.MethodName)) + .AddModifiers(bytecodeInfo.Modifiers.Select(Token).ToArray()) + .AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")) + .AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(D2DPixelShaderSourceAttribute).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(D2DPixelShaderSourceAttribute).Assembly.GetName().Version.ToString())))))) + .WithOpenBracketToken(Token(TriviaList(Comment( + $"/// ")), + SyntaxKind.OpenBracketToken, + TriviaList())), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))) + .WithBody(methodBlock); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs new file mode 100644 index 00000000..decf1272 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; +using ComputeSharp.D2D1.Exceptions; +using ComputeSharp.D2D1.Shaders.Translation; +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class D2DPixelShaderSourceGenerator +{ + /// + /// A container for all the logic for . + /// + private static partial class Execute + { + /// + /// Validates that the return type of the annotated method is valid and returns the type name. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The HLSL source to compile, if present. + public static string? GetInvalidReturnType(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + { + if (!(methodSymbol.ReturnType is INamedTypeSymbol + { + Name: "ReadOnlySpan", + ContainingNamespace.Name: "System", + IsGenericType: true, + TypeParameters.Length: 1 + } returnType && returnType.TypeArguments[0].SpecialType == SpecialType.System_Byte)) + { + diagnostics.Add( + InvalidD2DPixelShaderSourceMethodReturnType, + methodSymbol, + methodSymbol.Name, + methodSymbol.ContainingType, + methodSymbol.ReturnType); + + return methodSymbol.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + } + + return null; + } + + /// + /// Extracts the HLSL source from a method with the annotation. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The HLSL source to compile, if present. + public static string GetHlslSource(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + { + _ = methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute", out AttributeData? attributeData); + + if (!attributeData!.TryGetConstructorArgument(0, out string? hlslSource)) + { + diagnostics.Add( + InvalidD2DPixelShaderSource, + methodSymbol, + methodSymbol.Name, + methodSymbol.ContainingType); + } + + return hlslSource ?? ""; + } + + /// + /// Extracts the shader profile for a target method, if present. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The shader profile to use to compile the shader, if present. + public static D2D1ShaderProfile GetShaderProfile(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + { + if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out AttributeData? attributeData)) + { + return (D2D1ShaderProfile)attributeData!.ConstructorArguments[0].Value!; + } + + if (methodSymbol.ContainingAssembly.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out attributeData)) + { + return (D2D1ShaderProfile)attributeData!.ConstructorArguments[0].Value!; + } + + diagnostics.Add( + MissingShaderProfileForD2DPixelShaderSource, + methodSymbol, + methodSymbol.Name, + methodSymbol.ContainingType); + + return D2D1ShaderProfile.PixelShader50; + } + + /// + /// Extracts the compile options for the current shader. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The compile options to use to compile the shader, if present. + public static D2D1CompileOptions GetCompileOptions(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + { + if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData)) + { + return (D2D1CompileOptions)attributeData!.ConstructorArguments[0].Value!; + } + + if (methodSymbol.ContainingAssembly.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out attributeData)) + { + return (D2D1CompileOptions)attributeData!.ConstructorArguments[0].Value!; + } + + diagnostics.Add( + MissingCompileOptionsForD2DPixelShaderSource, + methodSymbol, + methodSymbol.Name, + methodSymbol.ContainingType); + + return D2D1CompileOptions.Default; + } + + /// + /// Gets an instance with the compiled bytecode for the current shader. + /// + /// The source info for the shader to compile. + /// The used to cancel the operation, if needed. + /// The resulting diagnostic from the processing operation, if any. + /// The instance with the compiled shader bytecode. + public static unsafe ImmutableArray GetBytecode(HlslShaderMethodSourceInfo sourceInfo, CancellationToken token, out DiagnosticInfo? diagnostic) + { + ImmutableArray bytecode = ImmutableArray.Empty; + + // Skip compilation if there are any errors + if (sourceInfo is { HasErrors: true }) + { + diagnostic = null; + + goto End; + } + + try + { + token.ThrowIfCancellationRequested(); + + // Compile the shader bytecode using the requested parameters + using ComPtr dxcBlobBytecode = D3DCompiler.Compile( + sourceInfo.HlslSource.AsSpan(), + sourceInfo.ShaderProfile, + sourceInfo.CompileOptions); + + token.ThrowIfCancellationRequested(); + + byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); + int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); + + byte[] array = new ReadOnlySpan(buffer, length).ToArray(); + + bytecode = Unsafe.As>(ref array); + diagnostic = null; + } + catch (Win32Exception e) + { + diagnostic = new DiagnosticInfo( + D2DPixelShaderSourceCompilationFailedWithWin32Exception, + sourceInfo.MethodName, + e.HResult, + ID2D1ShaderGenerator.LoadBytecode.FixupExceptionMessage(e.Message)); + } + catch (FxcCompilationException e) + { + diagnostic = new DiagnosticInfo( + D2DPixelShaderSourceCompilationFailedWithFxcCompilationException, + sourceInfo.MethodName, + ID2D1ShaderGenerator.LoadBytecode.FixupExceptionMessage(e.Message)); + } + + End: + return bytecode; + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs new file mode 100644 index 00000000..011d5b62 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +/// A source generator compiling methods annotated with . +/// +[Generator(LanguageNames.CSharp)] +public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerator +{ + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + // Get all method declarations with the [D2DPixelShaderSource] attribute + IncrementalValuesProvider<(MethodDeclarationSyntax Syntax, IMethodSymbol Symbol)> methodSymbols = + context.SyntaxProvider + .CreateSyntaxProvider( + static (node, _) => node is MethodDeclarationSyntax { Parent: ClassDeclarationSyntax, AttributeLists.Count: > 0 }, + static (context, _) => ( + (MethodDeclarationSyntax)context.Node, + Symbol: (IMethodSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!)) + .Where(static pair => pair.Symbol.HasAttributeWithFullyQualifiedName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute")); + + // Gather info for all annotated methods + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderMethodSourceInfo Source, ImmutableArray Diagnostics)> shaderInfoWithErrors = + methodSymbols + .Select(static (item, _) => + { + ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + + // Get all necessary info for the current shader + ImmutableArray modifiers = item.Syntax.Modifiers.Select(token => token.Kind()).ToImmutableArray(); + string methodName = item.Symbol.Name; + string? invalidReturnType = Execute.GetInvalidReturnType(diagnostics, item.Symbol); + string hlslSource = Execute.GetHlslSource(diagnostics, item.Symbol); + D2D1ShaderProfile shaderProfile = Execute.GetShaderProfile(diagnostics, item.Symbol); + D2D1CompileOptions compileOptions = Execute.GetCompileOptions(diagnostics, item.Symbol); + + HlslShaderMethodSourceInfo sourceInfo = new( + modifiers, + methodName, + invalidReturnType, + hlslSource, + shaderProfile, + compileOptions, + HasErrors: diagnostics.Count > 0); + + HierarchyInfo hierarchy = HierarchyInfo.From(item.Symbol.ContainingType!); + + return (hierarchy, sourceInfo, diagnostics.ToImmutable()); + }); + + // Output the diagnostics + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, _) => item.Diagnostics)); + + // Filter all items to enable caching at a coarse level, and remove diagnostics + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderMethodSourceInfo Source)> shaderInfo = + shaderInfoWithErrors + .Select(static (item, token) => (item.Hierarchy, item.Source)) + .WithComparers(HierarchyInfo.Comparer.Default, HlslShaderMethodSourceInfo.Comparer.Default); + + // Compile the requested shader bytecodes + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeMethodInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = + shaderInfo + .Select(static (item, token) => + { + ImmutableArray bytecode = Execute.GetBytecode( + item.Source, + token, + out DiagnosticInfo? diagnostic); + + token.ThrowIfCancellationRequested(); + + EmbeddedBytecodeMethodInfo bytecodeInfo = new( + item.Source.Modifiers, + item.Source.MethodName, + item.Source.InvalidReturnType, + item.Source.HlslSource, + bytecode); + + return (item.Hierarchy, bytecodeInfo, diagnostic); + }); + + // Gather the diagnostics + IncrementalValuesProvider embeddedBytecodeDiagnostics = + embeddedBytecodeWithErrors + .Select(static (item, token) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic)) + .Where(static item => item.Diagnostic is not null) + .Combine(context.CompilationProvider) + .Select(static (item, token) => + { + INamedTypeSymbol typeSymbol = item.Right.GetTypeByMetadataName(item.Left.FullyQualifiedMetadataName)!; + + return Diagnostic.Create( + item.Left.Diagnostic!.Descriptor, + typeSymbol.Locations.FirstOrDefault(), + new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Args).ToArray()); + }); + + // Output the diagnostics + context.ReportDiagnostics(embeddedBytecodeDiagnostics); + + // Get the filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeMethodInfo BytecodeInfo)> embeddedBytecode = + embeddedBytecodeWithErrors + .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo)) + .WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeMethodInfo.Comparer.Default); + + // Generate the shader bytecode methods + context.RegisterSourceOutput(embeddedBytecode, static (context, item) => + { + MethodDeclarationSyntax loadBytecodeMethod = Execute.GetSyntax(item.BytecodeInfo, out Func fixup); + CompilationUnitSyntax compilationUnit = item.Hierarchy.GetSyntax(loadBytecodeMethod); + SourceText text = fixup(compilationUnit); + + context.AddSource($"{item.Hierarchy.FilenameHint}.{item.BytecodeInfo.MethodName}", text); + }); + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 0a87ce13..2701ce43 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -463,7 +463,7 @@ partial class DiagnosticDescriptors /// Format: "The shader of type {0} failed to compile due to an HLSL compiler error (Message: "{1}")". /// /// - public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithDxcCompilationException = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithFxcCompilationException = new DiagnosticDescriptor( id: "CMPSD2D0034", title: "Embedded bytecode compilation failed due to an HLSL compiler error", messageFormat: "The shader of type {0} failed to compile due to an HLSL compiler error (Message: \"{1}\")", @@ -744,4 +744,100 @@ partial class DiagnosticDescriptors isEnabledByDefault: true, description: "The element type of D2D1 resource texture fields in a D2D1 shader must be either float or float4.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid HLSL source in [D2DPixelShaderSource]. + /// + /// Format: "The method \"{0}\" (in type {1}) is using [D2DPixelShaderSource] with an invalid HLSL source argument". + /// + /// + public static readonly DiagnosticDescriptor InvalidD2DPixelShaderSource = new DiagnosticDescriptor( + id: "CMPSD2D0052", + title: "Invalid [D2DPixelShaderSource] HLSL source argument", + messageFormat: "The method \"{0}\" (in type {1}) is using [D2DPixelShaderSource] with an invalid HLSL source argument", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Methods using [D2DPixelShaderSource] must pass a valid string as the HLSL source argument.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an embedded bytecode D2D shader failed due to a Win32 exception. + /// + /// Format: "Compiling the HLSL source for method \"{1}\" (in type {0}) failed due to a Win32 exception (HRESULT: {2:X8}, Message: \"{3}\")". + /// + /// + public static readonly DiagnosticDescriptor D2DPixelShaderSourceCompilationFailedWithWin32Exception = new DiagnosticDescriptor( + id: "CMPSD2D0053", + title: "D2D shader compilation failed due to Win32 exception", + messageFormat: "Compiling the HLSL source for method \"{1}\" (in type {0}) failed due to a Win32 exception (HRESULT: {2:X8}, Message: \"{3}\")", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The embedded bytecode for an input HLSl source failed to be compiled due to a Win32 exception.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an embedded bytecode D2D shader failed due to an HLSL compilation exception. + /// + /// Format: "Compiling the HLSL source for method \"{1}\" (in type {0}) failed due to an HLSL compiler error (Message: \"{2}\")". + /// + /// + public static readonly DiagnosticDescriptor D2DPixelShaderSourceCompilationFailedWithFxcCompilationException = new DiagnosticDescriptor( + id: "CMPSD2D0054", + title: "D2D shader compilation failed due to an HLSL compiler error", + messageFormat: "Compiling the HLSL source for method \"{1}\" (in type {0}) failed due to an HLSL compiler error (Message: \"{2}\")", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The embedded bytecode for an input HLSl source failed to be compiled due to an HLSL compiler error.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an embedded bytecode D2D shader with no shader profile set. + /// + /// Format: "The method \"{0}\" (in type {1}) is using [D2DPixelShaderSource] but has not specified the shader profile to use". + /// + /// + public static readonly DiagnosticDescriptor MissingShaderProfileForD2DPixelShaderSource = new DiagnosticDescriptor( + id: "CMPSD2D0055", + title: "Missing shader profile for D2D pixel shader source", + messageFormat: "The method \"{0}\" (in type {1}) is using [D2DPixelShaderSource] but has not specified the shader profile to use", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Precompiled shaders using [D2DPixelShaderSource] must explicitly indicate the shader profile to use.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an embedded bytecode D2D shader with no compile options set. + /// + /// Format: "The method \"{0}\" (in type {1}) is using [D2DPixelShaderSource] but has not specified the compile options to use". + /// + /// + public static readonly DiagnosticDescriptor MissingCompileOptionsForD2DPixelShaderSource = new DiagnosticDescriptor( + id: "CMPSD2D0056", + title: "Missing compile options for D2D pixel shader source", + messageFormat: "The method \"{0}\" (in type {1}) is using [D2DPixelShaderSource] but has not specified the compile options to use", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Precompiled shaders using [D2DPixelShaderSource] must explicitly indicate the compile options.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for when a method with [D2DPixelShaderSource] has an invalid return type. + /// + /// Format: "The method \"{0}\" (in type {1}) is using [D2DPixelShaderSource] but has an invalid return type {2} (it must return a ReadOnlySpan<byte>)". + /// + /// + public static readonly DiagnosticDescriptor InvalidD2DPixelShaderSourceMethodReturnType = new DiagnosticDescriptor( + id: "CMPSD2D0057", + title: "Missing compile options for D2D pixel shader source", + messageFormat: "The method \"{0}\" (in type {1}) is using [D2DPixelShaderSource] but has an invalid return type {2} (it must return a ReadOnlySpan)", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Methods using using [D2DPixelShaderSource] must use ReadOnlySpan as the return type.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index be30d274..32b042eb 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -214,7 +214,7 @@ partial class ID2D1ShaderGenerator /// /// The input shader bytecode to serialize. /// A formatted with the serialized data. - private static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode) + internal static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode) { //The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs index a9cc40d5..a8dd4db6 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs @@ -11,8 +11,6 @@ using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -25,7 +23,7 @@ partial class ID2D1ShaderGenerator /// /// A helper with all logic to generate the LoadBytecode method. /// - private static partial class LoadBytecode + internal static partial class LoadBytecode { /// /// Extracts the shader profile for the current shader. @@ -34,12 +32,12 @@ partial class ID2D1ShaderGenerator /// The shader profile to use to compile the shader, if present. public static D2D1ShaderProfile? GetShaderProfile(INamedTypeSymbol structDeclarationSymbol) { - if (structDeclarationSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DEmbeddedBytecodeAttribute", out AttributeData? attributeData)) + if (structDeclarationSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out AttributeData? attributeData)) { return (D2D1ShaderProfile)attributeData!.ConstructorArguments[0].Value!; } - if (structDeclarationSymbol.ContainingAssembly.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DEmbeddedBytecodeAttribute", out attributeData)) + if (structDeclarationSymbol.ContainingAssembly.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out attributeData)) { return (D2D1ShaderProfile)attributeData!.ConstructorArguments[0].Value!; } @@ -142,7 +140,7 @@ partial class ID2D1ShaderGenerator } /// - /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// Gets an instance with the compiled bytecode for the current shader. /// /// The source info for the shader to compile. /// The used to cancel the operation, if needed. @@ -200,7 +198,7 @@ partial class ID2D1ShaderGenerator catch (FxcCompilationException e) { options = default; - diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithDxcCompilationException, FixupExceptionMessage(e.Message)); + diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithFxcCompilationException, FixupExceptionMessage(e.Message)); } End: @@ -212,7 +210,7 @@ partial class ID2D1ShaderGenerator /// /// The input exception message. /// The updated exception message. - private static string FixupExceptionMessage(string message) + internal static string FixupExceptionMessage(string message) { // Add square brackets around error headers message = Regex.Replace(message, @"((?:error|warning) \w+):", static m => $"[{m.Groups[1].Value}]:"); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs index 532a839e..cf51ee76 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs @@ -7,7 +7,7 @@ using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators.Models; /// -/// A model representing a shared and its compiled bytecode, if available. +/// A model representing info on a shader that has requested to be precompiled at build time. /// /// The HLSL source for the shader. /// The shader profile to use to compile the shader, if requested. diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs new file mode 100644 index 00000000..5cb0a4b3 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Runtime.InteropServices; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using Microsoft.CodeAnalysis.CSharp; + +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing info on a shader method that has requested to be precompiled at build time. +/// +/// The modifiers for the annotated method. +/// The name of the annotated method. +/// The fully qualified name of the return type, if invalid. +/// The HLSL source. +/// The compiled shader bytecode, if available. +internal sealed record EmbeddedBytecodeMethodInfo( + ImmutableArray Modifiers, + string MethodName, + string? InvalidReturnType, + string HlslSource, + ImmutableArray Bytecode) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, EmbeddedBytecodeMethodInfo obj) + { + hashCode.AddRange(obj.Modifiers); + hashCode.Add(obj.MethodName); + hashCode.Add(obj.InvalidReturnType); + hashCode.Add(obj.HlslSource); + hashCode.AddBytes(obj.Bytecode.AsSpan()); + } + + /// + protected override bool AreEqual(EmbeddedBytecodeMethodInfo x, EmbeddedBytecodeMethodInfo y) + { + return + MemoryMarshal.Cast(x.Modifiers.AsSpan()).SequenceEqual(MemoryMarshal.Cast(y.Modifiers.AsSpan())) && + x.MethodName == y.MethodName && + x.InvalidReturnType == y.InvalidReturnType && + x.HlslSource == y.HlslSource && + x.Bytecode.SequenceEqual(y.Bytecode); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs new file mode 100644 index 00000000..25b20451 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Immutable; +using System.Runtime.InteropServices; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using Microsoft.CodeAnalysis.CSharp; + +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model for extracted info on a processed HLSL shader method. +/// +/// The modifiers for the annotated method. +/// The name of the annotated method. +/// The fully qualified name of the return type, if invalid. +/// The HLSL source. +/// The shader profile to use to compile the shader. +/// The compile options to use to compile the shader. +/// Whether any errors have been detected, and therefore the shader compilation should be skipped. +internal sealed record HlslShaderMethodSourceInfo( + ImmutableArray Modifiers, + string MethodName, + string? InvalidReturnType, + string HlslSource, + D2D1ShaderProfile ShaderProfile, + D2D1CompileOptions CompileOptions, + bool HasErrors) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, HlslShaderMethodSourceInfo obj) + { + hashCode.AddRange(obj.Modifiers); + hashCode.Add(obj.MethodName); + hashCode.Add(obj.InvalidReturnType); + hashCode.Add(obj.HlslSource); + hashCode.Add(obj.ShaderProfile); + hashCode.Add(obj.CompileOptions); + hashCode.Add(obj.HasErrors); + } + + /// + protected override bool AreEqual(HlslShaderMethodSourceInfo x, HlslShaderMethodSourceInfo y) + { + return + MemoryMarshal.Cast(x.Modifiers.AsSpan()).SequenceEqual(MemoryMarshal.Cast(y.Modifiers.AsSpan())) && + x.MethodName == y.MethodName && + x.InvalidReturnType == y.InvalidReturnType && + x.HlslSource == y.HlslSource && + x.ShaderProfile == y.ShaderProfile && + x.CompileOptions == y.CompileOptions && + x.HasErrors == y.HasErrors; + } + } +} diff --git a/src/ComputeSharp.D2D1/Attributes/D2DCompileOptionsAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DCompileOptionsAttribute.cs index 232ad1bd..ba474e40 100644 --- a/src/ComputeSharp.D2D1/Attributes/D2DCompileOptionsAttribute.cs +++ b/src/ComputeSharp.D2D1/Attributes/D2DCompileOptionsAttribute.cs @@ -4,7 +4,7 @@ namespace ComputeSharp.D2D1; /// /// An attribute that indicates the compile options that should be used when compiling a given D2D1 shader. -/// This applies when the shader is precompiled (through ) as well. +/// This applies when the shader is precompiled (through ) as well. /// /// This attribute can be used to annotate shader types as follows: /// @@ -26,7 +26,7 @@ namespace ComputeSharp.D2D1; /// This attribute can also be added to a whole assembly, and will be used by default if not overridden by a shader type. /// /// -[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = false)] +[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Assembly | AttributeTargets.Method, AllowMultiple = false)] public sealed class D2DCompileOptionsAttribute : Attribute { /// diff --git a/src/ComputeSharp.D2D1/Attributes/D2DPixelShaderSourceAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DPixelShaderSourceAttribute.cs new file mode 100644 index 00000000..00e23ace --- /dev/null +++ b/src/ComputeSharp.D2D1/Attributes/D2DPixelShaderSourceAttribute.cs @@ -0,0 +1,51 @@ +using System; +using System.Diagnostics.CodeAnalysis; + +namespace ComputeSharp.D2D1; + +/// +/// An attribute that indicates that a given D2D1 shader should be precompiled at build time and embedded +/// directly into the containing assembly as static bytecode, to be retrieved as a . +/// +/// This attribute can be used to annotate methods as follows: +/// +/// [D2DPixelShaderSource(""" +/// #define D2D_INPUT_COUNT 1 +/// #define D2D_INPUT0_SIMPLE +/// +/// #include ""d2d1effecthelpers.hlsli"" +/// +/// D2D_PS_ENTRY(PSMain) +/// { +/// float4 color = D2DGetInput(0); +/// float3 rgb = saturate(1.0 - color.rgb); +/// return float4(rgb, 1); +/// } +/// """")] +/// static partial ReadOnlySpan<byte> GetBytecode(); +/// +/// +/// +/// +/// +/// Methods can also be annotated with and +/// to further customize the shader profile to use when compiling the HLSL source, and the compile options to use. +/// +/// +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] +public sealed class D2DPixelShaderSourceAttribute : Attribute +{ + /// + /// Creates a new instance of the type with the specified arguments. + /// + /// The number of texture inputs for the shader. + public D2DPixelShaderSourceAttribute([StringSyntax("Hlsl")] string hlslSource) + { + HlslSource = hlslSource; + } + + /// + /// Gets the number of texture inputs for the shader. + /// + public string HlslSource { get; } +} diff --git a/src/ComputeSharp.D2D1/Attributes/D2DEmbeddedBytecodeAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DShaderProfileAttribute.cs similarity index 65% rename from src/ComputeSharp.D2D1/Attributes/D2DEmbeddedBytecodeAttribute.cs rename to src/ComputeSharp.D2D1/Attributes/D2DShaderProfileAttribute.cs index 1a8cf87d..15ca30f8 100644 --- a/src/ComputeSharp.D2D1/Attributes/D2DEmbeddedBytecodeAttribute.cs +++ b/src/ComputeSharp.D2D1/Attributes/D2DShaderProfileAttribute.cs @@ -3,12 +3,12 @@ namespace ComputeSharp.D2D1; /// -/// An attribute that indicates that a given D2D1 shader should be precompiled at build time and embedded -/// directly into the containing assembly as static bytecode, to avoid compiling it at runtime. +/// An attribute that indicates that a given D2D1 shader should be precompiled at build time using a specific shader +/// profile and embedded directly into the containing assembly as static bytecode, to avoid compiling it at runtime. /// /// This attribute can be used to annotate shader types as follows: /// -/// [D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)] +/// [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] /// struct MyShader : ID2D1PixelShader /// { /// } @@ -24,20 +24,20 @@ namespace ComputeSharp.D2D1; /// This attribute can also be added to a whole assembly, and will be used by default if not overridden by a shader type. /// /// -[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = false)] -public sealed class D2DEmbeddedBytecodeAttribute : Attribute +[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Assembly | AttributeTargets.Method, AllowMultiple = false)] +public sealed class D2DShaderProfileAttribute : Attribute { /// - /// Creates a new instance with the specified parameters. + /// Creates a new instance with the specified parameters. /// /// The target shader profile to use to compile the shader. - public D2DEmbeddedBytecodeAttribute(D2D1ShaderProfile shaderProfile) + public D2DShaderProfileAttribute(D2D1ShaderProfile shaderProfile) { ShaderProfile = shaderProfile; } /// - /// Gets the number of threads in each thread group for the X axis + /// The shader profile used to compile the annotated D2D1 pixel shader. /// public D2D1ShaderProfile ShaderProfile { get; } } diff --git a/src/ComputeSharp.D2D1/Attributes/Enums/D2D1CompileOptions.cs b/src/ComputeSharp.D2D1/Attributes/Enums/D2D1CompileOptions.cs index a0209386..5727953a 100644 --- a/src/ComputeSharp.D2D1/Attributes/Enums/D2D1CompileOptions.cs +++ b/src/ComputeSharp.D2D1/Attributes/Enums/D2D1CompileOptions.cs @@ -163,7 +163,7 @@ public enum D2D1CompileOptions /// /// The default options for shaders compiled by ComputeSharp.D2D1. Specifically, this combination - /// of options is the one used by precompiled shaders (ie. when using ), + /// of options is the one used by precompiled shaders (ie. when using ), /// and when using or any of the overloads. /// /// diff --git a/src/ComputeSharp.D2D1/Attributes/Enums/D2D1ShaderProfile.cs b/src/ComputeSharp.D2D1/Attributes/Enums/D2D1ShaderProfile.cs index 2580c5d2..e68a8aad 100644 --- a/src/ComputeSharp.D2D1/Attributes/Enums/D2D1ShaderProfile.cs +++ b/src/ComputeSharp.D2D1/Attributes/Enums/D2D1ShaderProfile.cs @@ -1,7 +1,7 @@ namespace ComputeSharp.D2D1; /// -/// A to be used with to indicate the shader profile to use to precompile a shader. +/// A to be used with to indicate the shader profile to use to precompile a shader. /// public enum D2D1ShaderProfile { diff --git a/src/ComputeSharp.D2D1/Properties/Polyfills/StringSyntaxAttribute.cs b/src/ComputeSharp.D2D1/Properties/Polyfills/StringSyntaxAttribute.cs new file mode 100644 index 00000000..02abeb35 --- /dev/null +++ b/src/ComputeSharp.D2D1/Properties/Polyfills/StringSyntaxAttribute.cs @@ -0,0 +1,42 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies the syntax used in a string. +/// +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)] +internal sealed class StringSyntaxAttribute : Attribute +{ + /// + /// Initializes the with the identifier of the syntax used. + /// + /// The syntax identifier. + public StringSyntaxAttribute(string syntax) + { + Syntax = syntax; + Arguments = Array.Empty(); + } + + /// + /// Initializes the with the identifier of the syntax used. + /// + /// The syntax identifier. + /// Optional arguments associated with the specific syntax employed. + public StringSyntaxAttribute(string syntax, params object?[] arguments) + { + Syntax = syntax; + Arguments = arguments; + } + + /// + /// Gets the identifier of the syntax used. + /// + public string Syntax { get; } + + /// + /// Optional arguments associated with the specific syntax employed. + /// + public object?[] Arguments { get; } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs index 16aa8a6a..5acc5ac7 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs @@ -21,7 +21,7 @@ public static class D2D1ReflectionServices /// The type of D2D1 shader to retrieve info for. /// The resulting instance. /// - /// If the target shader type is precompiled (ie. it's annotated with ), that bytecode will + /// If the target shader type is precompiled (ie. it's annotated with ), that bytecode will /// be reused to reflect on the shader, so the same shader profile and compile options will be reused, which can make the returned metadata more accurate. /// /// If the shader is not precompiled, it will be compiled on the fly using the default settings for both the shader profile and the compile options. That is, diff --git a/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/D2D1PixelShaderTests.cs b/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/D2D1PixelShaderTests.cs index 62e052f6..481ff5d3 100644 --- a/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/D2D1PixelShaderTests.cs +++ b/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/D2D1PixelShaderTests.cs @@ -65,7 +65,7 @@ public partial class D2D1PixelShaderTests [D2DInputSimple(0)] [D2DInputSimple(1)] [D2DInputSimple(2)] - [D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] private readonly partial struct ShaderWithOverriddenProfile : ID2D1PixelShader { public float4 Execute() @@ -133,7 +133,7 @@ public partial class D2D1PixelShaderTests [D2DInputSimple(0)] [D2DInputSimple(1)] [D2DInputSimple(2)] - [D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] [D2DCompileOptions(D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision)] private readonly partial struct ShaderWithOverriddenProfileAndOptions : ID2D1PixelShader { diff --git a/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/Properties/AssemblyInfo.cs b/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/Properties/AssemblyInfo.cs index 654a9470..24c73837 100644 --- a/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/Properties/AssemblyInfo.cs +++ b/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ using ComputeSharp.D2D1; -[assembly: D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader41)] +[assembly: D2DShaderProfile(D2D1ShaderProfile.PixelShader41)] [assembly: D2DCompileOptions(D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision)] \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs index a0375100..27fea62a 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs @@ -212,7 +212,7 @@ public partial class D2D1PixelShaderTests [D2DInputSimple(2)] [D2DInputComplex(1)] [D2DInputComplex(3)] - [D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] [AutoConstructor] partial struct ShaderWithResourceTextures : ID2D1PixelShader { @@ -291,7 +291,7 @@ public partial class D2D1PixelShaderTests [D2DInputSimple(0)] [D2DInputSimple(1)] [D2DInputSimple(2)] - [D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader40Level91)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader40Level91)] private readonly partial struct ShaderWithEmbeddedBytecode : ID2D1PixelShader { public float4 Execute() @@ -337,7 +337,7 @@ public partial class D2D1PixelShaderTests [D2DInputSimple(0)] [D2DInputSimple(1)] [D2DInputSimple(2)] - [D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader40Level91)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader40Level91)] [D2DCompileOptions(D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2)] private readonly partial struct ShaderWithEmbeddedBytecodeAndCompileOptions : ID2D1PixelShader { diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1ShaderCompilerTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1ShaderCompilerTests.cs index a3c14922..aaa84f9e 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1ShaderCompilerTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1ShaderCompilerTests.cs @@ -18,7 +18,6 @@ public partial class D2D1ShaderCompilerTests #include ""d2d1effecthelpers.hlsli"" - D2D_PS_ENTRY(PSMain) { float4 color = D2DGetInput(0); @@ -44,7 +43,6 @@ public partial class D2D1ShaderCompilerTests #include ""d2d1effecthelpers.hlsli"" - D2D_PS_ENTRY(PSMain) { float4 color = D2DGetInput(0); @@ -71,7 +69,6 @@ public partial class D2D1ShaderCompilerTests #include ""d2d1effecthelpers.hlsli"" - D2D_PS_ENTRY(PSMain) { float4 color = D2DGetInput(0); @@ -98,7 +95,6 @@ public partial class D2D1ShaderCompilerTests #include ""d2d1effecthelpers.hlsli"" - D2D_PS_ENTRY(PSMain) { float4 color = D2DGetInput(99); diff --git a/tests/ComputeSharp.D2D1.Tests/D2DPixelShaderSourceTests.cs b/tests/ComputeSharp.D2D1.Tests/D2DPixelShaderSourceTests.cs new file mode 100644 index 00000000..3c891a8d --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/D2DPixelShaderSourceTests.cs @@ -0,0 +1,34 @@ +using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.D2D1.Tests; + +[TestClass] +[TestCategory("D2DPixelShaderSource")] +public partial class D2DPixelShaderSourceTests +{ + [D2DPixelShaderSource(@" + #define D2D_INPUT_COUNT 1 + #define D2D_INPUT0_SIMPLE + + #include ""d2d1effecthelpers.hlsli"" + + D2D_PS_ENTRY(Execute) + { + float4 color = D2DGetInput(0); + float3 rgb = saturate(1.0 - color.rgb); + return float4(rgb, 1); + } + ")] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] + [D2DCompileOptions(D2D1CompileOptions.OptimizationLevel0)] + private static partial ReadOnlySpan InvertEffect(); + + [TestMethod] + public void VerifyInvertEffectBytecode() + { + ReadOnlySpan bytecode = InvertEffect(); + + Assert.IsTrue(bytecode.Length > 0); + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/CheckerboardClipEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/CheckerboardClipEffect.cs index 028f59b6..b7a02601 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/CheckerboardClipEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/CheckerboardClipEffect.cs @@ -3,7 +3,7 @@ [D2DInputCount(1)] [D2DInputSimple(0)] [D2DRequiresScenePosition] -[D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)] +[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] [AutoConstructor] public partial struct CheckerboardClipEffect : ID2D1PixelShader { diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/InvertEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/InvertEffect.cs index 277fcd82..dbf1dccf 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/InvertEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/InvertEffect.cs @@ -2,7 +2,7 @@ [D2DInputCount(1)] [D2DInputSimple(0)] -[D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)] +[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] public partial struct InvertEffect : ID2D1PixelShader { /// diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/InvertWithThresholdEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/InvertWithThresholdEffect.cs index 6d98d350..6d0d9698 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/InvertWithThresholdEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/InvertWithThresholdEffect.cs @@ -2,7 +2,7 @@ [D2DInputCount(1)] [D2DInputSimple(0)] -[D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)] +[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] [AutoConstructor] public partial struct InvertWithThresholdEffect : ID2D1PixelShader { diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/PixelateEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/PixelateEffect.cs index 898df187..84aa3544 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/PixelateEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/PixelateEffect.cs @@ -27,7 +27,7 @@ public sealed partial class PixelateEffect : ID2D1TransformMapper