Merge pull request #128 from Sergio0694/optimization/reflection-free-rendering

Reflection free rendering, shader metaprogramming
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2021-07-14 20:48:04 +02:00
コミット 9bf8564374
62ファイル変更
+3094 -3098

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

+4 -1
ファイルの表示
@@ -1,12 +1,15 @@
using System;
using ComputeSharp.__Internals;
using ComputeSharp.Interop;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
#pragma warning disable CS0618
namespace ComputeSharp.SwapChain.Backend
{
internal sealed class SwapChainApplication<T> : Win32Application
where T : struct, IPixelShader<Float4>
where T : struct, IPixelShader<Float4>, IShader<T>
{
/// <summary>
/// The <see cref="Func{T1, TResult}"/> instance used to create shaders to run.
+43 -45
ファイルの表示
@@ -7,50 +7,48 @@
Rule ID | Category | Severity | Notes
--------|----------|----------|-------
CMPS0001 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0002 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0003 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0004 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0005 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0006 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0007 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0008 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0009 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0010 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0011 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0012 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0013 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0014 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0015 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0016 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0017 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0018 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0019 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0020 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0021 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0022 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0023 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0024 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0025 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0026 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0027 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0028 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0029 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0030 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0031 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0032 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0033 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0034 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0035 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0036 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0001 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0002 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0003 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0004 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0005 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0006 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0007 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0008 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0009 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0010 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0011 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0012 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0013 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0014 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0015 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0016 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0017 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0018 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0019 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0020 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0021 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0022 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0023 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0024 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0025 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0026 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0027 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0028 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0029 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0030 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0031 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0032 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0033 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0034 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0035 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0036 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0037 | ComputeSharp.SourceGenerators.AutoConstructorGenerator | Warning | AutoConstructorGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0038 | ComputeSharp.SourceGenerators.IComputeShaderDataLoaderGenerator | Warning | IComputeShaderDataLoaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0039 | ComputeSharp.SourceGenerators.IComputeShaderHashCodeGenerator | Warning | IComputeShaderHashCodeGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0040 | ComputeSharp.SourceGenerators.IComputeShaderSourceGenerator | Warning | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0040 | ComputeSharp.SourceGenerators.IShaderGenerator | Warning | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.IComputeShader | Error | IComputeShaderDataLoaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0047 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0047 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+1 -1
ファイルの表示
@@ -101,7 +101,7 @@ namespace ComputeSharp.SourceGenerators
var source =
CompilationUnit().AddMembers(
NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax))
.NormalizeWhitespace()
.NormalizeWhitespace(eol: "\n")
.ToFullString();
// Add the partial type
-4
ファイルの表示
@@ -14,8 +14,6 @@
<Compile Include="..\ComputeSharp\Core\Attributes\AutoConstructorAttribute.cs" Link="Core\Attributes\AutoConstructorAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\GroupSharedAttribute.cs" Link="Core\Attributes\GroupSharedAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\ShaderMethodAttribute.cs" Link="Core\Attributes\ShaderMethodAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\__Internals\ComputeRoot32BitConstantsAttribute.cs" Link="Core\Attributes\__Internals\ComputeRoot32BitConstantsAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\__Internals\IComputeShaderSourceAttribute.cs" Link="Core\Attributes\__Internals\IComputeShaderSourceAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" Link="Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Dispatch\DispatchSize.cs" Link="Core\Dispatch\DispatchSize.cs" />
<Compile Include="..\ComputeSharp\Core\Dispatch\GridIds.cs" Link="Core\Dispatch\GridIds.cs" />
@@ -24,8 +22,6 @@
<Compile Include="..\ComputeSharp\Core\Dispatch\ThreadIds.cs" Link="Core\Dispatch\ThreadIds.cs" />
<Compile Include="..\ComputeSharp\Core\Dispatch\ThreadIds.Normalized.cs" Link="Core\Dispatch\ThreadIds.Normalized.cs" />
<Compile Include="..\ComputeSharp\Core\Exceptions\InvalidExecutionContextException.cs" Link="Core\Exceptions\InvalidExecutionContextException.cs" />
<Compile Include="..\ComputeSharp\Core\Exceptions\MissingMethodSourceException.cs" Link="Core\Exceptions\MissingMethodSourceException.cs" />
<Compile Include="..\ComputeSharp\Core\Exceptions\MissingShaderMetadataException.cs" Link="Core\Exceptions\MissingShaderMetadataException.cs" />
<Compile Include="..\ComputeSharp\Core\Extensions\MethodInfoExtensions.cs" Link="Core\Extensions\MethodInfoExtensions.cs" />
<Compile Include="..\ComputeSharp\Core\Helpers\AlignmentHelper.cs" Link="Core\Helpers\AlignmentHelper.cs" />
<Compile Include="..\ComputeSharp\Core\Interfaces\IComputeShader.cs" Link="Core\Interfaces\IComputeShader.cs" />
+8 -40
ファイルの表示
@@ -513,51 +513,19 @@ namespace ComputeSharp.SourceGenerators.Diagnostics
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="IComputeShaderDataLoaderGenerator"/>.
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="IShaderGenerator"/>.
/// <para>
/// Format: <c>"The generator IComputeShaderDataLoaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash"</c>.
/// Format: <c>"The generator IShaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor IComputeShaderDataLoaderGeneratorError = new(
id: "CMPS0038",
title: $"Internal error for {nameof(IComputeShaderDataLoaderGenerator)}",
messageFormat: $"The generator {nameof(IComputeShaderDataLoaderGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash",
category: typeof(IComputeShaderDataLoaderGenerator).FullName,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: $"The {nameof(IComputeShaderDataLoaderGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="IComputeShaderHashCodeGenerator"/>.
/// <para>
/// Format: <c>"The generator IComputeShaderHashCodeGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor IComputeShaderHashCodeGeneratorError = new(
id: "CMPS0039",
title: $"Internal error for {nameof(IComputeShaderHashCodeGenerator)}",
messageFormat: $"The generator {nameof(IComputeShaderHashCodeGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash",
category: typeof(IComputeShaderHashCodeGenerator).FullName,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: $"The {nameof(IComputeShaderHashCodeGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="IComputeShaderSourceGenerator"/>.
/// <para>
/// Format: <c>"The generator IComputeShaderSourceGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor IComputeShaderSourceGeneratorError = new(
public static readonly DiagnosticDescriptor IShaderGeneratorError = new(
id: "CMPS0040",
title: $"Internal error for {nameof(IComputeShaderSourceGenerator)}",
messageFormat: $"The generator {nameof(IComputeShaderSourceGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash",
category: typeof(IComputeShaderSourceGenerator).FullName,
title: $"Internal error for {nameof(IShaderGenerator)}",
messageFormat: $"The generator {nameof(IShaderGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash",
category: typeof(IShaderGenerator).FullName,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: $"The {nameof(IComputeShaderSourceGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
description: $"The {nameof(IShaderGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
@@ -657,7 +625,7 @@ namespace ComputeSharp.SourceGenerators.Diagnostics
id: "CMPS0047",
title: "Multiple shader implementations for type declaration",
messageFormat: $"The shader of type {{0}} cannot implement more than one shader interface",
category: typeof(IComputeShaderSourceGenerator).FullName,
category: typeof(IShaderGenerator).FullName,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A shader type cannot implement more than one shader interface.",
+4 -86
ファイルの表示
@@ -12,68 +12,19 @@ namespace ComputeSharp.SourceGenerators.Helpers
/// </summary>
internal static class SyntaxFactoryHelper
{
/// <summary>
/// Creates a <see cref="string"/>[] array expression from the given sequence of <see cref="string"/> instances.
/// <para>
/// That it, it applies the following transformation:
/// <code>
/// { "S1", "S2" } => new string[] { "S1", "S2" }
/// </code>
/// </para>
/// </summary>
/// <param name="values">The input sequence of <see cref="string"/> instances.</param>
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
[Pure]
public static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable<string> values)
{
return
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray()));
}
/// <summary>
/// Creates an <see cref="object"/>[] array expression with the nested groups in the input sequence.
/// <para>
/// That it, it applies the following transformation:
/// <code>
/// { ("K1", "V1"), ("K2", "V2") } => new object[] { new[] { "K1", "V1" }, new[] { "K2", "V2" } }
/// { ("K1", "V1"), ("K2", "V2") } => new object[] { new string[] { "K1", "V1" }, new string[] { "K2", "V2" } }
/// </code>
/// </para>
/// </summary>
/// <param name="values">The input sequence of <see cref="string"/> groups.</param>
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
[Pure]
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<IEnumerable<string?>> groups)
{
return
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(groups.Select(static group =>
ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression).AddExpressions(
group.Select(static item => item is null
? LiteralExpression(SyntaxKind.NullLiteralExpression)
: LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))
.ToArray()))).ToArray()));
}
/// <summary>
/// Creates an <see cref="object"/>[] array expression with the nested groups in the input sequence.
/// <para>
/// That it, it applies the following transformation:
/// <code>
/// { ("K1", "V1", I1), ("K2", "V2", null) } => new object[] { new object[] { "K1", "V1", I1 }, new object[] { "K2", "V2", null } }
/// </code>
/// </para>
/// </summary>
/// <param name="values">The input sequence of <see cref="string"/> groups.</param>
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
[Pure]
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B, int? C)> groups)
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B)> groups)
{
return
ArrayCreationExpression(
@@ -82,45 +33,12 @@ namespace ComputeSharp.SourceGenerators.Helpers
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(groups.Select(static group =>
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword)))
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)),
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B)),
group.C is int i
? LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(i))
: LiteralExpression(SyntaxKind.NullLiteralExpression)))).ToArray()));
}
/// <summary>
/// Creates a <see cref="string"/>[]? array expression from the given tuple instance.
/// <para>
/// That it, it applies the following transformation:
/// <code>
/// null => null
/// ("S1", "S2") => new string[] { "S1", "S2" }
/// </code>
/// </para>
/// </summary>
/// <param name="values">The input tuple instance.</param>
/// <returns>An <see cref="ExpressionSyntax"/> instance with the described contents.</returns>
[Pure]
public static ExpressionSyntax ArrayExpression((string First, string Second)? values)
{
if (values is null)
{
return LiteralExpression(SyntaxKind.NullLiteralExpression);
}
return
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.First)),
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.Second))));
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B))))).ToArray()));
}
}
}
@@ -1,49 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators
{
/// <inheritdoc/>
public sealed partial class IComputeShaderDataLoaderGenerator
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
{
/// <summary>
/// The list of info gathered during exploration.
/// </summary>
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
if (context.Node is StructDeclarationSyntax structDeclaration &&
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
structSymbol.Interfaces.Any(static interfaceSymbol =>
interfaceSymbol.Name == nameof(IComputeShader) ||
interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) }))
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
}
}
/// <summary>
/// A model for a group of item representing a discovered type to process.
/// </summary>
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol);
}
}
}
-307
ファイルの表示
@@ -1,307 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.Core.Helpers;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators
{
/// <summary>
/// A source generator creating data loaders for <see cref="IComputeShader"/> types.
/// </summary>
[Generator]
public sealed partial class IComputeShaderDataLoaderGenerator : ISourceGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
// Type attributes
AttributeListSyntax[] attributes = new[]
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This type is not intended to be used directly by user code"))))))
};
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
{
try
{
OnExecute(context, item.StructDeclaration, item.StructSymbol, ref attributes);
}
catch
{
context.ReportDiagnostic(IComputeShaderDataLoaderGeneratorError, item.StructDeclaration, item.StructSymbol);
}
}
}
/// <summary>
/// Processes a given target type.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="attributes">The list of <see cref="AttributeListSyntax"/> instances to append to the first copy of the partial class being generated.</param>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, ref AttributeListSyntax[] attributes)
{
TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString());
BlockSyntax block = Block(GetDispatchDataLoadingStatements(context, structDeclarationSymbol, out int root32BitConstantsCount));
// Create a static method to create the combined hashcode for a given shader type.
// This code takes a block syntax and produces a compilation unit as follows:
//
// using System;
// using System.ComponentModel;
//
// namespace ComputeSharp.__Internals
// {
// internal static partial class DispatchDataLoader
// {
// [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
// [System.Obsolete("This method is not intended to be called directly by user code")]
// [return: ComputeRoot32BitConstants(42)]
// public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1)
// {
// ...
// }
// }
// }
var source =
CompilationUnit().AddUsings(
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.ComponentModel")),
UsingDirective(IdentifierName("System.Runtime.CompilerServices"))).AddMembers(
NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers(
ClassDeclaration("DispatchDataLoader").AddModifiers(
Token(SyntaxKind.InternalKeyword),
Token(SyntaxKind.StaticKeyword),
Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers(
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("LoadDispatchData")).AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be called directly by user code")))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(nameof(ComputeRoot32BitConstantsAttribute).Replace("Attribute", "")))
.AddArgumentListArguments(AttributeArgument(LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(root32BitConstantsCount))))))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.ReturnKeyword)))).AddModifiers(
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.StaticKeyword)).AddParameterListParameters(
Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.GraphicsDevice")),
Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType),
Parameter(Identifier("r0")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ULongKeyword))),
Parameter(Identifier("r1")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.WithBody(block)))
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
.NormalizeWhitespace()
.ToFullString();
// Clear the attribute list to avoid duplicates
attributes = Array.Empty<AttributeListSyntax>();
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="count">The total number of 32 bit root constants to load.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
[Pure]
private static IEnumerable<StatementSyntax> GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out int count)
{
List<StatementSyntax> statements = new();
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
var isComputeShader = pixelShaderSymbol is null;
int
resourceOffset = 0,
rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
AppendFields(structDeclarationSymbol, Array.Empty<string>(), ref resourceOffset, ref rawDataOffset, statements);
// After all the captured fields have been processed, ansure the reported byte size for
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
// enable loading all the dispatch data after reinterpreting it to a sequence of values
// of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int));
statements.Add(ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset))));
count = rawDataOffset / sizeof(int);
// A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
// Loaded values in the root signature have the following costs:
// - Root constants cost 1 DWORD each, since they are 32-bit values.
// - Descriptor tables cost 1 DWORD each.
// - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
// So here we check whether the current signature respects that constraint,
// and emit a build error otherwise. For more info on this, see the docs here:
// https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
int rootSignatureDwordSize = count + resourceOffset;
if (rootSignatureDwordSize > 64)
{
context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
}
return statements;
}
/// <summary>
/// Explores a given type hierarchy and generates statements to load fields.
/// </summary>
/// <param name="currentTypeSymbol">The current type being explored.</param>
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
/// <param name="resourceOffset">The current offset in the root table of loaded resources.</param>
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
/// <param name="statements">The target list of statements being generated.</param>
private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection<string> fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection<StatementSyntax> statements)
{
bool isFirstField = true;
foreach (
IFieldSymbol fieldSymbol in
from fieldSymbol in currentTypeSymbol.GetMembers().OfType<IFieldSymbol>()
where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
!fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer
select fieldSymbol)
{
string typeName = fieldSymbol.Type.GetFullMetadataName();
// The first item in each nested struct needs to be aligned to 16 bytes
if (isFirstField && fieldPath.Count > 0)
{
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
isFirstField = false;
}
if (HlslKnownTypes.IsTypedResourceType(typeName))
{
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"),
ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)"))));
}
else if (HlslKnownTypes.IsKnownHlslType(typeName))
{
AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldSymbol.Name }), typeName, ref rawDataOffset, statements);
}
else if (fieldSymbol.Type.IsUnmanagedType)
{
// Custom struct type defined by the user
AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldSymbol.Name }).ToArray(), ref resourceOffset, ref rawDataOffset, statements);
}
}
}
/// <summary>
/// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix).
/// </summary>
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
/// <param name="typeName">The type name currently being read.</param>
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
/// <param name="statements">The target list of statements being generated.</param>
private static void AppendHlslKnownTypeField(IEnumerable<string> fieldPath, string typeName, ref int rawDataOffset, ICollection<StatementSyntax> statements)
{
// For scalar, vector and linear matrix types, serialize the value normally.
// Only the initial alignment needs to be considered, while data is packed.
var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
// Check if the current type is a matrix type with more than one row. In this
// case, each row is aligned as if it was a separate array, so the start of
// each row needs to be at a multiple of 16 bytes (a float4 register).
if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
{
string
rowTypeName = $"ComputeSharp.{elementName}{columns}",
rowLocalName = $"__{string.Join("_", fieldPath)}__row0";
statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in shader.{string.Join(".", fieldPath)}));"));
// Generate the loading code for each individual row, with proper alignment.
// This will result in the following (assuming Float2x3 m):
//
// ref Float3 __m__row0 = ref Unsafe.As<Float2x3, Float3>(ref Unsafe.AsRef(in shader.m));
// Unsafe.As<byte, Float3>(ref Unsafe.Add(ref r1, rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0);
// Unsafe.As<byte, Float3>(ref Unsafe.Add(ref r1, rawDataOffset + 16)) = Unsafe.Add(ref __m__row0, 1);
for (int j = 0; j < rows; j++)
{
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.As<byte, {rowTypeName}>(ref Unsafe.Add(ref r1, {rawDataOffset}))"),
ParseExpression($"Unsafe.Add(ref {rowLocalName}, {j})"))));
rawDataOffset += fieldPack * columns;
}
}
else
{
// Calculate the right offset with 16-bytes padding (HLSL constant buffer).
// Since we're in a constant buffer, we need to both pad the starting offset
// to be aligned to the packing size of the type, and also to align the initial
// offset to ensure that values do not cross 16 bytes boundaries either.
rawDataOffset = AlignmentHelper.AlignToBoundary(
AlignmentHelper.Pad(rawDataOffset, fieldPack),
fieldSize,
16);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.As<byte, {typeName}>(ref Unsafe.Add(ref r1, {rawDataOffset}))"),
ParseExpression($"shader.{string.Join(".", fieldPath)}"))));
rawDataOffset += fieldSize;
}
}
}
}
-49
ファイルの表示
@@ -1,49 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators
{
/// <inheritdoc/>
public sealed partial class IComputeShaderHashCodeGenerator
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
{
/// <summary>
/// The list of info gathered during exploration.
/// </summary>
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
if (context.Node is StructDeclarationSyntax structDeclaration &&
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
structSymbol.Interfaces.Any(static interfaceSymbol =>
interfaceSymbol.Name == nameof(IComputeShader) ||
interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) }))
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
}
}
/// <summary>
/// A model for a group of item representing a discovered type to process.
/// </summary>
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol);
}
}
}
-156
ファイルの表示
@@ -1,156 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Text;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators
{
/// <summary>
/// A source generator creating hash code factories for <see cref="IComputeShader"/> types.
/// </summary>
[Generator]
public sealed partial class IComputeShaderHashCodeGenerator : ISourceGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
// Type attributes
AttributeListSyntax[] attributes = new[]
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This type is not intended to be used directly by user code"))))))
};
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
{
try
{
OnExecute(context, item.StructDeclaration, item.StructSymbol, ref attributes);
}
catch
{
context.ReportDiagnostic(IComputeShaderHashCodeGeneratorError, item.StructDeclaration, item.StructSymbol);
}
}
}
/// <summary>
/// Processes a given target type.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="attributes">The list of <see cref="AttributeListSyntax"/> instances to append to the first copy of the partial class being generated.</param>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, ref AttributeListSyntax[] attributes)
{
TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString());
BlockSyntax block = Block(GetDelegateHashCodeStatements(structDeclarationSymbol));
if (block.Statements.Count == 1) return;
// Create a static method to create the combined hashcode for a given shader type.
// This code takes a block syntax and produces a compilation unit as follows:
//
// using System;
// using System.ComponentModel;
//
// namespace ComputeSharp.__Internals
// {
// internal static partial class HashCodeProvider
// {
// [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
// [System.Obsolete("This method is not intended to be called directly by user code")]
// public static int CombineHashCode(int hash, in ShaderType shader)
// {
// return ...;
// }
// }
// }
var source =
CompilationUnit().AddUsings(
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.ComponentModel"))).AddMembers(
NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers(
ClassDeclaration("HashCodeProvider").AddModifiers(
Token(SyntaxKind.InternalKeyword),
Token(SyntaxKind.StaticKeyword),
Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers(
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("CombineHash")).AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be called directly by user code"))))))).AddModifiers(
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.StaticKeyword)).AddParameterListParameters(
Parameter(Identifier("hash")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType))
.WithBody(block))))
.NormalizeWhitespace()
.ToFullString();
// Clear the attribute list to avoid duplicates
attributes = Array.Empty<AttributeListSyntax>();
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Gets a sequence of statements to process the hashcode of the captured delegates.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to hash the captured delegates.</returns>
[Pure]
private static IEnumerable<StatementSyntax> GetDelegateHashCodeStatements(INamedTypeSymbol structDeclarationSymbol)
{
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
if (fieldSymbol.Type is not INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false } typeSymbol)
{
continue;
}
// hash += hash << 5;
yield return ExpressionStatement(ParseExpression($"hash += hash << 5"));
// hash += shader.Field[#i].Method.GetHashCode();
yield return ExpressionStatement(ParseExpression($"hash += shader.{fieldSymbol.Name}.Method.GetHashCode()"));
}
yield return ReturnStatement(IdentifierName("hash"));
}
}
}
-480
ファイルの表示
@@ -1,480 +0,0 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Helpers;
using ComputeSharp.SourceGenerators.Mappings;
using ComputeSharp.SourceGenerators.SyntaxRewriters;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators
{
/// <summary>
/// A source generator for processing <see cref="IComputeShader"/> types.
/// </summary>
[Generator]
public sealed partial class IComputeShaderSourceGenerator : ISourceGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
{
SemanticModelProvider semanticModel = new(context.Compilation);
try
{
OnExecute(context, item.StructDeclaration, semanticModel, item.StructSymbol);
}
catch
{
context.ReportDiagnostic(IComputeShaderSourceGeneratorError, item.StructDeclaration, item.StructSymbol);
}
}
}
/// <summary>
/// Processes a given target type.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> with metadata on the types being processed.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, SemanticModelProvider semanticModel, INamedTypeSymbol structDeclarationSymbol)
{
// Properties are not supported
DetectAndReportPropertyDeclarations(context, structDeclarationSymbol);
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// A given type can only represent a single shader type
if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader<byte>) }) > 1)
{
context.ReportDiagnostic(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol);
}
// Explore the syntax tree and extract the processed info
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
var isComputeShader = pixelShaderSymbol is null;
var implicitTextureField = isComputeShader ? default((string, string)?) : (HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!), "__outputTexture");
var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray();
var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
var (entryPoint, processedMethods, forwardDeclarations, isSamplerUsed) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader);
var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?);
var processedTypes = GetProcessedTypes(discoveredTypes).ToArray();
var processedConstants = GetProcessedConstants(constantDefinitions);
var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
// Create the compilation unit with the source attribute
var source =
CompilationUnit().AddUsings(
UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments(
AttributeArgument(TypeOfExpression(IdentifierName(structDeclarationSymbol.ToDisplayString()))),
AttributeArgument(ArrayExpression(processedTypes)),
AttributeArgument(ArrayExpression(implicitTextureField)),
AttributeArgument(ArrayExpression(implicitSamplerField)),
AttributeArgument(NestedArrayExpression(processedMembers)),
AttributeArgument(ArrayExpression(forwardDeclarations)),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))),
AttributeArgument(ArrayExpression(processedMethods)),
AttributeArgument(NestedArrayExpression(processedConstants)),
AttributeArgument(NestedArrayExpression(staticFields)),
AttributeArgument(NestedArrayExpression(sharedBuffers)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace()
.ToFullString();
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Gets a sequence of captured fields and their mapped names.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="types">The collection of currently discovered types.</param>
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
/// <returns>A sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<IEnumerable<string>> GetProcessedFields(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> types,
bool isComputeShader)
{
bool hlslResourceFound = false;
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
if (fieldSymbol.IsStatic) continue;
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
// Group shared fields must be static
if (attribute is not null)
{
context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name);
}
// Captured fields must be named type symbols
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol)
{
context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
string metadataName = typeSymbol.GetFullMetadataName();
// Allowed fields must be either resources, unmanaged values or delegates
if (HlslKnownTypes.IsTypedResourceType(metadataName))
{
hlslResourceFound = true;
// Track the type of items in the current buffer
if (HlslKnownTypes.IsStructuredBufferType(metadataName))
{
types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]);
}
}
else if (!typeSymbol.IsUnmanagedType &&
typeSymbol.TypeKind != TypeKind.Delegate)
{
// Shaders can only capture valid HLSL resource types or unmanaged types
context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol);
continue;
}
else if (!HlslKnownTypes.IsKnownHlslType(metadataName))
{
// Track the type if it's a custom struct
types.Add(typeSymbol);
}
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
// Yield back the current mapping for the name (if the name used a reserved keyword)
yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName };
}
// If the shader is a compute one (so no implicit output texture), it has to contain at least one resource
if (!hlslResourceFound && isComputeShader)
{
context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol);
}
}
/// <summary>
/// Gets a sequence of shader static fields and their mapped names.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the current type.</param>
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<IEnumerable<string?>> GetStaticFields(
GeneratorExecutionContext context,
SemanticModelProvider semanticModel,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
foreach (var fieldDeclaration in structDeclaration.Members.OfType<FieldDeclarationSyntax>())
{
foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables)
{
IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!;
if (!fieldSymbol.IsStatic || fieldSymbol.IsConst)
{
continue;
}
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
if (attribute is not null) continue;
// Constant properties must be of a primitive, vector or matrix type
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol ||
!HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName()))
{
context.ReportDiagnostic(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
string typeDeclaration = fieldSymbol.IsReadOnly switch
{
true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}",
false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}"
};
StaticFieldRewriter staticFieldRewriter = new(
semanticModel,
discoveredTypes,
constantDefinitions,
context);
string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace().ToFullString();
yield return new[] { mapping ?? fieldSymbol.Name, typeDeclaration, assignment };
}
}
}
/// <summary>
/// Gets a sequence of captured members and their mapped names.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="types">The collection of currently discovered types.</param>
/// <returns>A sequence of captured members in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> types)
{
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
if (!fieldSymbol.IsStatic) continue;
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
if (attribute is null) continue;
if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol)
{
context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
if (!typeSymbol.ElementType.IsUnmanagedType)
{
context.ReportDiagnostic(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value;
string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol);
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize);
types.Add((INamedTypeSymbol)typeSymbol.ElementType);
}
}
/// <summary>
/// Gets a sequence of processed methods declared within a given type.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the current type.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
[Pure]
private static (string EntryPoint, IEnumerable<string> Methods, IEnumerable<string> Declarations, bool IsSamplerUser) GetProcessedMethods(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
bool isComputeShader)
{
// Find all declared methods in the type
ImmutableArray<MethodDeclarationSyntax> methodDeclarations = (
from syntaxNode in structDeclaration.DescendantNodes()
where syntaxNode.IsKind(SyntaxKind.MethodDeclaration)
select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray();
string? entryPoint = null;
List<string> methods = new();
List<string> declarations = new();
bool isSamplerUsed = false;
foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations)
{
IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!;
bool isShaderEntryPoint =
(isComputeShader &&
methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) &&
methodDeclarationSymbol.ReturnsVoid &&
methodDeclarationSymbol.TypeParameters.Length == 0 &&
methodDeclarationSymbol.Parameters.Length == 0) ||
(!isComputeShader &&
methodDeclarationSymbol.Name == nameof(IPixelShader<byte>.Execute) &&
methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type
methodDeclarationSymbol.TypeParameters.Length == 0 &&
methodDeclarationSymbol.Parameters.Length == 0);
// Create the source rewriter for the current method
ShaderSourceRewriter shaderSourceRewriter = new(
structDeclarationSymbol,
semanticModel,
discoveredTypes,
staticMethods,
constantDefinitions,
context,
isShaderEntryPoint);
// Rewrite the method syntax tree
MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
// Track the implicit sampler, if used
isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed;
// Emit the extracted local functions first
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
{
methods.Add(localFunction.Value.NormalizeWhitespace().ToFullString());
declarations.Add(localFunction.Value.AsDefinition().NormalizeWhitespace().ToFullString());
}
// If the method is the shader entry point, do additional processing
if (isShaderEntryPoint)
{
processedMethod = isComputeShader switch
{
true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!,
false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)!
};
entryPoint = processedMethod.NormalizeWhitespace().ToFullString();
}
else
{
methods.Add(processedMethod.NormalizeWhitespace().ToFullString());
declarations.Add(processedMethod.AsDefinition().NormalizeWhitespace().ToFullString());
}
}
// Process static methods as well
foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
{
methods.Add(staticMethod.NormalizeWhitespace().ToFullString());
declarations.Add(staticMethod.AsDefinition().NormalizeWhitespace().ToFullString());
}
return (entryPoint!, methods, declarations, isSamplerUsed);
}
/// <summary>
/// Gets a sequence of discovered constants.
/// </summary>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of discovered constants to declare in the shader.</returns>
[Pure]
internal static IEnumerable<IEnumerable<string>> GetProcessedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
{
foreach (var constant in constantDefinitions)
{
var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
yield return new string[] { constantName, constant.Value };
}
}
/// <summary>
/// Gets the sequence of processed discovered custom types.
/// </summary>
/// <param name="types">The sequence of discovered custom types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
internal static IEnumerable<string> GetProcessedTypes(IEnumerable<INamedTypeSymbol> types)
{
foreach (var type in HlslKnownTypes.GetCustomTypes(types))
{
var structType = type.GetFullMetadataName().ToHlslIdentifierName();
var structDeclaration = StructDeclaration(structType);
// Declare the fields of the current type
foreach (var field in type.GetMembers().OfType<IFieldSymbol>())
{
INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
// Convert the name to the fully qualified HLSL version
if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped))
{
mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName();
}
structDeclaration = structDeclaration.AddMembers(
FieldDeclaration(VariableDeclaration(
IdentifierName(mapped!)).AddVariables(
VariableDeclarator(Identifier(field.Name)))));
}
// Insert the trailing ; right after the closing bracket (after normalization)
yield return
structDeclaration
.NormalizeWhitespace()
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
.ToFullString();
}
}
/// <summary>
/// Finds and reports all declared properties in a shader.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
private static void DetectAndReportPropertyDeclarations(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol)
{
foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType<IPropertySymbol>())
{
context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol);
}
}
}
}
+821
ファイルの表示
@@ -0,0 +1,821 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Helpers;
using ComputeSharp.SourceGenerators.Mappings;
using ComputeSharp.SourceGenerators.SyntaxRewriters;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators
{
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
out string? implicitTextureType,
out bool isSamplerUsed,
out bool isHashSetDirectiveNeeded)
{
// Properties are not supported
DetectAndReportPropertyDeclarations(context, structDeclarationSymbol);
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// A given type can only represent a single shader type
if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader<byte>) }) > 1)
{
context.ReportDiagnostic(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol);
}
// Explore the syntax tree and extract the processed info
var semanticModel = new SemanticModelProvider(context.Compilation);
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
var isComputeShader = pixelShaderSymbol is null;
var pixelShaderTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!);
var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray();
var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
var (entryPoint, processedMethods, accessesStaticSampler) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader);
var implicitSamplerField = accessesStaticSampler ? ("SamplerState", "__sampler") : default((string, string)?);
var processedTypes = GetProcessedTypes(discoveredTypes).ToArray();
var processedConstants = GetProcessedConstants(constantDefinitions);
var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
string structName = structDeclaration.Identifier.Text;
SyntaxTokenList structModifiers = structDeclaration.Modifiers;
IEnumerable<StatementSyntax> bodyStatements = GenerateRenderMethodBody(
processedConstants,
staticFields,
processedTypes,
isComputeShader,
processedMembers,
pixelShaderTextureType,
accessesStaticSampler,
sharedBuffers,
processedMethods,
entryPoint,
out isHashSetDirectiveNeeded);
implicitTextureType = pixelShaderTextureType;
isSamplerUsed = accessesStaticSampler;
// This code produces a method declaration as follows:
//
// public readonly void BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("BuildHlslString"))
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword))
.AddParameterListParameters(
Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("ArrayPoolStringBuilder")),
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
.WithBody(Block(bodyStatements));
}
/// <summary>
/// Gets a sequence of captured fields and their mapped names.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="types">The collection of currently discovered types.</param>
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
/// <returns>A sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> GetProcessedFields(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> types,
bool isComputeShader)
{
bool hlslResourceFound = false;
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
if (fieldSymbol.IsStatic) continue;
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
// Group shared fields must be static
if (attribute is not null)
{
context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name);
}
// Captured fields must be named type symbols
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol)
{
context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
string metadataName = typeSymbol.GetFullMetadataName();
// Allowed fields must be either resources, unmanaged values or delegates
if (HlslKnownTypes.IsTypedResourceType(metadataName))
{
hlslResourceFound = true;
// Track the type of items in the current buffer
if (HlslKnownTypes.IsStructuredBufferType(metadataName))
{
types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]);
}
}
else if (!typeSymbol.IsUnmanagedType &&
typeSymbol.TypeKind != TypeKind.Delegate)
{
// Shaders can only capture valid HLSL resource types or unmanaged types
context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol);
continue;
}
else if (typeSymbol.IsUnmanagedType &&
!HlslKnownTypes.IsKnownHlslType(metadataName))
{
// Track the type if it's a custom struct
types.Add(typeSymbol);
}
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
// Yield back the current mapping for the name (if the name used a reserved keyword)
yield return (fieldSymbol, mapping ?? fieldSymbol.Name, typeName);
}
// If the shader is a compute one (so no implicit output texture), it has to contain at least one resource
if (!hlslResourceFound && isComputeShader)
{
context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol);
}
}
/// <summary>
/// Gets a sequence of shader static fields and their mapped names.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the current type.</param>
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
GeneratorExecutionContext context,
SemanticModelProvider semanticModel,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
foreach (var fieldDeclaration in structDeclaration.Members.OfType<FieldDeclarationSyntax>())
{
foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables)
{
IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!;
if (!fieldSymbol.IsStatic || fieldSymbol.IsConst)
{
continue;
}
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
if (attribute is not null) continue;
// Constant properties must be of a primitive, vector or matrix type
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol ||
!HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName()))
{
context.ReportDiagnostic(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
string typeDeclaration = fieldSymbol.IsReadOnly switch
{
true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}",
false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}"
};
StaticFieldRewriter staticFieldRewriter = new(
semanticModel,
discoveredTypes,
constantDefinitions,
context);
string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString();
yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment);
}
}
}
/// <summary>
/// Gets a sequence of captured members and their mapped names.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="types">The collection of currently discovered types.</param>
/// <returns>A sequence of captured members in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> types)
{
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
if (!fieldSymbol.IsStatic) continue;
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
if (attribute is null) continue;
if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol)
{
context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
if (!typeSymbol.ElementType.IsUnmanagedType)
{
context.ReportDiagnostic(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value;
string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol);
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize);
types.Add((INamedTypeSymbol)typeSymbol.ElementType);
}
}
/// <summary>
/// Gets a sequence of processed methods declared within a given type.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the current type.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
[Pure]
private static (string EntryPoint, IEnumerable<(string Signature, string Definition)> ProcessedMethods, bool IsSamplerUser) GetProcessedMethods(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
bool isComputeShader)
{
// Find all declared methods in the type
ImmutableArray<MethodDeclarationSyntax> methodDeclarations = (
from syntaxNode in structDeclaration.DescendantNodes()
where syntaxNode.IsKind(SyntaxKind.MethodDeclaration)
select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray();
string? entryPoint = null;
List<(string, string)> processedMethods = new();
bool isSamplerUsed = false;
foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations)
{
IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!;
bool isShaderEntryPoint =
(isComputeShader &&
methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) &&
methodDeclarationSymbol.ReturnsVoid &&
methodDeclarationSymbol.TypeParameters.Length == 0 &&
methodDeclarationSymbol.Parameters.Length == 0) ||
(!isComputeShader &&
methodDeclarationSymbol.Name == nameof(IPixelShader<byte>.Execute) &&
methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type
methodDeclarationSymbol.TypeParameters.Length == 0 &&
methodDeclarationSymbol.Parameters.Length == 0);
// Create the source rewriter for the current method
ShaderSourceRewriter shaderSourceRewriter = new(
structDeclarationSymbol,
semanticModel,
discoveredTypes,
staticMethods,
constantDefinitions,
context,
isShaderEntryPoint);
// Rewrite the method syntax tree
MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
// Track the implicit sampler, if used
isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed;
// Emit the extracted local functions first
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
{
processedMethods.Add((
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
}
// If the method is the shader entry point, do additional processing
if (isShaderEntryPoint)
{
processedMethod = isComputeShader switch
{
true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!,
false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)!
};
entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString();
}
else
{
processedMethods.Add((
processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
processedMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
}
}
// Process static methods as well
foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
{
processedMethods.Add((
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
}
return (entryPoint!, processedMethods, isSamplerUsed);
}
/// <summary>
/// Gets a sequence of discovered constants.
/// </summary>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of discovered constants to declare in the shader.</returns>
[Pure]
internal static IEnumerable<(string Name, string Value)> GetProcessedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
{
foreach (var constant in constantDefinitions)
{
var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
yield return (constantName, constant.Value);
}
}
/// <summary>
/// Gets the sequence of processed discovered custom types.
/// </summary>
/// <param name="types">The sequence of discovered custom types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
internal static IEnumerable<(string Name, string Definition)> GetProcessedTypes(IEnumerable<INamedTypeSymbol> types)
{
foreach (var type in HlslKnownTypes.GetCustomTypes(types))
{
var structType = type.GetFullMetadataName().ToHlslIdentifierName();
var structDeclaration = StructDeclaration(structType);
// Declare the fields of the current type
foreach (var field in type.GetMembers().OfType<IFieldSymbol>())
{
INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
// Convert the name to the fully qualified HLSL version
if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped))
{
mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName();
}
structDeclaration = structDeclaration.AddMembers(
FieldDeclaration(VariableDeclaration(
IdentifierName(mapped!)).AddVariables(
VariableDeclarator(Identifier(field.Name)))));
}
// Insert the trailing ; right after the closing bracket (after normalization)
yield return
(structType,
structDeclaration
.NormalizeWhitespace(eol: "\n")
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
.ToFullString());
}
}
/// <summary>
/// Finds and reports all declared properties in a shader.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
private static void DetectAndReportPropertyDeclarations(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol)
{
foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType<IPropertySymbol>())
{
context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol);
}
}
/// <summary>
/// Produces the series of statements to build the current HLSL source.
/// </summary>
/// <param name="definedConstants">The sequence of defined constants for the shader.</param>
/// <param name="staticFields">The sequence of static fields referenced by the shader.</param>
/// <param name="declaredTypes">The sequence of declared types used by the shader.</param>
/// <param name="isComputeShader">Whether or not the current shader is a compute shader (or a pixel shader).</param>
/// <param name="instanceFields">The sequence of instance fields for the current shader.</param>
/// <param name="implicitTextureType">The type of the implicit target texture, if present.</param>
/// <param name="isSamplerUsed">Whether the static sampler is used by the shader.</param>
/// <param name="sharedBuffers">The sequence of shared buffers declared by the shader.</param>
/// <param name="processedMethods">The sequence of processed methods used by the shader.</param>
/// <param name="executeMethod">The body of the entry point of the shader.</param>
/// <param name="isHashSetDirectiveNeeded">Indicates whether or not the <see langword="using"/> directive for <see cref="HashSet{T}"/> is needed.</param>
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
private static IEnumerable<StatementSyntax> GenerateRenderMethodBody(
IEnumerable<(string Name, string Value)> definedConstants,
IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
IEnumerable<(string Name, string Definition)> declaredTypes,
bool isComputeShader,
IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields,
string? implicitTextureType,
bool isSamplerUsed,
IEnumerable<(string Name, string Type, int? Count)> sharedBuffers,
IEnumerable<(string Signature, string Definition)> processedMethods,
string executeMethod,
out bool isHashSetDirectiveNeeded)
{
List<StatementSyntax> statements = new();
StringBuilder textBuilder = new();
int capturedDelegates = 0;
int prologueStatements = 0;
int sizeHint = 64;
void AppendLF()
{
textBuilder.Append('\n');
}
void AppendLine(string text)
{
textBuilder.Append(text);
}
void AppendLineAndLF(string text)
{
textBuilder.Append(text);
textBuilder.Append('\n');
}
void AppendCharacterAndLF(char c)
{
textBuilder.Append(c);
textBuilder.Append('\n');
}
void AppendParsedStatement(string text)
{
FlushText();
statements.Add(ParseStatement(text));
}
void FlushText()
{
if (textBuilder.Length > 0)
{
sizeHint += textBuilder.Length;
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append")))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(textBuilder.ToString()))))));
textBuilder.Clear();
}
}
// Declare the hashsets to track imported members and types from delegates, if needed
if (instanceFields.Any(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
{
void DeclareMapping(int index, string name, IEnumerable<string> items)
{
// HashSet<string> <NAME> = new();
statements.Insert(index,
LocalDeclarationStatement(VariableDeclaration(
GenericName(Identifier("HashSet"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword))))
.AddVariables(
VariableDeclarator(Identifier(name))
.WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))));
prologueStatements++;
// <NAME>.Add("<ITEM>");
foreach (var item in items)
{
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(name),
IdentifierName("Add")))
.AddArgumentListArguments(Argument(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))))));
prologueStatements++;
}
}
DeclareMapping(0, "__typeNames", declaredTypes.Select(static t => t.Name));
DeclareMapping(1, "__constantNames", definedConstants.Select(static t => t.Name));
DeclareMapping(2, "__methodNames", processedMethods.Select(static t => t.Signature));
// Go through all existing delegate fields, if any
foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
{
// ShaderMethodSourceAttribute __<DELEGATE_NAME>Attribute = ShaderMethodSourceAttribute.GetForDelegate(<DELEGATE_NAME>, "<DELEGATE_NAME>");
statements.Add(
LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute)))
.AddVariables(
VariableDeclarator(Identifier($"__{fieldName}Attribute"))
.WithInitializer(
EqualsValueClause(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(nameof(ShaderMethodSourceAttribute)),
IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate))))
.AddArgumentListArguments(
Argument(IdentifierName(fieldName)),
Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName)))))))));
capturedDelegates++;
prologueStatements++;
}
}
isHashSetDirectiveNeeded = capturedDelegates > 0;
// Header
AppendLineAndLF("// ================================================");
AppendLineAndLF("// AUTO GENERATED");
AppendLineAndLF("// ================================================");
AppendLineAndLF("// This shader was created by ComputeSharp.");
AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp.");
// Group size constants
AppendLF();
AppendLine("#define __GroupSize__get_X ");
AppendParsedStatement("builder.Append(threadsX);");
AppendLF();
AppendLine("#define __GroupSize__get_Y ");
AppendParsedStatement("builder.Append(threadsY);");
AppendLF();
AppendLine("#define __GroupSize__get_Z ");
AppendParsedStatement("builder.Append(threadsZ);");
AppendLF();
// Define declarations
foreach (var (name, value) in definedConstants)
{
AppendLineAndLF($"#define {name} {value}");
}
// Defines from captured delegates
foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
{
AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);");
}
// Static fields
if (staticFields.Any())
{
AppendLF();
foreach (var field in staticFields)
{
if (field.Assignment is string assignment)
{
AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};");
}
else
{
AppendLineAndLF($"{field.TypeDeclaration} {field.Name};");
}
}
}
// Declared types
foreach (var (_, typeDefinition) in declaredTypes)
{
AppendLF();
AppendLineAndLF(typeDefinition);
}
// Declared types from captured delegates
foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
{
AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);");
}
// Captured variables
AppendLF();
AppendLineAndLF("cbuffer _ : register(b0)");
AppendCharacterAndLF('{');
AppendLineAndLF(" uint __x;");
AppendLineAndLF(" uint __y;");
if (isComputeShader)
{
AppendLineAndLF(" uint __z;");
}
// User-defined values
foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.IsUnmanagedType))
{
AppendLineAndLF($" {fieldType} {fieldName};");
}
AppendCharacterAndLF('}');
int
constantBuffersCount = 1,
readOnlyBuffersCount = 0,
readWriteBuffersCount = 0;
// Optional implicit texture field
if (!isComputeShader)
{
AppendLF();
AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});");
}
// Optional sampler field
if (isSamplerUsed)
{
AppendLF();
AppendLineAndLF("SamplerState __sampler : register(s);");
}
// Resources
foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields)
{
string metadataName = fieldSymbol.Type.GetFullMetadataName();
if (HlslKnownTypes.IsConstantBufferType(metadataName))
{
AppendLF();
AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})");
AppendCharacterAndLF('{');
AppendLineAndLF($" {fieldType} {fieldName}[2];");
AppendCharacterAndLF('}');
}
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName))
{
AppendLF();
AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});");
}
else if (HlslKnownTypes.IsTypedResourceType(metadataName))
{
AppendLF();
AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});");
}
}
// Shared buffers
foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers)
{
object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ";
AppendLF();
AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];");
}
// Forward declarations
foreach (var (forwardDeclaration, _) in processedMethods)
{
AppendLF();
AppendLineAndLF(forwardDeclaration);
}
// Forward declarations from captured delegates
foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
{
AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);");
}
// Remove all forward declarations from methods that are embedded into the shader.
// This is necessary to avoid duplicate definitions from methods from delegates.
if (capturedDelegates > 0)
{
// <NAME>.Add("<ITEM>");
foreach (var (forwardDeclaration, _) in processedMethods)
{
FlushText();
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("__methodNames"),
IdentifierName("Remove")))
.AddArgumentListArguments(Argument(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration))))));
}
}
// Captured methods
foreach (var (_, method) in processedMethods)
{
AppendLF();
AppendLineAndLF(method);
}
// Captured methods from captured delegates
foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
{
AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);");
}
// Captured delegate methods
foreach (var (fieldSymbol, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
{
AppendLF();
AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");");
AppendLF();
}
// Entry point
AppendLF();
AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]");
AppendLineAndLF(executeMethod);
FlushText();
// builder = ArrayPoolStringBuilder.Create(<SIZE_HINT>);
statements.Insert(
prologueStatements,
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("builder"),
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("ArrayPoolStringBuilder"),
IdentifierName("Create")))
.AddArgumentListArguments(
Argument(LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(sizeHint)))))));
return statements;
}
}
}
+96
ファイルの表示
@@ -0,0 +1,96 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators
{
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol)
{
// This code produces a method declaration as follows:
//
// public readonly int GetDispatchId()
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("GetDispatchId"))
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword))
.WithBody(GetShaderHashCodeBody(structDeclarationSymbol));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
[Pure]
private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol)
{
var delegateFields = structDeclarationSymbol
.GetMembers()
.OfType<IFieldSymbol>()
.Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
.ToImmutableArray();
if (delegateFields.Length == 0)
{
// return 0;
return
Block(ReturnStatement(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))));
}
List<StatementSyntax> blockStatements = new(4);
// HashCode hashCode = default;
blockStatements.Add(LocalDeclarationStatement(
VariableDeclaration(IdentifierName("HashCode"))
.AddVariables(
VariableDeclarator(Identifier("hashCode"))
.WithInitializer(EqualsValueClause(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword)))))));
foreach (IFieldSymbol fieldSymbol in delegateFields)
{
// hashCode.Add(delegateField.Method);
blockStatements.Add(ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("Add")))
.AddArgumentListArguments(Argument(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(fieldSymbol.Name),
IdentifierName("Method"))))));
}
// return hashCode.ToHashCode();
blockStatements.Add(ReturnStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("ToHashCode")))));
return Block(blockStatements);
}
}
}
+342
ファイルの表示
@@ -0,0 +1,342 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ComputeSharp.Core.Helpers;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators
{
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
out IReadOnlyCollection<string> discoveredResources,
out int root32BitConstantsCount)
{
// This code produces a method declaration as follows:
//
// public readonly void LoadDispatchData<TDataLoader>(ref TDataLoader loader, GraphicsDevice device, int x, int y, int z)
// where TDataLoader : struct, IDispatchDataLoader
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchData"))
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TDataLoader")),
Parameter(Identifier("device")).WithType(IdentifierName("GraphicsDevice")),
Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
.AddConstraintClauses(
TypeParameterConstraintClause(IdentifierName("TDataLoader"))
.AddConstraints(
ClassOrStructConstraint(SyntaxKind.StructConstraint),
TypeConstraint(IdentifierName("IDispatchDataLoader"))))
.WithBody(Block(GetDispatchDataLoadingStatements(context, structDeclarationSymbol, out discoveredResources, out root32BitConstantsCount)));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="discoveredResources">The collection of discovered resources in the current shader type.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the current shader type.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static IEnumerable<StatementSyntax> GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection<string> discoveredResources, out int root32BitConstantsCount)
{
List<StatementSyntax> statements = new();
List<string> resources = new();
discoveredResources = resources;
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
var isComputeShader = pixelShaderSymbol is null;
int
resourceOffset = 0,
rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
// Append the statements for the dispatch ranges:
//
// span0[0] = (uint)x;
// span0[1] = (uint)y;
// span0[2] = (uint)z;
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x")))));
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y")))));
if (isComputeShader)
{
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
}
// Append the statements to load all fields (both resources and other captured values)
AppendFields(structDeclarationSymbol, Array.Empty<string>(), ref resourceOffset, ref rawDataOffset, resources, statements);
// After all the captured fields have been processed, ansure the reported byte size for
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
// enable loading all the dispatch data after reinterpreting it to a sequence of values
// of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int));
root32BitConstantsCount = rawDataOffset / sizeof(int);
// A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
// Loaded values in the root signature have the following costs:
// - Root constants cost 1 DWORD each, since they are 32-bit values.
// - Descriptor tables cost 1 DWORD each.
// - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
// So here we check whether the current signature respects that constraint,
// and emit a build error otherwise. For more info on this, see the docs here:
// https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
int rootSignatureDwordSize = root32BitConstantsCount + resourceOffset;
if (rootSignatureDwordSize > 64)
{
context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
}
// Span<uint> span0 = stackalloc uint[<VARIABLES>];
statements.Insert(0,
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
// ref uint r0 = ref span0[0];
statements.Insert(1,
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// loader.LoadCapturedValues(span0);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedValues")))
.AddArgumentListArguments(Argument(IdentifierName("span0")))));
if (resourceOffset > 0)
{
// Span<ulong> span1 = stackalloc ulong[<RESOURCES>];
statements.Insert(1,
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceOffset)))))))))));
// ref ulong r1 = ref span1[0];
statements.Insert(3,
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// loader.LoadCapturedResources(span1);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedResources")))
.AddArgumentListArguments(Argument(IdentifierName("span1")))));
}
return statements;
}
/// <summary>
/// Explores a given type hierarchy and generates statements to load fields.
/// </summary>
/// <param name="currentTypeSymbol">The current type being explored.</param>
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
/// <param name="resourceOffset">The current offset in the root table of loaded resources.</param>
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
/// <param name="resources">The target list of resources in the current shader type.</param>
/// <param name="statements">The target list of statements being generated.</param>
private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection<string> fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection<string> resources, ICollection<StatementSyntax> statements)
{
bool isFirstField = true;
foreach (
IFieldSymbol fieldSymbol in
from fieldSymbol in currentTypeSymbol.GetMembers().OfType<IFieldSymbol>()
where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
!fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer
select fieldSymbol)
{
string
fieldName = fieldSymbol.Name,
typeName = fieldSymbol.Type.GetFullMetadataName();
// Disambiguates the name of target fields against the current input parameters
if (fieldName is "loader" or "device" or "x" or "y" or "z")
{
fieldName = $"this.{fieldName}";
}
// The first item in each nested struct needs to be aligned to 16 bytes
if (isFirstField && fieldPath.Count > 0)
{
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
isFirstField = false;
}
if (HlslKnownTypes.IsTypedResourceType(typeName))
{
resources.Add(typeName);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.Add(ref r1, {resourceOffset++})"),
ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)"))));
}
else if (HlslKnownTypes.IsKnownHlslType(typeName))
{
AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldName }), typeName, ref rawDataOffset, statements);
}
else if (fieldSymbol.Type.IsUnmanagedType)
{
// Custom struct type defined by the user
AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldName }).ToArray(), ref resourceOffset, ref rawDataOffset, resources, statements);
}
}
}
/// <summary>
/// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix).
/// </summary>
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
/// <param name="typeName">The type name currently being read.</param>
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
/// <param name="statements">The target list of statements being generated.</param>
private static void AppendHlslKnownTypeField(IEnumerable<string> fieldPath, string typeName, ref int rawDataOffset, ICollection<StatementSyntax> statements)
{
// For scalar, vector and linear matrix types, serialize the value normally.
// Only the initial alignment needs to be considered, while data is packed.
var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
// Check if the current type is a matrix type with more than one row. In this
// case, each row is aligned as if it was a separate array, so the start of
// each row needs to be at a multiple of 16 bytes (a float4 register).
if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
{
string
rowTypeName = $"ComputeSharp.{elementName}{columns}",
rowLocalName = $"__{string.Join("_", fieldPath)}__row0";
statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in {string.Join(".", fieldPath)}));"));
// Generate the loading code for each individual row, with proper alignment.
// This will result in the following (assuming Float2x3 m):
//
// ref Float3 __m__row0 = ref Unsafe.As<Float2x3, Float3>(ref Unsafe.AsRef(in m));
// Unsafe.As<uint, Float3>(ref Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0);
// Unsafe.As<uint, Float3>(ref Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = Unsafe.Add(ref __m__row0, 1);
for (int j = 0; j < rows; j++)
{
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.As<uint, {rowTypeName}>(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"),
ParseExpression($"Unsafe.Add(ref {rowLocalName}, {j})"))));
rawDataOffset += fieldPack * columns;
}
}
else
{
// Calculate the right offset with 16-bytes padding (HLSL constant buffer).
// Since we're in a constant buffer, we need to both pad the starting offset
// to be aligned to the packing size of the type, and also to align the initial
// offset to ensure that values do not cross 16 bytes boundaries either.
rawDataOffset = AlignmentHelper.AlignToBoundary(
AlignmentHelper.Pad(rawDataOffset, fieldPack),
fieldSize,
16);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.As<uint, {typeName}>(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"),
ParseExpression($"{string.Join(".", fieldPath)}"))));
rawDataOffset += fieldSize;
}
}
}
}
@@ -0,0 +1,161 @@
using System;
using System.Collections.Generic;
using ComputeSharp.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators
{
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(
string? implicitTextureType,
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed)
{
// This code produces a method declaration as follows:
//
// public readonly void LoadDispatchMetadata<TMetadataLoader>(ref TMetadataLoader loader, out IntPtr result)
// where TMetadataLoader : struct, IDispatchMetadataLoader
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchMetadata"))
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TMetadataLoader")),
Parameter(Identifier("result"))
.AddModifiers(Token(SyntaxKind.OutKeyword))
.WithType(IdentifierName(typeof(IntPtr).Name)))
.AddConstraintClauses(
TypeParameterConstraintClause(IdentifierName("TMetadataLoader"))
.AddConstraints(
ClassOrStructConstraint(SyntaxKind.StructConstraint),
TypeConstraint(IdentifierName("IDispatchMetadataLoader"))))
.WithBody(Block(GetDispatchMetadataLoadingStatements(implicitTextureType, discoveredResources, root32BitConstantsCount, isSamplerUsed)));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch metadata for a given shader type.
/// </summary>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="discoveredResources">The collection of resources used by the shader.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the shader.</param>
/// <param name="isSamplerUsed">Whether or not the shader requires a static sampler to be available.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static IEnumerable<StatementSyntax> GetDispatchMetadataLoadingStatements(
string? implicitTextureType,
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed)
{
// Span<byte> span0 = stackalloc byte[5];
yield return
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5))))))))));
// Compute the total number of resources (discovered ones and the implicit target texture, if present)
int totalResourcesCount = discoveredResources.Count + (implicitTextureType is not null ? 1 : 0);
// Span<ResourceDescriptor> span1 = stackalloc ResourceDescriptor[<ADJUSTED_COUNT>];
yield return
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(IdentifierName("ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(IdentifierName("ResourceDescriptor"))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount))))))))));
// ref byte r0 = ref span0[0];
yield return
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0)))))))));
// ref ResourceDescriptor r1 = ref span1[0];
yield return
LocalDeclarationStatement(
VariableDeclaration(RefType(IdentifierName("ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0)))))))));
// Serialized shader metadata
yield return ParseStatement($"Unsafe.WriteUnaligned<int>(ref Unsafe.Add(ref r0, 0), {root32BitConstantsCount});");
yield return ParseStatement($"Unsafe.WriteUnaligned<bool>(ref Unsafe.Add(ref r0, 4), {isSamplerUsed.ToString().ToLowerInvariant()});");
int
constantBufferOffset = 1,
readOnlyResourceOffset = 0,
readWriteResourceOffset = 0,
resourceOffset = 0;
// Add the implicit texture descriptor, if needed
if (implicitTextureType is not null)
{
yield return ParseStatement($"ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));");
}
// Populate the sequence of resource descriptors
foreach (var resource in discoveredResources)
{
if (HlslKnownTypes.IsConstantBufferType(resource))
{
yield return ParseStatement($"ResourceDescriptor.Create(2, {constantBufferOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));");
}
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource))
{
yield return ParseStatement($"ResourceDescriptor.Create(0, {readOnlyResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));");
}
else
{
yield return ParseStatement($"ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));");
}
}
// Invoke the value delegate to create the opaque root signature handle
yield return ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);");
}
}
}
@@ -7,7 +7,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators
{
/// <inheritdoc/>
public sealed partial class IComputeShaderSourceGenerator
public sealed partial class IShaderGenerator
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
+225
ファイルの表示
@@ -0,0 +1,225 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
namespace ComputeSharp.SourceGenerators
{
/// <summary>
/// A source generator creating data loaders for <see cref="IComputeShader"/> and <see cref="IPixelShader{TPixel}"/> types.
/// </summary>
[Generator]
public sealed partial class IShaderGenerator : ISourceGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
{
try
{
OnExecute(context, item.StructDeclaration, item.StructSymbol);
}
catch
{
context.ReportDiagnostic(IShaderGeneratorError, item.StructDeclaration, item.StructSymbol);
}
}
}
/// <summary>
/// Processes a given target type.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol)
{
// Create the required interface methods for the current shader type
MethodDeclarationSyntax
getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol),
loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants),
buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out bool isHashSetDirectiveNeeded),
loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed);
// Reorder the method declarations to respect the order in the interface definition
MethodDeclarationSyntax[] methods =
{
getDispatchIdMethod,
loadDispatchDataMethod,
loadDispatchMetadataMethod,
buildHlslStringMethod
};
// Method attributes
AttributeListSyntax[] attributes = new[]
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be used directly by user code"))))))
};
string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
string structName = structDeclaration.Identifier.Text;
SyntaxTokenList structModifiers = structDeclaration.Modifiers;
// Create the partial shader type declaration with the hashcode interface method implementation.
// This code produces a struct declaration as follows:
//
// public struct ShaderType : IShader<ShaderType>
// {
// <METHODS_LIST>
// }
var structDeclarationSyntax =
StructDeclaration(structName)
.WithModifiers(structModifiers)
.AddBaseListTypes(SimpleBaseType(
GenericName(Identifier("IShader"))
.AddTypeArgumentListArguments(IdentifierName(structName))))
.AddMembers(methods.Select(m => m.AddAttributeLists(attributes)).ToArray());
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
{
typeDeclarationSyntax = parentType
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
.WithBaseList(null)
.WithAttributeLists(List<AttributeListSyntax>())
.WithoutTrivia();
}
// Prepare the necessary using directives
List<UsingDirectiveSyntax> usingDirectives = new()
{
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.CodeDom.Compiler")),
UsingDirective(IdentifierName("System.ComponentModel")),
UsingDirective(IdentifierName("System.Diagnostics")),
UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")),
UsingDirective(IdentifierName("System.Runtime.CompilerServices")),
UsingDirective(IdentifierName("ComputeSharp")),
UsingDirective(IdentifierName("ComputeSharp.__Internals"))
};
if (isHashSetDirectiveNeeded)
{
usingDirectives.Insert(2, UsingDirective(IdentifierName("System.Collections.Generic")));
}
// Create a static method to create the combined hashcode for a given shader type.
// This code takes a block syntax and produces a compilation unit as follows:
//
// using System;
// using System.CodeDom.Compiler;
// using System.ComponentModel;
// using System.Diagnostics;
// using System.Diagnostics.CodeAnalysis;
// using System.Runtime.CompilerServices;
// using ComputeSharp.__Internals;
//
// #pragma warning disable
//
// namespace <SHADER_NAMESPACE>
// {
// <SHADER_DECLARATION>
// }
var source =
CompilationUnit().AddUsings(usingDirectives.ToArray()).AddMembers(
NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
.NormalizeWhitespace(eol: "\n")
.ToFullString();
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
/// </summary>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="discoveredResources">The collection of discovered resources in the current shader type.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the current shader type.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
out IReadOnlyCollection<string> discoveredResources,
out int root32BitConstantsCount);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="isSamplerUsed">Whether or not the current shader type requires a static sampler to be available.</param>
/// <param name="isHashSetDirectiveNeeded">Indicates whether or not the <see langword="using"/> directive for <see cref="HashSet{T}"/> is needed.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
out string? implicitTextureType,
out bool isSamplerUsed,
out bool isHashSetDirectiveNeeded);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.
/// </summary>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="discoveredResources">The collection of resources used by the shader.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the shader.</param>
/// <param name="isSamplerUsed">Whether or not the shader requires a static sampler to be available.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.</returns>
private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(
string? implicitTextureType,
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed);
}
}
+31
ファイルの表示
@@ -101,6 +101,16 @@ namespace ComputeSharp.SourceGenerators.Mappings
return knownTypes;
}
/// <summary>
/// Checks whether or not a given type name matches a constant buffer type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a constant buffer type.</returns>
public static bool IsConstantBufferType(string typeName)
{
return typeName == "ComputeSharp.ConstantBuffer`1";
}
/// <summary>
/// Checks whether or not a given type name matches a structured buffer type.
/// </summary>
@@ -118,6 +128,27 @@ namespace ComputeSharp.SourceGenerators.Mappings
};
}
/// <summary>
/// Checks whether or not a given type name matches a readonly typed resource type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a readonly typed resource type.</returns>
public static bool IsReadOnlyTypedResourceType(string typeName)
{
switch (typeName)
{
case "ComputeSharp.ReadOnlyBuffer`1":
case "ComputeSharp.ReadOnlyTexture2D`1":
case "ComputeSharp.ReadOnlyTexture2D`2":
case "ComputeSharp.ReadOnlyTexture3D`1":
case "ComputeSharp.ReadOnlyTexture3D`2":
case "ComputeSharp.IReadOnlyTexture2D`1":
case "ComputeSharp.IReadOnlyTexture3D`1":
return true;
default: return false;
};
}
/// <summary>
/// Checks whether or not a given type name matches a typed resource type.
/// </summary>
+24 -15
ファイルの表示
@@ -66,13 +66,12 @@ namespace ComputeSharp.SourceGenerators
{
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// Explore the syntax tree and extract the processed info
var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray();
var processedConstants = IComputeShaderSourceGenerator.GetProcessedConstants(constantDefinitions);
var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions);
var processedTypes = IShaderGenerator.GetProcessedTypes(discoveredTypes).ToArray();
var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions);
// Create the compilation unit with the source attribute
var source =
@@ -80,13 +79,13 @@ namespace ComputeSharp.SourceGenerators
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))),
AttributeArgument(ArrayExpression(processedTypes)),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))),
AttributeArgument(ArrayExpression(processedMethods)),
AttributeArgument(NestedArrayExpression(processedTypes)),
AttributeArgument(NestedArrayExpression(processedMethods)),
AttributeArgument(NestedArrayExpression(processedConstants)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace()
.NormalizeWhitespace(eol: "\n")
.ToFullString();
// Add the method source attribute
@@ -100,18 +99,18 @@ namespace ComputeSharp.SourceGenerators
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the current method.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the method to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/> (main method and local functions).</returns>
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/> (main method and all captured methods).</returns>
[Pure]
private static (string TargetMethod, IEnumerable<string> LocalFunctions) GetProcessedMethods(
private static (string TargetMethod, IEnumerable<(string Signature, string Definition)> ProcessedMethods) GetProcessedMethods(
GeneratorExecutionContext context,
MethodDeclarationSyntax methodDeclaration,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, context);
// Rewrite the method syntax tree
@@ -119,18 +118,28 @@ namespace ComputeSharp.SourceGenerators
.Visit(methodDeclaration)!
.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier))
.WithoutTrivia()
.NormalizeWhitespace()
.NormalizeWhitespace(eol: "\n")
.ToFullString();
List<string> localFunctions = new(shaderSourceRewriter.LocalFunctions.Count);
List<(string, string)> processedMethods = new(shaderSourceRewriter.LocalFunctions.Count);
// Emit the extracted local functions
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
{
localFunctions.Add(localFunction.Value.NormalizeWhitespace().ToFullString());
processedMethods.Add((
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
}
return (targetMethod, localFunctions);
// Emit the discovered static methods
foreach (var staticMethod in staticMethods.Values)
{
processedMethods.Add((
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
}
return (targetMethod, processedMethods);
}
}
}
-15
ファイルの表示
@@ -171,21 +171,6 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return base.VisitUsingStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitVariableDeclarator(VariableDeclaratorSyntax node)
{
var updatedNode = (VariableDeclaratorSyntax)base.VisitVariableDeclarator(node)!;
if (node.Initializer is null &&
node.Parent is VariableDeclarationSyntax declaration &&
SemanticModel.For(node).GetTypeInfo(declaration.Type).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
Context.ReportDiagnostic(InvalidObjectDeclaration, node, type);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node)
{
+19
ファイルの表示
@@ -73,6 +73,25 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
}
/// <inheritdoc/>
public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node)
{
var updatedNode = (VariableDeclarationSyntax)base.VisitVariableDeclaration(node)!;
if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
Context.ReportDiagnostic(InvalidObjectDeclaration, node, type);
}
// If var is used, replace it with the explicit type
if (updatedNode.Type is IdentifierNameSyntax { IsVar: true })
{
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
{
+1 -1
ファイルの表示
@@ -406,7 +406,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Context);
MethodDeclarationSyntax
methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(),
processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace().WithoutTrivia();
processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia();
this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier)));
}
-29
ファイルの表示
@@ -1,29 +0,0 @@
using System;
using System.ComponentModel;
namespace ComputeSharp.__Internals
{
/// <summary>
/// An attribute that contains info on the number of 32 bit constants for a given shader.
/// </summary>
/// <remarks>This attribute is not meant to be directly used by applications using ComputeSharp.</remarks>
[AttributeUsage(AttributeTargets.ReturnValue, AllowMultiple = false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This attribute is not intended to be used directly by user code")]
public sealed class ComputeRoot32BitConstantsAttribute : Attribute
{
/// <summary>
/// Creates a new <see cref="ComputeRoot32BitConstantsAttribute"/> instance with the specified parameters.
/// </summary>
/// <param name="count">The number of 32 bit constants for the annotated method.</param>
public ComputeRoot32BitConstantsAttribute(int count)
{
Count = count;
}
/// <summary>
/// Gets the number of 32 bit constants for the annotated method.
/// </summary>
internal int Count { get; }
}
}
-134
ファイルの表示
@@ -1,134 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using ComputeSharp.Exceptions;
namespace ComputeSharp.__Internals
{
/// <summary>
/// An attribute that contains info on a processed compute shader that can be executed.
/// </summary>
/// <remarks>This attribute is not meant to be directly used by applications using ComputeSharp.</remarks>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This attribute is not intended to be used directly by user code")]
public sealed class IComputeShaderSourceAttribute : Attribute
{
/// <summary>
/// Creates a new <see cref="IComputeShaderSourceAttribute"/> instance with the specified parameters.
/// </summary>
/// <param name="shaderType">The type of the current shader.</param>
/// <param name="types">The collection of custom types.</param>
/// <param name="implicitTextureField">The implicit texture field info, if present.</param>
/// <param name="implicitSamplerFields">The implicit texture sampler field info, if present.</param>
/// <param name="fields">The mapped collection of shader fields.</param>
/// <param name="forwardDeclarations">The forward declarations for static methods.</param>
/// <param name="executeMethod">The source code for the <see cref="IComputeShader.Execute"/> method.</param>
/// <param name="methods">The collection of processed methods.</param>
/// <param name="defines">The collection of discovered defines.</param>
/// <param name="staticFields">The collection of discovered static fields.</param>
/// <param name="sharedBuffers">The collection of group shared buffers.</param>
public IComputeShaderSourceAttribute(
Type shaderType,
string[] types,
string[]? implicitTextureField,
string[]? implicitSamplerFields,
object[] fields,
string[] forwardDeclarations,
string executeMethod,
string[] methods,
object[] defines,
object[] staticFields,
object[] sharedBuffers)
{
ShaderType = shaderType;
Types = types;
ImplicitTextureField = implicitTextureField is null ? null : (implicitTextureField[0], implicitTextureField[1]);
ImplicitSamplerField = implicitSamplerFields is null ? null : (implicitSamplerFields[0], implicitSamplerFields[1]);
Fields = fields.Cast<string[]>().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2]));
ForwardDeclarations = forwardDeclarations;
ExecuteMethod = executeMethod;
Methods = methods;
Defines = defines.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
StaticFields = staticFields.Cast<string?[]>().ToDictionary(static arg => arg[0]!, static arg => (arg[1]!, arg[2]));
SharedBuffers = sharedBuffers.Cast<object[]>().ToDictionary(static t => (string)t[0], static t => ((string)t[1], (int?)t[2]));
}
/// <summary>
/// Gets the type of the current shader.
/// </summary>
internal Type ShaderType { get; }
/// <summary>
/// Gets the collection of processed custom types.
/// </summary>
internal IReadOnlyCollection<string> Types { get; }
/// <summary>
/// Gets the mapping for the implicit texture field, if the shader is a pixel shader.
/// </summary>
internal (string Name, string Type)? ImplicitTextureField { get; }
/// <summary>
/// Gets the mapping for the implicit sampler field, if necessary.
/// </summary>
internal (string Name, string Type)? ImplicitSamplerField { get; }
/// <summary>
/// Gets the mapping of field names.
/// </summary>
internal IReadOnlyDictionary<string, (string Name, string Type)> Fields { get; }
/// <summary>
/// The forward declarations for static methods.
/// </summary>
internal IReadOnlyCollection<string> ForwardDeclarations { get; }
/// <summary>
/// Gets the source code for the <see cref="IComputeShader.Execute"/> method.
/// </summary>
internal string ExecuteMethod { get; }
/// <summary>
/// Gets the collection of processed methods.
/// </summary>
internal IReadOnlyCollection<string> Methods { get; }
/// <summary>
/// Gets the collection of discovered define declarations.
/// </summary>
internal IReadOnlyDictionary<string, string> Defines { get; }
/// <summary>
/// Gets the collection of discovered static fields.
/// </summary>
internal IReadOnlyDictionary<string, (string TypeDeclaration, string? Assignment)> StaticFields { get; }
/// <summary>
/// Gets the collection of discovered shared buffers.
/// </summary>
internal IReadOnlyDictionary<string, (string Type, int? Count)> SharedBuffers { get; }
/// <summary>
/// Gets the associated <see cref="IComputeShaderSourceAttribute"/> instance for a specified type.
/// </summary>
/// <typeparam name="T">The shader type to get the attribute for.</typeparam>
/// <returns>The associated <see cref="IComputeShaderSourceAttribute"/> instance for type <typeparamref name="T"/>.</returns>
[Pure]
internal static IComputeShaderSourceAttribute GetForType<T>()
{
IEnumerable<IComputeShaderSourceAttribute> attributes = typeof(T).Assembly.GetCustomAttributes<IComputeShaderSourceAttribute>();
IComputeShaderSourceAttribute? attribute = attributes.SingleOrDefault(static attribute => attribute.ShaderType == typeof(T));
if (attribute is null)
{
MissingShaderMetadataException.Throw<T>();
}
return attribute!;
}
}
}
@@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
namespace ComputeSharp.__Internals
{
/// <inheritdoc/>
public sealed partial class ShaderMethodSourceAttribute : Attribute
{
/// <summary>
/// Appends the mapped source code for the current method.
/// </summary>
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
/// <param name="mapping">The mapping of already discovered constant names.</param>
public void AppendConstants(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
{
foreach (KeyValuePair<string, string> constant in this.constants)
{
if (mapping.Add(constant.Key))
{
builder.Append($"#define {constant.Key} {constant.Value}\n");
}
}
}
/// <summary>
/// Appends the discovered types for the current method.
/// </summary>
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
/// <param name="mapping">The mapping of already discovered type names.</param>
public void AppendTypes(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
{
foreach (KeyValuePair<string, string> type in this.types)
{
if (mapping.Add(type.Key))
{
builder.Append("\n");
builder.Append(type.Value);
builder.Append("\n");
}
}
}
/// <summary>
/// Appends the discovered forward declarations for the current method.
/// </summary>
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
/// <param name="mapping">The mapping of already discovered type names.</param>
public void AppendForwardDeclarations(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
{
foreach (KeyValuePair<string, string> method in this.methods)
{
if (mapping.Add(method.Key))
{
builder.Append("\n");
builder.Append(method.Key);
builder.Append("\n");
}
}
}
/// <summary>
/// Appends the discovered methods for the current method.
/// </summary>
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
/// <param name="mapping">The mapping of already discovered type names.</param>
public void AppendMethods(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
{
foreach (KeyValuePair<string, string> method in this.methods)
{
if (mapping.Remove(method.Key))
{
builder.Append("\n");
builder.Append(method.Value);
builder.Append("\n");
}
}
}
/// <summary>
/// Appends the mapped source code for the current method.
/// </summary>
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
/// <param name="name">The name to bind the method to.</param>
public void AppendMappedInvokeMethod(ref ArrayPoolStringBuilder builder, string name)
{
builder.Append(this.invokeMethod.Replace(InvokeMethodIdentifier, name));
}
}
}
+44 -46
ファイルの表示
@@ -5,7 +5,6 @@ using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using ComputeSharp.Core.Extensions;
using ComputeSharp.Exceptions;
namespace ComputeSharp.__Internals
{
@@ -17,78 +16,67 @@ namespace ComputeSharp.__Internals
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This attribute is not intended to be used directly by user code")]
public sealed class ShaderMethodSourceAttribute : Attribute
public sealed partial class ShaderMethodSourceAttribute : Attribute
{
/// <summary>
/// The identifier for the invoke method, for late binding.
/// </summary>
internal const string InvokeMethodIdentifier = "__<NAME>__";
/// <summary>
/// The fully qualified name of the current method.
/// </summary>
private readonly string methodName;
/// <summary>
/// The source code for the target entry point method.
/// </summary>
private readonly string invokeMethod;
/// <summary>
/// The collection of custom types.
/// </summary>
private readonly Dictionary<string, string> types;
/// <summary>
/// The collection of processed methods.
/// </summary>
private readonly Dictionary<string, string> methods;
/// <summary>
/// The collection of discovered constants.
/// </summary>
private readonly Dictionary<string, string> constants;
/// <summary>
/// Creates a new <see cref="ShaderMethodSourceAttribute"/> instance with the specified parameters.
/// </summary>
/// <param name="methodName">The fully qualified name of the current method.</param>
/// <param name="types">The collection of custom types.</param>
/// <param name="invokeMethod">The source code for the target entry point method.</param>
/// <param name="types">The collection of custom types.</param>
/// <param name="methods">The collection of processed methods.</param>
/// <param name="constants">The collection of discovered constants.</param>
public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods, object[] constants)
public ShaderMethodSourceAttribute(string methodName, string invokeMethod, object[] types, object[] methods, object[] constants)
{
this.methodName = methodName;
this.invokeMethod = invokeMethod;
MethodName = methodName;
Types = types;
Methods = methods;
Constants = constants.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
}
/// <summary>
/// Gets the fully qualified name of the shader type.
/// </summary>
internal string MethodName { get; }
/// <summary>
/// Gets the collection of processed custom types.
/// </summary>
internal IReadOnlyCollection<string> Types { get; }
/// <summary>
/// Gets the collection of processed methods.
/// </summary>
internal IReadOnlyCollection<string> Methods { get; }
/// <summary>
/// Gets the collection of discovered constants.
/// </summary>
internal IReadOnlyDictionary<string, string> Constants { get; }
/// <summary>
/// Gets the mapped source code for the current method.
/// </summary>
/// <param name="name">The name to bind the method to.</param>
/// <returns>The mapped source code for the current mehtod.</returns>
[Pure]
internal string GetMappedInvokeMethod(string name)
{
return this.invokeMethod.Replace(InvokeMethodIdentifier, name);
this.types = types.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
this.methods = methods.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
this.constants = constants.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
}
/// <summary>
/// Gets the associated <see cref="ShaderMethodSourceAttribute"/> instance for a specified delegate.
/// </summary>
/// <param name="function">The input <see cref="Delegate"/> instance to get info for.</param>
/// <param name="name">The name of the shader field containing <paramref name="function"/>.</param>
/// <returns>The associated <see cref="ShaderMethodSourceAttribute"/> instance for the given delegate.</returns>
[Pure]
internal static ShaderMethodSourceAttribute GetForDelegate(Delegate function)
public static ShaderMethodSourceAttribute GetForDelegate(Delegate function, string name)
{
if (!function.Method.IsStatic)
{
ThrowArgumentExceptionForNonStaticShader();
return ThrowArgumentExceptionForNonStaticMethod(name);
}
var attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes<ShaderMethodSourceAttribute>();
@@ -96,21 +84,31 @@ namespace ComputeSharp.__Internals
foreach (var attribute in attributes)
{
if (attribute.MethodName.Equals(methodName))
if (attribute.methodName.Equals(methodName))
{
return attribute;
}
}
return MissingMethodSourceException.Throw(function);
return ThrowArgumentExceptionForMissingShaderMethodAttribute(name);
}
/// <summary>
/// Throws an <see cref="ArgumentException"/> when a given <see cref="Delegate"/> is not static.
/// </summary>
private static void ThrowArgumentExceptionForNonStaticShader()
/// <param name="name">The name of the shader field containing the invalid method.</param>
private static ShaderMethodSourceAttribute ThrowArgumentExceptionForNonStaticMethod(string name)
{
throw new ArgumentException("Captured delegates in a shader need to wrap a static method.", "function");
throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a non static method (only static methods are supported for captured delegates).", name);
}
/// <summary>
/// Throws an <see cref="ArgumentException"/> when a given <see cref="Delegate"/> doesn't have <see cref="ShaderMethodAttribute"/> applied to it.
/// </summary>
/// <param name="name">The name of the shader field containing the invalid method.</param>
private static ShaderMethodSourceAttribute ThrowArgumentExceptionForMissingShaderMethodAttribute(string name)
{
throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a method without the [ShaderMethod] attribute applied to it.", name);
}
}
}
-53
ファイルの表示
@@ -1,53 +0,0 @@
using System;
using System.Diagnostics.Contracts;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.Core.Extensions;
#pragma warning disable CS0618
namespace ComputeSharp.Exceptions
{
/// <summary>
/// A custom <see cref="InvalidOperationException"/> that indicates when an HLSL-only API is called from C#
/// </summary>
public sealed class MissingMethodSourceException : InvalidOperationException
{
/// <summary>
/// Creates a new <see cref="MissingMethodSourceException"/> instance.
/// </summary>
/// <param name="message">The exception message to display.</param>
private MissingMethodSourceException(string message)
: base(message)
{
}
/// <summary>
/// Creates a new <see cref="MissingMethodSourceException"/> instance from the specified parameters.
/// </summary>
/// <param name="method">The target <see cref="Delegate"/> that couldn't be processed.</param>
/// <returns>A new <see cref="MissingMethodSourceException"/> instance with a formatted error message.</returns>
[Pure]
private static MissingMethodSourceException Create(Delegate method)
{
StringBuilder builder = new(512);
builder.AppendLine("The processed source for a method captured as a delegate in a shader was not found.");
builder.AppendLine($"The delegate was of type {method.GetType()} and it was wrapping the method {method.Method.GetFullName()}.");
builder.Append($"Make sure that the target method is annotated with [{nameof(ShaderMethodAttribute)}].");
builder.ToString();
return new(builder.ToString());
}
/// <summary>
/// Throws a new <see cref="MissingMethodSourceException"/> for a given delegate.
/// </summary>
/// <param name="method">The target <see cref="Delegate"/> that couldn't be processed.</param>
/// <returns>This method always throws and never actually returns anything.</returns>
internal static ShaderMethodSourceAttribute Throw(Delegate method)
{
throw Create(method);
}
}
}
-47
ファイルの表示
@@ -1,47 +0,0 @@
using System;
using System.Diagnostics.Contracts;
using System.Text;
namespace ComputeSharp.Exceptions
{
/// <summary>
/// A custom <see cref="Exception"/> type that indicates when metadata is missing for a given shader.
/// </summary>
public sealed class MissingShaderMetadataException : Exception
{
/// <summary>
/// Creates a new <see cref="MissingShaderMetadataException"/> instance.
/// </summary>
/// <param name="error">The error message to include in the exception..</param>
private MissingShaderMetadataException(string error)
: base(error)
{
}
/// <summary>
/// Gets a formatted exception message for a given error.
/// </summary>
/// <param name="type">The type of shader that was failed to be loaded.</param>
/// <returns>A new <see cref="MissingShaderMetadataException"/> instance with a formatted error message.</returns>
[Pure]
private static MissingShaderMetadataException Create(Type type)
{
StringBuilder builder = new(512);
builder.AppendLine($"Failed to retrieve the shader metadata for type {type}.");
builder.AppendLine("This usually indicates that the necessary source generator failed to run. Make sure to be using a IDE with full support " +
"for source generators, and that there are no build warnings in the errors window upon building your project. If a source " +
"generator fails to run correctly, please open an issue at https://github.com/Sergio0694/ComputeSharp and include a working repro along with it.");
return new(builder.ToString());
}
/// <summary>
/// Throws a new <see cref="MissingShaderMetadataException"/> for a given delegate.
/// </summary>
internal static void Throw<T>()
{
throw Create(typeof(T));
}
}
}
+2 -2
ファイルの表示
@@ -23,10 +23,10 @@ namespace ComputeSharp.Core.Extensions
{
var arguments = string.Join(", ", method.GetGenericArguments().Select(static t => t.FullName));
return $"{method.DeclaringType!.FullName}.{method.Name}<{arguments}>({parameters})";
return $"{method.DeclaringType!.FullName!.Replace('+', '.')}.{method.Name}<{arguments}>({parameters})";
}
return $"{method.DeclaringType!.FullName}.{method.Name}({parameters})";
return $"{method.DeclaringType!.FullName!.Replace('+', '.')}.{method.Name}({parameters})";
}
}
}
+25
ファイルの表示
@@ -0,0 +1,25 @@
using System;
using System.ComponentModel;
namespace ComputeSharp.__Internals
{
/// <summary>
/// A base <see langword="interface"/> representing a data loader for a shader being dispatched.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This interface is not intended to be used directly by user code")]
public interface IDispatchDataLoader
{
/// <summary>
/// Loads the captured values used by the shader to be dispatched.
/// </summary>
/// <param name="data">The sequence of serialized captured values.</param>
void LoadCapturedValues(ReadOnlySpan<uint> data);
/// <summary>
/// Loads the captured resources used by the shader to be dispatched.
/// </summary>
/// <param name="data">The sequence of serialized resources.</param>
void LoadCapturedResources(ReadOnlySpan<ulong> data);
}
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
using System;
using System.ComponentModel;
namespace ComputeSharp.__Internals
{
/// <summary>
/// A base <see langword="interface"/> representing a metadatadata loader for a shader being dispatched.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This interface is not intended to be used directly by user code")]
public interface IDispatchMetadataLoader
{
/// <summary>
/// Loads an opaque metadata handle from the given shader metadata.
/// </summary>
/// <param name="serializedMetadata">The serialized metadata for the current shader.</param>
/// <param name="resourceDescriptors">The sequence of resource descriptors for the current shader.</param>
/// <param name="result">The resulting opaque metadata handle.</param>
void LoadMetadataHandle(ReadOnlySpan<byte> serializedMetadata, ReadOnlySpan<ResourceDescriptor> resourceDescriptors, out IntPtr result);
}
}
+59
ファイルの表示
@@ -0,0 +1,59 @@
using System;
using System.ComponentModel;
namespace ComputeSharp.__Internals
{
/// <summary>
/// A base <see langword="interface"/> representing a given shader that can be dispatched.
/// </summary>
/// <typeparam name="TSelf">The type of shader.</typeparam>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This interface is not intended to be used directly by user code")]
public interface IShader<TSelf>
where TSelf : struct, IShader<TSelf>
{
/// <summary>
/// Gets a unique dispatch identifier for the shader.
/// </summary>
/// <returns>The unique dispatch identifier for the shader.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be used directly by user code")]
int GetDispatchId();
/// <summary>
/// Loads the dispatch data for the shader.
/// </summary>
/// <typeparam name="TDataLoader">The type of data loader being used.</typeparam>
/// <param name="loader">The <typeparamref name="TDataLoader"/> instance to use to load the data.</param>
/// <param name="device">The device the shader is being dispatched on.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
void LoadDispatchData<TDataLoader>(ref TDataLoader loader, GraphicsDevice device, int x, int y, int z)
where TDataLoader : struct, IDispatchDataLoader;
/// <summary>
/// Loads an opaque metadata handle from the metadata of the current shader.
/// </summary>
/// <typeparam name="TMetadataLoader">The type of data loader being used.</typeparam>
/// <param name="loader">The <typeparamref name="TMetadataLoader"/> instance to use to load the data.</param>
/// <param name="result">The resulting opaque metadata handle.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
void LoadDispatchMetadata<TMetadataLoader>(ref TMetadataLoader loader, out IntPtr result)
where TMetadataLoader : struct, IDispatchMetadataLoader;
/// <summary>
/// Builds the HLSL source code for the current shader instance.
/// </summary>
/// <param name="builder">The resulting <see cref="ArrayPoolStringBuilder"/> instance containing the HLSL source.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
void BuildHlslString(out ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ);
}
}
+9 -11
ファイルの表示
@@ -1,9 +1,7 @@
using System;
using System.Diagnostics.Contracts;
using ComputeSharp.Shaders;
using ComputeSharp.__Internals;
using ComputeSharp.Graphics.Helpers;
using ComputeSharp.Resources;
using ComputeSharp.Shaders;
#pragma warning disable CS0618
namespace ComputeSharp
{
@@ -20,7 +18,7 @@ namespace ComputeSharp
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(this GraphicsDevice device, int x, in T shader)
where T : struct, IComputeShader
where T : struct, IComputeShader, IShader<T>
{
ShaderRunner<T>.Run(device, x, 1, 1, in shader);
}
@@ -34,7 +32,7 @@ namespace ComputeSharp
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(this GraphicsDevice device, int x, int y, in T shader)
where T : struct, IComputeShader
where T : struct, IComputeShader, IShader<T>
{
ShaderRunner<T>.Run(device, x, y, 1, in shader);
}
@@ -49,7 +47,7 @@ namespace ComputeSharp
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(this GraphicsDevice device, int x, int y, int z, in T shader)
where T : struct, IComputeShader
where T : struct, IComputeShader, IShader<T>
{
ShaderRunner<T>.Run(device, x, y, z, in shader);
}
@@ -67,7 +65,7 @@ namespace ComputeSharp
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(this GraphicsDevice device, int x, int y, int z, int threadsX, int threadsY, int threadsZ, in T shader)
where T : struct, IComputeShader
where T : struct, IComputeShader, IShader<T>
{
ShaderRunner<T>.Run(device, x, y, z, threadsX, threadsY, threadsZ, in shader);
}
@@ -80,7 +78,7 @@ namespace ComputeSharp
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="texture">The target texture to apply the pixel shader to.</param>
public static void ForEach<T, TPixel>(this GraphicsDevice device, IReadWriteTexture2D<TPixel> texture)
where T : struct, IPixelShader<TPixel>
where T : struct, IPixelShader<TPixel>, IShader<T>
where TPixel : unmanaged
{
ShaderRunner<T>.Run(device, texture, default);
@@ -95,7 +93,7 @@ namespace ComputeSharp
/// <param name="texture">The target texture to apply the pixel shader to.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the pixel shader to run.</param>
public static void ForEach<T, TPixel>(this GraphicsDevice device, IReadWriteTexture2D<TPixel> texture, in T shader)
where T : struct, IPixelShader<TPixel>
where T : struct, IPixelShader<TPixel>, IShader<T>
where TPixel : unmanaged
{
ShaderRunner<T>.Run(device, texture, in shader);
-18
ファイルの表示
@@ -34,8 +34,6 @@ namespace ComputeSharp.__Internals
/// <param name="buffer">The input <see cref="Buffer{T}"/> instance to check.</param>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <returns>The GPU descriptor handle for the buffer.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ValidateAndGetGpuDescriptorHandle<T>(Buffer<T> buffer, GraphicsDevice device)
where T : unmanaged
@@ -53,8 +51,6 @@ namespace ComputeSharp.__Internals
/// <param name="texture">The input <see cref="ReadOnlyTexture2D{T}"/> instance to check.</param>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <returns>The GPU descriptor handle for the texture.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ValidateAndGetGpuDescriptorHandle<T>(ReadOnlyTexture2D<T> texture, GraphicsDevice device)
where T : unmanaged
@@ -72,8 +68,6 @@ namespace ComputeSharp.__Internals
/// <param name="texture">The input <see cref="ReadWriteTexture2D{T}"/> instance to check.</param>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <returns>The GPU descriptor handle for the texture.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ValidateAndGetGpuDescriptorHandle<T>(ReadWriteTexture2D<T> texture, GraphicsDevice device)
where T : unmanaged
@@ -91,8 +85,6 @@ namespace ComputeSharp.__Internals
/// <param name="texture">The input <see cref="IReadOnlyTexture2D{TPixel}"/> instance to check.</param>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <returns>The GPU descriptor handle for the texture.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe ulong ValidateAndGetGpuDescriptorHandle<TPixel>(IReadOnlyTexture2D<TPixel> texture, GraphicsDevice device)
where TPixel : unmanaged
@@ -114,8 +106,6 @@ namespace ComputeSharp.__Internals
/// <param name="texture">The input <see cref="IReadWriteTexture2D{TPixel}"/> instance to check.</param>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <returns>The GPU descriptor handle for the texture.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe ulong ValidateAndGetGpuDescriptorHandle<TPixel>(IReadWriteTexture2D<TPixel> texture, GraphicsDevice device)
where TPixel : unmanaged
@@ -137,8 +127,6 @@ namespace ComputeSharp.__Internals
/// <param name="texture">The input <see cref="ReadOnlyTexture3D{T}"/> instance to check.</param>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <returns>The GPU descriptor handle for the texture.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ValidateAndGetGpuDescriptorHandle<T>(ReadOnlyTexture3D<T> texture, GraphicsDevice device)
where T : unmanaged
@@ -156,8 +144,6 @@ namespace ComputeSharp.__Internals
/// <param name="texture">The input <see cref="ReadWriteTexture3D{T}"/> instance to check.</param>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <returns>The GPU descriptor handle for the texture.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ValidateAndGetGpuDescriptorHandle<T>(ReadWriteTexture3D<T> texture, GraphicsDevice device)
where T : unmanaged
@@ -175,8 +161,6 @@ namespace ComputeSharp.__Internals
/// <param name="texture">The input <see cref="IReadOnlyTexture3D{TPixel}"/> instance to check.</param>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <returns>The GPU descriptor handle for the texture.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe ulong ValidateAndGetGpuDescriptorHandle<TPixel>(IReadOnlyTexture3D<TPixel> texture, GraphicsDevice device)
where TPixel : unmanaged
@@ -198,8 +182,6 @@ namespace ComputeSharp.__Internals
/// <param name="texture">The input <see cref="IReadWriteTexture3D{TPixel}"/> instance to check.</param>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <returns>The GPU descriptor handle for the texture.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe ulong ValidateAndGetGpuDescriptorHandle<TPixel>(IReadWriteTexture3D<TPixel> texture, GraphicsDevice device)
where TPixel : unmanaged
+52
ファイルの表示
@@ -0,0 +1,52 @@
using System;
using System.ComponentModel;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_FLAGS;
#pragma warning disable IDE0052, CS0414
namespace ComputeSharp.__Internals
{
/// <summary>
/// An opaque type describing a captured resource to be used in a shader.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This interface is not intended to be used directly by user code")]
public struct ResourceDescriptor
{
/// <inheritdoc cref="D3D12_DESCRIPTOR_RANGE1.RangeType"/>
private D3D12_DESCRIPTOR_RANGE_TYPE RangeType;
/// <inheritdoc cref="D3D12_DESCRIPTOR_RANGE1.NumDescriptors"/>
private uint NumDescriptors;
/// <inheritdoc cref="D3D12_DESCRIPTOR_RANGE1.BaseShaderRegister"/>
private uint BaseShaderRegister;
/// <inheritdoc cref="D3D12_DESCRIPTOR_RANGE1.RegisterSpace"/>
private uint RegisterSpace;
/// <inheritdoc cref="D3D12_DESCRIPTOR_RANGE1.Flags"/>
private D3D12_DESCRIPTOR_RANGE_FLAGS Flags;
/// <inheritdoc cref="D3D12_DESCRIPTOR_RANGE1.OffsetInDescriptorsFromTableStart"/>
private uint OffsetInDescriptorsFromTableStart;
/// <summary>
/// Initializes a new <see cref="ResourceDescriptor"/> instance.
/// </summary>
/// <param name="type">The type of resource to create the descriptor for.</param>
/// <param name="offset">The offset in the resource from the start of the shader mapping.</param>
/// <param name="descriptor">The resulting <see cref="ResourceDescriptor"/> instance.</param>
public static void Create(int type, uint offset, out ResourceDescriptor descriptor)
{
descriptor.RangeType = (D3D12_DESCRIPTOR_RANGE_TYPE)type;
descriptor.NumDescriptors = 1;
descriptor.BaseShaderRegister = offset;
descriptor.RegisterSpace = 0;
descriptor.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE;
descriptor.OffsetInDescriptorsFromTableStart = FX.D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
}
}
}
+57
ファイルの表示
@@ -0,0 +1,57 @@
using System;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.__Internals;
using TerraFX.Interop;
using System.Runtime.InteropServices;
#pragma warning disable CS0618
namespace ComputeSharp.Shaders.Dispatching
{
/// <summary>
/// A data loader for compute shaders.
/// </summary>
internal readonly unsafe struct ComputeShaderDispatchDataLoader : IDispatchDataLoader
{
/// <summary>
/// The <see cref="ID3D12GraphicsCommandList"/> object in use.
/// </summary>
private readonly ID3D12GraphicsCommandList* d3D12GraphicsCommandList;
/// <summary>
/// Creates a new <see cref="ComputeShaderDispatchDataLoader"/> instance.
/// </summary>
/// <param name="d3D12GraphicsCommandList">The <see cref="ID3D12GraphicsCommandList"/> object to use.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ComputeShaderDispatchDataLoader(ID3D12GraphicsCommandList* d3D12GraphicsCommandList)
{
this.d3D12GraphicsCommandList = d3D12GraphicsCommandList;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void LoadCapturedValues(ReadOnlySpan<uint> data)
{
this.d3D12GraphicsCommandList->SetComputeRoot32BitConstants(data);
}
/// <inheritdoc/>
public void LoadCapturedResources(ReadOnlySpan<ulong> data)
{
ID3D12GraphicsCommandList* d3D12GraphicsCommandList = this.d3D12GraphicsCommandList;
ref ulong resourcesRef = ref MemoryMarshal.GetReference(data);
ref D3D12_GPU_DESCRIPTOR_HANDLE startRef = ref Unsafe.As<ulong, D3D12_GPU_DESCRIPTOR_HANDLE>(ref resourcesRef);
ref D3D12_GPU_DESCRIPTOR_HANDLE endRef = ref Unsafe.Add(ref startRef, data.Length);
uint offset = 1;
while (Unsafe.IsAddressLessThan(ref startRef, ref endRef))
{
d3D12GraphicsCommandList->SetComputeRootDescriptorTable(offset, startRef);
startRef = ref Unsafe.Add(ref startRef, 1);
offset++;
}
}
}
}
+61
ファイルの表示
@@ -0,0 +1,61 @@
using System;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.__Internals;
using TerraFX.Interop;
using System.Runtime.InteropServices;
#pragma warning disable CS0618
namespace ComputeSharp.Shaders.Dispatching
{
/// <summary>
/// A data loader for pixel shaders.
/// </summary>
internal readonly unsafe struct PixelShaderDispatchDataLoader : IDispatchDataLoader
{
/// <summary>
/// The <see cref="ID3D12GraphicsCommandList"/> object in use.
/// </summary>
private readonly ID3D12GraphicsCommandList* d3D12GraphicsCommandList;
/// <summary>
/// Creates a new <see cref="PixelShaderDispatchDataLoader"/> instance.
/// </summary>
/// <param name="d3D12GraphicsCommandList">The <see cref="ID3D12GraphicsCommandList"/> object to use.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal PixelShaderDispatchDataLoader(ID3D12GraphicsCommandList* d3D12GraphicsCommandList)
{
this.d3D12GraphicsCommandList = d3D12GraphicsCommandList;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void LoadCapturedValues(ReadOnlySpan<uint> data)
{
this.d3D12GraphicsCommandList->SetComputeRoot32BitConstants(data);
}
/// <inheritdoc/>
public void LoadCapturedResources(ReadOnlySpan<ulong> data)
{
ID3D12GraphicsCommandList* d3D12GraphicsCommandList = this.d3D12GraphicsCommandList;
ref ulong resourcesRef = ref MemoryMarshal.GetReference(data);
ref D3D12_GPU_DESCRIPTOR_HANDLE startRef = ref Unsafe.As<ulong, D3D12_GPU_DESCRIPTOR_HANDLE>(ref resourcesRef);
ref D3D12_GPU_DESCRIPTOR_HANDLE endRef = ref Unsafe.Add(ref startRef, data.Length);
uint offset = 2;
// Skip the first target resource, as that is loaded explicitly by the shader runner using the
// target texture passed in by the user, which is not actually captured by the shader itself.
// The target root descriptor table index is therefore 2 in this case, as it needs to skip not
// only the this implicit texture to draw on, but also the constant buffer with capture values.
while (Unsafe.IsAddressLessThan(ref startRef, ref endRef))
{
d3D12GraphicsCommandList->SetComputeRootDescriptorTable(offset, startRef);
startRef = ref Unsafe.Add(ref startRef, 1);
offset++;
}
}
}
}
+47
ファイルの表示
@@ -0,0 +1,47 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Shaders.Extensions;
using ComputeSharp.__Internals;
using Microsoft.Toolkit.Diagnostics;
using TerraFX.Interop;
#pragma warning disable CS0618
namespace ComputeSharp.Shaders.Dispatching
{
/// <summary>
/// A data loader for compute shaders.
/// </summary>
internal readonly unsafe struct ShaderDispatchMetadataLoader : IDispatchMetadataLoader
{
/// <summary>
/// The <see cref="ID3D12Device"/> object in use.
/// </summary>
private readonly ID3D12Device* d3D12Device;
/// <summary>
/// Creates a new <see cref="ShaderDispatchMetadataLoader"/> instance.
/// </summary>
/// <param name="d3D12Device">The <see cref="ID3D12Device"/> object to use.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ShaderDispatchMetadataLoader(ID3D12Device* d3D12Device)
{
this.d3D12Device = d3D12Device;
}
/// <inheritdoc/>
public unsafe void LoadMetadataHandle(ReadOnlySpan<byte> serializedMetadata, ReadOnlySpan<ResourceDescriptor> resourceDescriptors, out IntPtr result)
{
Guard.HasSizeEqualTo(serializedMetadata, 5, nameof(serializedMetadata));
fixed (IntPtr* p = &result)
{
*(ComPtr<ID3D12RootSignature>*)p = this.d3D12Device->CreateRootSignature(
MemoryMarshal.Read<int>(serializedMetadata),
MemoryMarshal.Cast<ResourceDescriptor, D3D12_DESCRIPTOR_RANGE1>(resourceDescriptors),
MemoryMarshal.Read<bool>(serializedMetadata[4..]));
}
}
}
}
+12 -9
ファイルの表示
@@ -1,11 +1,13 @@
using System;
using System.Runtime.CompilerServices;
using ComputeSharp.__Internals;
using ComputeSharp.Core.Extensions;
using ComputeSharp.Shaders.Renderer;
using ComputeSharp.Shaders.Translation;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
#pragma warning disable CS0618
namespace ComputeSharp.Interop
{
/// <summary>
@@ -28,7 +30,7 @@ namespace ComputeSharp.Interop
/// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead.
/// </remarks>
public static void GetShaderInfo<T>(out ShaderInfo shaderInfo)
where T : struct, IComputeShader
where T : struct, IComputeShader, IShader<T>
{
GetNonGenericShaderInfo(default(T), out shaderInfo);
}
@@ -45,7 +47,7 @@ namespace ComputeSharp.Interop
/// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead.
/// </remarks>
public static unsafe void GetShaderInfo<T>(in T shader, out ShaderInfo shaderInfo)
where T : struct, IComputeShader
where T : struct, IComputeShader, IShader<T>
{
GetNonGenericShaderInfo(in shader, out shaderInfo);
}
@@ -66,7 +68,7 @@ namespace ComputeSharp.Interop
/// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead.
/// </remarks>
public static void GetShaderInfo<T, TPixel>(out ShaderInfo shaderInfo)
where T : struct, IPixelShader<TPixel>
where T : struct, IPixelShader<TPixel>, IShader<T>
where TPixel : unmanaged
{
GetNonGenericShaderInfo(default(T), out shaderInfo);
@@ -85,7 +87,7 @@ namespace ComputeSharp.Interop
/// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead.
/// </remarks>
public static unsafe void GetShaderInfo<T, TPixel>(in T shader, out ShaderInfo shaderInfo)
where T : struct, IPixelShader<TPixel>
where T : struct, IPixelShader<TPixel>, IShader<T>
where TPixel : unmanaged
{
GetNonGenericShaderInfo(in shader, out shaderInfo);
@@ -98,15 +100,16 @@ namespace ComputeSharp.Interop
/// <param name="shader">The input shader to retrieve info for.</param>
/// <param name="shaderInfo">The resulting <see cref="ShaderInfo"/> instance.</param>
private static unsafe void GetNonGenericShaderInfo<T>(in T shader, out ShaderInfo shaderInfo)
where T : struct
where T : struct, IShader<T>
{
ShaderLoader<T> shaderLoader = ShaderLoader<T>.Load(in shader);
using var shaderSource = HlslShaderRenderer.Render(1, 1, 1, shaderLoader);
shader.BuildHlslString(out ArrayPoolStringBuilder shaderSource, 1, 1, 1);
using ComPtr<IDxcBlob> dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan);
shaderSource.Dispose();
using ComPtr<IDxcUtils> dxcUtils = default;
Guid dxcLibraryClsid = FX.CLSID_DxcLibrary;
FX.DxcCreateInstance(&dxcLibraryClsid, FX.__uuidof<IDxcUtils>(), dxcUtils.GetVoidAddressOf()).Assert();
-356
ファイルの表示
@@ -1,356 +0,0 @@
using System;
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Shaders.Renderer.Models;
using ComputeSharp.Shaders.Translation;
namespace ComputeSharp.Shaders.Renderer
{
/// <summary>
/// A type that renders an HLSL template from the previously loaded shader data.
/// </summary>
internal static class HlslShaderRenderer
{
/// <summary>
/// Renders a new HLSL shader source with the given parameters.
/// </summary>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="info">The input <see cref="IShaderLoader"/> instance with the shader information.</param>
/// <returns>The source code for the new HLSL shader.</returns>
[Pure]
public static ArrayPoolStringBuilder Render(int threadsX, int threadsY, int threadsZ, IShaderLoader info)
{
var builder = ArrayPoolStringBuilder.Create();
// Header
builder.AppendLine("// ================================================");
builder.AppendLine("// AUTO GENERATED");
builder.AppendLine("// ================================================");
builder.AppendLine("// This shader was created by ComputeSharp.");
builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp.");
// Group size constants
builder.AppendLine();
builder.Append("#define __GroupSize__get_X ");
builder.AppendLine(threadsX.ToString());
builder.Append("#define __GroupSize__get_Y ");
builder.AppendLine(threadsY.ToString());
builder.Append("#define __GroupSize__get_Z ");
builder.AppendLine(threadsZ.ToString());
// Define declarations
foreach (var define in info.DefinesInfo)
{
builder.Append("#define ");
builder.Append(define.Key);
builder.Append(' ');
builder.AppendLine(define.Value);
}
// Static fields
if (info.StaticFields.Count > 0)
{
builder.AppendLine();
foreach (var constant in info.StaticFields)
{
builder.Append(constant.Value.TypeDeclaration);
builder.Append(' ');
builder.Append(constant.Key);
if (constant.Value.Assignment is string assignment)
{
builder.Append(" = ");
builder.Append(assignment);
}
builder.AppendLine(";");
}
}
// Declared types
foreach (var type in info.DeclaredTypes)
{
builder.AppendLine();
builder.AppendLine(type);
}
// Captured variables
builder.AppendLine();
builder.AppendLine("cbuffer _ : register(b0)");
builder.AppendLine('{');
builder.AppendLine(" uint __x;");
builder.AppendLine(" uint __y;");
if (info.IsComputeShader)
{
builder.AppendLine(" uint __z;");
}
foreach (var local in info.FieldsInfo)
{
builder.Append(" ");
builder.Append(local.FieldType);
builder.Append(' ');
builder.Append(local.FieldName);
builder.AppendLine(';');
}
builder.AppendLine('}');
// Resources
foreach (var resource in info.HlslResourceInfo)
{
builder.AppendLine();
switch (resource)
{
// Constant buffer go to cbuffer fields with a dummy local
case HlslResourceInfo.Constant _:
builder.Append("cbuffer _");
builder.Append(resource.FieldName);
builder.Append(" : register(b");
builder.Append(resource.RegisterIndex.ToString());
builder.AppendLine(')');
builder.AppendLine('{');
builder.Append(" ");
builder.Append(resource.FieldType);
builder.Append(' ');
builder.Append(resource.FieldName);
builder.AppendLine("[2];");
builder.AppendLine('}');
break;
// Structured buffer have the same syntax but different id
case HlslResourceInfo.ReadOnly _:
char registerId = 't';
goto StructuredBuffer;
case HlslResourceInfo.ReadWrite _:
registerId = 'u';
StructuredBuffer:
builder.Append(resource.FieldType);
builder.Append(' ');
builder.Append(resource.FieldName);
builder.Append(" : register(");
builder.Append(registerId);
builder.Append(resource.RegisterIndex.ToString());
builder.AppendLine(");");
break;
// Texture samplers
case HlslResourceInfo.Sampler _:
builder.Append(resource.FieldType);
builder.Append(' ');
builder.Append(resource.FieldName);
builder.Append(" : register(");
builder.Append('s');
builder.Append(resource.RegisterIndex.ToString());
builder.AppendLine(");");
break;
}
}
// Shared buffers
foreach (var buffer in info.SharedBuffers)
{
builder.AppendLine();
builder.Append("groupshared ");
builder.Append(buffer.Value.Type);
builder.Append(' ');
builder.Append(buffer.Key);
builder.Append('[');
if (buffer.Value.Count is int count) builder.Append(count.ToString());
else builder.Append((threadsX * threadsY * threadsZ).ToString());
builder.AppendLine("];");
}
// Forward declarations
foreach (var declaration in info.ForwardDeclarations)
{
builder.AppendLine();
builder.AppendLine(declaration);
}
// Captured methods
foreach (var function in info.MethodsInfo)
{
builder.AppendLine();
builder.AppendLine(function);
}
// Entry point
builder.AppendLine();
builder.AppendLine("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]");
builder.AppendLine(info.EntryPoint);
return builder;
}
/// <summary>
/// A helper type that implements a pooled buffer writer for <see cref="char"/> values.
/// </summary>
[DebuggerTypeProxy(typeof(DebugView))]
public ref struct ArrayPoolStringBuilder
{
/// <summary>
/// The underlying <see cref="char"/> array.
/// </summary>
private char[] array;
/// <summary>
/// The starting offset within <see cref="array"/>.
/// </summary>
private int index;
/// <summary>
/// Creates a new <see cref="ArrayPoolStringBuilder"/> instance ready to use.
/// </summary>
/// <returns>A new <see cref="ArrayPoolStringBuilder"/> instance with default values.</returns>
[Pure]
public static ArrayPoolStringBuilder Create()
{
ArrayPoolStringBuilder builder;
builder.array = ArrayPool<char>.Shared.Rent(1024);
builder.index = 0;
return builder;
}
/// <inheritdoc/>
public ReadOnlySpan<char> WrittenSpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new(this.array, 0, this.index);
}
/// <summary>
/// Appends the input sequence of characters to the current buffer.
/// </summary>
/// <param name="value">The input characters to write.</param>
public void Append(string value)
{
EnsureCapacity(value.Length);
value.AsSpan().CopyTo(this.array.AsSpan(this.index));
this.index += value.Length;
}
/// <summary>
/// Appends a character to the current buffer.
/// </summary>
public void Append(char character)
{
EnsureCapacity(1);
this.array[this.index++] = character;
}
/// <summary>
/// Appends the input sequence of characters to the current buffer, with a trailing new line.
/// </summary>
/// <param name="value">The input characters to write.</param>
public void AppendLine(string value)
{
EnsureCapacity(value.Length + 1);
value.AsSpan().CopyTo(this.array.AsSpan(this.index));
this.index += value.Length;
this.array[this.index++] = '\n';
}
/// <summary>
/// Appends a character and a new line to the current buffer.
/// </summary>
public void AppendLine(char character)
{
EnsureCapacity(2);
this.array[this.index++] = character;
this.array[this.index++] = '\n';
}
/// <summary>
/// Appends a new line to the current buffer.
/// </summary>
public void AppendLine()
{
EnsureCapacity(1);
this.array[this.index++] = '\n';
}
/// <summary>
/// Ensures that <see cref="array"/> has enough free space to contain a given number of new items.
/// </summary>
/// <param name="requestedSize">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCapacity(int requestedSize)
{
if (requestedSize > this.array.Length - this.index)
{
ResizeBuffer(requestedSize);
}
}
/// <summary>
/// Resizes <see cref="array"/> to ensure it can fit the specified number of new items.
/// </summary>
/// <param name="sizeHint">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void ResizeBuffer(int sizeHint)
{
int minimumSize = this.index + sizeHint;
// Rent a new array with the specified size, and copy as many items from the current array
// as possible to the new array. This mirrors the behavior of the Array.Resize API from
// the BCL: if the new size is greater than the length of the current array, copy all the
// items from the original array into the new one. Otherwise, copy as many items as possible,
// until the new array is completely filled, and ignore the remaining items in the first array.
char[] newArray = ArrayPool<char>.Shared.Rent(minimumSize);
int itemsToCopy = Math.Min(this.array.Length, minimumSize);
Array.Copy(this.array, 0, newArray, 0, itemsToCopy);
ArrayPool<char>.Shared.Return(array);
this.array = newArray;
}
/// <inheritdoc/>
public void Dispose()
{
ArrayPool<char>.Shared.Return(this.array);
}
/// <summary>
/// A debug proxy used for displaying debug info.
/// </summary>
internal sealed class DebugView
{
/// <summary>
/// Initializes a new instance of the <see cref="DebugView"/> class with the specified parameters.
/// </summary>
/// <param name="builder">The input <see cref="ArrayPoolStringBuilder"/> instance to display.</param>
public DebugView(ArrayPoolStringBuilder builder)
{
Text = builder.WrittenSpan.ToString();
}
/// <summary>
/// Gets the text to display for the current instance.
/// </summary>
public string Text { get; }
}
}
}
}
-11
ファイルの表示
@@ -1,11 +0,0 @@
#pragma warning disable CS1572, CS1573
namespace ComputeSharp.Shaders.Renderer.Models
{
/// <summary>
/// A model that contains info on a shader field.
/// </summary>
/// <param name="FieldType">The type of the current field in the HLSL shader.</param>
/// <param name="FieldName">The name to use for the current field.</param>
internal record CapturedFieldInfo(string FieldType, string FieldName);
}
-43
ファイルの表示
@@ -1,43 +0,0 @@
namespace ComputeSharp.Shaders.Renderer.Models
{
/// <summary>
/// A model that contains info on a shader resource field.
/// </summary>
/// <param name="FieldType">The type of the current field in the HLSL shader.</param>
/// <param name="FieldName">The name to use for the current field.</param>
/// <param name="RegisterIndex">The register index to bind the resource to.</param>
internal abstract record HlslResourceInfo(string FieldType, string FieldName, int RegisterIndex)
: CapturedFieldInfo(FieldType, FieldName)
{
/// <summary>
/// A model that represents a captured constant buffer in a shader.
/// </summary>
/// <inheritdoc/>
public sealed record Constant(string FieldType, string FieldName, int RegisterIndex)
: HlslResourceInfo(FieldType, FieldName, RegisterIndex);
/// <summary>
/// A model that represents a captured readonly typed resource in a shader.
/// Maps to either <see cref="ComputeSharp.ReadOnlyBuffer{T}"/> or <see cref="ComputeSharp.ReadOnlyTexture2D{T}"/>.
/// </summary>
/// <inheritdoc/>
public sealed record ReadOnly(string FieldType, string FieldName, int RegisterIndex)
: HlslResourceInfo(FieldType, FieldName, RegisterIndex);
/// <summary>
/// A model that represents a captured writeable buffer in a shader.
/// Maps to either <see cref="ComputeSharp.ReadWriteBuffer{T}"/> or <see cref="ComputeSharp.ReadWriteTexture2D{T}"/>.
/// </summary>
/// <inheritdoc/>
public sealed record ReadWrite(string FieldType, string FieldName, int RegisterIndex)
: HlslResourceInfo(FieldType, FieldName, RegisterIndex);
/// <summary>
/// A model that represents a captured sampler in a shader.
/// This resource type doesn't have a mapping to a public API.
/// </summary>
/// <inheritdoc/>
public sealed record Sampler(string FieldType, string FieldName, int RegisterIndex)
: HlslResourceInfo(FieldType, FieldName, RegisterIndex);
}
}
+26 -57
ファイルの表示
@@ -2,11 +2,9 @@
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Shaders.Dispatching;
using ComputeSharp.Shaders.Extensions;
using ComputeSharp.Shaders.Renderer;
using ComputeSharp.Shaders.Translation;
using ComputeSharp.Shaders.Translation.Interop;
using ComputeSharp.Shaders.Translation.Models;
using ComputeSharp.__Internals;
using Microsoft.Toolkit.Diagnostics;
@@ -23,12 +21,12 @@ namespace ComputeSharp.Shaders
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
internal static class ShaderRunner<T>
where T : struct
where T : struct, IShader<T>
{
/// <summary>
/// The mapping used to cache and reuse compiled shaders.
/// </summary>
private static readonly Dictionary<ShaderKey, CachedShader<T>> ShadersCache = new();
private static readonly Dictionary<ShaderKey, CachedShader> ShadersCache = new();
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
@@ -120,7 +118,6 @@ namespace ComputeSharp.Shaders
Guard.IsBetweenOrEqualTo(threadsZ, 1, 64, nameof(threadsZ));
Guard.IsLessThanOrEqualTo(threadsX * threadsY * threadsZ, 1024, "threadsXYZ");
// Calculate the dispatch values
int
groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1),
groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1),
@@ -130,15 +127,13 @@ namespace ComputeSharp.Shaders
Guard.IsBetweenOrEqualTo(groupsY, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX));
Guard.IsBetweenOrEqualTo(groupsZ, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX));
// Create the shader key
ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(in shader), threadsX, threadsY, threadsZ);
CachedShader<T> shaderData;
ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, threadsZ);
PipelineData? pipelineData;
lock (ShadersCache)
{
// Get or preload the shader
if (!ShadersCache.TryGetValue(key, out shaderData))
if (!ShadersCache.TryGetValue(key, out CachedShader? shaderData))
{
LoadShader(threadsX, threadsY, threadsZ, in shader, out shaderData);
@@ -153,27 +148,15 @@ namespace ComputeSharp.Shaders
}
}
// Create the commands list and set the pipeline state
using CommandList commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE);
commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature);
commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineData.D3D12PipelineState);
// Extract the dispatch data for the shader invocation
using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in shader, x, y, z);
ComputeShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList);
// Initialize the loop targets and the captured values
commandList.D3D12GraphicsCommandList->SetComputeRoot32BitConstants(dispatchData.Variables);
shader.LoadDispatchData(ref dataLoader, device, x, y, z);
ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> resources = dispatchData.Resources;
for (int i = 0; i < resources.Length; i++)
{
// Load the captured buffers
commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable((uint)i + 1, resources[i]);
}
// Dispatch and wait for completion
commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, (uint)groupsZ);
commandList.ExecuteAndWaitForCompletion();
}
@@ -202,14 +185,13 @@ namespace ComputeSharp.Shaders
Guard.IsBetweenOrEqualTo(groupsY, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX));
// Create the shader key
ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(in shader), threadsX, threadsY, 1);
CachedShader<T> shaderData;
ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, 1);
PipelineData? pipelineData;
lock (ShadersCache)
{
// Get or preload the shader
if (!ShadersCache.TryGetValue(key, out shaderData))
if (!ShadersCache.TryGetValue(key, out CachedShader? shaderData))
{
LoadShader(threadsX, threadsY, 1, in shader, out shaderData);
@@ -230,29 +212,15 @@ namespace ComputeSharp.Shaders
commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature);
commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineData.D3D12PipelineState);
// Extract the dispatch data for the shader invocation
using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in shader, x, y, 1);
PixelShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList);
// Initialize the loop targets and the captured values
commandList.D3D12GraphicsCommandList->SetComputeRoot32BitConstants(dispatchData.Variables);
shader.LoadDispatchData(ref dataLoader, device, x, y, 1);
// Load the implicit output texture
commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable(
1,
((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuDescriptorHandle(device));
// Skip the last (missing) resource, as the internal counter is exceeding the number of explicit
// resources that the shader has actually captured (since it includes the target texture too).
// For the same reason, the target root descriptor table index is also offset by 2, as it needs
// to skip not only the constant buffer with capture values, but the implicit texture as well.
ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> resources = dispatchData.Resources[..^1];
for (int i = 0; i < resources.Length; i++)
{
// Load the captured buffers
commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable((uint)i + 2, resources[i]);
}
// Dispatch and wait for completion
commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, 1);
commandList.ExecuteAndWaitForCompletion();
@@ -265,34 +233,35 @@ namespace ComputeSharp.Shaders
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
/// <param name="shaderData">The <see cref="CachedShader{T}"/> instance to return with the cached shader data.</param>
/// <param name="shaderData">The <see cref="CachedShader"/> instance to return with the cached shader data.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader<T> shaderData)
private static unsafe void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader shaderData)
{
// Load the input shader
ShaderLoader<T> shaderLoader = ShaderLoader<T>.Load(in shader);
shader.BuildHlslString(out ArrayPoolStringBuilder builder, threadsX, threadsY, threadsZ);
// Render the loaded shader
using var shaderSource = HlslShaderRenderer.Render(threadsX, threadsY, threadsZ, shaderLoader);
using ComPtr<IDxcBlob> dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(builder.WrittenSpan);
// Compile the loaded shader to HLSL bytecode
IDxcBlobObject shaderBytecode = new(ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan));
builder.Dispose();
// Get the cached shader data
shaderData = new CachedShader<T>(shaderLoader, shaderBytecode);
shaderData = new CachedShader(dxcBlobBytecode.Get());
}
/// <summary>
/// Creates and caches a <see cref="PipelineData"/> instance for a given shader.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="shaderData">The <see cref="CachedShader{T}"/> instance with the data on the loaded shader.</param>
/// <param name="shaderData">The <see cref="CachedShader"/> instance with the data on the loaded shader.</param>
/// <param name="pipelineData">The resulting <see cref="PipelineData"/> instance to use to run the shader.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe void CreatePipelineData(GraphicsDevice device, in CachedShader<T> shaderData, out PipelineData pipelineData)
private static unsafe void CreatePipelineData(GraphicsDevice device, CachedShader shaderData, out PipelineData pipelineData)
{
using ComPtr<ID3D12RootSignature> d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12Root32BitConstantsCount, shaderData.Loader.D3D12DescriptorRanges1, shaderData.Loader.IsStaticSamplerUsed);
using ComPtr<ID3D12PipelineState> d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.Bytecode.D3D12ShaderBytecode);
using ComPtr<ID3D12RootSignature> d3D12RootSignature = default;
ShaderDispatchMetadataLoader metadataLoader = new(device.D3D12Device);
default(T).LoadDispatchMetadata(ref metadataLoader, out *(IntPtr*)&d3D12RootSignature);
using ComPtr<ID3D12PipelineState> d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.D3D12ShaderBytecode);
pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get());
-61
ファイルの表示
@@ -1,61 +0,0 @@
using System.Collections.Generic;
using ComputeSharp.Shaders.Renderer.Models;
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> responsible for loading and processing shaders of any type.
/// </summary>
internal interface IShaderLoader
{
/// <summary>
/// Gets the generated source code for the method in the current shader.
/// </summary>
string EntryPoint { get; }
/// <summary>
/// Gets whether or not the current shader is a compute shader (and not a pixel shader).
/// </summary>
bool IsComputeShader { get; }
/// <summary>
/// Gets the collection of <see cref="Renderer.Models.HlslResourceInfo"/> items for the shader fields.
/// </summary>
IReadOnlyList<HlslResourceInfo> HlslResourceInfo { get; }
/// <summary>
/// Gets the collection of <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
IReadOnlyList<CapturedFieldInfo> FieldsInfo { get; }
/// <summary>
/// Gets the forward declarations for static methods.
/// </summary>
IReadOnlyCollection<string> ForwardDeclarations { get; }
/// <summary>
/// Gets the collection of methods to be used in the shader.
/// </summary>
IReadOnlyCollection<string> MethodsInfo { get; }
/// <summary>
/// Gets the collection of define declarations to be added to the shader.
/// </summary>
IReadOnlyDictionary<string, string> DefinesInfo { get; }
/// <summary>
/// Gets the collection of discovered static fields.
/// </summary>
IReadOnlyDictionary<string, (string TypeDeclaration, string? Assignment)> StaticFields { get; }
/// <summary>
/// Gets the collection of declared types for the shader.
/// </summary>
IReadOnlyCollection<string> DeclaredTypes { get; }
/// <summary>
/// Gets the collection of discovered group shared buffers.
/// </summary>
IReadOnlyDictionary<string, (string Type, int? Count)> SharedBuffers { get; }
}
}
-38
ファイルの表示
@@ -1,38 +0,0 @@
using ComputeSharp.Interop;
using TerraFX.Interop;
namespace ComputeSharp.Shaders.Translation.Interop
{
/// <summary>
/// An object wrapping an <see cref="IDxcBlob"/> instance.
/// </summary>
internal sealed unsafe class IDxcBlobObject : NativeObject
{
/// <summary>
/// The <see cref="IDxcBlob"/> instance currently in use.
/// </summary>
private ComPtr<IDxcBlob> dxcBlob;
/// <summary>
/// Creates a new <see cref="IDxcBlobObject"/> instance with the specified parameters.
/// </summary>
/// <param name="dxcBlob">The <see cref="IDxcBlob"/> instance to wrap.</param>
public IDxcBlobObject(ComPtr<IDxcBlob> dxcBlob)
{
this.dxcBlob = dxcBlob;
}
/// <summary>
/// Gets a raw pointer to the <see cref="IDxcBlob"/> instance in use.
/// </summary>
public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new((ID3DBlob*)this.dxcBlob.Get());
/// <inheritdoc/>
protected override bool OnDispose()
{
this.dxcBlob.Dispose();
return true;
}
}
}
-147
ファイルの表示
@@ -1,147 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Numerics;
namespace ComputeSharp.Shaders.Mappings
{
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL type names to common .NET types.
/// </summary>
internal static class HlslKnownTypes
{
/// <summary>
/// The set of HLSL vector types.
/// </summary>
private static HashSet<Type> HlslMappedVectorTypes { get; } = new(new[]
{
typeof(Bool2), typeof(Bool3), typeof(Bool4),
typeof(Int2), typeof(Int3), typeof(Int4),
typeof(UInt2), typeof(UInt3), typeof(UInt4),
typeof(Float2), typeof(Float3), typeof(Float4),
typeof(Double2), typeof(Double3), typeof(Double4)
});
/// <summary>
/// The set of HLSL matrix types.
/// </summary>
private static HashSet<Type> HlslMappedMatrixTypes { get; } = new(new[]
{
typeof(Bool1x1), typeof(Bool1x2), typeof(Bool1x3), typeof(Bool1x4),
typeof(Bool2x1), typeof(Bool2x2), typeof(Bool2x3), typeof(Bool2x4),
typeof(Bool3x1), typeof(Bool3x2), typeof(Bool3x3), typeof(Bool3x4),
typeof(Bool4x1), typeof(Bool4x2), typeof(Bool4x3), typeof(Bool4x4),
typeof(Int1x1), typeof(Int1x2), typeof(Int1x3), typeof(Int1x4),
typeof(Int2x1), typeof(Int2x2), typeof(Int2x3), typeof(Int2x4),
typeof(Int3x1), typeof(Int3x2), typeof(Int3x3), typeof(Int3x4),
typeof(Int4x1), typeof(Int4x2), typeof(Int4x3), typeof(Int4x4),
typeof(UInt1x1), typeof(UInt1x2), typeof(UInt1x3), typeof(UInt1x4),
typeof(UInt2x1), typeof(UInt2x2), typeof(UInt2x3), typeof(UInt2x4),
typeof(UInt3x1), typeof(UInt3x2), typeof(UInt3x3), typeof(UInt3x4),
typeof(UInt4x1), typeof(UInt4x2), typeof(UInt4x3), typeof(UInt4x4),
typeof(Float1x1), typeof(Float1x2), typeof(Float1x3), typeof(Float1x4),
typeof(Float2x1), typeof(Float2x2), typeof(Float2x3), typeof(Float2x4),
typeof(Float3x1), typeof(Float3x2), typeof(Float3x3), typeof(Float3x4),
typeof(Float4x1), typeof(Float4x2), typeof(Float4x3), typeof(Float4x4),
typeof(Double1x1), typeof(Double1x2), typeof(Double1x3), typeof(Double1x4),
typeof(Double2x1), typeof(Double2x2), typeof(Double2x3), typeof(Double2x4),
typeof(Double3x1), typeof(Double3x2), typeof(Double3x3), typeof(Double3x4),
typeof(Double4x1), typeof(Double4x2), typeof(Double4x3), typeof(Double4x4)
});
/// <summary>
/// Checks whether or not the input type is a known scalar type.
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known HLSL scalar type.</returns>
[Pure]
public static bool IsKnownScalarType(Type type) => type == typeof(bool) ||
type == typeof(Bool) ||
type == typeof(int) ||
type == typeof(uint) ||
type == typeof(float) ||
type == typeof(double);
/// <summary>
/// Checks whether or not the input type is a known vector type.
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known HLSL vector type.</returns>
[Pure]
public static bool IsKnownVectorType(Type type) => HlslMappedVectorTypes.Contains(type) ||
type == typeof(Vector2) ||
type == typeof(Vector3) ||
type == typeof(Vector4);
/// <summary>
/// Checks whether or not the input type is a known matrix type.
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known HLSL matrix type.</returns>
[Pure]
public static bool IsKnownMatrixType(Type type) => HlslMappedMatrixTypes.Contains(type);
/// <summary>
/// Checks whether or not the input type is a known buffer type.
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known buffer type.</returns>
[Pure]
public static bool IsKnownBufferType(Type type) => IsConstantBufferType(type) ||
IsReadOnlyResourceType(type) ||
IsReadWriteResourceType(type);
/// <summary>
/// Checks whether or not the input type is a <see cref="ConstantBuffer{T}"/> value.
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a <see cref="ConstantBuffer{T}"/> instance.</returns>
[Pure]
public static bool IsConstantBufferType(Type type) => type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(ConstantBuffer<>);
/// <summary>
/// Checks whether or not the input type is a known readonly resource type (buffer or texture).
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is a readonly resource type.</returns>
[Pure]
public static bool IsReadOnlyResourceType(Type type)
{
if (!type.IsGenericType) return false;
Type genericType = type.GetGenericTypeDefinition();
return
genericType == typeof(ReadOnlyBuffer<>) ||
genericType == typeof(ReadOnlyTexture2D<>) ||
genericType == typeof(ReadOnlyTexture2D<,>) ||
genericType == typeof(ReadOnlyTexture3D<>) ||
genericType == typeof(ReadOnlyTexture3D<,>) ||
genericType == typeof(IReadOnlyTexture2D<>) ||
genericType == typeof(IReadOnlyTexture3D<>);
}
/// <summary>
/// Checks whether or not the input type is a known writeable resource type (buffer or texture).
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is a writeable resource type.</returns>
[Pure]
public static bool IsReadWriteResourceType(Type type)
{
if (!type.IsGenericType) return false;
Type genericType = type.GetGenericTypeDefinition();
return
genericType == typeof(ReadWriteBuffer<>) ||
genericType == typeof(ReadWriteTexture2D<>) ||
genericType == typeof(ReadWriteTexture2D<,>) ||
genericType == typeof(ReadWriteTexture3D<>) ||
genericType == typeof(ReadWriteTexture3D<,>) ||
genericType == typeof(IReadWriteTexture2D<>) ||
genericType == typeof(IReadWriteTexture3D<>); ;
}
}
}
+45
ファイルの表示
@@ -0,0 +1,45 @@
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Interop;
using TerraFX.Interop;
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
/// A class that contains info on a cached shader.
/// </summary>
internal sealed unsafe class CachedShader : NativeObject
{
/// <summary>
/// The <see cref="IDxcBlob"/> instance currently in use.
/// </summary>
private ComPtr<IDxcBlob> dxcBlobBytecode;
/// <summary>
/// Creates a new <see cref="CachedShader"/> instance with the specified parameters.
/// </summary>
/// <param name="dxcBlobBytecode">The <see cref="IDxcBlob"/> bytecode instance to wrap.</param>
public CachedShader(IDxcBlob* dxcBlobBytecode)
{
this.dxcBlobBytecode = new ComPtr<IDxcBlob>(dxcBlobBytecode);
}
/// <summary>
/// Gets the map of cached <see cref="PipelineData"/> instances for each GPU in use.
/// </summary>
public ConditionalWeakTable<GraphicsDevice, PipelineData> CachedPipelines { get; } = new();
/// <summary>
/// Gets a raw pointer to the <see cref="IDxcBlob"/> instance in use.
/// </summary>
public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new((ID3DBlob*)this.dxcBlobBytecode.Get());
/// <inheritdoc/>
protected override bool OnDispose()
{
this.dxcBlobBytecode.Dispose();
return true;
}
}
}
-41
ファイルの表示
@@ -1,41 +0,0 @@
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Shaders.Translation.Interop;
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
/// A <see langword="struct"/> that contains info on a cached shader.
/// </summary>
/// <typeparam name="T">The type of compute shader in use.</typeparam>
internal readonly struct CachedShader<T>
where T : struct
{
/// <summary>
/// The <see cref="ShaderLoader{T}"/> instance with the shader metadata.
/// </summary>
public readonly ShaderLoader<T> Loader;
/// <summary>
/// The compiled shader bytecode.
/// </summary>
public readonly IDxcBlobObject Bytecode;
/// <summary>
/// The map of cached <see cref="PipelineData"/> instances for each GPU in use.
/// </summary>
public readonly ConditionalWeakTable<GraphicsDevice, PipelineData> CachedPipelines;
/// <summary>
/// Creates a new <see cref="CachedShader{T}"/> instance with the specified parameters.
/// </summary>
/// <param name="loader">The <see cref="ShaderLoader{T}"/> instance with the shader metadata.</param>
/// <param name="bytecode">The compiled shader bytecode.</param>
public CachedShader(ShaderLoader<T> loader, IDxcBlobObject bytecode)
{
Loader = loader;
Bytecode = bytecode;
CachedPipelines = new();
}
}
}
-87
ファイルの表示
@@ -1,87 +0,0 @@
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop;
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
/// A <see langword="struct"/> that contains all the captured data to dispatch a shader.
/// </summary>
internal readonly ref struct DispatchData
{
/// <summary>
/// The <see cref="ulong"/> array (actually <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> values) with the captured buffers.
/// </summary>
private readonly ulong[] resourcesArray;
/// <summary>
/// The number of <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> values in <see cref="resourcesArray"/>.
/// </summary>
private readonly int resourcesCount;
/// <summary>
/// The <see cref="byte"/> array with all the captured variables, with proper padding.
/// </summary>
private readonly byte[] variablesArray;
/// <summary>
/// The actual size in bytes to use from <see cref="variablesArray"/>.
/// </summary>
private readonly int variablesByteSize;
/// <summary>
/// Creates a new <see cref="DispatchData"/> instance with the specified parameters.
/// </summary>
/// <param name="resourcesArray">The <see cref="ulong"/> array with the captured buffers.</param>
/// <param name="resourcesCount">The number of <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances in <see cref="resourcesArray"/>.</param>
/// <param name="variablesArray">The <see cref="byte"/> array with all the captured variables, with proper padding.</param>
/// <param name="variablesByteSize">The actual size in bytes to use from <see cref="variablesArray"/>.</param>
public DispatchData(ulong[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize)
{
this.resourcesArray = resourcesArray;
this.variablesArray = variablesArray;
this.resourcesCount = resourcesCount;
this.variablesByteSize = variablesByteSize;
}
/// <summary>
/// Gets a <see cref="ReadOnlySpan{T}"/> with all the captured buffers.
/// </summary>
public ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> Resources
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray);
ref D3D12_GPU_DESCRIPTOR_HANDLE r1 = ref Unsafe.As<ulong, D3D12_GPU_DESCRIPTOR_HANDLE>(ref r0);
return MemoryMarshal.CreateReadOnlySpan(ref r1, this.resourcesCount);
}
}
/// <summary>
/// Gets a <see cref="ReadOnlySpan{T}"/> with the padded data representing all the captured variables.
/// </summary>
public unsafe ReadOnlySpan<uint> Variables
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray);
ref uint r1 = ref Unsafe.As<byte, uint>(ref r0);
int length = (int)((uint)this.variablesByteSize / sizeof(uint));
return MemoryMarshal.CreateReadOnlySpan(ref r1, length);
}
}
/// <inheritdoc cref="IDisposable.Dispose"/>
public void Dispose()
{
ArrayPool<ulong>.Shared.Return(this.resourcesArray);
ArrayPool<byte>.Shared.Return(this.variablesArray);
}
}
}
-75
ファイルの表示
@@ -1,75 +0,0 @@
using System;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="static"/> <see langword="class"/> that handles the cache system for the generated shaders.
/// </summary>
internal static class ShaderHashCodeProvider
{
/// <summary>
/// A type containing static info for a given shader type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
private static class TypeInfo<T>
where T : struct
{
/// <summary>
/// The id of the compute shader type in use.
/// </summary>
public static readonly int Id;
/// <summary>
/// The optional <see cref="Hasher{T}"/> instance, if needed.
/// </summary>
public static readonly Hasher<T>? Hasher;
/// <summary>
/// Initializes the static members of the <see cref="TypeInfo{T}"/> type.
/// </summary>
static TypeInfo()
{
Id = HashCode.Combine(typeof(T));
// Get the generated hasher, if one if present
if (typeof(T).Assembly.GetType("ComputeSharp.__Internals.HashCodeProvider") is Type type &&
type.GetMethod("CombineHash", new[] { typeof(int), typeof(T).MakeByRefType() }) is MethodInfo method)
{
Hasher = method.CreateDelegate<Hasher<T>>();
}
}
}
/// <summary>
/// Gets a unique hashcode for the input compute shader instance.
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the shader to run.</param>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetHashCode<T>(in T shader)
where T : struct
{
int hash = TypeInfo<T>.Id;
Hasher<T>? hasher = TypeInfo<T>.Hasher;
if (hasher != null) hash = hasher(hash, in shader);
return hash;
}
/// <summary>
/// A <see langword="delegate"/> that represents an aggregate hash function for a given <typeparamref name="T"/> instance.
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
/// <param name="hash">The initial hash value.</param>
/// <param name="shader">The compute shader instance to use to compute the final hash value.</param>
/// <returns>The final hash value for the input closure.</returns>
private delegate int Hasher<T>(int hash, in T shader)
where T : struct;
}
}
-97
ファイルの表示
@@ -1,97 +0,0 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
using ComputeSharp.Shaders.Translation.Models;
using TerraFX.Interop;
#pragma warning disable CS0419, CS0618
namespace ComputeSharp.Shaders.Translation
{
/// <inheritdoc cref="ShaderLoader{T}"/>
internal sealed partial class ShaderLoader<T>
{
/// <summary>
/// A <see langword="delegate"/> that loads all the captured members from a shader instance.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="shader">The shader instance to load the data from.</param>
/// <param name="r0">
/// A reference to the buffer with all the captured <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances.
/// This is just represented as a <see cref="ulong"/> reference, to avoid exposing the type publicly.
/// </param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types.</param>
/// <returns>The returned value indicates the total number of written bytes into <paramref name="r1"/>.</returns>
private delegate int DispatchDataLoader(GraphicsDevice device, in T shader, ref ulong r0, ref byte r1);
/// <summary>
/// The number of captured graphics resources (buffers).
/// </summary>
private int totalResourceCount;
/// <summary>
/// The cached <see cref="DispatchDataLoader"/> instance to load dispatch data before execution.
/// </summary>
private DispatchDataLoader? dispatchDataLoader;
/// <summary>
/// The <see cref="List{T}"/> of <see cref="FieldInfo"/> instances mapping the captured variables in the current shader.
/// </summary>
private readonly List<FieldInfo> capturedFields = new();
/// <summary>
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
[Pure]
public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z)
{
// Resources and variables buffers
ulong[] resources = ArrayPool<ulong>.Shared.Rent(this.totalResourceCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(256);
ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources);
ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables);
// Set the x, y and (optionally) z counters
Unsafe.As<byte, int>(ref r1) = x;
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 1) = y;
if (IsComputeShader)
{
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
}
// Invoke the dynamic method to extract the captured data
int totalVariablesByteSize = this.dispatchDataLoader!(device, in shader, ref r0, ref r1);
return new(resources, this.totalResourceCount, variables, totalVariablesByteSize);
}
/// <summary>
/// Initializes the <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type.
/// </summary>
private void InitializeDispatchDataLoader()
{
// Get the generated data loader
Type[] argumentTypes = new[] { typeof(GraphicsDevice), typeof(T).MakeByRefType(), typeof(ulong).MakeByRefType(), typeof(byte).MakeByRefType() };
Type type = typeof(T).Assembly.GetType("ComputeSharp.__Internals.DispatchDataLoader")!;
MethodInfo method = type.GetMethod("LoadDispatchData", argumentTypes)!;
// Extract the computed count of 32 bit root constants to load
D3D12Root32BitConstantsCount = ((ComputeRoot32BitConstantsAttribute)method.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count;
// Create a delegate from the generated shader data loader
this.dispatchDataLoader = method.CreateDelegate<DispatchDataLoader>();
}
}
}
-295
ファイルの表示
@@ -1,295 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using ComputeSharp.__Internals;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Renderer.Models;
using Microsoft.Toolkit.Diagnostics;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE;
#pragma warning disable CS0419, CS0618, CS8618
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> responsible for loading and processing shaders of a given type.
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
internal sealed partial class ShaderLoader<T> : IShaderLoader
where T : struct
{
/// <summary>
/// The associated <see cref="IComputeShaderSourceAttribute"/> instance for the current shader type.
/// </summary>
private static readonly IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType<T>();
/// <summary>
/// The number of constant buffers to define in the shader.
/// </summary>
/// <remarks>
/// This starts at 1 as there's always an initial constant buffer before user-defined ones, containing
/// the captured scalar and vector values as well as the iteration ranges for the shader dispatch.
/// </remarks>
private uint constantBuffersCount = 1;
/// <summary>
/// The number of readonly buffers to define in the shader.
/// </summary>
private uint readOnlyBuffersCount;
/// <summary>
/// The number of read write buffers to define in the shader.
/// </summary>
private uint readWriteBuffersCount;
/// <summary>
/// The number of samplers to define in the shader.
/// </summary>
private uint samplersCount;
/// <summary>
/// The array of <see cref="D3D12_DESCRIPTOR_RANGE1"/> items that are required to load the captured values.
/// </summary>
private D3D12_DESCRIPTOR_RANGE1[] d3D12DescriptorRanges1;
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="Renderer.Models.HlslResourceInfo"/> items for the shader fields.
/// </summary>
private readonly List<HlslResourceInfo> hlslResourceInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
private readonly List<CapturedFieldInfo> fieldsInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the collected methods for the shader.
/// </summary>
private readonly List<string> methodsInfo = new();
/// <summary>
/// The <see cref="Dictionary{TKey,TValue}"/> with the discovered define declarations for the shader.
/// </summary>
private readonly Dictionary<string, string> definesInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the collected declared types for the shader.
/// </summary>
private readonly List<string> declaredTypes = new();
/// <summary>
/// Creates a new <see cref="ShaderLoader{T}"/> instance.
/// </summary>
private ShaderLoader()
{
}
/// <summary>
/// Gets the number of 32 bit constants in the root signature for the shader.
/// </summary>
public int D3D12Root32BitConstantsCount { get; private set; }
/// <summary>
/// Gets a <see cref="Span{T}"/> with the loaded <see cref="D3D12_DESCRIPTOR_RANGE1"/> items for the shader.
/// </summary>
public ReadOnlySpan<D3D12_DESCRIPTOR_RANGE1> D3D12DescriptorRanges1
{
get => this.d3D12DescriptorRanges1;
}
/// <inheritdoc/>
public string EntryPoint { get; private set; }
/// <inheritdoc/>
public bool IsComputeShader { get; private set; }
/// <summary>
/// Gets whether or not the current shader requires access to a static sampler.
/// </summary>
public bool IsStaticSamplerUsed { get; private set; }
/// <inheritdoc/>
public IReadOnlyList<HlslResourceInfo> HlslResourceInfo => this.hlslResourceInfo;
/// <inheritdoc/>
public IReadOnlyList<CapturedFieldInfo> FieldsInfo => this.fieldsInfo;
/// <inheritdoc/>
public IReadOnlyCollection<string> ForwardDeclarations { get; private set; }
/// <inheritdoc/>
public IReadOnlyCollection<string> MethodsInfo => this.methodsInfo;
/// <inheritdoc/>
public IReadOnlyDictionary<string, string> DefinesInfo => this.definesInfo;
/// <inheritdoc/>
public IReadOnlyCollection<string> DeclaredTypes => this.declaredTypes;
/// <inheritdoc/>
public IReadOnlyDictionary<string, (string TypeDeclaration, string? Assignment)> StaticFields { get; private set; }
/// <inheritdoc/>
public IReadOnlyDictionary<string, (string Type, int? Count)> SharedBuffers { get; private set; }
/// <summary>
/// Loads and processes an input<typeparamref name="T"/> shadeer.
/// </summary>
/// <param name="shader">The <typeparamref name="T"/> instance to use to build the shader.</param>
/// <returns>A new <see cref="ShaderLoader{T}"/> instance representing the input shader.</returns>
[Pure]
public static ShaderLoader<T> Load(in T shader)
{
ShaderLoader<T> @this = new();
@this.LoadMethodMetadata();
// Reading members through reflection requires an object parameter, so here we're just boxing
// the input shader once to avoid allocating it multiple times while processing the shader.
@this.d3D12DescriptorRanges1 = @this.LoadFieldsInfo(shader);
@this.InitializeDispatchDataLoader();
return @this;
}
/// <summary>
/// Loads the metadata info for the current shader.
/// </summary>
private void LoadMethodMetadata()
{
ForwardDeclarations = Attribute.ForwardDeclarations;
EntryPoint = Attribute.ExecuteMethod;
StaticFields = Attribute.StaticFields;
SharedBuffers = Attribute.SharedBuffers;
this.declaredTypes.AddRange(Attribute.Types);
this.methodsInfo.AddRange(Attribute.Methods);
foreach (var pair in Attribute.Defines)
{
this.definesInfo.Add(pair.Key, pair.Value);
}
}
/// <summary>
/// Loads the fields info for the current shader being loaded.
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader.</param>
/// <returns>The array of <see cref="D3D12_DESCRIPTOR_RANGE1"/> items that are required to load the captured values.</returns>
private D3D12_DESCRIPTOR_RANGE1[] LoadFieldsInfo(object shader)
{
IReadOnlyList<FieldInfo> shaderFields = typeof(T).GetFields(
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic).ToArray();
List<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges1 = new();
// Add the implicit texture descriptor if the shader is a pixel shader
foreach (Type interfaceType in typeof(T).GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition() == typeof(IPixelShader<>))
{
d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount));
(string hlslType, string hlslName) = Attribute.ImplicitTextureField!.Value;
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++));
this.totalResourceCount++;
break;
}
}
// Set the current shader type
IsComputeShader = d3D12DescriptorRanges1.Count == 0;
// Ensure the shader has a valid number of captured resources
if (shaderFields.Count == 0 && d3D12DescriptorRanges1.Count == 0)
{
ThrowHelper.ThrowInvalidOperationException("The shader body must contain at least one field");
}
// Add the implicit sampler descriptor if necessary
if (Attribute.ImplicitSamplerField is not null)
{
(string hlslType, string hlslName) = Attribute.ImplicitSamplerField!.Value;
this.hlslResourceInfo.Add(new HlslResourceInfo.Sampler(hlslType, hlslName, (int)this.samplersCount++));
IsStaticSamplerUsed = true;
}
// Inspect the captured fields
foreach (FieldInfo fieldInfo in shaderFields)
{
LoadFieldInfo(shader, fieldInfo, d3D12DescriptorRanges1);
}
return d3D12DescriptorRanges1.ToArray();
}
/// <summary>
/// Loads a specified <see cref="FieldInfo"/> and adds it to the shader model.
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader.</param>
/// <param name="fieldInfo">The target <see cref="FieldInfo"/> to load.</param>
/// <param name="d3D12DescriptorRanges1">The list of discovered <see cref="D3D12_DESCRIPTOR_RANGE1"/> values.</param>
private void LoadFieldInfo(object shader, FieldInfo fieldInfo, List<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges1)
{
Type fieldType = fieldInfo.FieldType;
(string hlslName, string hlslType) = Attribute.Fields[fieldInfo.Name];
if (HlslKnownTypes.IsConstantBufferType(fieldType))
{
d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount));
this.capturedFields.Add(fieldInfo);
this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++));
this.totalResourceCount++;
}
else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType))
{
d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, this.readOnlyBuffersCount));
this.capturedFields.Add(fieldInfo);
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++));
this.totalResourceCount++;
}
else if (HlslKnownTypes.IsReadWriteResourceType(fieldType))
{
d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount));
this.capturedFields.Add(fieldInfo);
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++));
this.totalResourceCount++;
}
else if (fieldInfo.GetValue(shader) is Delegate func)
{
Guard.IsTrue(func.Method.IsStatic, fieldInfo.Name, "Captured delegates must be pointing to static methods");
// Captured static delegates with a return type
var methodSource = ShaderMethodSourceAttribute.GetForDelegate(func);
this.declaredTypes.AddRange(methodSource.Types);
this.methodsInfo.Add(methodSource.GetMappedInvokeMethod(hlslName));
this.methodsInfo.AddRange(methodSource.Methods);
foreach (var pair in methodSource.Constants)
{
this.definesInfo[pair.Key] = pair.Value;
}
}
else
{
this.capturedFields.Add(fieldInfo);
this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName));
}
}
}
}
+137
ファイルの表示
@@ -0,0 +1,137 @@
using System;
using System.Buffers;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace ComputeSharp.__Internals
{
/// <summary>
/// A helper type that implements a pooled buffer writer for <see cref="char"/> values.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This type is not intended to be used directly by user code")]
[DebuggerTypeProxy(typeof(DebugView))]
public ref struct ArrayPoolStringBuilder
{
/// <summary>
/// The underlying <see cref="char"/> array.
/// </summary>
private char[] array;
/// <summary>
/// The starting offset within <see cref="array"/>.
/// </summary>
private int index;
/// <summary>
/// Creates a new <see cref="ArrayPoolStringBuilder"/> instance ready to use.
/// </summary>
/// <param name="sizeHint">The size hint for the internal buffer to allocate.</param>
/// <returns>A new <see cref="ArrayPoolStringBuilder"/> instance with default values.</returns>
[Pure]
public static ArrayPoolStringBuilder Create(int sizeHint)
{
ArrayPoolStringBuilder builder;
builder.array = ArrayPool<char>.Shared.Rent(sizeHint);
builder.index = 0;
return builder;
}
/// <inheritdoc/>
public ReadOnlySpan<char> WrittenSpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new(this.array, 0, this.index);
}
/// <summary>
/// Appends the input sequence of characters to the current buffer.
/// </summary>
/// <param name="value">The input characters to write.</param>
public void Append(string value)
{
EnsureCapacity(value.Length);
value.AsSpan().CopyTo(this.array.AsSpan(this.index));
this.index += value.Length;
}
/// <summary>
/// Appends the text representation of the input value to the current buffer.
/// </summary>
/// <param name="value">The input value to write.</param>
public void Append(int value)
{
// TODO: switch to ISpanFormattable on .NET 6
Append(value.ToString());
}
/// <summary>
/// Ensures that <see cref="array"/> has enough free space to contain a given number of new items.
/// </summary>
/// <param name="requestedSize">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCapacity(int requestedSize)
{
if (requestedSize > this.array.Length - this.index)
{
ResizeBuffer(requestedSize);
}
}
/// <summary>
/// Resizes <see cref="array"/> to ensure it can fit the specified number of new items.
/// </summary>
/// <param name="sizeHint">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void ResizeBuffer(int sizeHint)
{
int minimumSize = this.index + sizeHint;
// Rent a new array with the specified size, and copy as many items from the current array
// as possible to the new array. This mirrors the behavior of the Array.Resize API from
// the BCL: if the new size is greater than the length of the current array, copy all the
// items from the original array into the new one. Otherwise, copy as many items as possible,
// until the new array is completely filled, and ignore the remaining items in the first array.
char[] newArray = ArrayPool<char>.Shared.Rent(minimumSize);
int itemsToCopy = Math.Min(this.array.Length, minimumSize);
Array.Copy(this.array, 0, newArray, 0, itemsToCopy);
ArrayPool<char>.Shared.Return(array);
this.array = newArray;
}
/// <inheritdoc/>
public void Dispose()
{
ArrayPool<char>.Shared.Return(this.array);
}
/// <summary>
/// A debug proxy used for displaying debug info.
/// </summary>
internal sealed class DebugView
{
/// <summary>
/// Initializes a new instance of the <see cref="DebugView"/> class with the specified parameters.
/// </summary>
/// <param name="builder">The input <see cref="ArrayPoolStringBuilder"/> instance to display.</param>
public DebugView(ArrayPoolStringBuilder builder)
{
Text = builder.WrittenSpan.ToString();
}
/// <summary>
/// Gets the text to display for the current instance.
/// </summary>
public string Text { get; }
}
}
}
+56
ファイルの表示
@@ -0,0 +1,56 @@
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.__Internals;
#pragma warning disable CS0618
namespace ComputeSharp.Tests.Internals.Helpers
{
/// <summary>
/// A debug data loader for generic shaders.
/// </summary>
internal readonly unsafe struct DebugDispatchDataLoader : IDispatchDataLoader
{
/// <summary>
/// The backing, mutable data for <see cref="Values"/> and <see cref="Resources"/>.
/// </summary>
private readonly StrongBox<(uint[] Values, ulong[] Resources)> data;
/// <summary>
/// Gets the captured values.
/// </summary>
public uint[] Values => this.data.Value.Values;
/// <summary>
/// Gets the captured resources.
/// </summary>
public ulong[] Resources => this.data.Value.Resources;
/// <summary>
/// Creates a new <see cref="DebugDispatchDataLoader"/> instance.
/// </summary>
/// <returns>A new <see cref="DebugDispatchDataLoader"/> instance to use.</returns>
[Pure]
public static DebugDispatchDataLoader Create()
{
DebugDispatchDataLoader @this = default;
Unsafe.AsRef(in @this.data) = new StrongBox<(uint[], ulong[])>((Array.Empty<uint>(), Array.Empty<ulong>()));
return @this;
}
/// <inheritdoc/>
public void LoadCapturedValues(ReadOnlySpan<uint> data)
{
this.data.Value.Values = data.ToArray();
}
/// <inheritdoc/>
public void LoadCapturedResources(ReadOnlySpan<ulong> data)
{
this.data.Value.Resources = data.ToArray();
}
}
}
+209 -123
ファイルの表示
@@ -1,4 +1,4 @@
using ComputeSharp.__Internals;
using ComputeSharp.Tests.Internals.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#pragma warning disable CS0618
@@ -22,16 +22,19 @@ namespace ComputeSharp.Tests.Internals
[TestMethod]
public unsafe void CapturedResource()
{
ulong* p0 = stackalloc ulong[128];
byte* p1 = stackalloc byte[256];
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(16);
int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, new CapturedResourceShader(buffer), ref *p0, ref *p1);
DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create();
Assert.AreEqual(12, size);
new CapturedResourceShader(buffer).LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333);
Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr);
Assert.AreEqual(3, dataLoader.Values.Length);
Assert.AreEqual(1, dataLoader.Resources.Length);
Assert.AreEqual(111, (int)dataLoader.Values[0]);
Assert.AreEqual(222, (int)dataLoader.Values[1]);
Assert.AreEqual(333, (int)dataLoader.Values[2]);
Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]);
}
[AutoConstructor]
@@ -51,22 +54,24 @@ namespace ComputeSharp.Tests.Internals
[TestMethod]
public unsafe void LoadMultipleResourcesAndPrimitives()
{
ulong* p0 = stackalloc ulong[128];
byte* p1 = stackalloc byte[256];
using ReadWriteBuffer<float> buffer0 = Gpu.Default.AllocateReadWriteBuffer<float>(16);
using ReadWriteBuffer<float> buffer1 = Gpu.Default.AllocateReadWriteBuffer<float>(16);
int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, new MultipleResourcesAndPrimitivesShader(buffer0, buffer1, 1, 22, 77), ref *p0, ref *p1);
DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create();
Assert.AreEqual(24, size);
new MultipleResourcesAndPrimitivesShader(buffer0, buffer1, 1, 22, 77).LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333);
Assert.AreEqual(p0[0], buffer0.D3D12GpuDescriptorHandle.ptr);
Assert.AreEqual(p0[1], buffer1.D3D12GpuDescriptorHandle.ptr);
Assert.AreEqual(6, dataLoader.Values.Length);
Assert.AreEqual(2, dataLoader.Resources.Length);
Assert.AreEqual(1, *(int*)&p1[12]);
Assert.AreEqual(22, *(int*)&p1[16]);
Assert.AreEqual(77, *(int*)&p1[20]);
Assert.AreEqual(111, (int)dataLoader.Values[0]);
Assert.AreEqual(222, (int)dataLoader.Values[1]);
Assert.AreEqual(333, (int)dataLoader.Values[2]);
Assert.AreEqual(1, (int)dataLoader.Values[3]);
Assert.AreEqual(22, (int)dataLoader.Values[4]);
Assert.AreEqual(77, (int)dataLoader.Values[5]);
Assert.AreEqual(buffer0.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]);
Assert.AreEqual(buffer1.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[1]);
}
[AutoConstructor]
@@ -88,28 +93,36 @@ namespace ComputeSharp.Tests.Internals
[TestMethod]
public unsafe void LoadScalarAndVectorTypes()
{
ulong* p0 = stackalloc ulong[128];
byte* p1 = stackalloc byte[256];
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(16);
DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create();
ScalarAndVectorTypesShader shader = new(buffer, new(55, 44, 888), 22, 77, new(3.14, 6.28), 42, 9999);
int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1);
shader.LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333);
Assert.AreEqual(72, size);
Assert.AreEqual(18, dataLoader.Values.Length);
Assert.AreEqual(1, dataLoader.Resources.Length);
Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr);
Assert.AreEqual(111, (int)dataLoader.Values[0]);
Assert.AreEqual(222, (int)dataLoader.Values[1]);
Assert.AreEqual(333, (int)dataLoader.Values[2]);
Assert.AreEqual(55, *(float*)&p1[16]);
Assert.AreEqual(44, *(float*)&p1[20]);
Assert.AreEqual(888, *(float*)&p1[24]);
Assert.AreEqual(22, *(int*)&p1[28]);
Assert.AreEqual(77, *(int*)&p1[32]);
Assert.AreEqual(3.14, *(double*)&p1[48]);
Assert.AreEqual(6.28, *(double*)&p1[56]);
Assert.AreEqual(42, *(int*)&p1[64]);
Assert.AreEqual(9999, *(int*)&p1[68]);
Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]);
fixed (void* p0 = &dataLoader.Values[0])
{
byte* p1 = (byte*)p0;
Assert.AreEqual(55, *(float*)&p1[16]);
Assert.AreEqual(44, *(float*)&p1[20]);
Assert.AreEqual(888, *(float*)&p1[24]);
Assert.AreEqual(22, *(int*)&p1[28]);
Assert.AreEqual(77, *(int*)&p1[32]);
Assert.AreEqual(3.14, *(double*)&p1[48]);
Assert.AreEqual(6.28, *(double*)&p1[56]);
Assert.AreEqual(42, *(int*)&p1[64]);
Assert.AreEqual(9999, *(int*)&p1[68]);
}
}
[AutoConstructor]
@@ -133,11 +146,9 @@ namespace ComputeSharp.Tests.Internals
[TestMethod]
public unsafe void LoadScalarVectorAndMatrixTypes()
{
ulong* p0 = stackalloc ulong[128];
byte* p1 = stackalloc byte[256];
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(16);
DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create();
ScalarVectorAndMatrixTypesShader shader = new(
buffer,
f2x3: new(55, 44, 888, 111, 222, 333),
@@ -149,32 +160,42 @@ namespace ComputeSharp.Tests.Internals
i2x2: new(11, 22, 33, 44),
d: 9999);
int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1);
shader.LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333);
Assert.AreEqual(124, size);
Assert.AreEqual(31, dataLoader.Values.Length);
Assert.AreEqual(1, dataLoader.Resources.Length);
Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr);
Assert.AreEqual(111, (int)dataLoader.Values[0]);
Assert.AreEqual(222, (int)dataLoader.Values[1]);
Assert.AreEqual(333, (int)dataLoader.Values[2]);
Assert.AreEqual(55, *(float*)&p1[16]);
Assert.AreEqual(44, *(float*)&p1[20]);
Assert.AreEqual(888, *(float*)&p1[24]);
Assert.AreEqual(111, *(float*)&p1[32]);
Assert.AreEqual(222, *(float*)&p1[36]);
Assert.AreEqual(333, *(float*)&p1[40]);
Assert.AreEqual(22, *(int*)&p1[44]);
Assert.AreEqual(1, *(int*)&p1[48]);
Assert.AreEqual(2, *(int*)&p1[52]);
Assert.AreEqual(3, *(int*)&p1[56]);
Assert.AreEqual(3.14, *(double*)&p1[64]);
Assert.AreEqual(6.28, *(double*)&p1[72]);
Assert.AreEqual(42, *(int*)&p1[80]);
Assert.AreEqual(111, *(int*)&p1[84]);
Assert.AreEqual(222, *(int*)&p1[88]);
Assert.AreEqual(11, *(int*)&p1[96]);
Assert.AreEqual(22, *(int*)&p1[100]);
Assert.AreEqual(33, *(int*)&p1[112]);
Assert.AreEqual(44, *(int*)&p1[116]);
Assert.AreEqual(9999, *(int*)&p1[120]);
Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]);
fixed (void* p0 = &dataLoader.Values[0])
{
byte* p1 = (byte*)p0;
Assert.AreEqual(55, *(float*)&p1[16]);
Assert.AreEqual(44, *(float*)&p1[20]);
Assert.AreEqual(888, *(float*)&p1[24]);
Assert.AreEqual(111, *(float*)&p1[32]);
Assert.AreEqual(222, *(float*)&p1[36]);
Assert.AreEqual(333, *(float*)&p1[40]);
Assert.AreEqual(22, *(int*)&p1[44]);
Assert.AreEqual(1, *(int*)&p1[48]);
Assert.AreEqual(2, *(int*)&p1[52]);
Assert.AreEqual(3, *(int*)&p1[56]);
Assert.AreEqual(3.14, *(double*)&p1[64]);
Assert.AreEqual(6.28, *(double*)&p1[72]);
Assert.AreEqual(42, *(int*)&p1[80]);
Assert.AreEqual(111, *(int*)&p1[84]);
Assert.AreEqual(222, *(int*)&p1[88]);
Assert.AreEqual(11, *(int*)&p1[96]);
Assert.AreEqual(22, *(int*)&p1[100]);
Assert.AreEqual(33, *(int*)&p1[112]);
Assert.AreEqual(44, *(int*)&p1[116]);
Assert.AreEqual(9999, *(int*)&p1[120]);
}
}
[AutoConstructor]
@@ -204,11 +225,9 @@ namespace ComputeSharp.Tests.Internals
[TestMethod]
public unsafe void LoadFlatCustomTypeShader()
{
ulong* p0 = stackalloc ulong[128];
byte* p1 = stackalloc byte[256];
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(16);
DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create();
FlatCustomTypeShader shader = new(
buffer,
new SimpleTypes(
@@ -221,32 +240,42 @@ namespace ComputeSharp.Tests.Internals
i2x2: new(11, 22, 33, 44),
d: 9999));
int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1);
shader.LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333);
Assert.AreEqual(124, size);
Assert.AreEqual(31, dataLoader.Values.Length);
Assert.AreEqual(1, dataLoader.Resources.Length);
Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr);
Assert.AreEqual(111, (int)dataLoader.Values[0]);
Assert.AreEqual(222, (int)dataLoader.Values[1]);
Assert.AreEqual(333, (int)dataLoader.Values[2]);
Assert.AreEqual(55, *(float*)&p1[16]);
Assert.AreEqual(44, *(float*)&p1[20]);
Assert.AreEqual(888, *(float*)&p1[24]);
Assert.AreEqual(111, *(float*)&p1[32]);
Assert.AreEqual(222, *(float*)&p1[36]);
Assert.AreEqual(333, *(float*)&p1[40]);
Assert.AreEqual(22, *(int*)&p1[44]);
Assert.AreEqual(1, *(int*)&p1[48]);
Assert.AreEqual(2, *(int*)&p1[52]);
Assert.AreEqual(3, *(int*)&p1[56]);
Assert.AreEqual(3.14, *(double*)&p1[64]);
Assert.AreEqual(6.28, *(double*)&p1[72]);
Assert.AreEqual(42, *(int*)&p1[80]);
Assert.AreEqual(111, *(int*)&p1[84]);
Assert.AreEqual(222, *(int*)&p1[88]);
Assert.AreEqual(11, *(int*)&p1[96]);
Assert.AreEqual(22, *(int*)&p1[100]);
Assert.AreEqual(33, *(int*)&p1[112]);
Assert.AreEqual(44, *(int*)&p1[116]);
Assert.AreEqual(9999, *(int*)&p1[120]);
Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]);
fixed (void* p0 = &dataLoader.Values[0])
{
byte* p1 = (byte*)p0;
Assert.AreEqual(55, *(float*)&p1[16]);
Assert.AreEqual(44, *(float*)&p1[20]);
Assert.AreEqual(888, *(float*)&p1[24]);
Assert.AreEqual(111, *(float*)&p1[32]);
Assert.AreEqual(222, *(float*)&p1[36]);
Assert.AreEqual(333, *(float*)&p1[40]);
Assert.AreEqual(22, *(int*)&p1[44]);
Assert.AreEqual(1, *(int*)&p1[48]);
Assert.AreEqual(2, *(int*)&p1[52]);
Assert.AreEqual(3, *(int*)&p1[56]);
Assert.AreEqual(3.14, *(double*)&p1[64]);
Assert.AreEqual(6.28, *(double*)&p1[72]);
Assert.AreEqual(42, *(int*)&p1[80]);
Assert.AreEqual(111, *(int*)&p1[84]);
Assert.AreEqual(222, *(int*)&p1[88]);
Assert.AreEqual(11, *(int*)&p1[96]);
Assert.AreEqual(22, *(int*)&p1[100]);
Assert.AreEqual(33, *(int*)&p1[112]);
Assert.AreEqual(44, *(int*)&p1[116]);
Assert.AreEqual(9999, *(int*)&p1[120]);
}
}
[AutoConstructor]
@@ -288,11 +317,9 @@ namespace ComputeSharp.Tests.Internals
[TestMethod]
public unsafe void LoadNestedCustomTypes()
{
ulong* p0 = stackalloc ulong[128];
byte* p1 = stackalloc byte[256];
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(16);
DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create();
NestedCustomTypesShader shader = new(
buffer,
new CustomType1(
@@ -317,45 +344,104 @@ namespace ComputeSharp.Tests.Internals
a: 888888,
b: new(333.3f, 444.4f))));
int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1);
shader.LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333);
Assert.AreEqual(188, size);
Assert.AreEqual(47, dataLoader.Values.Length);
Assert.AreEqual(1, dataLoader.Resources.Length);
Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr);
Assert.AreEqual(111, (int)dataLoader.Values[0]);
Assert.AreEqual(222, (int)dataLoader.Values[1]);
Assert.AreEqual(333, (int)dataLoader.Values[2]);
Assert.AreEqual(3.14f, *(float*)&p1[16]);
Assert.AreEqual(6.28f, *(float*)&p1[20]);
Assert.AreEqual(123.4f, *(float*)&p1[24]);
Assert.AreEqual(55, *(float*)&p1[32]);
Assert.AreEqual(44, *(float*)&p1[36]);
Assert.AreEqual(888, *(float*)&p1[40]);
Assert.AreEqual(111, *(float*)&p1[48]);
Assert.AreEqual(222, *(float*)&p1[52]);
Assert.AreEqual(333, *(float*)&p1[56]);
Assert.AreEqual(22, *(int*)&p1[60]);
Assert.AreEqual(1, *(int*)&p1[64]);
Assert.AreEqual(2, *(int*)&p1[68]);
Assert.AreEqual(3, *(int*)&p1[72]);
Assert.AreEqual(3.14, *(double*)&p1[80]);
Assert.AreEqual(6.28, *(double*)&p1[88]);
Assert.AreEqual(42, *(int*)&p1[96]);
Assert.AreEqual(111, *(int*)&p1[100]);
Assert.AreEqual(222, *(int*)&p1[104]);
Assert.AreEqual(11, *(int*)&p1[112]);
Assert.AreEqual(22, *(int*)&p1[116]);
Assert.AreEqual(33, *(int*)&p1[128]);
Assert.AreEqual(44, *(int*)&p1[132]);
Assert.AreEqual(9999, *(int*)&p1[136]);
Assert.AreEqual(42, *(int*)&p1[140]);
Assert.AreEqual(1234567, *(int*)&p1[144]);
Assert.AreEqual(44.4f, *(float*)&p1[148]);
Assert.AreEqual(55.5f, *(float*)&p1[152]);
Assert.AreEqual(7654321, *(int*)&p1[160]);
Assert.AreEqual(111.1f, *(float*)&p1[164]);
Assert.AreEqual(222.2f, *(float*)&p1[168]);
Assert.AreEqual(888888, *(int*)&p1[176]);
Assert.AreEqual(333.3f, *(float*)&p1[180]);
Assert.AreEqual(444.4f, *(float*)&p1[184]);
Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]);
fixed (void* p0 = &dataLoader.Values[0])
{
byte* p1 = (byte*)p0;
Assert.AreEqual(3.14f, *(float*)&p1[16]);
Assert.AreEqual(6.28f, *(float*)&p1[20]);
Assert.AreEqual(123.4f, *(float*)&p1[24]);
Assert.AreEqual(55, *(float*)&p1[32]);
Assert.AreEqual(44, *(float*)&p1[36]);
Assert.AreEqual(888, *(float*)&p1[40]);
Assert.AreEqual(111, *(float*)&p1[48]);
Assert.AreEqual(222, *(float*)&p1[52]);
Assert.AreEqual(333, *(float*)&p1[56]);
Assert.AreEqual(22, *(int*)&p1[60]);
Assert.AreEqual(1, *(int*)&p1[64]);
Assert.AreEqual(2, *(int*)&p1[68]);
Assert.AreEqual(3, *(int*)&p1[72]);
Assert.AreEqual(3.14, *(double*)&p1[80]);
Assert.AreEqual(6.28, *(double*)&p1[88]);
Assert.AreEqual(42, *(int*)&p1[96]);
Assert.AreEqual(111, *(int*)&p1[100]);
Assert.AreEqual(222, *(int*)&p1[104]);
Assert.AreEqual(11, *(int*)&p1[112]);
Assert.AreEqual(22, *(int*)&p1[116]);
Assert.AreEqual(33, *(int*)&p1[128]);
Assert.AreEqual(44, *(int*)&p1[132]);
Assert.AreEqual(9999, *(int*)&p1[136]);
Assert.AreEqual(42, *(int*)&p1[140]);
Assert.AreEqual(1234567, *(int*)&p1[144]);
Assert.AreEqual(44.4f, *(float*)&p1[148]);
Assert.AreEqual(55.5f, *(float*)&p1[152]);
Assert.AreEqual(7654321, *(int*)&p1[160]);
Assert.AreEqual(111.1f, *(float*)&p1[164]);
Assert.AreEqual(222.2f, *(float*)&p1[168]);
Assert.AreEqual(888888, *(int*)&p1[176]);
Assert.AreEqual(333.3f, *(float*)&p1[180]);
Assert.AreEqual(444.4f, *(float*)&p1[184]);
}
}
[AutoConstructor]
public partial struct AmbiguousNamesShader : IComputeShader
{
public ReadWriteBuffer<float> a;
public ReadWriteBuffer<float> b;
public ReadWriteBuffer<float> c;
public ReadWriteBuffer<float> x;
public ReadWriteBuffer<float> y;
public ReadWriteBuffer<float> z;
public int dataLoader;
public int device;
public int dummy;
public void Execute()
{
}
}
[TestMethod]
public unsafe void AmbiguousNames()
{
using ReadWriteBuffer<float> a = Gpu.Default.AllocateReadWriteBuffer<float>(16);
using ReadWriteBuffer<float> b = Gpu.Default.AllocateReadWriteBuffer<float>(16);
using ReadWriteBuffer<float> c = Gpu.Default.AllocateReadWriteBuffer<float>(16);
using ReadWriteBuffer<float> x = Gpu.Default.AllocateReadWriteBuffer<float>(16);
using ReadWriteBuffer<float> y = Gpu.Default.AllocateReadWriteBuffer<float>(16);
using ReadWriteBuffer<float> z = Gpu.Default.AllocateReadWriteBuffer<float>(16);
DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create();
new AmbiguousNamesShader(a, b, c, x, y, z, 7777, 8888, 9999).LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333);
Assert.AreEqual(6, dataLoader.Values.Length);
Assert.AreEqual(6, dataLoader.Resources.Length);
Assert.AreEqual(111, (int)dataLoader.Values[0]);
Assert.AreEqual(222, (int)dataLoader.Values[1]);
Assert.AreEqual(333, (int)dataLoader.Values[2]);
Assert.AreEqual(7777, (int)dataLoader.Values[3]);
Assert.AreEqual(8888, (int)dataLoader.Values[4]);
Assert.AreEqual(9999, (int)dataLoader.Values[5]);
Assert.AreEqual(a.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]);
Assert.AreEqual(b.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[1]);
Assert.AreEqual(c.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[2]);
Assert.AreEqual(x.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[3]);
Assert.AreEqual(y.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[4]);
Assert.AreEqual(z.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[5]);
}
}
}
+11 -10
ファイルの表示
@@ -1,14 +1,15 @@
using System;
using ComputeSharp.Shaders.Translation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#pragma warning disable CS0618
namespace ComputeSharp.Tests.Internals
{
[TestClass]
[TestCategory("ShaderHashCode")]
public class ShaderHashCodeTests
public partial class ShaderHashCodeTests
{
public struct Shader1 : IComputeShader
public partial struct Shader1 : IComputeShader
{
public float A;
public ReadWriteBuffer<float> B;
@@ -28,19 +29,19 @@ namespace ComputeSharp.Tests.Internals
Shader1 shader1 = new() { A = value, B = buffer };
int
hash1 = ShaderHashCodeProvider.GetHashCode(shader1),
hash2 = ShaderHashCodeProvider.GetHashCode(shader1);
hash1 = shader1.GetDispatchId(),
hash2 = shader1.GetDispatchId();
Assert.IsTrue(hash1 == hash2);
Shader1 shader2 = new() { A = value, B = buffer };
int hash3 = ShaderHashCodeProvider.GetHashCode(shader2);
int hash3 = shader2.GetDispatchId();
Assert.IsTrue(hash1 == hash3);
}
public struct Shader2 : IComputeShader
public partial struct Shader2 : IComputeShader
{
public float A;
public ReadWriteBuffer<float> B;
@@ -62,8 +63,8 @@ namespace ComputeSharp.Tests.Internals
Shader2 shader1 = new() { A = 1, B = buffer, F = f };
int
hash1 = ShaderHashCodeProvider.GetHashCode(shader1),
hash2 = ShaderHashCodeProvider.GetHashCode(shader1);
hash1 = shader1.GetDispatchId(),
hash2 = shader1.GetDispatchId();
Assert.IsTrue(hash1 == hash2);
@@ -71,7 +72,7 @@ namespace ComputeSharp.Tests.Internals
Shader2 shader2 = new() { A = 1, B = buffer, F = f };
int hash3 = ShaderHashCodeProvider.GetHashCode(shader2);
int hash3 = shader2.GetDispatchId();
Assert.IsFalse(hash1 == hash3);
}
+3 -3
ファイルの表示
@@ -75,7 +75,7 @@ namespace ComputeSharp.Tests.SourceGenerators
/// <param name="source">The input source to process.</param>
/// <param name="index">The target index to check in the resulting output.</param>
/// <param name="expectedBody">The expected body to compare with the generated code.</param>
private void VerifyGeneratedMethodLines<TGenerator>(string source, int index, string expectedBody)
private static void VerifyGeneratedMethodLines<TGenerator>(string source, int index, string expectedBody)
where TGenerator : class, ISourceGenerator, new()
{
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source);
@@ -97,8 +97,8 @@ namespace ComputeSharp.Tests.SourceGenerators
string outputBody = outputCompilation.SyntaxTrees.Skip(index + 1).First().ToString();
string[]
outputLines = outputBody.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
expectedLines = expectedBody.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
outputLines = outputBody.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
expectedLines = expectedBody.Replace("\r", "").Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Assert.AreEqual(expectedLines.Length, outputLines.Length);
+49 -49
ファイルの表示
@@ -35,7 +35,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0001");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0001");
}
[TestMethod]
@@ -60,7 +60,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0001");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0001");
}
[TestMethod]
@@ -88,7 +88,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0002");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0002");
}
[TestMethod]
@@ -116,7 +116,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0003");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0003");
}
[TestMethod]
@@ -142,7 +142,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0004");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0004");
}
[TestMethod]
@@ -159,7 +159,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0005");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0005");
}
[TestMethod]
@@ -194,7 +194,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}}
}}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, diagnosticsId);
VerifyGeneratedDiagnostics<IShaderGenerator>(source, diagnosticsId);
}
[TestMethod]
@@ -226,7 +226,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}}
}}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, diagnosticsId);
VerifyGeneratedDiagnostics<IShaderGenerator>(source, diagnosticsId);
}
[TestMethod]
@@ -256,7 +256,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}}
}}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0006");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0006");
}
[TestMethod]
@@ -283,7 +283,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0010");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0010", "CMPS0031");
}
[TestMethod]
@@ -310,7 +310,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0010");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0010", "CMPS0031");
}
[TestMethod]
@@ -337,7 +337,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0011");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0011", "CMPS0031");
}
[TestMethod]
@@ -366,7 +366,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0012");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0012");
}
[TestMethod]
@@ -392,7 +392,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0012");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0012");
}
[TestMethod]
@@ -419,7 +419,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0012", "CMPS0013");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0012", "CMPS0013");
}
[TestMethod]
@@ -448,7 +448,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}}
}}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0014");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0014");
}
[TestMethod]
@@ -480,7 +480,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}}
}}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0015");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0015");
}
[TestMethod]
@@ -512,7 +512,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0016", "CMPS0032");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0016", "CMPS0032");
}
[TestMethod]
@@ -544,7 +544,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0017");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0017");
}
[TestMethod]
@@ -573,7 +573,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0018");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0018");
}
[TestMethod]
@@ -603,7 +603,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0019");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0019");
}
[TestMethod]
@@ -633,7 +633,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0020");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0020");
}
[TestMethod]
@@ -665,7 +665,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0021");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0021");
}
[TestMethod]
@@ -695,7 +695,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0022");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0022");
}
[TestMethod]
@@ -727,7 +727,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0023");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0023");
}
[TestMethod]
@@ -754,7 +754,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0024");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0024");
}
[TestMethod]
@@ -781,7 +781,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0032", "CMPS0025");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0032", "CMPS0025");
}
[TestMethod]
@@ -808,7 +808,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0026");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0026");
}
[TestMethod]
@@ -840,7 +840,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0027");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0027");
}
[TestMethod]
@@ -867,7 +867,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0028");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0028");
}
[TestMethod]
@@ -894,7 +894,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0029");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0029", "CMPS0031");
}
[TestMethod]
@@ -923,7 +923,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0029");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0029", "CMPS0031");
}
[TestMethod]
@@ -956,7 +956,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0030");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0030");
}
[TestMethod]
@@ -983,7 +983,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0031");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0031");
}
[TestMethod]
@@ -1010,7 +1010,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0032");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0032");
}
[TestMethod]
@@ -1037,7 +1037,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0033");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0033");
}
[TestMethod]
@@ -1066,7 +1066,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0034");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0034");
}
[TestMethod]
@@ -1095,7 +1095,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0035");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0035");
}
[TestMethod]
@@ -1124,7 +1124,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0035");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0035");
}
[TestMethod]
@@ -1151,7 +1151,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0036");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0036");
}
[TestMethod]
@@ -1192,7 +1192,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0042");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0042");
}
[TestMethod]
@@ -1220,7 +1220,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0043");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0043");
}
[TestMethod]
@@ -1248,7 +1248,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0045");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0045");
}
[TestMethod]
@@ -1279,7 +1279,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0045");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0045");
}
[TestMethod]
@@ -1307,7 +1307,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0045");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0045");
}
[TestMethod]
@@ -1335,7 +1335,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0045");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0045");
}
[TestMethod]
@@ -1367,7 +1367,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderDataLoaderGenerator>(source, "CMPS0046");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0046");
}
[TestMethod]
@@ -1392,7 +1392,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0047");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0047");
}
/// <summary>
@@ -1402,7 +1402,7 @@ namespace ComputeSharp.Tests.SourceGenerators
/// <param name="source">The input source to process.</param>
/// <param name="index">The target index to check in the resulting output.</param>
/// <param name="expectedBody">The expected body to compare with the generated code.</param>
private void VerifyGeneratedDiagnostics<TGenerator>(string source, params string[] diagnosticsIds)
private static void VerifyGeneratedDiagnostics<TGenerator>(string source, params string[] diagnosticsIds)
where TGenerator : class, ISourceGenerator, new()
{
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source);
+240
ファイルの表示
@@ -0,0 +1,240 @@
using System;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#pragma warning disable IDE0062
namespace ComputeSharp.Tests
{
[TestClass]
[TestCategory("Metaprogramming")]
public partial class MetaprogrammingTests
{
[AutoConstructor]
internal readonly partial struct ActivationWithDelegateShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public readonly Func<int, int> activation;
public void Execute()
{
buffer[ThreadIds.X] = activation(ThreadIds.X);
}
}
public static class Activations
{
[ShaderMethod]
public static int Square(int x) => x * x;
[ShaderMethod]
public static int AddOne(int x) => x + 1;
// Missing attribute
public static int Identity(int x) => x;
[ShaderMethod]
public static int FunctionWithConstants(int x) => (int)(x + FourAndAHalf);
[ShaderMethod]
public static Position FunctionWithTypes(int x)
{
Point point = default;
point.A = x;
point.B = x * x;
Position position = default;
position.X = point.A;
position.Y = point.B;
return position;
}
public struct Point
{
public int A;
public int B;
}
[ShaderMethod]
public static int FunctionWithLocalFunctionAndStaticMethod(int x)
{
static int AddTwo(int x) => x + 2;
return Square(3 + AddOne(x) + AddTwo(x));
}
}
[CombinatorialTestMethod]
[AllDevices]
public unsafe void ActivationWithDelegate(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Square));
int[] result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], Activations.Square(i));
}
device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.AddOne));
result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], Activations.AddOne(i));
}
}
[CombinatorialTestMethod]
[AllDevices]
[ExpectedException(typeof(ArgumentException))]
public unsafe void DelegateWithMissingAttributeOnMethod(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Identity));
}
[CombinatorialTestMethod]
[AllDevices]
[ExpectedException(typeof(ArgumentException))]
public unsafe void DelegateWrappingNonStaticMethod(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
[ShaderMethod]
int Dummy(int x) => x;
device.Get().For(100, new ActivationWithDelegateShader(buffer, Dummy));
}
[AutoConstructor]
internal readonly partial struct ActivationWithMultipleDelegatesShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public readonly Func<int, int> f1;
public readonly Func<int, int> f2;
public void Execute()
{
buffer[ThreadIds.X] = f2(f1(ThreadIds.X));
}
}
[CombinatorialTestMethod]
[AllDevices]
public unsafe void ActivationWithMultipleDelegates(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new ActivationWithMultipleDelegatesShader(buffer, Activations.Square, Activations.AddOne));
int[] result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], Activations.AddOne(Activations.Square(i)));
}
}
public const float FourAndAHalf = 4.5f;
public const int MagicNumber = 42;
[AutoConstructor]
internal readonly partial struct DelegateWithConstantsShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public readonly Func<int, int> activation;
public void Execute()
{
buffer[ThreadIds.X] = MagicNumber + activation(ThreadIds.X);
}
}
[CombinatorialTestMethod]
[AllDevices]
public unsafe void DelegateWithConstants(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new DelegateWithConstantsShader(buffer, Activations.FunctionWithConstants));
int[] result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], MagicNumber + Activations.FunctionWithConstants(i));
}
}
public struct Position
{
public int X;
public int Y;
}
[AutoConstructor]
internal readonly partial struct DelegateWithTypesShader : IComputeShader
{
public readonly ReadWriteBuffer<Position> buffer;
public readonly Func<int, Position> activation;
public void Execute()
{
buffer[ThreadIds.X] = activation(ThreadIds.X);
}
}
[CombinatorialTestMethod]
[AllDevices]
public unsafe void DelegateWithTypes(Device device)
{
using ReadWriteBuffer<Position> buffer = device.Get().AllocateReadWriteBuffer<Position>(100);
device.Get().For(100, new DelegateWithTypesShader(buffer, Activations.FunctionWithTypes));
Position[] result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i].X, Activations.FunctionWithTypes(i).X);
Assert.AreEqual(result[i].Y, Activations.FunctionWithTypes(i).Y);
}
}
[AutoConstructor]
internal readonly partial struct DelegateWithLocalFunctionsAndStaticMethodsShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public readonly Func<int, int> activation;
public void Execute()
{
buffer[ThreadIds.X] = Activations.AddOne(ThreadIds.X) + activation(ThreadIds.X);
}
}
[CombinatorialTestMethod]
[AllDevices]
public unsafe void DelegateWithLocalFunctionsAndStaticMethods(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new DelegateWithLocalFunctionsAndStaticMethodsShader(buffer, Activations.FunctionWithLocalFunctionAndStaticMethod));
int[] result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], Activations.AddOne(i) + Activations.FunctionWithLocalFunctionAndStaticMethod(i));
}
}
}
}
+51
ファイルの表示
@@ -1,3 +1,4 @@
using ComputeSharp;
using ComputeSharp.Interop;
using ComputeSharp.Tests.Misc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
@@ -171,5 +172,55 @@ namespace ComputeSharp.Tests
return new(1, 1, 1, 1);
}
}
[AutoConstructor]
public readonly partial struct LoopWithVarCounterShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
/// <inheritdoc/>
public void Execute()
{
for (var i = 0; i < 10; i++)
{
buffer[ThreadIds.X * 10 + i] = i;
}
}
}
[TestMethod]
public void LoopWithVarCounter()
{
ReflectionServices.GetShaderInfo<LoopWithVarCounterShader>(out var info);
}
}
}
namespace ExternalNamespace
{
[TestClass]
[TestCategory("ShaderCompiler")]
public partial class ShaderCompilerTestsInExternalNamespace
{
[AutoConstructor]
public readonly partial struct UserDefinedTypeShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
/// <inheritdoc/>
public void Execute()
{
for (var i = 0; i < 10; i++)
{
buffer[ThreadIds.X * 10 + i] = i;
}
}
}
[TestMethod]
public void UserDefinedType()
{
ReflectionServices.GetShaderInfo<UserDefinedTypeShader>(out var info);
}
}
}
-1
ファイルの表示
@@ -1,4 +1,3 @@
using System;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
+8 -5
ファイルの表示
@@ -2,6 +2,7 @@ using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
using ComputeSharp.SwapChain.Shaders;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
@@ -10,6 +11,8 @@ using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Png;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
#pragma warning disable CS0618
namespace ComputeSharp.Tests
{
[TestClass]
@@ -112,7 +115,7 @@ namespace ComputeSharp.Tests
shaderType,
texture => new SwapChain.Shaders.Compute.ContouredLayers(texture, 0, background),
texture => new ContouredLayers(0, background),
0.0007f);
0.000703f);
}
/// <summary>
@@ -137,7 +140,7 @@ namespace ComputeSharp.Tests
if (shaderType.IsAssignableTo(typeof(IComputeShader)))
{
static void RunComputeShader<T>(ReadWriteTexture2D<Rgba32, Float4> texture)
where T : struct, IComputeShader
where T : struct, IComputeShader, IShader<T>
{
texture.GraphicsDevice.For(texture.Width, texture.Height, (T)Activator.CreateInstance(typeof(T), texture, 0f)!);
}
@@ -149,7 +152,7 @@ namespace ComputeSharp.Tests
else
{
static void RunPixelShader<T>(ReadWriteTexture2D<Rgba32, Float4> texture)
where T : struct, IPixelShader<Float4>
where T : struct, IPixelShader<Float4>, IShader<T>
{
texture.GraphicsDevice.ForEach(texture, (T)Activator.CreateInstance(typeof(T), 0f)!);
}
@@ -188,8 +191,8 @@ namespace ComputeSharp.Tests
Func<ReadWriteTexture2D<Rgba32, Float4>, TCompute> computeFactory,
Func<ReadWriteTexture2D<Rgba32, Float4>, TPixel> pixelFactory,
float delta)
where TCompute : struct, IComputeShader
where TPixel : struct, IPixelShader<Float4>
where TCompute : struct, IComputeShader, IShader<TCompute>
where TPixel : struct, IPixelShader<Float4>, IShader<TPixel>
{
_ = device.Get();