Merge pull request #577 from Sergio0694/dev/shader-bytecode-memory

Switch HLSL bytecode, shader profile and compile options to properties
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-09-28 17:03:32 +02:00
コミット 4fa5a7c35e
13ファイル変更
+498 -381

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

-1
ファイルの表示
@@ -78,7 +78,6 @@
<Compile Include="..\ComputeSharp.D2D1\Extensions\ComPtrExtensions.cs" Link="ComputeSharp.D2D1\Extensions\ComPtrExtensions.cs" />
<Compile Include="..\ComputeSharp.D2D1\Extensions\HRESULTExtensions.cs" Link="ComputeSharp.D2D1\Extensions\HRESULTExtensions.cs" />
<Compile Include="..\ComputeSharp.D2D1\Interfaces\ID2D1PixelShader.cs" Link="ComputeSharp.D2D1\Interfaces\ID2D1PixelShader.cs" />
<Compile Include="..\ComputeSharp.D2D1\Interfaces\__Internals\ID2D1BytecodeLoader.cs" Link="ComputeSharp.D2D1\Interfaces\__Internals\ID2D1BytecodeLoader.cs" />
<Compile Include="..\ComputeSharp.D2D1\Interfaces\__Internals\ID2D1DispatchDataLoader.cs" Link="ComputeSharp.D2D1\Interfaces\__Internals\ID2D1DispatchDataLoader.cs" />
<Compile Include="..\ComputeSharp.D2D1\Interfaces\__Internals\ID2D1Shader.cs" Link="ComputeSharp.D2D1\Interfaces\__Internals\ID2D1Shader.cs" />
<Compile Include="..\ComputeSharp.D2D1\Intrinsics\D2D.cs" Link="ComputeSharp.D2D1\Intrinsics\D2D.cs" />
@@ -22,63 +22,34 @@ partial class ID2D1ShaderGenerator
partial class LoadBytecode
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>TryGetBytecode</c> method.
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>ShaderProfile</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>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslSource</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func<SyntaxNode, SourceText> fixup)
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>ShaderProfile</c> property.</returns>
public static PropertyDeclarationSyntax GetShaderProfileSyntax(EmbeddedBytecodeInfo bytecodeInfo)
{
BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals);
if (bytecodeLiterals is not null)
{
fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8);
}
else
{
fixup = static tree => tree.GetText(Encoding.UTF8);
}
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadBytecode<TLoader>(ref TLoader loader, ref global::ComputeSharp.D2D1.D2D1ShaderProfile? shaderProfile, ref global::ComputeSharp.D2D1.D2D1CompileOptions? compileOptions)
// {
// <BODY>
// }
// readonly ComputeSharp.D2D1.D2D1ShaderProfile global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ShaderProfile => <SHADER_PROFILE>;
return
MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(LoadBytecode)))
PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1ShaderProfile"), Identifier(nameof(ID2D1Shader.ShaderProfile)))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader")),
Parameter(Identifier("shaderProfile")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"))),
Parameter(Identifier("compileOptions")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1.D2D1CompileOptions"))))
.WithBody(block);
.WithExpressionBody(ArrowExpressionClause(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"),
IdentifierName(bytecodeInfo.ShaderProfile.ToString(CultureInfo.InvariantCulture)))))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>CompileOptions</c> property.
/// </summary>
/// <param name="bytecodeInfo">The input bytecode info.</param>
/// <param name="bytecodeLiterals">The resulting bytecode literals to insert into the final source code.</param>
/// <returns>The <see cref="BlockSyntax"/> instance trying to retrieve the precompiled shader.</returns>
private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals)
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>CompileOptions</c> property.</returns>
public static PropertyDeclarationSyntax GetCompileOptionsSyntax(EmbeddedBytecodeInfo bytecodeInfo)
{
// This method needs to handle several different scenarions, which are as follows:
// 1) If [EmbeddedBytecode] is used, then the shader is precompiled and stored as a ReadOnlySpan<byte>. In this case,
// this bytecode would have been generated with some specific D2D1ShaderProfile and D2D1CompileOptions values. So,
// a branch is generated to try to retrieve this precompiled bytecode, which can be returned if and only if the
// requested shader profile and compile options are either null, or either matches the values that have been used
// to generate that bytecode. If this is the case, then no further work is done and that binary data is returned.
// 2) If either the requested shader profile or options do not match the values used to create the shader bytecode,
// then a call to the internal D2D1ShaderCompiler.LoadDynamicBytecode API is used, to create the shader on the fly.
// 3) If [EmbeddedBytecode] is not used, then regardless of the requested profile and options, a new shader is compiled.
// 4) If this is the case and either the shader profile or the options are null, then this method will manually set the
// value being null to the default one to use. That is, D2D1ShaderProfile.PixelShader50 will be used as the target,
// and the options will be set to D2D1CompileOptions.Default (and optionally, D2D1CompileOptions.EnableLinking too).
// Get a formatted representation of the compile options being used
ExpressionSyntax compileOptionsExpression =
ParseExpression(
@@ -88,134 +59,280 @@ partial class ID2D1ShaderGenerator
.Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}")
.Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right));
// Add parantheses if needed
if (compileOptionsExpression is BinaryExpressionSyntax)
// 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));
}
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for 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(
EmbeddedBytecodeInfo bytecodeInfo,
out Func<SyntaxNode, SourceText> fixup,
out TypeDeclarationSyntax[] additionalTypes)
{
ExpressionSyntax memoryExpression;
// If there is no bytecode, simply return a default expression.
// Otherwise, declare the memory manager and access it.
if (bytecodeInfo.Bytecode.Length == 0)
{
compileOptionsExpression = ParenthesizedExpression(compileOptionsExpression);
memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
fixup = static tree => tree.GetText(Encoding.UTF8);
additionalTypes = Array.Empty<TypeDeclarationSyntax>();
}
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(bytecodeInfo);
string bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan());
additionalTypes = new TypeDeclarationSyntax[] { memoryManagerDeclaration };
fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8);
}
// This code produces a block declaration as follows:
// This code produces a method declaration as follows:
//
// global::ComputeSharp.D2D1.D2D1ShaderProfile effectiveShaderProfile = shaderProfile ??= <DEFAULT_PROFILE>;
// global::ComputeSharp.D2D1.D2D1CompileOptions effectiveCompileOptions = compileOptions ??= <REQUESTED_OPTIONS>;
// 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.
/// </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)
{
// Create the MemoryManager<T> declaration:
//
// global::ComputeSharp.D2D1.__Internals.D2D1ShaderCompiler.LoadDynamicBytecode(ref loader, in this, effectiveShaderProfile, effectiveCompileOptions);
BlockSyntax dynamicLoadingBlock =
Block(
LocalDeclarationStatement(
VariableDeclaration(IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"))
.AddVariables(
VariableDeclarator(Identifier("effectiveShaderProfile"))
.WithInitializer(EqualsValueClause(
AssignmentExpression(
SyntaxKind.CoalesceAssignmentExpression,
IdentifierName("shaderProfile"),
IdentifierName($"global::ComputeSharp.D2D1.D2D1ShaderProfile.{D2D1ShaderProfile.PixelShader50}")))))),
LocalDeclarationStatement(
VariableDeclaration(IdentifierName("global::ComputeSharp.D2D1.D2D1CompileOptions"))
.AddVariables(
VariableDeclarator(Identifier("effectiveCompileOptions"))
.WithInitializer(EqualsValueClause(
AssignmentExpression(
SyntaxKind.CoalesceAssignmentExpression,
IdentifierName("compileOptions"),
compileOptionsExpression))))),
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("global::ComputeSharp.D2D1.__Internals.D2D1ShaderCompiler"),
IdentifierName("LoadDynamicBytecode")))
.AddArgumentListArguments(
Argument(IdentifierName("loader")).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)),
Argument(ThisExpression()).WithRefKindKeyword(Token(SyntaxKind.InKeyword)),
Argument(IdentifierName("effectiveShaderProfile")),
Argument(IdentifierName("effectiveCompileOptions")))));
// If there is no precompiled bytecode, just return the dynamic path
if (bytecodeInfo.Bytecode.IsDefaultOrEmpty)
{
bytecodeLiterals = null;
return dynamicLoadingBlock;
}
bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan());
// Prepare the expression for the default shader profile to use
ExpressionSyntax shaderProfileExpression =
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"),
IdentifierName(bytecodeInfo.ShaderProfile.ToString(CultureInfo.InvariantCulture)));
// This code produces a branch as follows:
//
// if (shaderProfile is null or <SHADER_PROFILE> && compileOptions is null or <COMPILE_OPTIONS>)
// /// <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>
// {
// global::System.ReadOnlySpan<byte> bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE };
//
// loader.LoadEmbeddedBytecode(bytecode);
//
// shaderProfile = <SHADER_PROFILE>;
// compileOptions = <COMPILE_OPTIONS>;
// }
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>"));
using ImmutableArrayBuilder<MemberDeclarationSyntax> memberDeclarations = ImmutableArrayBuilder<MemberDeclarationSyntax>.Rent();
// Declare the singleton property to get the memory manager:
//
// Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string
// is created by the generator. This greatly speeds up the code generation, as it avoids
// having to create/parse tens of thousands of literal expression nodes for every shader.
IfStatementSyntax embeddedBranch =
IfStatement(
BinaryExpression(
SyntaxKind.LogicalAndExpression,
IsPatternExpression(
IdentifierName("shaderProfile"),
BinaryPattern(
SyntaxKind.OrPattern,
ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression)),
ConstantPattern(shaderProfileExpression))),
IsPatternExpression(
IdentifierName("compileOptions"),
BinaryPattern(
SyntaxKind.OrPattern,
ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression)),
ConstantPattern(compileOptionsExpression)))),
Block(
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.ReadOnlySpan"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("bytecode"))
.WithInitializer(
EqualsValueClause(
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(
InitializerExpression(
SyntaxKind.ArrayInitializerExpression,
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))))),
ExpressionStatement(
InvocationExpression(
// /// <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>""")));
// 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>")));
// 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/>")));
// 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("loader"),
IdentifierName("LoadEmbeddedBytecode")))
.AddArgumentListArguments(Argument(IdentifierName("bytecode")))),
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("shaderProfile"),
shaderProfileExpression)),
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("compileOptions"),
compileOptionsExpression))));
IdentifierName("Data"),
IdentifierName("Length"))))))
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
// Return the combined block
return Block(embeddedBranch.WithElse(ElseClause(dynamicLoadingBlock)));
// 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 empty Unpin() method
memberDeclarations.Add(
MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Unpin"))
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword))
.WithBody(Block())
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
// 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/>")));
return typeDeclaration.AddMembers(memberDeclarations.ToArray());
}
}
}
+14 -4
ファイルの表示
@@ -362,11 +362,21 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
// Generate the LoadBytecode() methods
context.RegisterSourceOutput(embeddedBytecode, static (context, item) =>
{
MethodDeclarationSyntax loadBytecodeMethod = LoadBytecode.GetSyntax(item.BytecodeInfo, out Func<SyntaxNode, SourceText> fixup);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, loadBytecodeMethod, skipLocalsInit: false);
SourceText text = fixup(compilationUnit);
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}.{nameof(LoadBytecode)}.g.cs", text);
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)
-26
ファイルの表示
@@ -1,26 +0,0 @@
using System;
using System.ComponentModel;
namespace ComputeSharp.D2D1.__Internals;
/// <summary>
/// A base <see langword="interface"/> representing a bytecode loader for a D2D1 shader.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This interface is not intended to be used directly by user code")]
public interface ID2D1BytecodeLoader
{
/// <summary>
/// Loads a dynamic shader bytecode.
/// </summary>
/// <param name="handle">An opaque handle to the shader bytecode.</param>
/// <exception cref="InvalidOperationException">Thrown if the shader has already been initialized or a precompiled bytecode was requested when not available.</exception>
void LoadDynamicBytecode(IntPtr handle);
/// <summary>
/// Loads the embedded shader bytecode for the shader.
/// </summary>
/// <param name="bytecode">The shader bytecode.</param>
/// <exception cref="InvalidOperationException">Thrown if the shader has already been initialized.</exception>
void LoadEmbeddedBytecode(ReadOnlySpan<byte> bytecode);
}
+25 -10
ファイルの表示
@@ -1,6 +1,5 @@
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using ComputeSharp.D2D1.Interop;
namespace ComputeSharp.D2D1.__Internals;
@@ -128,16 +127,32 @@ public interface ID2D1Shader
string HlslSource { get; }
/// <summary>
/// Loads the bytecode for the current shader.
/// Gets the shader profile for the current shader.
/// </summary>
/// <typeparam name="TLoader">The type of bytecode loader being used.</typeparam>
/// <param name="loader">The <typeparamref name="TLoader"/> instance to use to load the bytecode.</param>
/// <param name="shaderProfile">The shader profile to use to get the shader bytecode (if <see langword="null"/>, the precompiled shader will be used).</param>
/// <param name="compileOptions">The compile options to use to get the shader bytecode (if <see langword="null"/>, the precompiled shader will be used).</param>
/// <exception cref="InvalidOperationException">Thrown if a precompiled bytecode was requested (<paramref name="shaderProfile"/> is <see langword="null"/>), but it wasn't availablle.</exception>
/// <remarks>When this method returns, <paramref name="shaderProfile"/> and <paramref name="compileOptions"/> will be set to the effective laues used to create the shader bytecode that was loaded.</remarks>
/// <remarks>
/// This shader profile is either explicitly set by users, or the default one for D2D1 shaders.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be used directly by user code")]
void LoadBytecode<TLoader>(ref TLoader loader, [NotNull] ref D2D1ShaderProfile? shaderProfile, [NotNull] ref D2D1CompileOptions? compileOptions)
where TLoader : struct, ID2D1BytecodeLoader;
D2D1ShaderProfile ShaderProfile { get; }
/// <summary>
/// Gets the compile options for the current shader.
/// </summary>
/// <remarks>
/// This compile options are either explicitly set by users, or the default one for D2D1 shaders.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be used directly by user code")]
D2D1CompileOptions CompileOptions { get; }
/// <summary>
/// Gets the HLSL bytecode for the current shader, if available.
/// </summary>
/// <remarks>
/// If no precompiled HLSL bytecode is available, the returned <see cref="ReadOnlyMemory{T}"/> instance will be empty.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be used directly by user code")]
ReadOnlyMemory<byte> HlslBytecode { get; }
}
+57 -20
ファイルの表示
@@ -1,7 +1,7 @@
using System;
using System.Runtime.CompilerServices;
using ComputeSharp.D2D1.Shaders.Interop.Buffers;
using ComputeSharp.D2D1.Shaders.Loaders;
using ComputeSharp.D2D1.Shaders.Translation;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
@@ -29,7 +29,18 @@ public static class D2D1PixelShader
public static ReadOnlyMemory<byte> LoadBytecode<T>()
where T : unmanaged, ID2D1PixelShader
{
return LoadOrCompileBytecode<T>(null, null, out _, out _);
Unsafe.SkipInit(out T shader);
// This method is the one used by the built-in ID2D1Effect, so it has special optimization
// to help both performance and especially trimming. That is, we first check whether the
// HLSL code is already available, which should get completely inlined when using the
// generated code. This allows the entire fallback path below to be trimmed out.
if (shader.HlslBytecode is ReadOnlyMemory<byte> { Length: > 0 } hlslBytecode)
{
return hlslBytecode;
}
return CompileBytecode<T>(null, null, out _, out _);
}
/// <summary>
@@ -191,6 +202,40 @@ public static class D2D1PixelShader
return LoadOrCompileBytecode<T>(shaderProfile, compileOptions | D2D1CompileOptions.PackMatrixRowMajor, out _, out _);
}
/// <summary>
/// Compiles the bytecode from an input D2D1 pixel shader.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader to load the bytecode for.</typeparam>
/// <param name="requestedShaderProfile">The requested shader profile to use to get the shader bytecode.</param>
/// <param name="requestedCompileOptions">The requested compile options to use to get the shader bytecode.</param>
/// <param name="effectiveShaderProfile">The effective shader profile that was used to get the shader bytecode.</param>
/// <param name="effectiveCompileOptions">The effective compile options that were used to get the shader bytecode.</param>
/// <returns>A <see cref="ReadOnlyMemory{T}"/> instance with the resulting shader bytecode.</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe ReadOnlyMemory<byte> CompileBytecode<T>(
D2D1ShaderProfile? requestedShaderProfile,
D2D1CompileOptions? requestedCompileOptions,
out D2D1ShaderProfile effectiveShaderProfile,
out D2D1CompileOptions effectiveCompileOptions)
where T : unmanaged, ID2D1PixelShader
{
Unsafe.SkipInit(out T shader);
string hlslSource = shader.HlslSource;
// Set the effective profile and option to the requested ones or the default values
effectiveShaderProfile = requestedShaderProfile ?? shader.ShaderProfile;
effectiveCompileOptions = requestedCompileOptions ?? shader.CompileOptions;
// Compile the shader with the current settings
using ComPtr<ID3DBlob> dynamicBytecode = D3DCompiler.Compile(hlslSource.AsSpan(), effectiveShaderProfile, effectiveCompileOptions);
byte* bytecodePtr = (byte*)dynamicBytecode.Get()->GetBufferPointer();
int bytecodeSize = (int)dynamicBytecode.Get()->GetBufferSize();
return new ReadOnlySpan<byte>(bytecodePtr, bytecodeSize).ToArray();
}
/// <summary>
/// Loads or compiles the bytecode from an input D2D1 pixel shader.
/// </summary>
@@ -200,7 +245,6 @@ public static class D2D1PixelShader
/// <param name="effectiveShaderProfile">The effective shader profile that was used to get the shader bytecode.</param>
/// <param name="effectiveCompileOptions">The effective compile options that were used to get the shader bytecode.</param>
/// <returns>A <see cref="ReadOnlyMemory{T}"/> instance with the resulting shader bytecode.</returns>
/// <exception cref="InvalidOperationException">Thrown if the input shader has not been precompiled.</exception>
private static unsafe ReadOnlyMemory<byte> LoadOrCompileBytecode<T>(
D2D1ShaderProfile? requestedShaderProfile,
D2D1CompileOptions? requestedCompileOptions,
@@ -208,28 +252,21 @@ public static class D2D1PixelShader
out D2D1CompileOptions effectiveCompileOptions)
where T : unmanaged, ID2D1PixelShader
{
D2D1ShaderBytecodeLoader bytecodeLoader = default;
Unsafe.SkipInit(out T shader);
shader.LoadBytecode(ref bytecodeLoader, ref requestedShaderProfile, ref requestedCompileOptions);
effectiveShaderProfile = requestedShaderProfile.GetValueOrDefault();
effectiveCompileOptions = requestedCompileOptions.GetValueOrDefault();
using ComPtr<ID3DBlob> dynamicBytecode = bytecodeLoader.GetResultingShaderBytecode(out ReadOnlySpan<byte> precompiledBytecode);
// If a precompiled shader is available, return it
if (!precompiledBytecode.IsEmpty)
// Check whether there is precompiled bytecode we can use
if (shader.HlslBytecode is ReadOnlyMemory<byte> { Length: > 0 } hlslBytecode &&
(requestedShaderProfile is null || shader.ShaderProfile == requestedShaderProfile.GetValueOrDefault()) &&
(requestedCompileOptions is null || shader.CompileOptions == requestedCompileOptions.GetValueOrDefault()))
{
return new PinnedBufferMemoryManager(precompiledBytecode).Memory;
effectiveShaderProfile = shader.ShaderProfile;
effectiveCompileOptions = shader.CompileOptions;
return hlslBytecode;
}
// Otherwise, return the dynamic shader instead
byte* bytecodePtr = (byte*)dynamicBytecode.Get()->GetBufferPointer();
int bytecodeSize = (int)dynamicBytecode.Get()->GetBufferSize();
return new ReadOnlySpan<byte>(bytecodePtr, bytecodeSize).ToArray();
// Fallback path just compiling the HLSL code on the fly
return CompileBytecode<T>(requestedShaderProfile, requestedCompileOptions, out effectiveShaderProfile, out effectiveCompileOptions);
}
/// <summary>
+23 -26
ファイルの表示
@@ -1,8 +1,7 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Shaders.Loaders;
using ComputeSharp.D2D1.Shaders.Translation;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
@@ -35,37 +34,35 @@ public static class D2D1ReflectionServices
string hlslSource = shader.HlslSource;
D2D1ShaderBytecodeLoader bytecodeLoader = default;
using ComPtr<ID3D11ShaderReflection> d3D11ShaderReflection = default;
D2D1ShaderProfile? shaderProfile = null;
D2D1CompileOptions? compileOptions = null;
shader.LoadBytecode(ref bytecodeLoader, ref shaderProfile, ref compileOptions);
using ComPtr<ID3DBlob> dynamicBytecode = bytecodeLoader.GetResultingShaderBytecode(out ReadOnlySpan<byte> precompiledBytecode);
byte* bytecodePtr;
int bytecodeSize;
if (!precompiledBytecode.IsEmpty)
// If the shader already has embedded bytecode, use that directly
if (shader.HlslBytecode is ReadOnlyMemory<byte> { Length: > 0 } hlslBytecode)
{
bytecodePtr = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(precompiledBytecode));
bytecodeSize = precompiledBytecode.Length;
fixed (byte* hlslBytecodePtr = hlslBytecode.Span)
{
DirectX.D3DReflect(
pSrcData: hlslBytecodePtr,
SrcDataSize: (nuint)hlslBytecode.Length,
pInterface: Windows.__uuidof<ID3D11ShaderReflection>(),
ppReflector: d3D11ShaderReflection.GetVoidAddressOf()).Assert();
}
}
else
{
bytecodePtr = (byte*)dynamicBytecode.Get()->GetBufferPointer();
bytecodeSize = (int)dynamicBytecode.Get()->GetBufferSize();
// Otherwise, compile it with default shader profile and compile options and use that.
// Note that we're intentionally retrieving an ID3DBlob instance here to avoid having
// to allocate a ReadOnlyMemory<byte> object to throw away immediately, as we don't
// actually need to keep the bytecode for later.
using ComPtr<ID3DBlob> dynamicBytecode = D3DCompiler.Compile(hlslSource.AsSpan(), shader.ShaderProfile, shader.CompileOptions);
DirectX.D3DReflect(
pSrcData: (byte*)dynamicBytecode.Get()->GetBufferPointer(),
SrcDataSize: dynamicBytecode.Get()->GetBufferSize(),
pInterface: Windows.__uuidof<ID3D11ShaderReflection>(),
ppReflector: d3D11ShaderReflection.GetVoidAddressOf()).Assert();
}
using ComPtr<ID3D11ShaderReflection> d3D11ShaderReflection = default;
DirectX.D3DReflect(
pSrcData: bytecodePtr,
SrcDataSize: (nuint)bytecodeSize,
pInterface: Windows.__uuidof<ID3D11ShaderReflection>(),
ppReflector: d3D11ShaderReflection.GetVoidAddressOf()).Assert();
D3D11_SHADER_DESC d3D11ShaderDescription;
d3D11ShaderReflection.Get()->GetDesc(&d3D11ShaderDescription).Assert();
+2 -2
ファイルの表示
@@ -74,7 +74,7 @@ public static class D2D1ShaderCompiler
options &= ~D2D1CompileOptions.EnableLinking;
// Compile the standalone D2D1 full shader
using ComPtr<ID3DBlob> d3DBlobFullShader = D3DCompiler.CompileShader(
using ComPtr<ID3DBlob> d3DBlobFullShader = D3DCompiler.Compile(
source: hlslSourceAscii,
macro: D3DCompiler.ASCII.D2D_FULL_SHADER,
d2DEntry: entryPointAscii,
@@ -91,7 +91,7 @@ public static class D2D1ShaderCompiler
}
// Compile the export function
using ComPtr<ID3DBlob> d3DBlobFunction = D3DCompiler.CompileShader(
using ComPtr<ID3DBlob> d3DBlobFunction = D3DCompiler.Compile(
source: hlslSourceAscii,
macro: D3DCompiler.ASCII.D2D_FUNCTION,
d2DEntry: entryPointAscii,
-68
ファイルの表示
@@ -1,68 +0,0 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.Extensions;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#pragma warning disable CS0618
namespace ComputeSharp.D2D1.Shaders.Loaders;
/// <summary>
/// A bytecode loader for D2D1 shaders.
/// </summary>
internal unsafe struct D2D1ShaderBytecodeLoader : ID2D1BytecodeLoader
{
/// <summary>
/// A pointer to the precompiled shader, if available.
/// </summary>
private byte* embeddedBytecodePtr;
/// <summary>
/// The length of the precompiled shader buffer, if available.
/// </summary>
private int embeddedBytecodeSize;
/// <summary>
/// The dynamically compiled shader bytecode blob, if available.
/// </summary>
private ComPtr<ID3DBlob> d3DBlob;
/// <summary>
/// Gets the resulting shader bytecode that was available.
/// </summary>
/// <param name="precompiledBytecode">The precompiled bytecode, if available.</param>
/// <returns>An <see cref="ID3DBlob"/> with the shader bytecode, if dynamically compiled.</returns>
/// <remarks>Either <paramref name="precompiledBytecode"/> is empty, or the returned pointer is <see langword="null"/>.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ComPtr<ID3DBlob> GetResultingShaderBytecode(out ReadOnlySpan<byte> precompiledBytecode)
{
precompiledBytecode = new ReadOnlySpan<byte>(this.embeddedBytecodePtr, this.embeddedBytecodeSize);
return this.d3DBlob.Move();
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void ID2D1BytecodeLoader.LoadDynamicBytecode(IntPtr handle)
{
default(InvalidOperationException).ThrowIf(this.embeddedBytecodePtr is not null);
default(InvalidOperationException).ThrowIf(this.d3DBlob.Get() is not null);
default(NotSupportedException).ThrowIf(handle == IntPtr.Zero);
this.d3DBlob = new ComPtr<ID3DBlob>((ID3DBlob*)handle);
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void ID2D1BytecodeLoader.LoadEmbeddedBytecode(ReadOnlySpan<byte> bytecode)
{
default(InvalidOperationException).ThrowIf(this.embeddedBytecodePtr is not null);
default(InvalidOperationException).ThrowIf(this.d3DBlob.Get() is not null);
this.embeddedBytecodePtr = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(bytecode));
this.embeddedBytecodeSize = bytecode.Length;
}
}
+4 -6
ファイルの表示
@@ -9,8 +9,6 @@ using ComputeSharp.D2D1.Extensions;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#pragma warning disable IDE1006
namespace ComputeSharp.D2D1.Shaders.Translation;
/// <summary>
@@ -39,7 +37,7 @@ internal static unsafe partial class D3DCompiler
try
{
// Compile the standalone D2D1 full shader
using ComPtr<ID3DBlob> d3DBlobFullShader = CompileShader(
using ComPtr<ID3DBlob> d3DBlobFullShader = Compile(
source: buffer.AsSpan(0, writtenBytes),
macro: ASCII.D2D_FULL_SHADER,
d2DEntry: ASCII.Execute,
@@ -53,7 +51,7 @@ internal static unsafe partial class D3DCompiler
}
// Compile the export function
using ComPtr<ID3DBlob> d3DBlobFunction = CompileShader(
using ComPtr<ID3DBlob> d3DBlobFunction = Compile(
source: buffer.AsSpan(0, writtenBytes),
macro: ASCII.D2D_FUNCTION,
d2DEntry: ASCII.Execute,
@@ -73,7 +71,7 @@ internal static unsafe partial class D3DCompiler
}
/// <summary>
/// Compiles a D2D1 pixel shader with the specified parameters.
/// Compiles an HLSL shader with the specified parameters.
/// </summary>
/// <param name="source">The HLSL source code to compile (in ASCII).</param>
/// <param name="macro">The target macro to define for the shader (either <c>D2D_FULL_SHADER</c> or <c>D2D_FUNCTION</c>).</param>
@@ -83,7 +81,7 @@ internal static unsafe partial class D3DCompiler
/// <param name="flags">The compilationm flag to use.</param>
/// <returns>The bytecode for the compiled shader.</returns>
/// <exception cref="FxcCompilationException">Thrown if the compilation fails.</exception>
public static ComPtr<ID3DBlob> CompileShader(
public static ComPtr<ID3DBlob> Compile(
ReadOnlySpan<byte> source,
ReadOnlySpan<byte> macro,
ReadOnlySpan<byte> d2DEntry,
-38
ファイルの表示
@@ -1,38 +0,0 @@
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
namespace ComputeSharp.D2D1.__Internals;
/// <summary>
/// A <see langword="class"/> that uses the DXC APIs to compile compute shaders.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This type is not intended to be used directly by user code")]
public static class D2D1ShaderCompiler
{
/// <summary>
/// Compiles a new HLSL shader from the input source code.
/// </summary>
/// <typeparam name="TLoader">The type of bytecode loader being used.</typeparam>
/// <typeparam name="T">The type of D2D1 shader being dispatched.</typeparam>
/// <param name="loader">The <typeparamref name="TLoader"/> instance to use to load the bytecode.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the D2D1 shader to run.</param>
/// <param name="shaderProfile">The shader profile to use to compile the shader.</param>
/// <param name="options">The compiler options to use to compile the shader.</param>
public static unsafe void LoadDynamicBytecode<TLoader, T>(ref TLoader loader, in T shader, D2D1ShaderProfile shaderProfile, D2D1CompileOptions options)
where TLoader : struct, ID2D1BytecodeLoader
where T : struct, ID2D1Shader
{
string hlslSource = Unsafe.AsRef(in shader).HlslSource;
using ComPtr<ID3DBlob> d3DBlobBytecode = Shaders.Translation.D3DCompiler.Compile(
hlslSource.AsSpan(),
shaderProfile,
options);
loader.LoadDynamicBytecode((IntPtr)d3DBlobBytecode.Get());
}
}
+53 -13
ファイルの表示
@@ -17,15 +17,32 @@ public partial class D2D1PixelShaderTests
// Verify the shader was precompiled
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
_ = D2D1PixelShader.LoadBytecode<ShaderWithNoCompileAttributes>(
// Compile with the same assembly level options
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithNoCompileAttributes>(
shaderProfile: D2D1ShaderProfile.PixelShader41,
compileOptions: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision);
// Verify the expected options were used
// Verify the same bytecode is returned
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Incorrect profile
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithNoCompileAttributes>(D2D1ShaderProfile.PixelShader50);
Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? _));
Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment<byte> segment));
Assert.AreEqual(0, segment.Offset);
Assert.IsTrue(segment.Count > 0);
// Incorrect options
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithNoCompileAttributes>(D2D1CompileOptions.Default);
Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? _));
Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out segment));
Assert.AreEqual(0, segment.Offset);
Assert.IsTrue(segment.Count > 0);
}
[D2DInputCount(3)]
@@ -51,14 +68,25 @@ public partial class D2D1PixelShaderTests
ReadOnlyMemory<byte> bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenProfile>();
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
_ = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenProfile>(
// Try to recompile with the correct combined options
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenProfile>(
shaderProfile: D2D1ShaderProfile.PixelShader50,
compileOptions: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Incorrect profile (overridden profile)
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenProfile>(
shaderProfile: D2D1ShaderProfile.PixelShader41,
compileOptions: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision);
Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? _));
Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment<byte> segment));
Assert.AreEqual(0, segment.Offset);
Assert.IsTrue(segment.Count > 0);
}
[D2DInputCount(3)]
@@ -85,14 +113,25 @@ public partial class D2D1PixelShaderTests
ReadOnlyMemory<byte> bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenOptions>();
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
_ = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenOptions>(
// Try to recompile with the correct combined options
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenOptions>(
shaderProfile: D2D1ShaderProfile.PixelShader41,
compileOptions: D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Incorrect profile (overridden compile options)
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenOptions>(
shaderProfile: D2D1ShaderProfile.PixelShader41,
compileOptions: D2D1CompileOptions.Default);
Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? _));
Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment<byte> segment));
Assert.AreEqual(0, segment.Offset);
Assert.IsTrue(segment.Count > 0);
}
[D2DInputCount(3)]
@@ -119,14 +158,15 @@ public partial class D2D1PixelShaderTests
ReadOnlyMemory<byte> bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenProfileAndOptions>();
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
_ = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenProfileAndOptions>(
// Try to get the new bytecode
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenProfileAndOptions>(
shaderProfile: D2D1ShaderProfile.PixelShader50,
compileOptions: D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
}
[D2DInputCount(3)]
+43 -7
ファイルの表示
@@ -273,6 +273,26 @@ public partial class D2D1PixelShaderTests
}
}
[TestMethod]
public unsafe void GetBytecode_FromDynamicBytecode()
{
ReadOnlyMemory<byte> bytecode = D2D1PixelShader.LoadBytecode<ShaderWithoutEmbeddedBytecode>();
Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? _));
Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment<byte> segment));
Assert.AreEqual(0, segment.Offset);
Assert.IsTrue(segment.Count > 0);
}
[D2DInputCount(0)]
private readonly partial struct ShaderWithoutEmbeddedBytecode : ID2D1PixelShader
{
public float4 Execute()
{
return 0;
}
}
[TestMethod]
public unsafe void GetBytecode_FromEmbeddedBytecode()
{
@@ -280,25 +300,41 @@ public partial class D2D1PixelShaderTests
ReadOnlyMemory<byte> bytecode = D2D1PixelShader.LoadBytecode<ShaderWithEmbeddedBytecode>();
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Matching shader profile
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithEmbeddedBytecode>(D2D1ShaderProfile.PixelShader40Level91);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Matching compile options
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithEmbeddedBytecode>(D2D1CompileOptions.Default | D2D1CompileOptions.EnableLinking);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Matching shader profile and compile options
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithEmbeddedBytecode>(D2D1ShaderProfile.PixelShader40Level91, D2D1CompileOptions.Default | D2D1CompileOptions.EnableLinking);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Incorrect profile
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithEmbeddedBytecode>(D2D1ShaderProfile.PixelShader50);
Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? _));
Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment<byte> segment));
Assert.AreEqual(0, segment.Offset);
Assert.IsTrue(segment.Count > 0);
// Incorrect options
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithEmbeddedBytecode>(D2D1CompileOptions.Default | D2D1CompileOptions.EnableStrictness);
Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? _));
Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out segment));
Assert.AreEqual(0, segment.Offset);
Assert.IsTrue(segment.Count > 0);
}
[TestMethod]
@@ -340,7 +376,7 @@ public partial class D2D1PixelShaderTests
ReadOnlyMemory<byte> bytecode = D2D1PixelShader.LoadBytecode<ShaderWithEmbeddedBytecodeAndCompileOptions>();
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Bytecode with all output parameters
ReadOnlyMemory<byte> bytecode2 = D2D1PixelShader.LoadBytecode<ShaderWithEmbeddedBytecodeAndCompileOptions>(out D2D1ShaderProfile shaderProfile, out D2D1CompileOptions compileOptions);
@@ -354,13 +390,13 @@ public partial class D2D1PixelShaderTests
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithEmbeddedBytecodeAndCompileOptions>(D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Matching shader profile and compile options
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithEmbeddedBytecodeAndCompileOptions>(D2D1ShaderProfile.PixelShader40Level91, D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
}
[D2DInputCount(3)]