Merge pull request #560 from Sergio0694/dev/effect-metadata
Add [D2DEffectId] and [D2DEffectDisplayName]
このコミットが含まれているのは:
20ファイル変更
+865
-23
検索条件に一致するファイルはありません
@@ -1,4 +1,4 @@
|
||||
; Shipped analyzer releases
|
||||
; Shipped analyzer releases
|
||||
; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
|
||||
|
||||
## Release 1.0
|
||||
@@ -65,3 +65,5 @@ CMPSD2D0055 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github
|
||||
CMPSD2D0056 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0057 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0058 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0059 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0060 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates an error whenever [D2DEffectName] is used with an invalid value.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidEffectDisplayNameValueAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidD2DEffectDisplayNameAttributeValue);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DEffectDisplayName] symbol
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DEffectDisplayNameAttribute") is not { } d2DEffectIdAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only struct types are possible targets
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (AttributeData attributeData in typeSymbol.GetAttributes())
|
||||
{
|
||||
// Look for the [D2DEffectDisplayName] use
|
||||
if (!SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DEffectIdAttributeSymbol))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate the effect display name
|
||||
if (!D2D1EffectMetadataParser.IsValidEffectDisplayName(attributeData))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidD2DEffectDisplayNameAttributeValue,
|
||||
attributeData.GetLocation()));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates an error whenever [D2DEffectId] is used with an invalid value.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidEffectIdValueAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidD2DEffectIdAttributeValue);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DEffectId] symbol
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DEffectIdAttribute") is not { } d2DEffectIdAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only struct types are possible targets
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (AttributeData attributeData in typeSymbol.GetAttributes())
|
||||
{
|
||||
// Look for the [D2DEffectId] use
|
||||
if (!SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DEffectIdAttributeSymbol))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate the GUID text and emit a diagnostic if needed
|
||||
if (attributeData.ConstructorArguments is not [{ Value: string value }] ||
|
||||
!Guid.TryParse(value, out _))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidD2DEffectIdAttributeValue,
|
||||
attributeData.GetLocation()));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -857,4 +857,36 @@ partial class DiagnosticDescriptors
|
||||
isEnabledByDefault: true,
|
||||
description: "A D2D1 shader must be annotated with the [D2DInputCount] attribute.",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for when the <c>[D2DEffectId]</c> attribute is being used with an invalid value.
|
||||
/// <para>
|
||||
/// Format: <c>"The [D2DEffectId] attribute is being used with an invalid value (the input text must be a valid GUID)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidD2DEffectIdAttributeValue = new DiagnosticDescriptor(
|
||||
id: "CMPSD2D0059",
|
||||
title: "Invalid [D2DEffectId] attribute value",
|
||||
messageFormat: "The [D2DEffectId] attribute is being used with an invalid value (the input text must be a valid GUID)",
|
||||
category: "ComputeSharp.D2D1.Shaders",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "The [D2DEffectId] attribute must use a valid GUID expression as value.",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for when the <c>[D2DEffectDisplayName]</c> attribute is being used with an invalid value.
|
||||
/// <para>
|
||||
/// Format: <c>"The [D2DEffectDisplayName] attribute is being used with an invalid value (the input text must be a valid GUID)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidD2DEffectDisplayNameAttributeValue = new DiagnosticDescriptor(
|
||||
id: "CMPSD2D0060",
|
||||
title: "Invalid [D2DEffectDisplayName] attribute value",
|
||||
messageFormat: "The [D2DEffectDisplayName] attribute is being used with an invalid value",
|
||||
category: "ComputeSharp.D2D1.Shaders",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "The [D2DEffectDisplayName] attribute must contain valid text.",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security;
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// A helper class to parse D2D metadata values.
|
||||
/// </summary>
|
||||
internal static class D2D1EffectMetadataParser
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see cref="Regex"/> instance to find all newlines.
|
||||
/// </summary>
|
||||
private static readonly Regex NewLinesRegex = new("[\r\n\v]", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a given <see cref="AttributeData"/> value contains a valid effect display name.
|
||||
/// </summary>
|
||||
/// <param name="attributeData">The input <see cref="AttributeData"/> object to inspect.</param>
|
||||
/// <returns>Whether <paramref name="attributeData"/> contains a valid effect display name.</returns>
|
||||
public static bool IsValidEffectDisplayName(AttributeData attributeData)
|
||||
{
|
||||
if (attributeData.ConstructorArguments is [{ Value: string { Length: > 0 } value }])
|
||||
{
|
||||
// Remove new lines (the values cannot span multiple lines in XML)
|
||||
string singleLineValue = NewLinesRegex.Replace(value, string.Empty);
|
||||
|
||||
// Trim directly and check that (no need to escape, as that wouldn't change things)
|
||||
return singleLineValue.AsSpan().Trim().Length > 0;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the defined effect display name for a given attribute.
|
||||
/// </summary>
|
||||
/// <param name="attributeData">The input <see cref="AttributeData"/> object to inspect.</param>
|
||||
/// <param name="effectDisplayName">The resulting defined effect display name, if found.</param>
|
||||
/// <returns>Whether or not a defined effect display name could be found.</returns>
|
||||
public static bool TryGetEffectDisplayName(AttributeData attributeData, [NotNullWhen(true)] out string? effectDisplayName)
|
||||
{
|
||||
// Check that the attribute is [D2DEffectDisplayName] and with a valid parameter
|
||||
if (attributeData.ConstructorArguments is [{ Value: string { Length: > 0 } value }])
|
||||
{
|
||||
// Remove new lines (the values cannot span multiple lines in XML)
|
||||
string singleLineValue = NewLinesRegex.Replace(value, string.Empty);
|
||||
|
||||
// Make sure to escape any invalid XML characters
|
||||
string escapedValue = SecurityElement.Escape(singleLineValue);
|
||||
|
||||
// Trim the display name as well
|
||||
if (escapedValue.AsSpan().Trim() is { Length: > 0 } trimmedValue)
|
||||
{
|
||||
effectDisplayName = trimmedValue.ToString();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
effectDisplayName = default;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
using ComputeSharp.D2D1.__Internals;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ID2D1ShaderGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
partial class EffectDisplayName
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectDisplayName</c> property.
|
||||
/// </summary>
|
||||
/// <param name="effectDisplayName">The input effect display name value.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectDisplayName</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetSyntax(string effectDisplayName)
|
||||
{
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.EffectDisplayName => "<EFFECT_DISPLAY_NAME>";
|
||||
return
|
||||
PropertyDeclaration(PredefinedType(Token(SyntaxKind.StringKeyword)), Identifier(nameof(EffectDisplayName)))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(effectDisplayName))))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
}
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ID2D1ShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the <c>EffectDisplayName</c> property.
|
||||
/// </summary>
|
||||
private static partial class EffectDisplayName
|
||||
{
|
||||
/// <summary>
|
||||
/// Extracts the effect display name info for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the shader type in use.</param>
|
||||
/// <returns>The resulting effect display name.</returns>
|
||||
public static string GetInfo(Compilation compilation, INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
if (TryGetDefinedEffectDisplayName(compilation, structDeclarationSymbol, out string? effectDisplayName))
|
||||
{
|
||||
return effectDisplayName;
|
||||
}
|
||||
|
||||
return structDeclarationSymbol.GetFullyQualifiedMetadataName();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the defined effect display name for a given shader type.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance.</param>
|
||||
/// <param name="effectDisplayName">The resulting defined effect display name, if found.</param>
|
||||
/// <returns>Whether or not a defined effect display name could be found.</returns>
|
||||
private static bool TryGetDefinedEffectDisplayName(Compilation compilation, INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out string? effectDisplayName)
|
||||
{
|
||||
INamedTypeSymbol effectIdAttributeSymbol = compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DEffectDisplayNameAttribute")!;
|
||||
|
||||
foreach (AttributeData attributeData in typeSymbol.GetAttributes())
|
||||
{
|
||||
// Check that the attribute is [D2DEffectDisplayName]
|
||||
if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, effectIdAttributeSymbol))
|
||||
{
|
||||
return D2D1EffectMetadataParser.TryGetEffectDisplayName(attributeData, out effectDisplayName);
|
||||
}
|
||||
}
|
||||
|
||||
effectDisplayName = default;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using ComputeSharp.D2D1.__Internals;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ID2D1ShaderGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
partial class EffectId
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectId</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="EffectIdInfo"/> instance.</param>
|
||||
/// <param name="fixup">An opaque <see cref="Func{TResult}"/> instance to transform the final tree into text.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectId</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetSyntax(EffectIdInfo info, out Func<SyntaxNode, SourceText> fixup)
|
||||
{
|
||||
// Create the local declaration:
|
||||
//
|
||||
// global::System.ReadOnlySpan<byte> bytes = new byte[] { __EMBEDDED_EFFECT_ID_BYTES };
|
||||
LocalDeclarationStatementSyntax guidBytesDeclaration =
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(
|
||||
GenericName(Identifier("global::System.ReadOnlySpan"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("bytes"))
|
||||
.WithInitializer(
|
||||
EqualsValueClause(
|
||||
ArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
|
||||
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
|
||||
.WithInitializer(
|
||||
InitializerExpression(
|
||||
SyntaxKind.ArrayInitializerExpression,
|
||||
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_EFFECT_ID_BYTES"))))))));
|
||||
|
||||
// Prepare the initialization text
|
||||
string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(info.Bytes.AsSpan());
|
||||
|
||||
// Set the fixup function
|
||||
fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_EFFECT_ID_BYTES", effectIdLiterals), Encoding.UTF8);
|
||||
|
||||
// Prepare the return statement:
|
||||
//
|
||||
// return
|
||||
// ref global::System.Runtime.CompilerServices.Unsafe.As<byte, global::System.Guid>(
|
||||
// ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(bytes));
|
||||
ReturnStatementSyntax returnStatement =
|
||||
ReturnStatement(
|
||||
RefExpression(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
|
||||
GenericName(Identifier("As"))
|
||||
.AddTypeArgumentListArguments(
|
||||
PredefinedType(Token(SyntaxKind.ByteKeyword)),
|
||||
IdentifierName("global::System.Guid"))))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"),
|
||||
IdentifierName("GetReference")))
|
||||
.AddArgumentListArguments(Argument(IdentifierName("bytes"))))
|
||||
.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))));
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly ref readonly global::System.Guid global::ComputeSharp.D2D1.__Internals.ID2D1Shader.EffectId
|
||||
// {
|
||||
// [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
|
||||
// get
|
||||
// {
|
||||
// <BYTES_DECLARATION>
|
||||
// <RETURN_STATEMENT>
|
||||
// }
|
||||
// }
|
||||
return
|
||||
PropertyDeclaration(
|
||||
RefType(IdentifierName("global::System.Guid")).WithReadOnlyKeyword(Token(SyntaxKind.ReadOnlyKeyword)),
|
||||
Identifier(nameof(EffectId)))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.AddAccessorListAccessors(
|
||||
AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
|
||||
.AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("global::System.Runtime.CompilerServices.MethodImpl"))
|
||||
.AddArgumentListArguments(
|
||||
AttributeArgument(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.CompilerServices.MethodImplOptions"),
|
||||
IdentifierName("AggressiveInlining")))))))
|
||||
.AddBodyStatements(guidBytesDeclaration, returnStatement));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Immutable;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ID2D1ShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the <c>EffectId</c> property.
|
||||
/// </summary>
|
||||
private static partial class EffectId
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="IncrementalHash"/> instance currently in use for the running thread, if any.
|
||||
/// </summary>
|
||||
[ThreadStatic]
|
||||
private static IncrementalHash? incrementalHash;
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the effect id info for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the shader type in use.</param>
|
||||
/// <returns>The resulting effect id.</returns>
|
||||
public static ImmutableArray<byte> GetInfo(Compilation compilation, INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
if (TryGetDefinedEffectId(compilation, structDeclarationSymbol, out ImmutableArray<byte> effectId))
|
||||
{
|
||||
return effectId;
|
||||
}
|
||||
|
||||
return CreateDefaultEffectId(structDeclarationSymbol);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the defined effect id for a given shader type.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance.</param>
|
||||
/// <param name="effectId">The resulting defined effect id, if found.</param>
|
||||
/// <returns>Whether or not a defined effect id could be found.</returns>
|
||||
private static bool TryGetDefinedEffectId(Compilation compilation, INamedTypeSymbol typeSymbol, out ImmutableArray<byte> effectId)
|
||||
{
|
||||
INamedTypeSymbol effectIdAttributeSymbol = compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DEffectIdAttribute")!;
|
||||
|
||||
foreach (AttributeData attributeData in typeSymbol.GetAttributes())
|
||||
{
|
||||
// Check that the attribute is [D2DEffectId] and with a valid parameter
|
||||
if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, effectIdAttributeSymbol) &&
|
||||
attributeData.ConstructorArguments is [{ Value: string value }] &&
|
||||
Guid.TryParse(value, out Guid guid))
|
||||
{
|
||||
byte[] bytes = guid.ToByteArray();
|
||||
|
||||
effectId = Unsafe.As<byte[], ImmutableArray<byte>>(ref bytes);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
effectId = default;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the default effect id for a given type symbol.
|
||||
/// </summary>
|
||||
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance.</param>
|
||||
/// <returns>The resulting effect id.</returns>
|
||||
private static ImmutableArray<byte> CreateDefaultEffectId(INamedTypeSymbol typeSymbol)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Initialize an instance using the MD5 algorithm. We use this for several reasons:
|
||||
// - We don't really need security, this is just to uniquely identify types
|
||||
// - The hash size is 128 bits, which is exactly the size of a GUID.
|
||||
IncrementalHash incrementalHash = EffectId.incrementalHash ??= IncrementalHash.CreateHash(HashAlgorithmName.MD5);
|
||||
|
||||
string assemblyName = typeSymbol.ContainingAssembly?.Name ?? string.Empty;
|
||||
|
||||
using ImmutableArrayBuilder<char> charBuffer = ImmutableArrayBuilder<char>.Rent();
|
||||
|
||||
// Format the fully qualified name into a pooled builder to avoid the string allocation
|
||||
typeSymbol.AppendFullyQualifiedMetadataName(in charBuffer);
|
||||
|
||||
int maxTypeNameByteCount = Encoding.UTF8.GetMaxByteCount(charBuffer.Count);
|
||||
int maxAssemblyNameByteCount = Encoding.UTF8.GetMaxByteCount(assemblyName.Length);
|
||||
int maxEncodedByteCount = Math.Max(maxTypeNameByteCount, maxAssemblyNameByteCount);
|
||||
|
||||
byte[] bufferUtf8 = ArrayPool<byte>.Shared.Rent(maxEncodedByteCount);
|
||||
|
||||
// UTF8 encode the fully qualified name first
|
||||
int typeNameBytesWritten = Encoding.UTF8.GetBytes(charBuffer.WrittenSpan, bufferUtf8.AsSpan());
|
||||
|
||||
// Append the UTF8 fully qualified name to the MD5 hash
|
||||
incrementalHash.AppendData(bufferUtf8, 0, typeNameBytesWritten);
|
||||
|
||||
// UTF8 encode the assembly name as well
|
||||
int assemblyNameBytesWritten = Encoding.UTF8.GetBytes(assemblyName.AsSpan(), bufferUtf8.AsSpan());
|
||||
|
||||
// Append the UTF8 assembly name to the MD5 hash
|
||||
incrementalHash.AppendData(bufferUtf8, 0, assemblyNameBytesWritten);
|
||||
|
||||
// The state is not fully in the incremental hash, we can return the array
|
||||
ArrayPool<byte>.Shared.Return(bufferUtf8);
|
||||
|
||||
// Get the resulting MD5 hash (128 bits)
|
||||
byte[] hash = incrementalHash.GetHashAndReset();
|
||||
|
||||
// We own this buffer, so we can just reinterpret to an immutable array
|
||||
return Unsafe.As<byte[], ImmutableArray<byte>>(ref hash);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Something went wrong, throw away the current incremental hash.
|
||||
// Realistically speaking, this should just never happen.
|
||||
incrementalHash = null;
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,12 +38,12 @@ partial class ID2D1ShaderGenerator
|
||||
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
|
||||
/// </summary>
|
||||
/// <param name="hierarchyInfo">The <see cref="HierarchyInfo"/> instance for the current type.</param>
|
||||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> item to insert.</param>
|
||||
/// <param name="memberDeclarationSyntax">The <see cref="MemberDeclarationSyntax"/> item to insert.</param>
|
||||
/// <param name="canUseSkipLocalsInit">Whether <c>[SkipLocalsInit]</c> can be used.</param>
|
||||
/// <returns>A <see cref="CompilationUnitSyntax"/> object wrapping <paramref name="methodDeclaration"/>.</returns>
|
||||
private static CompilationUnitSyntax GetCompilationUnitFromMethod(
|
||||
/// <returns>A <see cref="CompilationUnitSyntax"/> object wrapping <paramref name="memberDeclarationSyntax"/>.</returns>
|
||||
private static CompilationUnitSyntax GetCompilationUnitFromMember(
|
||||
HierarchyInfo hierarchyInfo,
|
||||
MethodDeclarationSyntax methodDeclaration,
|
||||
MemberDeclarationSyntax memberDeclarationSyntax,
|
||||
bool canUseSkipLocalsInit)
|
||||
{
|
||||
// Method attributes
|
||||
@@ -71,6 +71,6 @@ partial class ID2D1ShaderGenerator
|
||||
attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
|
||||
}
|
||||
|
||||
return hierarchyInfo.GetSyntax(methodDeclaration.AddAttributeLists(attributes.ToArray()));
|
||||
return hierarchyInfo.GetSyntax(memberDeclarationSyntax.AddAttributeLists(attributes.ToArray()));
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,16 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
|
||||
using ImmutableArrayBuilder<DiagnosticInfo> diagnostics = ImmutableArrayBuilder<DiagnosticInfo>.Rent();
|
||||
|
||||
// EffectId info
|
||||
ImmutableArray<byte> effectId = EffectId.GetInfo(context.SemanticModel.Compilation, typeSymbol);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// EffectDisplayName info
|
||||
string effectDisplayName = EffectDisplayName.GetInfo(context.SemanticModel.Compilation, typeSymbol);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// LoadDispatchData() info
|
||||
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
|
||||
diagnostics,
|
||||
@@ -115,6 +125,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
|
||||
return new D2D1ShaderInfo(
|
||||
Hierarchy: HierarchyInfo.From(typeSymbol),
|
||||
EffectId: new EffectIdInfo(effectId),
|
||||
EffectDisplayName: effectDisplayName,
|
||||
DispatchData: new DispatchDataInfo(fieldInfos, constantBufferSizeInBytes),
|
||||
InputTypes: new InputTypesInfo(inputTypes),
|
||||
ResourceTextureDescriptions: new ResourceTextureDescriptionsInfo(resourceTextureDescriptions),
|
||||
@@ -136,6 +148,35 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
shaderInfoWithErrors
|
||||
.Select(static (item, _) => item.Diagnostcs));
|
||||
|
||||
// Get the EffectDisplayName info (hierarchy and effect display name)
|
||||
IncrementalValuesProvider<(HierarchyInfo Hierarchy, string EffectDisplayName)> effectDisplayNameInfo =
|
||||
shaderInfoWithErrors
|
||||
.Select(static (item, _) => (item.Hierarchy, item.EffectDisplayName));
|
||||
|
||||
// Generate the EffectDisplayName properties
|
||||
context.RegisterSourceOutput(effectDisplayNameInfo, static (context, item) =>
|
||||
{
|
||||
PropertyDeclarationSyntax effectDisplayNameProperty = EffectDisplayName.GetSyntax(item.EffectDisplayName);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDisplayNameProperty, canUseSkipLocalsInit: false);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(EffectDisplayName)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
|
||||
});
|
||||
|
||||
// Get the EffectId info (hierarchy and effect id info)
|
||||
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EffectIdInfo EffectId)> effectIdInfo =
|
||||
shaderInfoWithErrors
|
||||
.Select(static (item, _) => (item.Hierarchy, item.EffectId));
|
||||
|
||||
// Generate the EffectId properties
|
||||
context.RegisterSourceOutput(effectIdInfo, static (context, item) =>
|
||||
{
|
||||
PropertyDeclarationSyntax effectDisplayNameProperty = EffectId.GetSyntax(item.EffectId, out Func<SyntaxNode, SourceText> fixup);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDisplayNameProperty, canUseSkipLocalsInit: false);
|
||||
SourceText text = fixup(compilationUnit);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(EffectId)}.g.cs", text);
|
||||
});
|
||||
|
||||
// Get the GetInputCount() info (hierarchy and input count)
|
||||
IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo =
|
||||
shaderInfoWithErrors
|
||||
@@ -145,7 +186,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
context.RegisterSourceOutput(inputCountInfo, static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax getInputCountMethod = GetInputCount.GetSyntax(item.InputCount);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getInputCountMethod, canUseSkipLocalsInit: false);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, getInputCountMethod, canUseSkipLocalsInit: false);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetInputCount)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
|
||||
});
|
||||
@@ -159,7 +200,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
context.RegisterSourceOutput(inputTypesInfo, static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax getInputTypeMethod = GetInputType.GetSyntax(item.InputTypes.InputTypes);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetInputType)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
|
||||
});
|
||||
@@ -173,7 +214,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
context.RegisterSourceOutput(resourceTextureDescriptionsInfo, static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax getInputTypeMethod = LoadResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadResourceTextureDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
|
||||
});
|
||||
@@ -187,7 +228,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
context.RegisterSourceOutput(initializeFromDispatchDataInfo, static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax loadDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Dispatch);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadDispatchDataMethod, canUseSkipLocalsInit: false);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, loadDispatchDataMethod, canUseSkipLocalsInit: false);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(InitializeFromDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
|
||||
});
|
||||
@@ -201,7 +242,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
context.RegisterSourceOutput(dispatchDataInfo, static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Info.Dispatch);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, loadDispatchDataMethod, item.CanUseSkipLocalsInit);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Info.Hierarchy, loadDispatchDataMethod, item.CanUseSkipLocalsInit);
|
||||
|
||||
context.AddSource($"{item.Info.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
|
||||
});
|
||||
@@ -221,7 +262,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
context.RegisterSourceOutput(hlslSourceInfo, static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Info.HlslSource, item.Info.Hierarchy.Hierarchy.Length, item.CanUseRawMultilineStringLiterals);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: false);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Info.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: false);
|
||||
|
||||
context.AddSource($"{item.Info.Hierarchy.FullyQualifiedMetadataName}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
|
||||
});
|
||||
@@ -279,7 +320,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
context.RegisterSourceOutput(embeddedBytecode, static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax loadBytecodeMethod = LoadBytecode.GetSyntax(item.BytecodeInfo, out Func<SyntaxNode, SourceText> fixup);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadBytecodeMethod, canUseSkipLocalsInit: false);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, loadBytecodeMethod, canUseSkipLocalsInit: false);
|
||||
SourceText text = fixup(compilationUnit);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", text);
|
||||
@@ -294,7 +335,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
context.RegisterSourceOutput(outputBufferInfo, static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax getOutputBufferMethod = GetOutputBuffer.GetSyntax(item.OutputBuffer);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getOutputBufferMethod, canUseSkipLocalsInit: false);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, getOutputBufferMethod, canUseSkipLocalsInit: false);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetOutputBuffer)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
|
||||
});
|
||||
@@ -309,7 +350,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
context.RegisterSourceOutput(inputDescriptionsInfo, static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax loadInputDescriptionsMethod = LoadInputDescriptions.GetSyntax(item.Info.InputDescriptions);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, loadInputDescriptionsMethod, item.CanUseSkipLocalsInit);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Info.Hierarchy, loadInputDescriptionsMethod, item.CanUseSkipLocalsInit);
|
||||
|
||||
context.AddSource($"{item.Info.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadInputDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
|
||||
});
|
||||
@@ -323,7 +364,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
context.RegisterSourceOutput(pixelOptionsInfo, static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax getPixelOptionsMethod = GetPixelOptions.GetSyntax(item.PixelOptions);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getPixelOptionsMethod, canUseSkipLocalsInit: false);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, getPixelOptionsMethod, canUseSkipLocalsInit: false);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetPixelOptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
|
||||
});
|
||||
|
||||
@@ -7,6 +7,8 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
/// A model representing all necessary info for a full generation pass for a D2D1 shader.
|
||||
/// </summary>
|
||||
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
|
||||
/// <param name="EffectId">The effect id info for the shader type.</param>
|
||||
/// <param name="EffectDisplayName">The effect display name for the shader type.</param>
|
||||
/// <param name="DispatchData">The gathered shader dispatch data.</param>
|
||||
/// <param name="InputTypes">The gathered input types for the shader.</param>
|
||||
/// <param name="ResourceTextureDescriptions">The gathered resource texture descriptions for the shader.</param>
|
||||
@@ -17,6 +19,8 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
|
||||
internal sealed record D2D1ShaderInfo(
|
||||
HierarchyInfo Hierarchy,
|
||||
EffectIdInfo EffectId,
|
||||
string EffectDisplayName,
|
||||
DispatchDataInfo DispatchData,
|
||||
InputTypesInfo InputTypes,
|
||||
ResourceTextureDescriptionsInfo ResourceTextureDescriptions,
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
|
||||
/// <summary>
|
||||
/// A model representing info to use to generate an effect id for a shader.
|
||||
/// </summary>
|
||||
/// <param name="Bytes">The bytes for the processed effect id.</param>
|
||||
internal sealed record EffectIdInfo(EquatableArray<byte> Bytes);
|
||||
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
|
||||
namespace ComputeSharp.D2D1;
|
||||
|
||||
/// <summary>
|
||||
/// An attribute for a D2D1 shader indicating the display name of the shader effect to create.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This only applies to effects created from <see cref="Interop.D2D1PixelShaderEffect"/>.
|
||||
/// </remarks>
|
||||
[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
|
||||
public sealed class D2DEffectDisplayNameAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="D2DEffectDisplayNameAttribute"/> type with the specified arguments.
|
||||
/// </summary>
|
||||
/// <param name="value">The value for the display name.</param>
|
||||
public D2DEffectDisplayNameAttribute(string value)
|
||||
{
|
||||
Value = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display name value.
|
||||
/// </summary>
|
||||
public string Value { get; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
|
||||
namespace ComputeSharp.D2D1;
|
||||
|
||||
/// <summary>
|
||||
/// An attribute for a D2D1 shader indicating the id of the shader effect to create.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This only applies to effects created from <see cref="Interop.D2D1PixelShaderEffect"/>.
|
||||
/// </remarks>
|
||||
[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
|
||||
public sealed class D2DEffectIdAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="D2DEffectIdAttribute"/> type with the specified arguments.
|
||||
/// </summary>
|
||||
/// <param name="value">The value for the effect id.</param>
|
||||
public D2DEffectIdAttribute(string value)
|
||||
{
|
||||
Value = Guid.Parse(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the effect id value.
|
||||
/// </summary>
|
||||
public Guid Value { get; }
|
||||
}
|
||||
@@ -11,6 +11,22 @@ namespace ComputeSharp.D2D1.__Internals;
|
||||
[Obsolete("This interface is not intended to be used directly by user code")]
|
||||
public interface ID2D1Shader
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the effect id of the D2D effect using this shader.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This only applies to effects created from <see cref="Interop.D2D1PixelShaderEffect"/>.
|
||||
/// </remarks>
|
||||
ref readonly Guid EffectId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display name of the D2D effect using this shader.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This only applies to effects created from <see cref="Interop.D2D1PixelShaderEffect"/>.
|
||||
/// </remarks>
|
||||
string EffectDisplayName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the current shader from a buffer with the serialized dispatch data.
|
||||
/// </summary>
|
||||
|
||||
@@ -18,6 +18,32 @@ namespace ComputeSharp.D2D1.Interop;
|
||||
/// </summary>
|
||||
public static unsafe class D2D1PixelShaderEffect
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the effect id of the D2D effect using this shader.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of D2D1 pixel shader to get the effect id for.</typeparam>
|
||||
/// <returns>The effect id of the D2D effect using <typeparamref name="T"/> shaders.</returns>
|
||||
public static ref readonly Guid GetEffectId<T>()
|
||||
where T : unmanaged, ID2D1PixelShader
|
||||
{
|
||||
Unsafe.SkipInit(out T shader);
|
||||
|
||||
return ref shader.EffectId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the effect display name of the D2D effect using this shader.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of D2D1 pixel shader to get the effect id for.</typeparam>
|
||||
/// <returns>The effect display name of the D2D effect using <typeparamref name="T"/> shaders.</returns>
|
||||
public static string GetEffectDisplayName<T>()
|
||||
where T : unmanaged, ID2D1PixelShader
|
||||
{
|
||||
Unsafe.SkipInit(out T shader);
|
||||
|
||||
return shader.EffectDisplayName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers an effect from an input D2D1 pixel shader, by calling <c>ID2D1Factory1::RegisterEffectFromString</c>.
|
||||
/// </summary>
|
||||
@@ -26,7 +52,10 @@ public static unsafe class D2D1PixelShaderEffect
|
||||
/// <param name="effectId">The <see cref="Guid"/> of the registered effect, which can be used to call <c>ID2D1DeviceContext::CreateEffect</c>.</param>
|
||||
/// <exception cref="ArgumentNullException">Thrown if <paramref name="d2D1Factory1"/> is <see langword="null"/>.</exception>
|
||||
/// <exception cref="InvalidOperationException">Thrown if an effect is registered multiple times with different properties.</exception>
|
||||
/// <remarks>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.</remarks>
|
||||
/// <remarks>
|
||||
/// <para>The returned <paramref name="effectId"/> value is the same as that returned by <see cref="GetEffectId{T}"/>.</para>
|
||||
/// <para>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.</para>
|
||||
/// </remarks>
|
||||
public static void RegisterForD2D1Factory1<T>(void* d2D1Factory1, out Guid effectId)
|
||||
where T : unmanaged, ID2D1PixelShader
|
||||
{
|
||||
@@ -42,7 +71,7 @@ public static unsafe class D2D1PixelShaderEffect
|
||||
<Effect>
|
||||
<Property name='DisplayName' type='string' value='
|
||||
""");
|
||||
writer.WriteRaw(typeof(T).FullName!);
|
||||
writer.WriteRaw(GetEffectDisplayName<T>());
|
||||
writer.WriteRaw("""
|
||||
'/>
|
||||
<Property name='Author' type='string' value='ComputeSharp.D2D1'/>
|
||||
@@ -261,9 +290,8 @@ public static unsafe class D2D1PixelShaderEffect
|
||||
/// To make the deserialization easier, the <see cref="D2D1EffectRegistrationData"/> type can be used to read and validate the returned blob.
|
||||
/// The leading blob id will determine what subtype should be used to deserialize the blob (eg. <see cref="D2D1EffectRegistrationData.V1"/>).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.
|
||||
/// </para>
|
||||
/// <para>The returned <paramref name="effectId"/> value is the same as that returned by <see cref="GetEffectId{T}"/>.</para>
|
||||
/// <para>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.</para>
|
||||
/// </remarks>
|
||||
public static ReadOnlyMemory<byte> GetRegistrationBlob<T>(out Guid effectId)
|
||||
where T : unmanaged, ID2D1PixelShader
|
||||
@@ -283,7 +311,7 @@ public static unsafe class D2D1PixelShaderEffect
|
||||
<Effect>
|
||||
<Property name='DisplayName' type='string' value='
|
||||
"""u8);
|
||||
writer.WriteAsUtf8(typeof(T).FullName!);
|
||||
writer.WriteAsUtf8(GetEffectDisplayName<T>());
|
||||
writer.WriteRaw("""
|
||||
'/>
|
||||
<Property name='Author' type='string' value='ComputeSharp.D2D1'/>
|
||||
|
||||
@@ -165,7 +165,7 @@ internal unsafe partial struct PixelShaderEffect
|
||||
private static For<T> CreateInstance()
|
||||
{
|
||||
// Load all shader properties
|
||||
Guid shaderId = typeof(T).GUID;
|
||||
Guid shaderId = D2D1PixelShaderEffect.GetEffectId<T>();
|
||||
int constantBufferSize = D2D1PixelShader.GetConstantBufferSize<T>();
|
||||
D2D1BufferPrecision bufferPrecision = D2D1PixelShader.GetOutputBufferPrecision<T>();
|
||||
D2D1ChannelDepth channelDepth = D2D1PixelShader.GetOutputBufferChannelDepth<T>();
|
||||
|
||||
@@ -8,6 +8,21 @@ namespace ComputeSharp.SourceGeneration.Extensions;
|
||||
/// </summary>
|
||||
internal static class AttributeDataExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Tries to get the location of the input <see cref="AttributeData"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="attributeData">The input <see cref="AttributeData"/> instance to get the location for.</param>
|
||||
/// <returns>The resulting location for <paramref name="attributeData"/>, if a syntax reference is available.</returns>
|
||||
public static Location? GetLocation(this AttributeData attributeData)
|
||||
{
|
||||
if (attributeData.ApplicationSyntaxReference is { } syntaxReference)
|
||||
{
|
||||
return syntaxReference.SyntaxTree.GetLocation(syntaxReference.Span);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get a constructor argument at a given index from the input <see cref="AttributeData"/> instance.
|
||||
/// </summary>
|
||||
|
||||
@@ -165,4 +165,116 @@ public partial class D2D1PixelShaderEffectTests
|
||||
return this.a + this.b + this.c.X + this.d + this.e;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void DefaultEffectId_MatchesValue()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<ShaderWithDefaultEffectId>(d2D1Factory2.Get(), out Guid effectId);
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<ShaderWithDefaultEffectId2>(d2D1Factory2.Get(), out Guid effectId2);
|
||||
|
||||
// Ensure that the dynamically generated GUIDs are deterministic and stable
|
||||
Assert.AreEqual(Guid.Parse("F5287184-0EC7-0BC6-3942-8BFB70E77C4B"), effectId);
|
||||
Assert.AreEqual(Guid.Parse("96310279-E716-D336-5097-BE516792CBF0"), effectId2);
|
||||
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectId<ShaderWithDefaultEffectId>(), effectId);
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectId<ShaderWithDefaultEffectId2>(), effectId2);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
private partial struct ShaderWithDefaultEffectId : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
private partial struct ShaderWithDefaultEffectId2 : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void ExplicitEffectId_MatchesValue()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<ShaderWithExplicitEffectId>(d2D1Factory2.Get(), out Guid effectId);
|
||||
|
||||
Assert.AreEqual(Guid.Parse("8E1F7F49-EF0D-4242-8912-08ADA36AB4EC"), effectId);
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectId<ShaderWithExplicitEffectId>(), effectId);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DEffectId("8E1F7F49-EF0D-4242-8912-08ADA36AB4EC")]
|
||||
private partial struct ShaderWithExplicitEffectId : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void DefaultEffectDisplayName_MatchesValue()
|
||||
{
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName<ShaderWithDefaultEffectDisplayName>(), typeof(ShaderWithDefaultEffectDisplayName).FullName);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
private partial struct ShaderWithDefaultEffectDisplayName : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void ExplicitEffectDisplayName_MatchesValue()
|
||||
{
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName<ShaderWithExplicitEffectDisplayName>(), "Fancy blur");
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName<ShaderWithExplicitEffectDisplayName2>(), "Fancy"<");
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName<ShaderWithExplicitEffectDisplayName3>(), "FancyBlurEffect");
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DEffectDisplayName("Fancy blur")]
|
||||
private partial struct ShaderWithExplicitEffectDisplayName : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DEffectDisplayName("Fancy\"<")]
|
||||
private partial struct ShaderWithExplicitEffectDisplayName2 : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DEffectDisplayName("Fancy\r\nBlur\nEffect")]
|
||||
private partial struct ShaderWithExplicitEffectDisplayName3 : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする