Merge pull request #578 from Sergio0694/dev/unified-d2d1-generator

Unify D2D1 source generator logic and emit a single file
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-09-29 10:11:01 +02:00
コミット 3e47704c80
22ファイル変更
+340 -536

検索条件に一致するファイルはありません

+2 -2
ファイルの表示
@@ -174,14 +174,14 @@ partial class D2DPixelShaderSourceGenerator
D2DPixelShaderSourceCompilationFailedWithWin32Exception,
sourceInfo.MethodName,
e.HResult,
ID2D1ShaderGenerator.LoadBytecode.FixupExceptionMessage(e.Message));
D3DCompiler.PrettifyFxcErrorMessage(e.Message));
}
catch (FxcCompilationException e)
{
diagnostic = DeferredDiagnosticInfo.Create(
D2DPixelShaderSourceCompilationFailedWithFxcCompilationException,
sourceInfo.MethodName,
ID2D1ShaderGenerator.LoadBytecode.FixupExceptionMessage(e.Message));
D3DCompiler.PrettifyFxcErrorMessage(e.Message));
}
End:
@@ -1,12 +1,7 @@
using System;
using System.Text;
using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Helpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
@@ -22,14 +17,18 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectId</c> property.
/// </summary>
/// <param name="info">The input <see cref="EffectIdInfo"/> instance.</param>
/// <param name="fixup">An opaque <see cref="Func{TResult}"/> instance to transform the final tree into text.</param>
/// <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(EffectIdInfo info, out Func<SyntaxNode, SourceText> fixup)
public static PropertyDeclarationSyntax GetSyntax(EquatableArray<byte> info)
{
// Prepare the initialization text
string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(info.AsSpan());
ExpressionSyntax effectIdExpression = ParseExpression($$"""new byte[] { {{effectIdLiterals}} }""");
// Create the local declaration:
//
// global::System.ReadOnlySpan<byte> bytes = new byte[] { __EMBEDDED_EFFECT_ID_BYTES };
// global::System.ReadOnlySpan<byte> bytes = new byte[] { <EMBEDDED_EFFECT_ID_BYTES> };
LocalDeclarationStatementSyntax guidBytesDeclaration =
LocalDeclarationStatement(
VariableDeclaration(
@@ -38,20 +37,7 @@ partial class ID2D1ShaderGenerator
.AddVariables(
VariableDeclarator(Identifier("bytes"))
.WithInitializer(
EqualsValueClause(
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(
InitializerExpression(
SyntaxKind.ArrayInitializerExpression,
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_EFFECT_ID_BYTES"))))))));
// Prepare the initialization text
string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(info.Bytes.AsSpan());
// Set the fixup function
fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_EFFECT_ID_BYTES", effectIdLiterals), Encoding.UTF8);
EqualsValueClause(effectIdExpression))));
// Prepare the return statement:
//
@@ -19,9 +19,9 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>InitializeFromDispatchData</c> method.
/// </summary>
/// <param name="dispatchInfo">The dispatch info gathered for the current shader.</param>
/// <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(DispatchDataInfo dispatchInfo)
public static MethodDeclarationSyntax GetSyntax(EquatableArray<FieldInfo> fields)
{
// This code produces a method declaration as follows:
//
@@ -35,7 +35,7 @@ partial class ID2D1ShaderGenerator
.AddParameterListParameters(Parameter(Identifier("data")).WithType(
GenericName(Identifier("global::System.ReadOnlySpan"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))))
.WithBody(Block(GetDispatchDataUnloadingStatements(dispatchInfo.FieldInfos)));
.WithBody(Block(GetDispatchDataUnloadingStatements(fields)));
}
/// <summary>
@@ -20,19 +20,19 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>InputDescriptions</c> property.
/// </summary>
/// <param name="inputDescriptionsInfo">The input descriptions info gathered for the current shader.</param>
/// <param name="additionalTypes">Any additional <see cref="TypeDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
/// <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(InputDescriptionsInfo inputDescriptionsInfo, out TypeDeclarationSyntax[] additionalTypes)
public static PropertyDeclarationSyntax GetSyntax(EquatableArray<InputDescription> inputDescriptions, out MemberDeclarationSyntax[] additionalDataMembers)
{
ExpressionSyntax memoryExpression;
// If there are no input descriptions, just return a default expression.
// Otherwise, declare the shared array and return it from the property.
if (inputDescriptionsInfo.InputDescriptions.Length == 0)
if (inputDescriptions.Length == 0)
{
memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
additionalTypes = Array.Empty<TypeDeclarationSyntax>();
additionalDataMembers = Array.Empty<MemberDeclarationSyntax>();
}
else
{
@@ -41,7 +41,7 @@ partial class ID2D1ShaderGenerator
IdentifierName("Data"),
IdentifierName(nameof(InputDescriptions)));
additionalTypes = new[] { GetArrayDeclaration(inputDescriptionsInfo) };
additionalDataMembers = new[] { GetArrayDeclaration(inputDescriptions) };
}
// This code produces a method declaration as follows:
@@ -61,13 +61,13 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Gets the array declaration for the given input descriptions.
/// </summary>
/// <param name="inputDescriptionsInfo">The input descriptions info gathered for the current shader.</param>
/// <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 TypeDeclarationSyntax GetArrayDeclaration(InputDescriptionsInfo inputDescriptionsInfo)
private static MemberDeclarationSyntax GetArrayDeclaration(EquatableArray<InputDescription> inputDescriptions)
{
using ImmutableArrayBuilder<ExpressionSyntax> inputDescriptionExpressions = ImmutableArrayBuilder<ExpressionSyntax>.Rent();
foreach (InputDescription inputDescription in inputDescriptionsInfo.InputDescriptions)
foreach (InputDescription inputDescription in inputDescriptions)
{
// Create the description expression (excluding level of detail):
//
@@ -109,7 +109,7 @@ partial class ID2D1ShaderGenerator
//
// /// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1InputDescription"/> array instance.</summary>
// public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = { <INPUT_DESCRIPTIONS> };
FieldDeclarationSyntax fieldDeclaration =
return
FieldDeclaration(
VariableDeclaration(
ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1InputDescription"))
@@ -124,11 +124,24 @@ partial class ID2D1ShaderGenerator
Token(SyntaxKind.StaticKeyword),
Token(SyntaxKind.ReadOnlyKeyword))
.WithLeadingTrivia(Comment("""/// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1InputDescription"/> array instance.</summary>"""));
}
/// <summary>
/// Gets any type declarations for additional members.
/// </summary>
/// <param name="memberDeclarations">The additional members that are needed.</param>
/// <returns>Any type declarations for additional members.</returns>
public static TypeDeclarationSyntax[] GetDataTypeDeclarations(MemberDeclarationSyntax[] memberDeclarations)
{
if (memberDeclarations.Length == 0)
{
return Array.Empty<TypeDeclarationSyntax>();
}
// Create the container type declaration:
//
// /// <summary>
// /// A container type for input descriptions.
// /// A container type for additional data needed by the shader.
// /// </summary>
// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
// [global::System.Diagnostics.DebuggerNonUserCode]
@@ -137,7 +150,7 @@ partial class ID2D1ShaderGenerator
// {
// <FIELD_DECLARATION>
// }
return
TypeDeclarationSyntax dataTypeDeclaration =
ClassDeclaration("Data")
.AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.StaticKeyword))
.AddAttributeLists(
@@ -147,11 +160,13 @@ partial class ID2D1ShaderGenerator
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")))))
.AddMembers(fieldDeclaration)
.AddMembers(memberDeclarations)
.WithLeadingTrivia(
Comment("/// <summary>"),
Comment("/// A container type for input descriptions."),
Comment("/// </summary>"));
return new[] { dataTypeDeclaration };
}
}
}
@@ -24,9 +24,9 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>ShaderProfile</c> property.
/// </summary>
/// <param name="bytecodeInfo">The input bytecode info.</param>
/// <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(EmbeddedBytecodeInfo bytecodeInfo)
public static PropertyDeclarationSyntax GetShaderProfileSyntax(D2D1ShaderProfile shaderProfile)
{
// This code produces a method declaration as follows:
//
@@ -39,21 +39,21 @@ partial class ID2D1ShaderGenerator
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"),
IdentifierName(bytecodeInfo.ShaderProfile.ToString(CultureInfo.InvariantCulture)))))
IdentifierName(shaderProfile.ToString(CultureInfo.InvariantCulture)))))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>CompileOptions</c> property.
/// </summary>
/// <param name="bytecodeInfo">The input bytecode info.</param>
/// <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(EmbeddedBytecodeInfo bytecodeInfo)
public static PropertyDeclarationSyntax GetCompileOptionsSyntax(D2D1CompileOptions compileOptions)
{
// Get a formatted representation of the compile options being used
ExpressionSyntax compileOptionsExpression =
ParseExpression(
bytecodeInfo.CompileOptions
compileOptions
.ToString(CultureInfo.InvariantCulture)
.Split(',')
.Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}")
@@ -78,7 +78,7 @@ partial class ID2D1ShaderGenerator
/// <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(
EmbeddedBytecodeInfo bytecodeInfo,
HlslBytecodeInfo bytecodeInfo,
out Func<SyntaxNode, SourceText> fixup,
out TypeDeclarationSyntax[] additionalTypes)
{
@@ -86,7 +86,7 @@ partial class ID2D1ShaderGenerator
// If there is no bytecode, simply return a default expression.
// Otherwise, declare the memory manager and access it.
if (bytecodeInfo.Bytecode.Length == 0)
if (bytecodeInfo is not HlslBytecodeInfo.Success success)
{
memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
fixup = static tree => tree.GetText(Encoding.UTF8);
@@ -106,8 +106,8 @@ partial class ID2D1ShaderGenerator
IdentifierName("Instance")),
IdentifierName("Memory"));
TypeDeclarationSyntax memoryManagerDeclaration = GetMemoryManagerDeclaration(bytecodeInfo);
string bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan());
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);
@@ -130,9 +130,8 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
/// </summary>
/// <param name="bytecodeInfo">The input bytecode info.</param>
/// <returns>The <see cref="BlockSyntax"/> instance trying to retrieve the precompiled shader.</returns>
private static unsafe TypeDeclarationSyntax GetMemoryManagerDeclaration(EmbeddedBytecodeInfo bytecodeInfo)
private static unsafe TypeDeclarationSyntax GetMemoryManagerDeclaration()
{
// Create the MemoryManager<T> declaration:
//
+74 -52
ファイルの表示
@@ -3,7 +3,6 @@ using System.Collections.Immutable;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using ComputeSharp.D2D1.Exceptions;
using ComputeSharp.D2D1.Shaders.Translation;
@@ -27,11 +26,11 @@ partial class ID2D1ShaderGenerator
internal static partial class LoadBytecode
{
/// <summary>
/// Extracts the shader profile for the current shader.
/// Extracts the requested shader profile for the current shader.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The shader profile to use to compile the shader, if present.</returns>
public static D2D1ShaderProfile? GetShaderProfile(INamedTypeSymbol structDeclarationSymbol)
/// <returns>The requested shader profile to use to compile the shader, if present.</returns>
public static D2D1ShaderProfile? GetRequestedShaderProfile(INamedTypeSymbol structDeclarationSymbol)
{
if (structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out AttributeData? attributeData))
{
@@ -47,12 +46,12 @@ partial class ID2D1ShaderGenerator
}
/// <summary>
/// Extracts the compile options for the current shader.
/// Extracts the requested compile options for the current shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The compile options to use to compile the shader, if present.</returns>
public static D2D1CompileOptions? GetCompileOptions(ImmutableArrayBuilder<DiagnosticInfo> diagnostics, INamedTypeSymbol structDeclarationSymbol)
/// <returns>The requested compile options to use to compile the shader, if present.</returns>
public static D2D1CompileOptions? GetRequestedCompileOptions(ImmutableArrayBuilder<DiagnosticInfo> diagnostics, INamedTypeSymbol structDeclarationSymbol)
{
if (structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData))
{
@@ -79,6 +78,30 @@ partial class ID2D1ShaderGenerator
return null;
}
/// <summary>
/// Gets the effective shader profile to use.
/// </summary>
/// <param name="shaderProfile">The requested shader profile.</param>
/// <returns>The effective shader profile.</returns>
public static D2D1ShaderProfile GetEffectiveShaderProfile(D2D1ShaderProfile? shaderProfile)
{
// The effective shader profile is either be the requested one, or the default value (which maps to PS5.0)
return shaderProfile ?? D2D1ShaderProfile.PixelShader50;
}
/// <summary>
/// Gets the effective compile options to use.
/// </summary>
/// <param name="compileOptions">The requested compile options.</param>
/// <param name="isLinkingSupported">Whether the input shader supports linking.</param>
/// <returns>The effective compile options.</returns>
public static D2D1CompileOptions GetEffectiveCompileOptions(D2D1CompileOptions? compileOptions, bool isLinkingSupported)
{
// If an explicit set of compile options is provided, use that directly. Otherwise, use the default
// options plus the option to enable linking only if the shader can potentially support it.
return compileOptions ?? (D2D1CompileOptions.Default | (isLinkingSupported ? D2D1CompileOptions.EnableLinking : 0));
}
/// <summary>
/// Extracts the metadata definition for the current shader.
/// </summary>
@@ -113,49 +136,31 @@ partial class ID2D1ShaderGenerator
}
/// <summary>
/// Gets an <see cref="ImmutableArray{T}"/> instance with the compiled bytecode for the current shader.
/// Gets the <see cref="HlslBytecodeInfo"/> instance for the input shader info.
/// </summary>
/// <param name="sourceInfo">The source info for the shader to compile.</param>
/// <param name="key">The <see cref="HlslBytecodeInfoKey"/> instance for the shader to compile.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <param name="shaderProfile">The effective shader profile used to create the shader bytecode, or the default profile to use.</param>
/// <param name="compileOptions">The effective compile options used to create the shader bytecode, or the default options to use.</param>
/// <param name="diagnostic">The resulting diagnostic from the processing operation, if any.</param>
/// <returns>The <see cref="ImmutableArray{T}"/> instance with the compiled shader bytecode.</returns>
public static unsafe ImmutableArray<byte> GetBytecode(
HlslShaderSourceInfo sourceInfo,
CancellationToken token,
out D2D1ShaderProfile shaderProfile,
out D2D1CompileOptions compileOptions,
out DeferredDiagnosticInfo? diagnostic)
/// <returns></returns>
public static unsafe HlslBytecodeInfo GetInfo(HlslBytecodeInfoKey key, CancellationToken token)
{
// Set the shader profile to either be the requested one, or the default value (which maps to PS5.0)
shaderProfile = sourceInfo.ShaderProfile ?? D2D1ShaderProfile.PixelShader50;
// If an explicit set of compile options is provided, use that directly. Otherwise, use the default
// options plus the option to enable linking only if the shader can potentially support it.
compileOptions = sourceInfo.CompileOptions ?? (D2D1CompileOptions.Default | (sourceInfo.IsLinkingSupported ? D2D1CompileOptions.EnableLinking : 0));
ImmutableArray<byte> bytecode = ImmutableArray<byte>.Empty;
// No embedded shader was requested, or there were some errors earlier in the pipeline.
// In this case, skip the compilation, as diagnostic will be emitted for those anyway.
// Compiling would just add overhead and result in more errors, as the HLSL would be invalid.
if (sourceInfo is { HasErrors: true } or { ShaderProfile: null })
// We also skip compilation if no shader profile has been requested (we never just assume one).
if (key.HasErrors || key.RequestedShaderProfile is null)
{
diagnostic = null;
goto End;
return HlslBytecodeInfo.Missing.Instance;
}
try
{
token.ThrowIfCancellationRequested();
// Compile the shader bytecode using the requested parameters
// Compile the shader bytecode using the effective parameters
using ComPtr<ID3DBlob> dxcBlobBytecode = D3DCompiler.Compile(
sourceInfo.HlslSource.AsSpan(),
sourceInfo.ShaderProfile.Value,
compileOptions);
key.HlslSource.AsSpan(),
key.EffectiveShaderProfile,
key.EffectiveCompileOptions);
token.ThrowIfCancellationRequested();
@@ -164,35 +169,52 @@ partial class ID2D1ShaderGenerator
byte[] array = new ReadOnlySpan<byte>(buffer, length).ToArray();
bytecode = Unsafe.As<byte[], ImmutableArray<byte>>(ref array);
diagnostic = null;
ImmutableArray<byte> bytecode = Unsafe.As<byte[], ImmutableArray<byte>>(ref array);
return new HlslBytecodeInfo.Success(bytecode);
}
catch (Win32Exception e)
{
compileOptions = default;
diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, FixupExceptionMessage(e.Message));
return new HlslBytecodeInfo.Win32Error(e.NativeErrorCode, D3DCompiler.PrettifyFxcErrorMessage(e.Message));
}
catch (FxcCompilationException e)
{
compileOptions = default;
diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithFxcCompilationException, FixupExceptionMessage(e.Message));
return new HlslBytecodeInfo.FxcError(D3DCompiler.PrettifyFxcErrorMessage(e.Message));
}
End:
return bytecode;
}
/// <summary>
/// Fixes up an exception message to improve the way it's displayed in VS.
/// Gets any diagnostics from a processed <see cref="HlslBytecodeInfo"/> instance.
/// </summary>
/// <param name="message">The input exception message.</param>
/// <returns>The updated exception message.</returns>
internal static string FixupExceptionMessage(string message)
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="info">The source <see cref="HlslBytecodeInfo"/> instance.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
public static void GetInfoDiagnostics(
INamedTypeSymbol structDeclarationSymbol,
HlslBytecodeInfo info,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics)
{
// Add square brackets around error headers
message = Regex.Replace(message, @"((?:error|warning) \w+):", static m => $"[{m.Groups[1].Value}]:");
DiagnosticInfo? diagnostic = null;
return message.NormalizeToSingleLine();
if (info is HlslBytecodeInfo.Win32Error win32Error)
{
diagnostic = DiagnosticInfo.Create(
EmbeddedBytecodeFailedWithWin32Exception,
structDeclarationSymbol,
new object[] { structDeclarationSymbol, win32Error.HResult, win32Error.Message });
}
else if (info is HlslBytecodeInfo.FxcError fxcError)
{
diagnostic = DiagnosticInfo.Create(
EmbeddedBytecodeFailedWithFxcCompilationException,
structDeclarationSymbol,
new object[] { structDeclarationSymbol, fxcError.Message });
}
if (diagnostic is not null)
{
diagnostics.Add(diagnostic);
}
}
}
}
@@ -24,19 +24,24 @@ partial class ID2D1ShaderGenerator
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
/// </summary>
/// <param name="hierarchyInfo">The hiararchy info of the shader type.</param>
/// <param name="dispatchInfo">The dispatch info gathered for the current shader.</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, DispatchDataInfo dispatchInfo, out TypeDeclarationSyntax[] additionalTypes)
public static MethodDeclarationSyntax GetSyntax(
HierarchyInfo hierarchyInfo,
EquatableArray<FieldInfo> fields,
int constantBufferSizeInBytes,
out TypeDeclarationSyntax[] additionalTypes)
{
// Declare the mapping constant buffer type, if needed (ie. if the shader has at least one field)
if (dispatchInfo.FieldInfos.Length == 0)
if (fields.Length == 0)
{
additionalTypes = Array.Empty<TypeDeclarationSyntax>();
}
else
{
additionalTypes = new[] { GetConstantBufferDeclaration(hierarchyInfo, dispatchInfo.FieldInfos, dispatchInfo.ConstantBufferSizeInBytes) };
additionalTypes = new[] { GetConstantBufferDeclaration(hierarchyInfo, fields, constantBufferSizeInBytes) };
}
// This code produces a method declaration as follows:
@@ -51,7 +56,7 @@ partial class ID2D1ShaderGenerator
.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(dispatchInfo.FieldInfos, dispatchInfo.ConstantBufferSizeInBytes)));
.WithBody(Block(GetDispatchDataLoadingStatements(fields, constantBufferSizeInBytes)));
}
/// <summary>
@@ -1,6 +1,5 @@
using System;
using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.SourceGenerators.Models;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
@@ -18,20 +17,20 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>BufferPrecision</c> property.
/// </summary>
/// <param name="info">The input info for the shader output buffer.</param>
/// <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(OutputBufferInfo info)
public static PropertyDeclarationSyntax GetBufferPrecisionSyntax(D2D1BufferPrecision bufferPrecision)
{
ExpressionSyntax bufferPrecisionExpression;
// Set the right expression if the buffer options are valid
if (Enum.IsDefined(typeof(D2D1BufferPrecision), info.BufferPrecision))
if (Enum.IsDefined(typeof(D2D1BufferPrecision), bufferPrecision))
{
bufferPrecisionExpression =
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("ComputeSharp.D2D1.D2D1BufferPrecision"),
IdentifierName(info.BufferPrecision.ToString()));
IdentifierName(bufferPrecision.ToString()));
}
else
{
@@ -53,20 +52,20 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>ChannelDepth</c> property.
/// </summary>
/// <param name="info">The input info for the shader output buffer.</param>
/// <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(OutputBufferInfo info)
public static PropertyDeclarationSyntax GetChannelDepthSyntax(D2D1ChannelDepth channelDepth)
{
ExpressionSyntax channelDepthExpression;
// Set the right expression if the buffer options are valid
if (Enum.IsDefined(typeof(D2D1ChannelDepth), info.ChannelDepth))
if (Enum.IsDefined(typeof(D2D1ChannelDepth), channelDepth))
{
channelDepthExpression =
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("ComputeSharp.D2D1.D2D1ChannelDepth"),
IdentifierName(info.ChannelDepth.ToString()));
IdentifierName(channelDepth.ToString()));
}
else
{
@@ -20,19 +20,19 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>ResourceTextureDescriptions</c> property.
/// </summary>
/// <param name="resourceTextureDescriptionsInfo">The resource texture descriptions info gathered for the current shader.</param>
/// <param name="additionalTypes">Any additional <see cref="TypeDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
/// <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(ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo, out TypeDeclarationSyntax[] additionalTypes)
public static PropertyDeclarationSyntax GetSyntax(EquatableArray<ResourceTextureDescription> resourceTextureDescriptions, out MemberDeclarationSyntax[] additionalDataMembers)
{
ExpressionSyntax memoryExpression;
// If there are no resource texture descriptions, just return a default expression.
// Otherwise, declare the shared array and return it from the property.
if (resourceTextureDescriptionsInfo.ResourceTextureDescriptions.Length == 0)
if (resourceTextureDescriptions.Length == 0)
{
memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
additionalTypes = Array.Empty<TypeDeclarationSyntax>();
additionalDataMembers = Array.Empty<MemberDeclarationSyntax>();
}
else
{
@@ -41,7 +41,7 @@ partial class ID2D1ShaderGenerator
IdentifierName("Data"),
IdentifierName(nameof(ResourceTextureDescriptions)));
additionalTypes = new[] { GetArrayDeclaration(resourceTextureDescriptionsInfo) };
additionalDataMembers = new[] { GetArrayDeclaration(resourceTextureDescriptions) };
}
// This code produces a method declaration as follows:
@@ -61,13 +61,13 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Gets the array declaration for the given resource texture descriptions.
/// </summary>
/// <param name="resourceTextureDescriptionsInfo">The resource texture descriptions info gathered for the current shader.</param>
/// <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 TypeDeclarationSyntax GetArrayDeclaration(ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo)
private static MemberDeclarationSyntax GetArrayDeclaration(EquatableArray<ResourceTextureDescription> resourceTextureDescriptions)
{
using ImmutableArrayBuilder<ExpressionSyntax> resourceTextureDescriptionExpressions = ImmutableArrayBuilder<ExpressionSyntax>.Rent();
foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptionsInfo.ResourceTextureDescriptions)
foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptions)
{
// Create the description expression:
//
@@ -87,7 +87,7 @@ partial class ID2D1ShaderGenerator
//
// /// <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> };
FieldDeclarationSyntax fieldDeclaration =
return
FieldDeclaration(
VariableDeclaration(
ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription"))
@@ -102,34 +102,6 @@ partial class ID2D1ShaderGenerator
Token(SyntaxKind.StaticKeyword),
Token(SyntaxKind.ReadOnlyKeyword))
.WithLeadingTrivia(Comment("""/// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription"/> array instance.</summary>"""));
// Create the container type declaration:
//
// /// <summary>
// /// A container type for input descriptions.
// /// </summary>
// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
// [global::System.Diagnostics.DebuggerNonUserCode]
// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
// file static class Data
// {
// <FIELD_DECLARATION>
// }
return
ClassDeclaration("Data")
.AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.StaticKeyword))
.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")))))
.AddMembers(fieldDeclaration)
.WithLeadingTrivia(
Comment("/// <summary>"),
Comment("/// A container type for resource texture descriptions."),
Comment("/// </summary>"));
}
}
}
+91 -277
ファイルの表示
@@ -1,7 +1,6 @@
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
@@ -23,7 +22,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Discover all shader types and extract all the necessary info from each of them
IncrementalValuesProvider<D2D1ShaderInfo> shaderInfoWithErrors =
IncrementalValuesProvider<D2D1ShaderInfo> shaderInfo =
context.SyntaxProvider
.CreateSyntaxProvider(
static (node, _) => node.IsTypeDeclarationWithOrPotentiallyWithBaseTypes<StructDeclarationSyntax>(),
@@ -93,6 +92,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
out ImmutableArray<int> inputComplexIndices,
out ImmutableArray<uint> inputTypes);
token.ThrowIfCancellationRequested();
// Get the resource texture info for ResourceTextureDescriptions
ResourceTextureDescriptions.GetInfo(
diagnostics,
@@ -100,6 +101,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
inputCount,
out ImmutableArray<ResourceTextureDescription> resourceTextureDescriptions);
token.ThrowIfCancellationRequested();
// Get HLSL source for HlslSource
string hlslSource = HlslSource.GetHlslSource(
diagnostics,
@@ -112,13 +115,6 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
token.ThrowIfCancellationRequested();
// Get the shader profile and linking info for LoadBytecode()
D2D1ShaderProfile? shaderProfile = LoadBytecode.GetShaderProfile(typeSymbol);
D2D1CompileOptions? compileOptions = LoadBytecode.GetCompileOptions(diagnostics, typeSymbol);
bool isLinkingSupported = LoadBytecode.IsSimpleInputShader(typeSymbol, inputCount);
token.ThrowIfCancellationRequested();
// Get the info for the output buffer properties
OutputBuffer.GetInfo(typeSymbol, out D2D1BufferPrecision bufferPrecision, out D2D1ChannelDepth channelDepth);
@@ -137,293 +133,111 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
token.ThrowIfCancellationRequested();
// Get the shader profile and linking info for LoadBytecode()
bool isLinkingSupported = LoadBytecode.IsSimpleInputShader(typeSymbol, inputCount);
D2D1ShaderProfile? requestedShaderProfile = LoadBytecode.GetRequestedShaderProfile(typeSymbol);
D2D1CompileOptions? requestedCompileOptions = LoadBytecode.GetRequestedCompileOptions(diagnostics, typeSymbol);
D2D1ShaderProfile effectiveShaderProfile = LoadBytecode.GetEffectiveShaderProfile(requestedShaderProfile);
D2D1CompileOptions effectiveCompileOptions = LoadBytecode.GetEffectiveCompileOptions(requestedCompileOptions, isLinkingSupported);
bool hasErrors = diagnostics.Count > 0;
token.ThrowIfCancellationRequested();
// As the last steps in the pipeline, try to compile the shader if needed.
// This is done last so that it can be skipped if any errors happened before.
HlslBytecodeInfoKey hlslInfoKey = new(
hlslSource,
requestedShaderProfile,
requestedCompileOptions,
effectiveShaderProfile,
effectiveCompileOptions,
hasErrors);
// TODO: cache this across transform runs
HlslBytecodeInfo hlslInfo = LoadBytecode.GetInfo(hlslInfoKey, token);
token.ThrowIfCancellationRequested();
// Append any diagnostic for the shader compilation
LoadBytecode.GetInfoDiagnostics(typeSymbol, hlslInfo, diagnostics);
token.ThrowIfCancellationRequested();
return new D2D1ShaderInfo(
Hierarchy: HierarchyInfo.From(typeSymbol),
EffectId: new EffectIdInfo(effectId),
EffectId: effectId,
EffectDisplayName: effectDisplayName,
EffectDescription: effectDescription,
EffectCategory: effectCategory,
EffectAuthor: effectAuthor,
DispatchData: new DispatchDataInfo(fieldInfos, constantBufferSizeInBytes),
InputTypes: new InputTypesInfo(inputTypes),
ResourceTextureDescriptions: new ResourceTextureDescriptionsInfo(resourceTextureDescriptions),
HlslShaderSource: new HlslShaderSourceInfo(
hlslSource,
shaderProfile,
compileOptions,
isLinkingSupported,
HasErrors: diagnostics.Count > 0),
OutputBuffer: new OutputBufferInfo(bufferPrecision, channelDepth),
InputDescriptions: new InputDescriptionsInfo(inputDescriptions),
ConstantBufferSizeInBytes: constantBufferSizeInBytes,
InputTypes: inputTypes,
InputDescriptions: inputDescriptions,
ResourceTextureDescriptions: resourceTextureDescriptions,
Fields: fieldInfos,
BufferPrecision: bufferPrecision,
ChannelDepth: channelDepth,
PixelOptions: pixelOptions,
HlslInfoKey: hlslInfoKey,
HlslInfo: hlslInfo,
Diagnostcs: diagnostics.ToImmutable());
})
.Where(static item => item is not null)!;
// We need to create two more incremental steps to ensure we correctly emit diagnostics and re-generate sources:
// - One with just the diagnostics, which will trigger every time any of them changes
// - One with just the shader info (and no diagnostics), so that changes there don't trigger generation unnecessarily
IncrementalValuesProvider<EquatableArray<DiagnosticInfo>> diagnosticInfo = shaderInfo.Select(static (item, _) => item.Diagnostcs);
IncrementalValuesProvider<D2D1ShaderInfo> outputInfo = shaderInfo.Select(static (item, _) => item with { Diagnostcs = default });
// Output the diagnostics, if any
context.ReportDiagnostics(
shaderInfoWithErrors
.Select(static (item, _) => item.Diagnostcs));
context.ReportDiagnostics(diagnosticInfo);
// Get the EffectId info (hierarchy and effect id info)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EffectIdInfo EffectId)> effectIdInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.EffectId));
// Generate the EffectId properties
context.RegisterSourceOutput(effectIdInfo, static (context, item) =>
{
PropertyDeclarationSyntax effectDisplayNameProperty = EffectId.GetSyntax(item.EffectId, out Func<SyntaxNode, SourceText> fixup);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDisplayNameProperty, skipLocalsInit: false);
SourceText text = fixup(compilationUnit);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(EffectId)}.g.cs", text);
});
// Get the EffectDisplayName info (hierarchy and effect display name)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, string? EffectDisplayName)> effectDisplayNameInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.EffectDisplayName));
// Generate the EffectDisplayName properties
context.RegisterSourceOutput(effectDisplayNameInfo, static (context, item) =>
// Generate the source files, if any
context.RegisterSourceOutput(outputInfo, static (context, item) =>
{
PropertyDeclarationSyntax effectIdProperty = EffectId.GetSyntax(item.EffectId);
PropertyDeclarationSyntax effectDisplayNameProperty = EffectMetadata.GetEffectDisplayNameSyntax(item.EffectDisplayName);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDisplayNameProperty, skipLocalsInit: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.EffectDisplayName.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the EffectDescription info (hierarchy and effect description)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, string? EffectDescription)> effectDescriptionInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.EffectDescription));
// Generate the EffectDescription properties
context.RegisterSourceOutput(effectDescriptionInfo, static (context, item) =>
{
PropertyDeclarationSyntax effectDescriptionProperty = EffectMetadata.GetEffectDescriptionSyntax(item.EffectDescription);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDescriptionProperty, skipLocalsInit: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.EffectDescription.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the EffectCategory info (hierarchy and effect description)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, string? EffectCategory)> effectCategoryInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.EffectCategory));
// Generate the EffectCategory properties
context.RegisterSourceOutput(effectCategoryInfo, static (context, item) =>
{
PropertyDeclarationSyntax effectCategoryProperty = EffectMetadata.GetEffectCategorySyntax(item.EffectCategory);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectCategoryProperty, skipLocalsInit: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.EffectCategory.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the EffectAuthor info (hierarchy and effect description)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, string? EffectAuthor)> effectAuthorInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.EffectAuthor));
// Generate the EffectAuthor properties
context.RegisterSourceOutput(effectAuthorInfo, static (context, item) =>
{
PropertyDeclarationSyntax effectCategoryProperty = EffectMetadata.GetEffectAuthorSyntax(item.EffectAuthor);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectCategoryProperty, skipLocalsInit: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.EffectAuthor.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the InputCount info (hierarchy and input count)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.InputTypes.InputTypes.Length));
// Generate the InputCount properties
context.RegisterSourceOutput(inputCountInfo, static (context, item) =>
{
PropertyDeclarationSyntax inputCountProperty = InputCount.GetSyntax(item.InputCount);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, inputCountProperty, skipLocalsInit: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(InputCount)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the InputTypes info (hierarchy and input types)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputTypesInfo InputTypes)> inputTypesInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.InputTypes));
// Generate the InputTypes properties
context.RegisterSourceOutput(inputTypesInfo, static (context, item) =>
{
PropertyDeclarationSyntax inputTypesProperty = InputTypes.GetSyntax(item.InputTypes.InputTypes, out TypeDeclarationSyntax[] additionalTypes);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, inputTypesProperty, skipLocalsInit: false, additionalMemberDeclarations: additionalTypes);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(InputTypes)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the ResourceTextureDescriptions info (hierarchy and resource texture descriptions)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, ResourceTextureDescriptionsInfo ResourceTextureDescriptions)> resourceTextureDescriptionsInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.ResourceTextureDescriptions));
// Generate the ResourceTextureDescriptions properties
context.RegisterSourceOutput(resourceTextureDescriptionsInfo, static (context, item) =>
{
PropertyDeclarationSyntax resourceTextureDescriptionsProperty = ResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions, out TypeDeclarationSyntax[] additionalTypes);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, resourceTextureDescriptionsProperty, skipLocalsInit: false, additionalMemberDeclarations: additionalTypes);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(ResourceTextureDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the info for InitializeFromDispatchData() and LoadDispatchData() (hierarchy and dispatch data)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch)> dispatchDataInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.DispatchData));
// Generate the InitializeFromDispatchData() and LoadDispatchData() methods
context.RegisterSourceOutput(dispatchDataInfo, static (context, item) =>
{
MethodDeclarationSyntax initializeFromDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Dispatch);
MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Hierarchy, item.Dispatch, out TypeDeclarationSyntax[] additionalTypes);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMembers(
item.Hierarchy,
memberDeclarations: new (MemberDeclarationSyntax, bool)[] { (initializeFromDispatchDataMethod, false), (loadDispatchDataMethod, true) },
additionalMemberDeclarations: additionalTypes);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the HlslSource info (hierarchy, HLSL source and parsing options)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource)> hlslSourceInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource.HlslSource));
// Generate the HlslSource properties
context.RegisterSourceOutput(hlslSourceInfo, static (context, item) =>
{
PropertyDeclarationSyntax hlslStringProperty = HlslSource.GetSyntax(item.HlslSource, item.Hierarchy.Hierarchy.Length);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, hlslStringProperty, skipLocalsInit: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(HlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get a filtered sequence to enable caching for the HLSL source info, before the shader compilation step
IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo Source)> shaderBytecodeInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource));
// Compile the requested shader bytecodes
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors =
shaderBytecodeInfo
.Select(static (item, token) =>
{
ImmutableArray<byte> bytecode = LoadBytecode.GetBytecode(
item.Source,
token,
out D2D1ShaderProfile shaderProfile,
out D2D1CompileOptions compileOptions,
out DeferredDiagnosticInfo? diagnostic);
token.ThrowIfCancellationRequested();
EmbeddedBytecodeInfo bytecodeInfo = new(
item.Source.HlslSource,
shaderProfile,
compileOptions,
bytecode);
return (item.Hierarchy, bytecodeInfo, diagnostic);
});
// Gather the diagnostics
IncrementalValuesProvider<DiagnosticInfo> embeddedBytecodeDiagnostics =
embeddedBytecodeWithErrors
.Select(static (item, _) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic))
.Where(static item => item.Diagnostic is not null)
.Combine(context.CompilationProvider)
.Select(static (item, _) =>
{
INamedTypeSymbol typeSymbol = item.Right.GetTypeByMetadataName(item.Left.FullyQualifiedMetadataName)!;
return DiagnosticInfo.Create(item.Left.Diagnostic!.Descriptor, typeSymbol, new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Arguments).ToArray());
});
// Output the diagnostics
context.ReportDiagnostics(embeddedBytecodeDiagnostics);
// Get the LoadBytecode() info (hierarchy and compiled bytecode)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode =
embeddedBytecodeWithErrors
.Select(static (item, _) => (item.Hierarchy, item.BytecodeInfo));
// Generate the LoadBytecode() methods
context.RegisterSourceOutput(embeddedBytecode, static (context, item) =>
{
PropertyDeclarationSyntax hlslBytecodeProperty = LoadBytecode.GetHlslBytecodeSyntax(item.BytecodeInfo, out Func<SyntaxNode, SourceText> fixup, out TypeDeclarationSyntax[] additionalTypes);
CompilationUnitSyntax hlslBytecodeCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, hlslBytecodeProperty, skipLocalsInit: false, additionalMemberDeclarations: additionalTypes);
SourceText text = fixup(hlslBytecodeCompilationUnit);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.HlslBytecode.g.cs", text);
PropertyDeclarationSyntax shaderProfileProperty = LoadBytecode.GetShaderProfileSyntax(item.BytecodeInfo);
CompilationUnitSyntax shaderProfileCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, shaderProfileProperty, skipLocalsInit: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.ShaderProfile.g.cs", shaderProfileCompilationUnit.GetText(Encoding.UTF8));
PropertyDeclarationSyntax compileOptionsProperty = LoadBytecode.GetCompileOptionsSyntax(item.BytecodeInfo);
CompilationUnitSyntax compileOptionsCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, compileOptionsProperty, skipLocalsInit: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.CompileOptions.g.cs", compileOptionsCompilationUnit.GetText(Encoding.UTF8));
});
// Get the output buffer info (hierarchy and output buffers)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, OutputBufferInfo OutputBuffer)> outputBufferInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.OutputBuffer));
// Generate the output buffer properties
context.RegisterSourceOutput(outputBufferInfo, static (context, item) =>
{
PropertyDeclarationSyntax bufferPrecisionProperty = OutputBuffer.GetBufferPrecisionSyntax(item.OutputBuffer);
CompilationUnitSyntax bufferPrecisionCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, bufferPrecisionProperty, skipLocalsInit: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.BufferPrecision.g.cs", bufferPrecisionCompilationUnit.GetText(Encoding.UTF8));
PropertyDeclarationSyntax channelDepthProperty = OutputBuffer.GetChannelDepthSyntax(item.OutputBuffer);
CompilationUnitSyntax channelDepthCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, channelDepthProperty, skipLocalsInit: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.ChannelDepth.g.cs", channelDepthCompilationUnit.GetText(Encoding.UTF8));
});
// Get the InputDescriptions info (hierarchy and input descriptions)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputDescriptionsInfo InputDescriptions)> inputDescriptionsInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.InputDescriptions));
// Generate the InputDescriptions properties
context.RegisterSourceOutput(inputDescriptionsInfo, static (context, item) =>
{
PropertyDeclarationSyntax inputDescriptionsProperty = InputDescriptions.GetSyntax(item.InputDescriptions, out TypeDeclarationSyntax[] additionalTypes);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, inputDescriptionsProperty, skipLocalsInit: false, additionalMemberDeclarations: additionalTypes);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(InputDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the PixelOptions info (hierarchy and pixel options)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, D2D1PixelOptions PixelOptions)> pixelOptionsInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.PixelOptions));
// Generate the PixelOptions properties
context.RegisterSourceOutput(pixelOptionsInfo, static (context, item) =>
{
PropertyDeclarationSyntax effectAuthorProperty = EffectMetadata.GetEffectAuthorSyntax(item.EffectAuthor);
PropertyDeclarationSyntax inputCountProperty = InputCount.GetSyntax(item.InputTypes.Length);
PropertyDeclarationSyntax inputTypesProperty = InputTypes.GetSyntax(item.InputTypes, out TypeDeclarationSyntax[] inputTypesAdditionalTypes);
PropertyDeclarationSyntax inputDescriptionsProperty = InputDescriptions.GetSyntax(item.InputDescriptions, out MemberDeclarationSyntax[] inputDescriptionsAdditionalDataMembers);
PropertyDeclarationSyntax resourceTextureDescriptionsProperty = ResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions, out MemberDeclarationSyntax[] resourceTexturesAditionalDataMembers);
PropertyDeclarationSyntax hlslStringProperty = HlslSource.GetSyntax(item.HlslInfoKey.HlslSource, item.Hierarchy.Hierarchy.Length);
PropertyDeclarationSyntax hlslBytecodeProperty = LoadBytecode.GetHlslBytecodeSyntax(item.HlslInfo, out Func<SyntaxNode, SourceText> fixup, out TypeDeclarationSyntax[] hlslBytecodeAdditionalTypes);
PropertyDeclarationSyntax shaderProfileProperty = LoadBytecode.GetShaderProfileSyntax(item.HlslInfoKey.EffectiveShaderProfile);
PropertyDeclarationSyntax compileOptionsProperty = LoadBytecode.GetCompileOptionsSyntax(item.HlslInfoKey.EffectiveCompileOptions);
PropertyDeclarationSyntax bufferPrecisionProperty = OutputBuffer.GetBufferPrecisionSyntax(item.BufferPrecision);
PropertyDeclarationSyntax channelDepthProperty = OutputBuffer.GetChannelDepthSyntax(item.ChannelDepth);
PropertyDeclarationSyntax pixelOptionsProperty = PixelOptions.GetSyntax(item.PixelOptions);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, pixelOptionsProperty, skipLocalsInit: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(PixelOptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
MethodDeclarationSyntax initializeFromDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Fields);
MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Hierarchy, item.Fields, item.ConstantBufferSizeInBytes, out TypeDeclarationSyntax[] loadDispatchDataAditionalTypes);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMembers(
hierarchyInfo: item.Hierarchy,
memberDeclarations: new (MemberDeclarationSyntax, bool)[]
{
(effectIdProperty, false), (effectDisplayNameProperty, false), (effectDescriptionProperty, false), (effectCategoryProperty, false), (effectAuthorProperty, false),
(inputCountProperty, false), (inputTypesProperty, false), (inputDescriptionsProperty, false), (resourceTextureDescriptionsProperty, false), (hlslStringProperty, false),
(hlslBytecodeProperty, false), (shaderProfileProperty, false), (compileOptionsProperty, false), (bufferPrecisionProperty, false), (channelDepthProperty, false),
(pixelOptionsProperty, false), (initializeFromDispatchDataMethod, true), (loadDispatchDataMethod, true)
},
additionalMemberDeclarations: new TypeDeclarationSyntax[][]
{
loadDispatchDataAditionalTypes,
InputDescriptions.GetDataTypeDeclarations(new[] { inputDescriptionsAdditionalDataMembers, resourceTexturesAditionalDataMembers }.SelectMany(static members => members).ToArray()),
inputTypesAdditionalTypes, hlslBytecodeAdditionalTypes
}
.SelectMany(static types => types)
.Cast<MemberDeclarationSyntax>()
.ToArray());
SourceText sourceText = fixup(compilationUnit);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", sourceText);
});
}
}
+18 -12
ファイルの表示
@@ -7,31 +7,37 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// A model representing all necessary info for a full generation pass for a D2D1 shader.
/// </summary>
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
/// <param name="EffectId">The effect id info for the shader type.</param>
/// <param name="EffectId">The GUID bytes for the effect id.</param>
/// <param name="EffectDisplayName">The effect display name for the shader type, if available.</param>
/// <param name="EffectDescription">The effect description for the shader type, if available.</param>
/// <param name="EffectCategory">The effect category for the shader type, if available.</param>
/// <param name="EffectAuthor">The effect author for the shader type, if available.</param>
/// <param name="DispatchData">The gathered shader dispatch data.</param>
/// <param name="ConstantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <param name="InputTypes">The gathered input types for the shader.</param>
/// <param name="ResourceTextureDescriptions">The gathered resource texture descriptions for the shader.</param>
/// <param name="HlslShaderSource">The processed HLSL source for the shader.</param>
/// <param name="OutputBuffer">The output buffer info for the shader.</param>
/// <param name="InputDescriptions">The gathered input descriptions for the shader.</param>
/// <param name="ResourceTextureDescriptions">The gathered resource texture descriptions for the shader.</param>
/// <param name="Fields">The description on shader instance fields.</param>
/// <param name="BufferPrecision">The buffer precision for the resulting output buffer.</param>
/// <param name="ChannelDepth">The channel depth for the resulting output buffer.</param>
/// <param name="PixelOptions">The pixel options used by the shader.</param>
/// <param name="HlslInfoKey">The key with processed info on the shader.</param>
/// <param name="HlslInfo">The value with processed info on the shader.</param>
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record D2D1ShaderInfo(
HierarchyInfo Hierarchy,
EffectIdInfo EffectId,
EquatableArray<byte> EffectId,
string? EffectDisplayName,
string? EffectDescription,
string? EffectCategory,
string? EffectAuthor,
DispatchDataInfo DispatchData,
InputTypesInfo InputTypes,
ResourceTextureDescriptionsInfo ResourceTextureDescriptions,
HlslShaderSourceInfo HlslShaderSource,
OutputBufferInfo OutputBuffer,
InputDescriptionsInfo InputDescriptions,
int ConstantBufferSizeInBytes,
EquatableArray<uint> InputTypes,
EquatableArray<InputDescription> InputDescriptions,
EquatableArray<ResourceTextureDescription> ResourceTextureDescriptions,
EquatableArray<FieldInfo> Fields,
D2D1BufferPrecision BufferPrecision,
D2D1ChannelDepth ChannelDepth,
D2D1PixelOptions PixelOptions,
HlslBytecodeInfoKey HlslInfoKey,
HlslBytecodeInfo HlslInfo,
EquatableArray<DiagnosticInfo> Diagnostcs);
-10
ファイルの表示
@@ -1,10 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing gathered info on a shader dispatch data.
/// </summary>
/// <param name="FieldInfos">The description on shader instance fields.</param>
/// <param name="ConstantBufferSizeInBytes">The size of the shader constant buffer.</param>
internal sealed record DispatchDataInfo(EquatableArray<FieldInfo> FieldInfos, int ConstantBufferSizeInBytes);
-9
ファイルの表示
@@ -1,9 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing info to use to generate an effect id for a shader.
/// </summary>
/// <param name="Bytes">The bytes for the processed effect id.</param>
internal sealed record EffectIdInfo(EquatableArray<byte> Bytes);
-12
ファイルの表示
@@ -1,12 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing info on a shader that has requested to be precompiled at build time.
/// </summary>
/// <param name="HlslSource">The HLSL source for the shader.</param>
/// <param name="ShaderProfile">The shader profile to use to compile the shader, or the default one.</param>
/// <param name="CompileOptions">The compile options to use to compile the shader, or the default one.</param>
/// <param name="Bytecode">The compiled shader bytecode, if available.</param>
internal sealed record EmbeddedBytecodeInfo(string HlslSource, D2D1ShaderProfile ShaderProfile, D2D1CompileOptions CompileOptions, EquatableArray<byte> Bytecode);
+39
ファイルの表示
@@ -0,0 +1,39 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing info on compiled HLSL bytecode, if available.
/// </summary>
internal abstract record HlslBytecodeInfo
{
/// <summary>
/// A successfully compiled HLSL shader.
/// </summary>
/// <param name="Bytecode">The resulting HLSL bytecode.</param>
public sealed record Success(EquatableArray<byte> Bytecode) : HlslBytecodeInfo;
/// <summary>
/// An HLSL shader that failed to compile due to a Win32 error.
/// </summary>
/// <param name="HResult">The HRESULT for the error.</param>
/// <param name="Message">The error message from compiling the shader.</param>
public sealed record Win32Error(int HResult, string Message) : HlslBytecodeInfo;
/// <summary>
/// An HLSL shader that failed to compile due to an FXC compiler error.
/// </summary>
/// <param name="Message">The error message from compiling the shader.</param>
public sealed record FxcError(string Message) : HlslBytecodeInfo;
/// <summary>
/// No HLSL bytecode is available (ie. compilation was not requested or some other error was detected).
/// </summary>
public sealed record Missing : HlslBytecodeInfo
{
/// <summary>
/// Gets the shared <see cref="Missing"/> instance.
/// </summary>
public static Missing Instance { get; } = new();
}
}
+18
ファイルの表示
@@ -0,0 +1,18 @@
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model with info to be a unique key for <see cref="HlslBytecodeInfo"/> instances.
/// </summary>
/// <param name="HlslSource">The input HLSL source code.</param>
/// <param name="RequestedShaderProfile">The requested shader profile, if available.</param>
/// <param name="RequestedCompileOptions">The requested compile options, if available.</param>
/// <param name="EffectiveShaderProfile">The effective shader profile.</param>
/// <param name="EffectiveCompileOptions">The effective compile options.</param>
/// <param name="HasErrors">Whether any errors were produced when analyzing the shader.</param>
internal sealed record HlslBytecodeInfoKey(
string HlslSource,
D2D1ShaderProfile? RequestedShaderProfile,
D2D1CompileOptions? RequestedCompileOptions,
D2D1ShaderProfile EffectiveShaderProfile,
D2D1CompileOptions EffectiveCompileOptions,
bool HasErrors);
-16
ファイルの表示
@@ -1,16 +0,0 @@
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model for extracted info on a processed HLSL shader.
/// </summary>
/// <param name="HlslSource">The HLSL source.</param>
/// <param name="ShaderProfile">The shader profile to use to compile the shader, if requested.</param>
/// <param name="CompileOptions">The compile options to use to compile the shader.</param>
/// <param name="IsLinkingSupported">Whether the shader supports linking.</param>
/// <param name="HasErrors">Whether any errors have been detected, and therefore the shader compilation should be skipped.</param>
internal sealed record HlslShaderSourceInfo(
string HlslSource,
D2D1ShaderProfile? ShaderProfile,
D2D1CompileOptions? CompileOptions,
bool IsLinkingSupported,
bool HasErrors);
-9
ファイルの表示
@@ -1,9 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing gathered input descriptions for a shader.
/// </summary>
/// <param name="InputDescriptions">The input descriptions for a given shader.</param>
internal sealed record InputDescriptionsInfo(EquatableArray<InputDescription> InputDescriptions);
-9
ファイルの表示
@@ -1,9 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing gathered info on a shader input types.
/// </summary>
/// <param name="InputTypes">The input types for a given shader.</param>
internal sealed record InputTypesInfo(EquatableArray<uint> InputTypes);
-8
ファイルの表示
@@ -1,8 +0,0 @@
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing the output buffer info for a shader.
/// </summary>
/// <param name="BufferPrecision">The buffer precision for the resulting output buffer.</param>
/// <param name="ChannelDepth">The channel depth for the resulting output buffer.</param>
internal sealed record OutputBufferInfo(D2D1BufferPrecision BufferPrecision, D2D1ChannelDepth ChannelDepth);
-9
ファイルの表示
@@ -1,9 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing gathered resource texture descriptions for a shader.
/// </summary>
/// <param name="ResourceTextureDescriptions">The resource textures for the current shader.</param>
internal sealed record ResourceTextureDescriptionsInfo(EquatableArray<ResourceTextureDescription> ResourceTextureDescriptions);
+19 -8
ファイルの表示
@@ -175,16 +175,12 @@ internal static unsafe partial class D3DCompiler
}
/// <summary>
/// Throws an exception when a shader compilation fails.
/// Returns a "prettified" version of an FXC error message.
/// </summary>
/// <param name="d3DOperationResult">The input (faulting) operation.</param>
/// <returns>This method always throws and never actually returs.</returns>
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowHslsCompilationException(ID3DBlob* d3DOperationResult)
/// <param name="message">The input error message.</param>
/// <returns>The "prettified" error message.</returns>
public static string PrettifyFxcErrorMessage(string message)
{
string message = new((sbyte*)d3DOperationResult->GetBufferPointer());
// The error message will be in a format like this:
// "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\Roslyn\Shader@0x0000019AD1B4BA70(22,32-35): error X3004: undeclared identifier 'this'"
// This regex tries to match the unnecessary header and remove it, if present. This doesn't need to be bulletproof, and this regex should match all cases anyway.
@@ -227,6 +223,21 @@ internal static unsafe partial class D3DCompiler
updatedMessage += '.';
}
return updatedMessage;
}
/// <summary>
/// Throws an exception when a shader compilation fails.
/// </summary>
/// <param name="d3DOperationResult">The input (faulting) operation.</param>
/// <returns>This method always throws and never actually returs.</returns>
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowHslsCompilationException(ID3DBlob* d3DOperationResult)
{
string message = new((sbyte*)d3DOperationResult->GetBufferPointer());
string updatedMessage = PrettifyFxcErrorMessage(message);
throw new FxcCompilationException(updatedMessage);
}