Switch D2D1 generation methods to use indented writer
このコミットが含まれているのは:
1 親
bc1fc17b21
コミット
6accd17c9f
14ファイル変更
+555
-1372
検索条件に一致するファイルはありません
+51
-79
@@ -1,10 +1,5 @@
|
||||
using ComputeSharp.D2D1.__Internals;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
@@ -15,85 +10,62 @@ partial class ID2D1ShaderGenerator
|
||||
partial class EffectId
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectId</c> property.
|
||||
/// Writes the <c>EffectId</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="EquatableArray{T}"/> instance with the effect GUID.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectId</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetSyntax(EquatableArray<byte> info)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// Prepare the initialization text
|
||||
string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(info.AsSpan());
|
||||
writer.WriteLine("readonly ref readonly global::System.Guid global::ComputeSharp.D2D1.__Internals.ID2D1Shader.EffectId");
|
||||
|
||||
ExpressionSyntax effectIdExpression = ParseExpression($$"""new byte[] { {{effectIdLiterals}} }""");
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
writer.WriteLine("[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]");
|
||||
writer.WriteLine("get");
|
||||
|
||||
// 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(effectIdExpression))));
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
writer.WriteLine($"global::System.ReadOnlySpan<byte> bytes = new byte[]");
|
||||
|
||||
// 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)))));
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Write the bytes like so:
|
||||
//
|
||||
// b[0], b[1], b[2], b[3],
|
||||
// b[4], b[5],
|
||||
// b[6], b[7],
|
||||
// b[8],
|
||||
// b[9],
|
||||
// b[10],
|
||||
// b[11],
|
||||
// b[12],
|
||||
// b[13],
|
||||
// b[14],
|
||||
// b[15],
|
||||
// b[16],
|
||||
// b[17]
|
||||
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[..4], writer);
|
||||
writer.WriteLine(",");
|
||||
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[4..6], writer);
|
||||
writer.WriteLine(",");
|
||||
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[6..8], writer);
|
||||
writer.WriteLine(",");
|
||||
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[8])},");
|
||||
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[9])},");
|
||||
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[10])},");
|
||||
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[11])},");
|
||||
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[12])},");
|
||||
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[13])},");
|
||||
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[14])},");
|
||||
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[15])},");
|
||||
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[16])},");
|
||||
writer.WriteLine(SyntaxFormattingHelper.GetByteExpression(info.EffectId[17]));
|
||||
}
|
||||
|
||||
// This code produces a property 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));
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("return ref global::System.Runtime.CompilerServices.Unsafe.As<byte, global::System.Guid>(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(bytes));");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
-44
@@ -1,9 +1,5 @@
|
||||
using ComputeSharp.D2D1.__Internals;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
@@ -14,69 +10,64 @@ partial class ID2D1ShaderGenerator
|
||||
partial class EffectMetadata
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectDisplayName</c> property.
|
||||
/// Writes the <c>EffectDisplayName</c> property.
|
||||
/// </summary>
|
||||
/// <param name="effectDisplayName">The input effect display name value, if available.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectDisplayName</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetEffectDisplayNameSyntax(string? effectDisplayName)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteEffectDisplayNameSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
return GetEffectMetadataSyntax("EffectDisplayName", effectDisplayName);
|
||||
WriteEffectMetadataSyntax("EffectDisplayName", info.EffectDisplayName, writer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectDescription</c> property.
|
||||
/// Writes the <c>EffectDescription</c> property.
|
||||
/// </summary>
|
||||
/// <param name="effectDescription">The input effect description value, if available.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectDescription</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetEffectDescriptionSyntax(string? effectDescription)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteEffectDescriptionSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
return GetEffectMetadataSyntax("EffectDescription", effectDescription);
|
||||
WriteEffectMetadataSyntax("EffectDescription", info.EffectDescription, writer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectCategory</c> property.
|
||||
/// Writes the <c>EffectCategory</c> property.
|
||||
/// </summary>
|
||||
/// <param name="effectCategory">The input effect category value, if available.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectCategory</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetEffectCategorySyntax(string? effectCategory)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteEffectCategorySyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
return GetEffectMetadataSyntax("EffectCategory", effectCategory);
|
||||
WriteEffectMetadataSyntax("EffectCategory", info.EffectCategory, writer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectAuthor</c> property.
|
||||
/// Writes the <c>EffectAuthor</c> property.
|
||||
/// </summary>
|
||||
/// <param name="effectAuthor">The input effect author value, if available.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectAuthor</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetEffectAuthorSyntax(string? effectAuthor)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteEffectAuthorSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
return GetEffectMetadataSyntax("EffectAuthor", effectAuthor);
|
||||
WriteEffectMetadataSyntax("EffectAuthor", info.EffectAuthor, writer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for a given metadata property.
|
||||
/// Writes a specified metadata property.
|
||||
/// </summary>
|
||||
/// <param name="propertyName">The property name to generate.</param>
|
||||
/// <param name="metadataValue">The input effect metadata value, if available.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the given metadata property.</returns>
|
||||
private static PropertyDeclarationSyntax GetEffectMetadataSyntax(string propertyName, string? metadataValue)
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
private static void WriteEffectMetadataSyntax(string propertyName, string? metadataValue, IndentedTextWriter writer)
|
||||
{
|
||||
// Get the expression: either a string literal, or just null
|
||||
ExpressionSyntax metadataValueExpression = metadataValue switch
|
||||
{
|
||||
{ } => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(metadataValue)),
|
||||
_ => LiteralExpression(SyntaxKind.NullLiteralExpression)
|
||||
};
|
||||
writer.Write($"readonly string? global::ComputeSharp.D2D1.__Internals.ID2D1Shader.{propertyName} => ");
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly string? global::ComputeSharp.D2D1.__Internals.ID2D1Shader.<PROPERTY_NAME> => <METADATA_VALUE>;
|
||||
return
|
||||
PropertyDeclaration(NullableType(PredefinedType(Token(SyntaxKind.StringKeyword))), Identifier(propertyName))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(metadataValueExpression))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
// Append null or the metadata value as a string literal
|
||||
if (metadataValue is null)
|
||||
{
|
||||
writer.WriteLine("null;");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine($"\"{metadataValue}\";");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-24
@@ -1,11 +1,5 @@
|
||||
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 static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
@@ -16,25 +10,16 @@ partial class ID2D1ShaderGenerator
|
||||
partial class HlslSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>HlslSource</c> property.
|
||||
/// Writes the <c>HlslSource</c> property.
|
||||
/// </summary>
|
||||
/// <param name="hlslSource">The input HLSL source.</param>
|
||||
/// <param name="hierarchyDepth">The depth of the hierarchy for this type (used to calculate the right indentation).</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>HlslSource</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetSyntax(string hlslSource, int hierarchyDepth)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// The indentation level is the current depth + 1 (for the property)
|
||||
SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSource, hierarchyDepth + 1);
|
||||
|
||||
// This code produces a property declaration as follows:
|
||||
//
|
||||
// readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslSource => <HLSL_SOURCE>;
|
||||
return
|
||||
PropertyDeclaration(PredefinedType(Token(SyntaxKind.StringKeyword)), Identifier("HlslSource"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression)))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
writer.WriteLine("readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslSource =>");
|
||||
writer.WriteLine("\"\"\"");
|
||||
writer.WriteLine(info.HlslInfoKey.HlslSource, isMultiline: true);
|
||||
writer.WriteLine("\"\"\";");
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
-146
@@ -1,12 +1,5 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.D2D1.__Internals;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
@@ -17,156 +10,63 @@ partial class ID2D1ShaderGenerator
|
||||
partial class InitializeFromDispatchData
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>InitializeFromDispatchData</c> method.
|
||||
/// Writes the <c>InitializeFromDispatchData</c> method.
|
||||
/// </summary>
|
||||
/// <param name="fields">The discovered fields of the current shader.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>InitializeFromDispatchData</c> method.</returns>
|
||||
public static MethodDeclarationSyntax GetSyntax(EquatableArray<FieldInfo> fields)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan<byte> data)
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(InitializeFromDispatchData)))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddParameterListParameters(Parameter(Identifier("data")).WithType(
|
||||
GenericName(Identifier("global::System.ReadOnlySpan"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))))
|
||||
.WithBody(Block(GetDispatchDataUnloadingStatements(fields)));
|
||||
}
|
||||
writer.WriteLine("readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan<byte> data)");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of statements to initialize a shader from a serialized dispatch data buffer.
|
||||
/// </summary>
|
||||
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
|
||||
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to initialize a shader from the serialized dispatch data buffer.</returns>
|
||||
private static ImmutableArray<StatementSyntax> GetDispatchDataUnloadingStatements(ImmutableArray<FieldInfo> fieldInfos)
|
||||
{
|
||||
// If there are no fields, just return no statements
|
||||
if (fieldInfos.IsEmpty)
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
return ImmutableArray<StatementSyntax>.Empty;
|
||||
}
|
||||
|
||||
using ImmutableArrayBuilder<StatementSyntax> statements = ImmutableArrayBuilder<StatementSyntax>.Rent();
|
||||
|
||||
// Insert the fallback for empty shaders. This will generate the following code:
|
||||
//
|
||||
// if (data.IsEmpty)
|
||||
// {
|
||||
// return;
|
||||
// }
|
||||
statements.Add(
|
||||
IfStatement(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("data"),
|
||||
IdentifierName("IsEmpty")),
|
||||
Block(ReturnStatement())));
|
||||
|
||||
// ref readonly ConstantBuffer buffer = ref global::System.Runtime.CompilerServices.Unsafe.As<byte, ConstantBuffer>(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data));
|
||||
statements.Add(
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(RefType(IdentifierName("ConstantBuffer")).WithReadOnlyKeyword(Token(SyntaxKind.ReadOnlyKeyword)))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("buffer"))
|
||||
.WithInitializer(
|
||||
EqualsValueClause(RefExpression(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
|
||||
GenericName(Identifier("As"))
|
||||
.AddTypeArgumentListArguments(
|
||||
PredefinedType(Token(SyntaxKind.ByteKeyword)),
|
||||
IdentifierName("ConstantBuffer"))))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"),
|
||||
IdentifierName("GetReference")))
|
||||
.AddArgumentListArguments(Argument(IdentifierName("data"))))
|
||||
.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))))))));
|
||||
|
||||
// Generate loading statements for each captured field
|
||||
foreach (FieldInfo fieldInfo in fieldInfos)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
// If there are no fields, the method body is just empty
|
||||
if (info.Fields.IsEmpty)
|
||||
{
|
||||
case FieldInfo.Primitive primitive:
|
||||
return;
|
||||
}
|
||||
|
||||
// Read a primitive value:
|
||||
//
|
||||
// global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.<FIELD_PATH>) = buffer.<CONSTANT_BUFFER_PATH>;
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
|
||||
IdentifierName("AsRef")))
|
||||
.AddArgumentListArguments(
|
||||
Argument(MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
ThisExpression(),
|
||||
IdentifierName(string.Join(".", primitive.FieldPath))))
|
||||
.WithRefKindKeyword(Token(SyntaxKind.InKeyword))),
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("buffer"),
|
||||
IdentifierName(string.Join("_", primitive.FieldPath))))));
|
||||
break;
|
||||
// Insert the fallback for empty shaders. This will generate the following code:
|
||||
writer.WriteLine("if (data.IsEmpty)");
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string fieldPath = string.Join(".", matrix.FieldPath);
|
||||
string fieldNamePrefix = string.Join("_", matrix.FieldPath);
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
writer.WriteLine("return;");
|
||||
}
|
||||
|
||||
// Read all rows of a given matrix type:
|
||||
//
|
||||
// global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.<FIELD_PATH>)[0] = buffer.<CONSTANT_BUFFER_ROW_0_PATH>;
|
||||
// global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.<FIELD_PATH>)[1] = buffer.<CONSTANT_BUFFER_ROW_1_PATH>;
|
||||
// ...
|
||||
// global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.<FIELD_PATH>)[N] = buffer.<CONSTANT_BUFFER_ROW_N_PATH>;
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ElementAccessExpression(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
|
||||
IdentifierName("AsRef")))
|
||||
.AddArgumentListArguments(
|
||||
Argument(MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
ThisExpression(),
|
||||
IdentifierName(fieldPath)))
|
||||
.WithRefKindKeyword(Token(SyntaxKind.InKeyword))))
|
||||
.AddArgumentListArguments(
|
||||
Argument(LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(j)))),
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("buffer"),
|
||||
IdentifierName($"{fieldNamePrefix}_{j}")))));
|
||||
}
|
||||
// Get a reference to the data through the generated native layout type
|
||||
writer.WriteLine("ref readonly ConstantBuffer buffer = ref global::System.Runtime.CompilerServices.Unsafe.As<byte, ConstantBuffer>(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data));");
|
||||
|
||||
break;
|
||||
// Generate loading statements for each captured field
|
||||
foreach (FieldInfo fieldInfo in info.Fields)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
{
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Read a primitive value
|
||||
writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.{string.Join(".", primitive.FieldPath)}) = buffer.{string.Join("_", primitive.FieldPath)};");
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string fieldPath = string.Join(".", matrix.FieldPath);
|
||||
string fieldNamePrefix = string.Join("_", matrix.FieldPath);
|
||||
|
||||
// Read all rows of a given matrix type:
|
||||
//
|
||||
// global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.<FIELD_PATH>)[0] = buffer.<CONSTANT_BUFFER_ROW_0_PATH>;
|
||||
// global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.<FIELD_PATH>)[1] = buffer.<CONSTANT_BUFFER_ROW_1_PATH>;
|
||||
// ...
|
||||
// global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.<FIELD_PATH>)[N] = buffer.<CONSTANT_BUFFER_ROW_N_PATH>;
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.{fieldPath})[0] = buffer.{fieldNamePrefix}_{j};");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return statements.ToImmutable();
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-19
@@ -1,9 +1,5 @@
|
||||
using ComputeSharp.D2D1.__Internals;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
@@ -16,21 +12,13 @@ partial class ID2D1ShaderGenerator
|
||||
private static partial class InputCount
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>InputCount</c> property.
|
||||
/// Writes the <c>InputCount</c> property.
|
||||
/// </summary>
|
||||
/// <param name="inputCount">The number of inputs for the shader.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>InputCount</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetSyntax(int inputCount)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// This code produces a property declaration as follows:
|
||||
//
|
||||
// readonly int global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputCount => <INPUT_COUNT>;
|
||||
return
|
||||
PropertyDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), Identifier(nameof(InputCount)))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(inputCount))))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
writer.WriteLine($"readonly int global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputCount => {info.InputTypes.Length};");
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
-92
@@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using ComputeSharp.D2D1.__Internals;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
@@ -7,8 +6,6 @@ using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -18,112 +15,63 @@ partial class ID2D1ShaderGenerator
|
||||
private static partial class InputDescriptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>InputDescriptions</c> property.
|
||||
/// Writes the <c>InputDescriptions</c> property.
|
||||
/// </summary>
|
||||
/// <param name="inputDescriptions">The input descriptions info gathered for the current shader.</param>
|
||||
/// <param name="additionalDataMembers">Any additional <see cref="MemberDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>InputDescriptions</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetSyntax(EquatableArray<InputDescription> inputDescriptions, out MemberDeclarationSyntax[] additionalDataMembers)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
ExpressionSyntax memoryExpression;
|
||||
writer.WriteLine("readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1InputDescription> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => ");
|
||||
|
||||
// If there are no input descriptions, just return a default expression.
|
||||
// Otherwise, declare the shared array and return it from the property.
|
||||
if (inputDescriptions.Length == 0)
|
||||
// Otherwise, return the shared array with cached input descriptions.
|
||||
if (info.InputDescriptions.IsEmpty)
|
||||
{
|
||||
memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
|
||||
additionalDataMembers = Array.Empty<MemberDeclarationSyntax>();
|
||||
writer.WriteLine("default;");
|
||||
}
|
||||
else
|
||||
{
|
||||
memoryExpression = MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("Data"),
|
||||
IdentifierName(nameof(InputDescriptions)));
|
||||
|
||||
additionalDataMembers = new[] { GetArrayDeclaration(inputDescriptions) };
|
||||
writer.WriteLine("Data.InputDescriptions;");
|
||||
}
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1InputDescription> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => <EXPRESSION>;
|
||||
return
|
||||
PropertyDeclaration(
|
||||
GenericName(Identifier("global::System.ReadOnlyMemory"))
|
||||
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1InputDescription")),
|
||||
Identifier(nameof(InputDescriptions)))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(memoryExpression))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the array declaration for the given input descriptions.
|
||||
/// Registers a callback to generate an additional data member, if needed.
|
||||
/// </summary>
|
||||
/// <param name="inputDescriptions">The input descriptions info gathered for the current shader.</param>
|
||||
/// <returns>The array declaration for the given input descriptions.</returns>
|
||||
private static MemberDeclarationSyntax GetArrayDeclaration(EquatableArray<InputDescription> inputDescriptions)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional data members.</param>
|
||||
public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks)
|
||||
{
|
||||
using ImmutableArrayBuilder<ExpressionSyntax> inputDescriptionExpressions = ImmutableArrayBuilder<ExpressionSyntax>.Rent();
|
||||
|
||||
foreach (InputDescription inputDescription in inputDescriptions)
|
||||
// If there are no input descriptions, there is nothing to di
|
||||
if (info.ResourceTextureDescriptions.IsEmpty)
|
||||
{
|
||||
// Create the description expression (excluding level of detail):
|
||||
//
|
||||
// new(<INDEX>, <FILTER>)
|
||||
ImplicitObjectCreationExpressionSyntax inputDescriptionExpression =
|
||||
ImplicitObjectCreationExpression()
|
||||
.AddArgumentListArguments(
|
||||
Argument(LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(inputDescription.Index))),
|
||||
Argument(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::ComputeSharp.D2D1.D2D1Filter"),
|
||||
IdentifierName(inputDescription.Filter.ToString()))));
|
||||
|
||||
// Add the level of detail, if needed:
|
||||
//
|
||||
// { LevelOfDetailCount = <LEVEL_OF_DETAIL_COUNT> }
|
||||
if (inputDescription.LevelOfDetailCount != 0)
|
||||
{
|
||||
inputDescriptionExpression =
|
||||
inputDescriptionExpression
|
||||
.WithInitializer(
|
||||
InitializerExpression(SyntaxKind.ObjectInitializerExpression)
|
||||
.AddExpressions(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
IdentifierName("LevelOfDetailCount"),
|
||||
LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(inputDescription.LevelOfDetailCount)))));
|
||||
}
|
||||
|
||||
inputDescriptionExpressions.Add(inputDescriptionExpression);
|
||||
return;
|
||||
}
|
||||
|
||||
// Declare the singleton property to get the memory instance:
|
||||
//
|
||||
// /// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1InputDescription"/> array instance.</summary>
|
||||
// public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = { <INPUT_DESCRIPTIONS> };
|
||||
return
|
||||
FieldDeclaration(
|
||||
VariableDeclaration(
|
||||
ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1InputDescription"))
|
||||
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier(nameof(InputDescriptions)))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
InitializerExpression(SyntaxKind.ArrayInitializerExpression)
|
||||
.AddExpressions(inputDescriptionExpressions.ToArray())))))
|
||||
.AddModifiers(
|
||||
Token(SyntaxKind.PublicKeyword),
|
||||
Token(SyntaxKind.StaticKeyword),
|
||||
Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithLeadingTrivia(Comment("""/// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1InputDescription"/> array instance.</summary>"""));
|
||||
// Declare the shared array with input descriptions
|
||||
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("""/// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1InputDescription"/> array instance.</summary>""");
|
||||
writer.WriteLine("""public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = """);
|
||||
|
||||
// Initialize all input descriptions
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
for (int i = 0; i < info.InputDescriptions.Length; i++)
|
||||
{
|
||||
InputDescription description = info.InputDescriptions[i];
|
||||
|
||||
writer.Write($$"""new global::ComputeSharp.D2D1.Interop.D2D1InputDescription({description.Index}, {description.Filter}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }""");
|
||||
|
||||
if (i < info.InputDescriptions.Length - 1)
|
||||
{
|
||||
writer.WriteLine(",");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
callbacks.Add(Callback);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+85
-252
@@ -1,13 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
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 static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
@@ -18,270 +10,111 @@ partial class ID2D1ShaderGenerator
|
||||
partial class InputTypes
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>InputTypes</c> property.
|
||||
/// Writes the <c>InputTypes</c> property.
|
||||
/// </summary>
|
||||
/// <param name="inputTypes">The input types for the shader.</param>
|
||||
/// <param name="additionalTypes">Any additional <see cref="TypeDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
|
||||
/// <returns>The resulting <see cref="MemberDeclarationSyntax"/> instance for the <c>InputTypes</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetSyntax(ImmutableArray<uint> inputTypes, out TypeDeclarationSyntax[] additionalTypes)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
ExpressionSyntax memoryExpression;
|
||||
writer.WriteLine("readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => ");
|
||||
|
||||
// If there are no inputs, simply return a default expression.
|
||||
// Otherwise, declare the memory manager and access it.
|
||||
if (inputTypes.Length == 0)
|
||||
// If there are no inputs, simply return a default expression. Otherwise, create
|
||||
// a ReadOnlyMemory<D2D1PixelShaderInputType> instance from the memory manager.
|
||||
if (info.InputTypes.IsEmpty)
|
||||
{
|
||||
memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
|
||||
additionalTypes = Array.Empty<TypeDeclarationSyntax>();
|
||||
writer.WriteLine("default;");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Create a ReadOnlyMemory<D2D1PixelShaderInputType> instance from the memory manager:
|
||||
//
|
||||
// InputTypesMemoryManager.Instance.Memory
|
||||
memoryExpression =
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("InputTypesMemoryManager"),
|
||||
IdentifierName("Instance")),
|
||||
IdentifierName("Memory"));
|
||||
|
||||
additionalTypes = new TypeDeclarationSyntax[] { GetMemoryManagerDeclaration(inputTypes) };
|
||||
writer.WriteLine("InputTypesMemoryManager.Instance.Memory;");
|
||||
}
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => <MEMORY_EXPRESSION>;
|
||||
return
|
||||
PropertyDeclaration(
|
||||
GenericName(Identifier("global::System.ReadOnlyMemory"))
|
||||
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")),
|
||||
Identifier(nameof(InputTypes)))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(memoryExpression))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the memory manager declaration for the input type data.
|
||||
/// Registers a callback to generate an additional type, if needed.
|
||||
/// </summary>
|
||||
/// <param name="inputTypes">The input types for the shader.</param>
|
||||
/// <returns>The memory manager declaration for the input type data.</returns>
|
||||
private static TypeDeclarationSyntax GetMemoryManagerDeclaration(ImmutableArray<uint> inputTypes)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
|
||||
public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks)
|
||||
{
|
||||
// Create the MemoryManager<T> declaration:
|
||||
//
|
||||
// /// <summary>
|
||||
// /// A <see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the input types.
|
||||
// /// </summary>
|
||||
// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
|
||||
// [global::System.Diagnostics.DebuggerNonUserCode]
|
||||
// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
// file sealed InputTypesMemoryManager : global::System.Buffers.MemoryManager<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType>
|
||||
// {
|
||||
// }
|
||||
TypeDeclarationSyntax typeDeclaration =
|
||||
ClassDeclaration("InputTypesMemoryManager")
|
||||
.AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.SealedKeyword))
|
||||
.AddBaseListTypes(SimpleBaseType(
|
||||
GenericName(Identifier("global::System.Buffers.MemoryManager"))
|
||||
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType"))))
|
||||
.AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))),
|
||||
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
|
||||
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))))
|
||||
.WithLeadingTrivia(
|
||||
Comment("/// <summary>"),
|
||||
Comment("""/// A <see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the input types."""),
|
||||
Comment("/// </summary>"));
|
||||
|
||||
using ImmutableArrayBuilder<MemberDeclarationSyntax> memberDeclarations = ImmutableArrayBuilder<MemberDeclarationSyntax>.Rent();
|
||||
|
||||
// Declare the singleton property to get the memory manager:
|
||||
//
|
||||
// /// <summary>The singleton <see cref="InputTypesMemoryManager"/> instance to use.</summary>
|
||||
// public static readonly InputTypesMemoryManager Instance = new();
|
||||
memberDeclarations.Add(
|
||||
FieldDeclaration(
|
||||
VariableDeclaration(IdentifierName("InputTypesMemoryManager"))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("Instance"))
|
||||
.WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))
|
||||
.AddModifiers(
|
||||
Token(SyntaxKind.PublicKeyword),
|
||||
Token(SyntaxKind.StaticKeyword),
|
||||
Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithLeadingTrivia(Comment("""/// <summary>The singleton <see cref="InputTypesMemoryManager"/> instance to use.</summary>""")));
|
||||
|
||||
using (ImmutableArrayBuilder<ExpressionSyntax> inputTypeExpressions = ImmutableArrayBuilder<ExpressionSyntax>.Rent())
|
||||
// If there are no inputs, no memory manager is needed
|
||||
if (info.InputTypes.IsEmpty)
|
||||
{
|
||||
// Build the sequence of expressions for all input types
|
||||
foreach (uint inputType in inputTypes)
|
||||
{
|
||||
inputTypeExpressions.Add(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType"),
|
||||
IdentifierName(inputType == 0 ? "Simple" : "Complex")));
|
||||
}
|
||||
|
||||
// Construct the RVA span property:
|
||||
//
|
||||
// /// <summary>The RVA data with the input type info.</summary>
|
||||
// private static global::System.ReadOnlySpan<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> Data => new[] { <INPUT_TYPES> };
|
||||
memberDeclarations.Add(
|
||||
PropertyDeclaration(
|
||||
GenericName(Identifier("global::System.ReadOnlySpan"))
|
||||
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")),
|
||||
Identifier("Data"))
|
||||
.AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword))
|
||||
.WithExpressionBody(
|
||||
ArrowExpressionClause(
|
||||
ImplicitArrayCreationExpression(
|
||||
InitializerExpression(
|
||||
SyntaxKind.ArrayInitializerExpression,
|
||||
SeparatedList(inputTypeExpressions.ToArray())))))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
|
||||
.WithLeadingTrivia(Comment("/// <summary>The RVA data with the input type info.</summary>")));
|
||||
return;
|
||||
}
|
||||
|
||||
// Add the GetSpan() method:
|
||||
//
|
||||
// /// <inheritdoc/>
|
||||
// public override unsafe global::System.Span<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> GetSpan
|
||||
// {
|
||||
// return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length);
|
||||
// }
|
||||
memberDeclarations.Add(
|
||||
MethodDeclaration(
|
||||
GenericName(Identifier("global::System.Span"))
|
||||
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")),
|
||||
Identifier("GetSpan"))
|
||||
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword))
|
||||
.AddBodyStatements(
|
||||
ReturnStatement(
|
||||
ImplicitObjectCreationExpression()
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
|
||||
IdentifierName("AsPointer")))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"),
|
||||
IdentifierName("GetReference")))
|
||||
.AddArgumentListArguments(Argument(IdentifierName("Data"))))
|
||||
.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))),
|
||||
Argument(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("Data"),
|
||||
IdentifierName("Length"))))))
|
||||
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
|
||||
// Declare the InputTypesMemoryManager custom memory manager type
|
||||
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine($$"""/// <summary>""");
|
||||
writer.WriteLine($$"""/// A <see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the input types.""");
|
||||
writer.WriteLine($$"""/// </summary>""");
|
||||
writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]""");
|
||||
writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]""");
|
||||
writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]""");
|
||||
writer.WriteLine($$"""file sealed class InputTypesMemoryManager : global::System.Buffers.MemoryManager<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType>""");
|
||||
|
||||
// Override the Memory<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> property:
|
||||
//
|
||||
// /// <inheritdoc/>
|
||||
// public override global::System.Memory<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> Memory
|
||||
// {
|
||||
// [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
|
||||
// get => CreateMemory(Data.Length);
|
||||
// }
|
||||
memberDeclarations.Add(
|
||||
PropertyDeclaration(
|
||||
GenericName(Identifier("global::System.Memory"))
|
||||
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")),
|
||||
Identifier("Memory"))
|
||||
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword))
|
||||
.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")))))))
|
||||
.WithExpressionBody(
|
||||
ArrowExpressionClause(
|
||||
InvocationExpression(IdentifierName("CreateMemory"))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("Data"),
|
||||
IdentifierName("Length"))))))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken)))
|
||||
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Static singleton instance (the object goes in the frozen heap, so there's no static constructor)
|
||||
writer.WriteLine($$"""/// <summary>The singleton <see cref="InputTypesMemoryManager"/> instance to use.</summary>""");
|
||||
writer.WriteLine($$"""public static readonly InputTypesMemoryManager Instance = new();""");
|
||||
|
||||
// Add the Pin(int elementIndex) method:
|
||||
//
|
||||
// /// <inheritdoc/>
|
||||
// public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex)
|
||||
// {
|
||||
// return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
|
||||
// }
|
||||
memberDeclarations.Add(
|
||||
MethodDeclaration(IdentifierName("global::System.Buffers.MemoryHandle"), Identifier("Pin"))
|
||||
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword))
|
||||
.AddParameterListParameters(Parameter(Identifier("elementIndex")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
|
||||
.AddBodyStatements(
|
||||
ReturnStatement(
|
||||
ImplicitObjectCreationExpression()
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
|
||||
IdentifierName("AsPointer")))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
|
||||
IdentifierName("AsRef")))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
ElementAccessExpression(IdentifierName("Data"))
|
||||
.AddArgumentListArguments(Argument(IdentifierName("elementIndex"))))
|
||||
.WithRefOrOutKeyword(Token(SyntaxKind.InKeyword))))
|
||||
.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))),
|
||||
Argument(ThisExpression()).WithNameColon(NameColon(IdentifierName("pinnable"))))))
|
||||
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
|
||||
// RVA field
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("/// <summary>The RVA data with the input type info.</summary>");
|
||||
writer.WriteLine("private static global::System.ReadOnlySpan<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> Data => new[]");
|
||||
|
||||
// Add the empty Unpin() method
|
||||
memberDeclarations.Add(
|
||||
MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Unpin"))
|
||||
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword))
|
||||
.WithBody(Block())
|
||||
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
|
||||
// Input types, one per line in the RVA field initializer
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
for (int i = 0; i < info.InputTypes.Length; i++)
|
||||
{
|
||||
writer.Write("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType.");
|
||||
writer.Write(info.InputTypes[i] == 0 ? "Simple" : "Complex");
|
||||
|
||||
// Add the empty Dispose(bool disposing) method
|
||||
memberDeclarations.Add(
|
||||
MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Dispose"))
|
||||
.AddModifiers(Token(SyntaxKind.ProtectedKeyword), Token(SyntaxKind.OverrideKeyword))
|
||||
.AddParameterListParameters(
|
||||
Parameter(Identifier("disposing")).WithType(PredefinedType(Token(SyntaxKind.BoolKeyword))))
|
||||
.WithBody(Block())
|
||||
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
|
||||
if (i < info.InputTypes.Length - 1)
|
||||
{
|
||||
writer.WriteLine(",");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return typeDeclaration.AddMembers(memberDeclarations.ToArray());
|
||||
// Add the remaining members for the memory manager
|
||||
writer.WriteLine("""
|
||||
/// <inheritdoc/>
|
||||
public override unsafe global::System.Span<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> GetSpan
|
||||
{
|
||||
return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override global::System.Memory<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> Memory
|
||||
{
|
||||
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
|
||||
get => CreateMemory(Data.Length);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex)
|
||||
{
|
||||
return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Unpin()
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
}
|
||||
""", isMultiline: true);
|
||||
}
|
||||
}
|
||||
|
||||
callbacks.Add(Callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
+88
-286
@@ -1,17 +1,7 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
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;
|
||||
|
||||
@@ -22,316 +12,128 @@ partial class ID2D1ShaderGenerator
|
||||
partial class LoadBytecode
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>ShaderProfile</c> property.
|
||||
/// Writes the <c>ShaderProfile</c> property.
|
||||
/// </summary>
|
||||
/// <param name="shaderProfile">The input shader profile.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>ShaderProfile</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetShaderProfileSyntax(D2D1ShaderProfile shaderProfile)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteShaderProfileSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly ComputeSharp.D2D1.D2D1ShaderProfile global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ShaderProfile => <SHADER_PROFILE>;
|
||||
return
|
||||
PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1ShaderProfile"), Identifier(nameof(ID2D1Shader.ShaderProfile)))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"),
|
||||
IdentifierName(shaderProfile.ToString(CultureInfo.InvariantCulture)))))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1ShaderProfile global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ShaderProfile => global::ComputeSharp.D2D1.D2D1ShaderProfile.{info.HlslInfoKey.EffectiveShaderProfile};");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>CompileOptions</c> property.
|
||||
/// Writes the <c>CompileOptions</c> property.
|
||||
/// </summary>
|
||||
/// <param name="compileOptions">The input compile options.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>CompileOptions</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetCompileOptionsSyntax(D2D1CompileOptions compileOptions)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteCompileOptionsSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// Get a formatted representation of the compile options being used
|
||||
ExpressionSyntax compileOptionsExpression =
|
||||
ParseExpression(
|
||||
compileOptions
|
||||
.ToString(CultureInfo.InvariantCulture)
|
||||
.Split(',')
|
||||
.Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}")
|
||||
.Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right));
|
||||
string compileOptionsExpression =
|
||||
info.HlslInfoKey.EffectiveCompileOptions
|
||||
.ToString()
|
||||
.Split(',')
|
||||
.Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}")
|
||||
.Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right);
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => <COMPILE_OPTIONS_EXPRESSION>;
|
||||
return
|
||||
PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1CompileOptions"), Identifier(nameof(ID2D1Shader.CompileOptions)))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(compileOptionsExpression))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
writer.Write($"readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => {compileOptionsExpression};");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>HlslBytecode</c> property.
|
||||
/// Writes the <c>HlslBytecode</c> property.
|
||||
/// </summary>
|
||||
/// <param name="bytecodeInfo">The input bytecode info.</param>
|
||||
/// <param name="fixup">An opaque <see cref="Func{TResult}"/> instance to transform the final tree into text.</param>
|
||||
/// <param name="additionalTypes">Any additional <see cref="TypeDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>HlslBytecode</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetHlslBytecodeSyntax(
|
||||
HlslBytecodeInfo bytecodeInfo,
|
||||
out Func<SyntaxNode, SourceText> fixup,
|
||||
out TypeDeclarationSyntax[] additionalTypes)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteHlslBytecodeSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
ExpressionSyntax memoryExpression;
|
||||
writer.WriteLine("readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => ");
|
||||
|
||||
// If there is no bytecode, simply return a default expression.
|
||||
// Otherwise, declare the memory manager and access it.
|
||||
if (bytecodeInfo is not HlslBytecodeInfo.Success success)
|
||||
// If there is no bytecode, just return a default expression.
|
||||
// Otherwise, return the memory manager backed memory instance.
|
||||
if (info.HlslInfo is not HlslBytecodeInfo.Success)
|
||||
{
|
||||
memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
|
||||
fixup = static tree => tree.GetText(Encoding.UTF8);
|
||||
additionalTypes = Array.Empty<TypeDeclarationSyntax>();
|
||||
writer.WriteLine("default;");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Create a ReadOnlyMemory<byte> instance from the memory manager:
|
||||
//
|
||||
// HlslBytecodeMemoryManager.Instance.Memory
|
||||
memoryExpression =
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("HlslBytecodeMemoryManager"),
|
||||
IdentifierName("Instance")),
|
||||
IdentifierName("Memory"));
|
||||
|
||||
TypeDeclarationSyntax memoryManagerDeclaration = GetMemoryManagerDeclaration();
|
||||
string bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(success.Bytecode.AsSpan());
|
||||
|
||||
additionalTypes = new TypeDeclarationSyntax[] { memoryManagerDeclaration };
|
||||
fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8);
|
||||
writer.WriteLine("HlslBytecodeMemoryManager.Instance.Memory;");
|
||||
}
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly global::System.ReadOnlyMemory<byte> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslBytecode => <MEMORY_EXPRESSION>;
|
||||
return
|
||||
PropertyDeclaration(
|
||||
GenericName(Identifier("global::System.ReadOnlyMemory"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))),
|
||||
Identifier(nameof(ID2D1Shader.HlslBytecode)))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(memoryExpression))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
|
||||
/// Registers a callback to generate an additional type, if needed.
|
||||
/// </summary>
|
||||
/// <returns>The <see cref="BlockSyntax"/> instance trying to retrieve the precompiled shader.</returns>
|
||||
private static unsafe TypeDeclarationSyntax GetMemoryManagerDeclaration()
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
|
||||
public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks)
|
||||
{
|
||||
// Create the MemoryManager<T> declaration:
|
||||
//
|
||||
// /// <summary>
|
||||
// /// <see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the HLSL bytecode.
|
||||
// /// </summary>
|
||||
// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
|
||||
// [global::System.Diagnostics.DebuggerNonUserCode]
|
||||
// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
// file sealed HlslBytecodeMemoryManager : global::System.Buffers.MemoryManager<byte>
|
||||
// {
|
||||
// }
|
||||
TypeDeclarationSyntax typeDeclaration =
|
||||
ClassDeclaration("HlslBytecodeMemoryManager")
|
||||
.AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.SealedKeyword))
|
||||
.AddBaseListTypes(SimpleBaseType(
|
||||
GenericName(Identifier("global::System.Buffers.MemoryManager"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))))
|
||||
.AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))),
|
||||
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
|
||||
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))))
|
||||
.WithLeadingTrivia(
|
||||
Comment("/// <summary>"),
|
||||
Comment("""/// A <see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the HLSL bytecode."""),
|
||||
Comment("/// </summary>"));
|
||||
// If there is no bytecode, no memory manager is needed
|
||||
if (info.HlslInfo is not HlslBytecodeInfo.Success)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using ImmutableArrayBuilder<MemberDeclarationSyntax> memberDeclarations = ImmutableArrayBuilder<MemberDeclarationSyntax>.Rent();
|
||||
// Declare the HlslBytecodeMemoryManager custom memory manager type
|
||||
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine($$"""/// <summary>""");
|
||||
writer.WriteLine($$"""<see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the HLSL bytecode.""");
|
||||
writer.WriteLine($$"""/// </summary>""");
|
||||
writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]""");
|
||||
writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]""");
|
||||
writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]""");
|
||||
writer.WriteLine($$"""file sealed class HlslBytecodeMemoryManager : global::System.Buffers.MemoryManager<byte>""");
|
||||
|
||||
// Declare the singleton property to get the memory manager:
|
||||
//
|
||||
// /// <summary>The singleton <see cref="HlslBytecodeMemoryManager"/> instance to use.</summary>
|
||||
// public static readonly HlslBytecodeMemoryManager Instance = new();
|
||||
memberDeclarations.Add(
|
||||
FieldDeclaration(
|
||||
VariableDeclaration(IdentifierName("HlslBytecodeMemoryManager"))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("Instance"))
|
||||
.WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))
|
||||
.AddModifiers(
|
||||
Token(SyntaxKind.PublicKeyword),
|
||||
Token(SyntaxKind.StaticKeyword),
|
||||
Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithLeadingTrivia(Comment("""/// <summary>The singleton <see cref="HlslBytecodeMemoryManager"/> instance to use.</summary>""")));
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Static singleton instance (to avoid the static constructor, just like with the input types)
|
||||
writer.WriteLine($$"""/// <summary>The singleton <see cref="HlslBytecodeMemoryManager"/> instance to use.</summary>""");
|
||||
writer.WriteLine($$"""public static readonly HlslBytecodeMemoryManager Instance = new();""");
|
||||
|
||||
// Construct the RVA span property:
|
||||
//
|
||||
// /// <summary>The RVA data with the HLSL bytecode.</summary>
|
||||
// private static global::System.ReadOnlySpan<byte> Data => new byte[] { __EMBEDDED_SHADER_BYTECODE };
|
||||
memberDeclarations.Add(
|
||||
PropertyDeclaration(
|
||||
GenericName(Identifier("global::System.ReadOnlySpan"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))),
|
||||
Identifier("Data"))
|
||||
.AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword))
|
||||
.WithExpressionBody(
|
||||
ArrowExpressionClause(
|
||||
ArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
|
||||
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))),
|
||||
InitializerExpression(
|
||||
SyntaxKind.ArrayInitializerExpression,
|
||||
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_SHADER_BYTECODE"))))))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
|
||||
.WithLeadingTrivia(Comment("/// <summary>The RVA data with the HLSL bytecode.</summary>")));
|
||||
// RVA field (with the compiled HLSL bytecode, on a single line)
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("/// <summary>The RVA data with the HLSL bytecode.</summary>");
|
||||
writer.Write("private static global::System.ReadOnlySpan<byte> Data => new[] { ");
|
||||
|
||||
// Override the Memory<byte> property:
|
||||
//
|
||||
// /// <inheritdoc/>
|
||||
// public override global::System.Memory<byte> Memory
|
||||
// {
|
||||
// [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
|
||||
// get => CreateMemory(Data.Length);
|
||||
// }
|
||||
memberDeclarations.Add(
|
||||
PropertyDeclaration(
|
||||
GenericName(Identifier("global::System.Memory"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))),
|
||||
Identifier("Memory"))
|
||||
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword))
|
||||
.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")))))))
|
||||
.WithExpressionBody(
|
||||
ArrowExpressionClause(
|
||||
InvocationExpression(IdentifierName("CreateMemory"))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("Data"),
|
||||
IdentifierName("Length"))))))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken)))
|
||||
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
|
||||
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(((HlslBytecodeInfo.Success)info.HlslInfo).Bytecode.AsSpan(), writer);
|
||||
|
||||
// Add the GetSpan() method:
|
||||
//
|
||||
// /// <inheritdoc/>
|
||||
// public override unsafe global::System.Span<byte> GetSpan
|
||||
// {
|
||||
// return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length);
|
||||
// }
|
||||
memberDeclarations.Add(
|
||||
MethodDeclaration(
|
||||
GenericName(Identifier("global::System.Span"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))),
|
||||
Identifier("GetSpan"))
|
||||
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword))
|
||||
.AddBodyStatements(
|
||||
ReturnStatement(
|
||||
ImplicitObjectCreationExpression()
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
|
||||
IdentifierName("AsPointer")))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"),
|
||||
IdentifierName("GetReference")))
|
||||
.AddArgumentListArguments(Argument(IdentifierName("Data"))))
|
||||
.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))),
|
||||
Argument(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("Data"),
|
||||
IdentifierName("Length"))))))
|
||||
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
|
||||
writer.WriteLine(" };");
|
||||
|
||||
// Add the Pin(int elementIndex) method:
|
||||
//
|
||||
// /// <inheritdoc/>
|
||||
// public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex)
|
||||
// {
|
||||
// return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
|
||||
// }
|
||||
memberDeclarations.Add(
|
||||
MethodDeclaration(IdentifierName("global::System.Buffers.MemoryHandle"), Identifier("Pin"))
|
||||
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword))
|
||||
.AddParameterListParameters(Parameter(Identifier("elementIndex")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
|
||||
.AddBodyStatements(
|
||||
ReturnStatement(
|
||||
ImplicitObjectCreationExpression()
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
|
||||
IdentifierName("AsPointer")))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
|
||||
IdentifierName("AsRef")))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
ElementAccessExpression(IdentifierName("Data"))
|
||||
.AddArgumentListArguments(Argument(IdentifierName("elementIndex"))))
|
||||
.WithRefOrOutKeyword(Token(SyntaxKind.InKeyword))))
|
||||
.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))),
|
||||
Argument(ThisExpression()).WithNameColon(NameColon(IdentifierName("pinnable"))))))
|
||||
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
|
||||
// Add the remaining members for the memory manager
|
||||
writer.WriteLine("""
|
||||
/// <inheritdoc/>
|
||||
public override unsafe global::System.Span<byte> GetSpan
|
||||
{
|
||||
return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length);
|
||||
}
|
||||
|
||||
// Add the empty Unpin() method
|
||||
memberDeclarations.Add(
|
||||
MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Unpin"))
|
||||
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword))
|
||||
.WithBody(Block())
|
||||
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
|
||||
/// <inheritdoc/>
|
||||
public override global::System.Memory<byte> Memory
|
||||
{
|
||||
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
|
||||
get => CreateMemory(Data.Length);
|
||||
}
|
||||
|
||||
// Add the empty Dispose(bool disposing) method
|
||||
memberDeclarations.Add(
|
||||
MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Dispose"))
|
||||
.AddModifiers(Token(SyntaxKind.ProtectedKeyword), Token(SyntaxKind.OverrideKeyword))
|
||||
.AddParameterListParameters(
|
||||
Parameter(Identifier("disposing")).WithType(PredefinedType(Token(SyntaxKind.BoolKeyword))))
|
||||
.WithBody(Block())
|
||||
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
|
||||
/// <inheritdoc/>
|
||||
public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex)
|
||||
{
|
||||
return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
|
||||
}
|
||||
|
||||
return typeDeclaration.AddMembers(memberDeclarations.ToArray());
|
||||
/// <inheritdoc/>
|
||||
public override void Unpin()
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
}
|
||||
""", isMultiline: true);
|
||||
}
|
||||
}
|
||||
|
||||
callbacks.Add(Callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
+102
-260
@@ -1,16 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.D2D1.__Internals;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
@@ -21,274 +11,126 @@ partial class ID2D1ShaderGenerator
|
||||
partial class LoadDispatchData
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
|
||||
/// Writes the <c>LoadDispatchData</c> method.
|
||||
/// </summary>
|
||||
/// <param name="hierarchyInfo">The hiararchy info of the shader type.</param>
|
||||
/// <param name="fields">The description on shader instance fields.</param>
|
||||
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
|
||||
/// <param name="additionalTypes">Any additional <see cref="TypeDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
|
||||
public static MethodDeclarationSyntax GetSyntax(
|
||||
HierarchyInfo hierarchyInfo,
|
||||
EquatableArray<FieldInfo> fields,
|
||||
int constantBufferSizeInBytes,
|
||||
out TypeDeclarationSyntax[] additionalTypes)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// Declare the mapping constant buffer type, if needed (ie. if the shader has at least one field)
|
||||
if (fields.Length == 0)
|
||||
{
|
||||
additionalTypes = Array.Empty<TypeDeclarationSyntax>();
|
||||
}
|
||||
else
|
||||
{
|
||||
additionalTypes = new[] { GetConstantBufferDeclaration(hierarchyInfo, fields, constantBufferSizeInBytes) };
|
||||
}
|
||||
writer.WriteLine("readonly unsafe void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadDispatchData<TLoader>(ref TLoader loader)");
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly unsafe void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadDispatchData<TLoader>(ref TLoader loader)
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(LoadDispatchData)))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword), Token(SyntaxKind.UnsafeKeyword))
|
||||
.AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
|
||||
.AddParameterListParameters(Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader")))
|
||||
.WithBody(Block(GetDispatchDataLoadingStatements(fields, constantBufferSizeInBytes)));
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// If there are no fields, just load an empty buffer
|
||||
if (info.Fields.IsEmpty)
|
||||
{
|
||||
writer.WriteLine("loader.LoadConstantBuffer(default);");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine("ConstantBuffer buffer;");
|
||||
|
||||
// Generate loading statements for each captured field
|
||||
foreach (FieldInfo fieldInfo in info.Fields)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
{
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Assign a primitive value
|
||||
writer.WriteLine($"buffer.{string.Join("_", primitive.FieldPath)} = this.{string.Join(".", primitive.FieldPath)};");
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string fieldPath = string.Join(".", matrix.FieldPath);
|
||||
string fieldNamePrefix = string.Join("_", matrix.FieldPath);
|
||||
|
||||
// Assign all rows of a given matrix type:
|
||||
//
|
||||
// buffer.<CONSTANT_BUFFER_ROW_0_PATH> = this.<FIELD_PATH>[0];
|
||||
// buffer.<CONSTANT_BUFFER_ROW_1_PATH> = this.<FIELD_PATH>[1];
|
||||
// ...
|
||||
// buffer.<CONSTANT_BUFFER_ROW_N_PATH> = this.<FIELD_PATH>[N];
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
writer.WriteLine($"buffer.{fieldNamePrefix}_{j} = this.{fieldPath}[{j}];");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a type definition to map the constant buffer of a given shader type.
|
||||
/// Registers a callback to generate an additional type, if needed.
|
||||
/// </summary>
|
||||
/// <param name="hierarchyInfo">The hiararchy info of the shader type.</param>
|
||||
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
|
||||
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
|
||||
/// <returns>The <see cref="TypeDeclarationSyntax"/> object for the mapped constant buffer for the current shader type.</returns>
|
||||
private static TypeDeclarationSyntax GetConstantBufferDeclaration(HierarchyInfo hierarchyInfo, ImmutableArray<FieldInfo> fieldInfos, int constantBufferSizeInBytes)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
|
||||
public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks)
|
||||
{
|
||||
string fullyQualifiedTypeName = hierarchyInfo.GetFullyQualifiedTypeName();
|
||||
|
||||
using ImmutableArrayBuilder<FieldDeclarationSyntax> fieldDeclarations = ImmutableArrayBuilder<FieldDeclarationSyntax>.Rent();
|
||||
|
||||
// Appends a new field declaration for a constant buffer field:
|
||||
//
|
||||
// <COMMENT>
|
||||
// [global::System.Runtime.InteropServices.FieldOffset(<FIELD_OFFSET>)]
|
||||
// public <FIELD_TYPE> <FIELD_NAME>;
|
||||
void AppendFieldDeclaration(
|
||||
string comment,
|
||||
TypeSyntax typeIdentifier,
|
||||
string identifierName,
|
||||
int fieldOffset)
|
||||
// If there are no fields, there is no need for a constant buffer type
|
||||
if (info.Fields.IsEmpty)
|
||||
{
|
||||
fieldDeclarations.Add(
|
||||
FieldDeclaration(
|
||||
VariableDeclaration(typeIdentifier)
|
||||
.AddVariables(VariableDeclarator(Identifier(identifierName))))
|
||||
.AddAttributeLists(AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("global::System.Runtime.InteropServices.FieldOffset"))
|
||||
.AddArgumentListArguments(AttributeArgument(
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(fieldOffset)))))))
|
||||
.AddModifiers(Token(SyntaxKind.PublicKeyword))
|
||||
.WithLeadingTrivia(Comment(comment)));
|
||||
return;
|
||||
}
|
||||
|
||||
// Declare fields for every mapped item from the shader layout
|
||||
foreach (FieldInfo fieldInfo in fieldInfos)
|
||||
// Declare the ConstantBuffer type
|
||||
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName();
|
||||
|
||||
writer.WriteLine($$"""/// <summary>""");
|
||||
writer.WriteLine($$"""/// A type representing the constant buffer native layout for <see cref="{{fullyQualifiedTypeName}}"/>.""");
|
||||
writer.WriteLine($$"""/// </summary>""");
|
||||
writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]""");
|
||||
writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]""");
|
||||
writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]""");
|
||||
writer.WriteLine($$"""[global::System.Runtime.InteropServices.StructLayout(global::System.Runtime.InteropServices.LayoutKind.Explicit, Size = {{info.ConstantBufferSizeInBytes}})]""");
|
||||
writer.WriteLine($$"""file struct ConstantBuffer""");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive:
|
||||
|
||||
// Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values)
|
||||
AppendFieldDeclaration(
|
||||
comment: $"""/// <inheritdoc cref="{fullyQualifiedTypeName}.{string.Join(".", primitive.FieldPath)}"/>""",
|
||||
typeIdentifier: IdentifierName("global::ComputeSharp.Bool"),
|
||||
identifierName: string.Join("_", primitive.FieldPath),
|
||||
fieldOffset: primitive.Offset);
|
||||
break;
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Append primitive fields of other types with their mapped names
|
||||
AppendFieldDeclaration(
|
||||
comment: $"""/// <inheritdoc cref="{fullyQualifiedTypeName}.{string.Join(".", primitive.FieldPath)}"/>""",
|
||||
typeIdentifier: IdentifierName(HlslKnownTypes.GetMappedName(primitive.TypeName)),
|
||||
identifierName: string.Join("_", primitive.FieldPath),
|
||||
fieldOffset: primitive.Offset);
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
|
||||
string fieldNamePrefix = string.Join("_", matrix.FieldPath);
|
||||
|
||||
// Declare a field for every row of the matrix type
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
// Declare fields for every mapped item from the shader layout
|
||||
for (int i = 0; i < info.Fields.Length; i++)
|
||||
{
|
||||
switch (info.Fields[i])
|
||||
{
|
||||
AppendFieldDeclaration(
|
||||
comment: $"""/// <summary>Row {j} of <see cref="{fullyQualifiedTypeName}.{string.Join(".", matrix.FieldPath)}"/>.</summary>""",
|
||||
typeIdentifier: IdentifierName(rowTypeName),
|
||||
identifierName: $"{fieldNamePrefix}_{j}",
|
||||
fieldOffset: matrix.Offsets[j]);
|
||||
}
|
||||
case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive:
|
||||
|
||||
break;
|
||||
// Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values)
|
||||
writer.WriteLine($$"""/// <inheritdoc cref="{{fullyQualifiedTypeName}}.{{string.Join(".", primitive.FieldPath)}}"/>""");
|
||||
writer.WriteLine($$"""[global::System.Runtime.InteropServices.FieldOffset({{primitive.Offset}})]""");
|
||||
writer.WriteLine($$"""public global::ComputeSharp.Bool {{string.Join("_", primitive.FieldPath)}};""");
|
||||
break;
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Append primitive fields of other types with their mapped names
|
||||
writer.WriteLine($$"""/// <inheritdoc cref="{{fullyQualifiedTypeName}}.{{string.Join(".", primitive.FieldPath)}}"/>""");
|
||||
writer.WriteLine($$"""[global::System.Runtime.InteropServices.FieldOffset({{primitive.Offset}})]""");
|
||||
writer.WriteLine($$"""public {{HlslKnownTypes.GetMappedName(primitive.TypeName)}} {{string.Join("_", primitive.FieldPath)}};""");
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
|
||||
string fieldNamePrefix = string.Join("_", matrix.FieldPath);
|
||||
|
||||
// Declare a field for every row of the matrix type
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
writer.WriteLine($$"""/// <summary>Row {j} of <see cref="{{fullyQualifiedTypeName}}.{{string.Join(".", matrix.FieldPath)}}"/>.</summary>""");
|
||||
writer.WriteLine($$"""[global::System.Runtime.InteropServices.FieldOffset({{matrix.Offsets[j]}})]""");
|
||||
writer.WriteLine($$"""public {{rowTypeName}} {{fieldNamePrefix}}_{{j}};""");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create the constant buffer type:
|
||||
//
|
||||
// /// <summary>
|
||||
// /// A type representing the constant buffer native layout for <see cref="<SHADER_TYPE"/>.
|
||||
// /// </summary>
|
||||
// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
|
||||
// [global::System.Diagnostics.DebuggerNonUserCode]
|
||||
// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
// [global::System.Runtime.InteropServices.StructLayout(global::System.Runtime.InteropServices.LayoutKind.Explicit, Size = <CONSTANT_BUFFER_SIZE>)]
|
||||
// file struct ConstantBuffer
|
||||
// {
|
||||
// <FIELD_DECLARATIONS>
|
||||
// }
|
||||
return
|
||||
StructDeclaration("ConstantBuffer")
|
||||
.AddModifiers(Token(SyntaxKind.FileKeyword))
|
||||
.AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))),
|
||||
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
|
||||
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))),
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("global::System.Runtime.InteropServices.StructLayout")).AddArgumentListArguments(
|
||||
AttributeArgument(MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::System.Runtime.InteropServices.LayoutKind"),
|
||||
IdentifierName("Explicit"))),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(constantBufferSizeInBytes)))
|
||||
.WithNameEquals(NameEquals(IdentifierName("Size")))))))
|
||||
.AddMembers(fieldDeclarations.ToArray())
|
||||
.WithLeadingTrivia(
|
||||
Comment("/// <summary>"),
|
||||
Comment($"""/// A type representing the constant buffer native layout for <see cref="{fullyQualifiedTypeName}"/>."""),
|
||||
Comment("/// </summary>"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of statements to load the dispatch data for a given shader.
|
||||
/// </summary>
|
||||
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
|
||||
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
|
||||
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load the shader dispatch data.</returns>
|
||||
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(ImmutableArray<FieldInfo> fieldInfos, int constantBufferSizeInBytes)
|
||||
{
|
||||
// If there are no fields, just load an empty buffer:
|
||||
//
|
||||
// loader.LoadConstantBuffer(default);
|
||||
if (fieldInfos.IsEmpty)
|
||||
{
|
||||
return
|
||||
ImmutableArray.Create<StatementSyntax>(
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("loader"),
|
||||
IdentifierName("LoadConstantBuffer")))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(
|
||||
SyntaxKind.DefaultLiteralExpression,
|
||||
Token(SyntaxKind.DefaultKeyword))))));
|
||||
}
|
||||
|
||||
using ImmutableArrayBuilder<StatementSyntax> statements = ImmutableArrayBuilder<StatementSyntax>.Rent();
|
||||
|
||||
// ConstantBuffer buffer;
|
||||
statements.Add(
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(IdentifierName("ConstantBuffer"))
|
||||
.AddVariables(VariableDeclarator(Identifier("buffer")))));
|
||||
|
||||
// Generate loading statements for each captured field
|
||||
foreach (FieldInfo fieldInfo in fieldInfos)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
{
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Assign a primitive value:
|
||||
//
|
||||
// buffer.<CONSTANT_BUFFER_PATH> = this.<FIELD_PATH>;
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("buffer"),
|
||||
IdentifierName(string.Join("_", primitive.FieldPath))),
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
ThisExpression(),
|
||||
IdentifierName(string.Join(".", primitive.FieldPath))))));
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string fieldPath = string.Join(".", matrix.FieldPath);
|
||||
string fieldNamePrefix = string.Join("_", matrix.FieldPath);
|
||||
|
||||
// Assign all rows of a given matrix type:
|
||||
//
|
||||
// buffer.<CONSTANT_BUFFER_ROW_0_PATH> = this.<FIELD_PATH>[0];
|
||||
// buffer.<CONSTANT_BUFFER_ROW_1_PATH> = this.<FIELD_PATH>[1];
|
||||
// ...
|
||||
// buffer.<CONSTANT_BUFFER_ROW_N_PATH> = this.<FIELD_PATH>[N];
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("buffer"),
|
||||
IdentifierName($"{fieldNamePrefix}_{j}")),
|
||||
ElementAccessExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
ThisExpression(),
|
||||
IdentifierName(fieldPath)))
|
||||
.AddArgumentListArguments(
|
||||
Argument(LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(j)))))));
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// loader.LoadConstantBuffer(new global::System.ReadOnlySpan<byte>(&buffer, sizeof(ConstantBuffer)));
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("loader"),
|
||||
IdentifierName("LoadConstantBuffer")))
|
||||
.AddArgumentListArguments(Argument(
|
||||
ObjectCreationExpression(
|
||||
GenericName(Identifier("global::System.ReadOnlySpan"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
PrefixUnaryExpression(
|
||||
SyntaxKind.AddressOfExpression,
|
||||
IdentifierName("buffer"))),
|
||||
Argument(SizeOfExpression(IdentifierName("ConstantBuffer"))))))));
|
||||
|
||||
return statements.ToImmutable();
|
||||
callbacks.Add(Callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
-61
@@ -1,10 +1,6 @@
|
||||
using System;
|
||||
using ComputeSharp.D2D1.__Internals;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
@@ -15,73 +11,38 @@ partial class ID2D1ShaderGenerator
|
||||
partial class OutputBuffer
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>BufferPrecision</c> property.
|
||||
/// Writes the <c>BufferPrecision</c> property.
|
||||
/// </summary>
|
||||
/// <param name="bufferPrecision">The buffer precision for the resulting output buffer.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>BufferPrecision</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetBufferPrecisionSyntax(D2D1BufferPrecision bufferPrecision)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteBufferPrecisionSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
ExpressionSyntax bufferPrecisionExpression;
|
||||
|
||||
// Set the right expression if the buffer options are valid
|
||||
if (Enum.IsDefined(typeof(D2D1BufferPrecision), bufferPrecision))
|
||||
// Set the right expression if the buffer options are valid.
|
||||
// If they are not, just return default (the analyzer will emit a diagnostic).
|
||||
string bufferPrecisionExpression = Enum.IsDefined(typeof(D2D1BufferPrecision), info.BufferPrecision) switch
|
||||
{
|
||||
bufferPrecisionExpression =
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("ComputeSharp.D2D1.D2D1BufferPrecision"),
|
||||
IdentifierName(bufferPrecision.ToString()));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise just return default (the analyzer will emit a diagnostic)
|
||||
bufferPrecisionExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
|
||||
}
|
||||
true => $"global::ComputeSharp.D2D1.D2D1BufferPrecision.{info.BufferPrecision}",
|
||||
false => "default"
|
||||
};
|
||||
|
||||
// This code produces a property declaration as follows:
|
||||
//
|
||||
// readonly ComputeSharp.D2D1.D2D1BufferPrecision global::ComputeSharp.D2D1.__Internals.ID2D1Shader.BufferPrecision => <BUFFER_PRECISION>;
|
||||
return
|
||||
PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1BufferPrecision"), Identifier("BufferPrecision"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(bufferPrecisionExpression))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1BufferPrecision global::ComputeSharp.D2D1.__Internals.ID2D1Shader.BufferPrecision => {bufferPrecisionExpression};");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>ChannelDepth</c> property.
|
||||
/// Writes the <c>ChannelDepth</c> property.
|
||||
/// </summary>
|
||||
/// <param name="channelDepth">The channel depth for the resulting output buffer.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>ChannelDepth</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetChannelDepthSyntax(D2D1ChannelDepth channelDepth)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteChannelDepthSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
ExpressionSyntax channelDepthExpression;
|
||||
|
||||
// Set the right expression if the buffer options are valid
|
||||
if (Enum.IsDefined(typeof(D2D1ChannelDepth), channelDepth))
|
||||
string channelDepthExpression = Enum.IsDefined(typeof(D2D1ChannelDepth), info.ChannelDepth) switch
|
||||
{
|
||||
channelDepthExpression =
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("ComputeSharp.D2D1.D2D1ChannelDepth"),
|
||||
IdentifierName(channelDepth.ToString()));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise just return default (the analyzer will emit a diagnostic)
|
||||
channelDepthExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
|
||||
}
|
||||
true => $"global::ComputeSharp.D2D1.D2D1ChannelDepth.{info.ChannelDepth}",
|
||||
false => "default"
|
||||
};
|
||||
|
||||
// This code produces a property declaration as follows:
|
||||
//
|
||||
// readonly ComputeSharp.D2D1.D2D1ChannelDepth global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ChannelDepth => <CHANNEL_DEPTH>;
|
||||
return
|
||||
PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1ChannelDepth"), Identifier("ChannelDepth"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(channelDepthExpression))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1ChannelDepth global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ChannelDepth => {channelDepthExpression};");
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-33
@@ -1,9 +1,5 @@
|
||||
using ComputeSharp.D2D1.__Internals;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
@@ -14,38 +10,20 @@ partial class ID2D1ShaderGenerator
|
||||
partial class PixelOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>PixelOptions</c> property.
|
||||
/// Writes the <c>PixelOptions</c> property.
|
||||
/// </summary>
|
||||
/// <param name="pixelOptions">The pixel options for the shader.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>PixelOptions</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetSyntax(D2D1PixelOptions pixelOptions)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
ExpressionSyntax pixelOptionsExpression;
|
||||
|
||||
// Set the right expression if the pixel options are valid
|
||||
if (pixelOptions is D2D1PixelOptions.None or D2D1PixelOptions.TrivialSampling)
|
||||
string pixelOptionsExpression = (info.PixelOptions is D2D1PixelOptions.None or D2D1PixelOptions.TrivialSampling) switch
|
||||
{
|
||||
pixelOptionsExpression =
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("ComputeSharp.D2D1.D2D1PixelOptions"),
|
||||
IdentifierName(pixelOptions.ToString()));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise just return default (the analyzer will emit a diagnostic)
|
||||
pixelOptionsExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
|
||||
}
|
||||
true => $"global::ComputeSharp.D2D1.D2D1PixelOptions.{info.PixelOptions}",
|
||||
false => "default"
|
||||
};
|
||||
|
||||
// This code produces a property declaration as follows:
|
||||
//
|
||||
// readonly ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.PixelOptions => <PIXEL_OPTIONS>;
|
||||
return
|
||||
PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1PixelOptions"), Identifier(nameof(PixelOptions)))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(pixelOptionsExpression))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.PixelOptions => {pixelOptionsExpression};");
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
-75
@@ -1,13 +1,5 @@
|
||||
using System;
|
||||
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 static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
@@ -18,90 +10,63 @@ partial class ID2D1ShaderGenerator
|
||||
private static partial class ResourceTextureDescriptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>ResourceTextureDescriptions</c> property.
|
||||
/// Writes the <c>ResourceTextureDescriptions</c> property.
|
||||
/// </summary>
|
||||
/// <param name="resourceTextureDescriptions">The resource texture descriptions info gathered for the current shader.</param>
|
||||
/// <param name="additionalDataMembers">Any additional <see cref="MemberDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
|
||||
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>ResourceTextureDescriptions</c> property.</returns>
|
||||
public static PropertyDeclarationSyntax GetSyntax(EquatableArray<ResourceTextureDescription> resourceTextureDescriptions, out MemberDeclarationSyntax[] additionalDataMembers)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
ExpressionSyntax memoryExpression;
|
||||
writer.WriteLine("readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => ");
|
||||
|
||||
// If there are no resource texture descriptions, just return a default expression.
|
||||
// Otherwise, declare the shared array and return it from the property.
|
||||
if (resourceTextureDescriptions.Length == 0)
|
||||
// Otherwise, return a memory instance from the generated static readonly array.
|
||||
if (info.ResourceTextureDescriptions.IsEmpty)
|
||||
{
|
||||
memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
|
||||
additionalDataMembers = Array.Empty<MemberDeclarationSyntax>();
|
||||
writer.WriteLine("default;");
|
||||
}
|
||||
else
|
||||
{
|
||||
memoryExpression = MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("Data"),
|
||||
IdentifierName(nameof(ResourceTextureDescriptions)));
|
||||
|
||||
additionalDataMembers = new[] { GetArrayDeclaration(resourceTextureDescriptions) };
|
||||
writer.WriteLine("Data.ResourceTextureDescriptions;");
|
||||
}
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => <EXPRESSION>;
|
||||
return
|
||||
PropertyDeclaration(
|
||||
GenericName(Identifier("global::System.ReadOnlyMemory"))
|
||||
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription")),
|
||||
Identifier(nameof(ResourceTextureDescriptions)))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithExpressionBody(ArrowExpressionClause(memoryExpression))
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the array declaration for the given resource texture descriptions.
|
||||
/// Registers a callback to generate an additional data member, if needed.
|
||||
/// </summary>
|
||||
/// <param name="resourceTextureDescriptions">The resource texture descriptions info gathered for the current shader.</param>
|
||||
/// <returns>The array declaration for the given resource texture descriptions.</returns>
|
||||
private static MemberDeclarationSyntax GetArrayDeclaration(EquatableArray<ResourceTextureDescription> resourceTextureDescriptions)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional data members.</param>
|
||||
public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks)
|
||||
{
|
||||
using ImmutableArrayBuilder<ExpressionSyntax> resourceTextureDescriptionExpressions = ImmutableArrayBuilder<ExpressionSyntax>.Rent();
|
||||
|
||||
foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptions)
|
||||
// If there are no resource texture descriptions, there is nothing to di
|
||||
if (info.ResourceTextureDescriptions.IsEmpty)
|
||||
{
|
||||
// Create the description expression:
|
||||
//
|
||||
// new(<INDEX>, <RANK>)
|
||||
resourceTextureDescriptionExpressions.Add(
|
||||
ImplicitObjectCreationExpression()
|
||||
.AddArgumentListArguments(
|
||||
Argument(LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(resourceTextureDescription.Index))),
|
||||
Argument(LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(resourceTextureDescription.Rank)))));
|
||||
return;
|
||||
}
|
||||
|
||||
// Declare the singleton property to get the memory instance:
|
||||
//
|
||||
// /// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription"/> array instance.</summary>
|
||||
// public static readonly global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription[] ResourceTextureDescriptions = { <RESOURCE_TEXTURE_DESCRIPTIONS> };
|
||||
return
|
||||
FieldDeclaration(
|
||||
VariableDeclaration(
|
||||
ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription"))
|
||||
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier(nameof(ResourceTextureDescriptions)))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
InitializerExpression(SyntaxKind.ArrayInitializerExpression)
|
||||
.AddExpressions(resourceTextureDescriptionExpressions.ToArray())))))
|
||||
.AddModifiers(
|
||||
Token(SyntaxKind.PublicKeyword),
|
||||
Token(SyntaxKind.StaticKeyword),
|
||||
Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithLeadingTrivia(Comment("""/// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription"/> array instance.</summary>"""));
|
||||
// Declare the shared array with resource texture descriptions
|
||||
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("""/// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription"/> array instance.</summary>""");
|
||||
writer.WriteLine("""public static readonly global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription[] ResourceTextureDescriptions =""");
|
||||
|
||||
// Initialize all resource texture descriptions
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
for (int i = 0; i < info.ResourceTextureDescriptions.Length; i++)
|
||||
{
|
||||
ResourceTextureDescription description = info.ResourceTextureDescriptions[i];
|
||||
|
||||
writer.Write($"new global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription({description.Index}, {description.Rank})");
|
||||
|
||||
if (i < info.ResourceTextureDescriptions.Length - 1)
|
||||
{
|
||||
writer.WriteLine(",");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
callbacks.Add(Callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,16 @@ internal static class SyntaxFormattingHelper
|
||||
"0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Gets an expression representing a single byte.
|
||||
/// </summary>
|
||||
/// <param name="value">The byte to format.</param>
|
||||
/// <returns>The expression for <paramref name="value"/>.</returns>
|
||||
public static string GetByteExpression(byte value)
|
||||
{
|
||||
return FormattedBytes[value];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a formatted expression to initialize a <see cref="ReadOnlySpan{T}"/> with a given content.
|
||||
/// </summary>
|
||||
@@ -58,7 +68,7 @@ internal static class SyntaxFormattingHelper
|
||||
ReadOnlySpan<string> expressions = FormattedBytes.AsSpan();
|
||||
|
||||
// First write the first item (which has no leading separator)
|
||||
expressions[0].AsSpan().CopyTo(span);
|
||||
expressions[bytecode[0]].AsSpan().CopyTo(span);
|
||||
|
||||
// Special case: stop early if there's only one element
|
||||
if (bytecode.Length == 1)
|
||||
|
||||
@@ -248,6 +248,14 @@ internal sealed class IndentedTextWriter : IDisposable
|
||||
this.builder.AddRange(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A delegate representing a callback to write data into an <see cref="IndentedTextWriter"/> instance.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of data to use.</typeparam>
|
||||
/// <param name="value">The input data to use to write into <paramref name="writer"/>.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public delegate void Callback<T>(T value, IndentedTextWriter writer);
|
||||
|
||||
/// <summary>
|
||||
/// Represents an indented block that needs to be closed.
|
||||
/// </summary>
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする