Remove IShader.GetDispatchId() infrastructure

このコミットが含まれているのは:
Sergio Pedri committed 2023-10-13 10:58:57 +02:00
1 親 9acb650627
コミット 3db275a157
19ファイル変更
+14 -709

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

-1
ファイルの表示
@@ -49,7 +49,6 @@ CMPS0039 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Ser
CMPS0040 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0041 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
-16
ファイルの表示
@@ -586,22 +586,6 @@ partial class DiagnosticDescriptors
description: "A shader type cannot implement more than one shader interface.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a dynamic shader annotated as an embedded bytecode.
/// <para>
/// Format: <c>"The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor EmbeddedBytecodeWithDynamicShader = new DiagnosticDescriptor(
id: "CMPS0043",
title: "Embedded bytecode for dynamic shader",
messageFormat: "The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)",
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A shader type cannot be precompiled if it captures one or more delegate values.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an embedded bytecode shader with invalid thread ids values.
/// <para>
@@ -1,4 +1,3 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using ComputeSharp.__Internals;
@@ -88,15 +87,9 @@ partial class IShaderGenerator
using ImmutableArrayBuilder<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);
@@ -132,67 +125,6 @@ partial class IShaderGenerator
}
}
// Declare the hashsets to track imported members and types from delegates, if needed
if (!hlslSourceInfo.Delegates.IsEmpty)
{
void DeclareMapping(int index, string name, IEnumerable<string> items)
{
// global::System.Collections.Generic.HashSet<string> <NAME> = new();
statements.Insert(index,
LocalDeclarationStatement(VariableDeclaration(
GenericName(Identifier("global::System.Collections.Generic.HashSet"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword))))
.AddVariables(
VariableDeclarator(Identifier(name))
.WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))));
prologueStatements++;
// <NAME>.Add("<ITEM>");
foreach (string 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", hlslSourceInfo.DefinedTypes);
DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants);
DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures);
// Go through all existing delegate fields, if any
foreach (string fieldName in hlslSourceInfo.Delegates)
{
// global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __<DELEGATE_NAME>Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(<DELEGATE_NAME>, "<DELEGATE_NAME>");
statements.Add(
LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"))
.AddVariables(
VariableDeclarator(Identifier($"__{fieldName}Attribute"))
.WithInitializer(
EqualsValueClause(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"),
IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate))))
.AddArgumentListArguments(
Argument(IdentifierName(fieldName)),
Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName)))))))));
capturedDelegates++;
prologueStatements++;
}
}
// Header and thread ids
AppendLine(hlslSourceInfo.HeaderAndThreadsX);
AppendParsedStatement("builder.Append(threadsX);");
@@ -204,68 +136,15 @@ partial class IShaderGenerator
// Define declarations
AppendLine(hlslSourceInfo.Defines);
// Defines from captured delegates
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);");
}
// Static fields and declared types
AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes);
// Declared types from captured delegates
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);");
}
// Captured variables
AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations);
// Forward declarations from captured delegates
foreach (string fieldName in hlslSourceInfo.Delegates)
{
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 (string forwardDeclaration in hlslSourceInfo.MethodSignatures)
{
FlushText();
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("__methodNames"),
IdentifierName("Remove")))
.AddArgumentListArguments(Argument(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration))))));
}
}
// Captured methods
AppendLine(hlslSourceInfo.CapturedMethods);
// Captured methods from captured delegates
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);");
}
// Captured delegate methods
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendLF();
AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");");
AppendLF();
}
// Entry point
AppendLine(hlslSourceInfo.EntryPoint);
+1 -6
ファイルの表示
@@ -62,7 +62,6 @@ partial class IShaderGenerator
bool isComputeShader = pixelShaderSymbol is null;
string? implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!);
(ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, ImmutableArray<(string Name, string HlslType)> valueFields) = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes, isComputeShader);
ImmutableArray<string> delegateInstanceFields = GetDispatchId.GetInfo(structDeclarationSymbol);
ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers = GetSharedBuffers(diagnostics, structDeclarationSymbol, discoveredTypes);
(string entryPoint, ImmutableArray<(string Signature, string Definition)> processedMethods, bool isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, isComputeShader);
(string, string)? implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?);
@@ -78,7 +77,6 @@ partial class IShaderGenerator
declaredTypes,
resourceFields,
valueFields,
delegateInstanceFields,
staticFields,
sharedBuffers,
processedMethods,
@@ -544,7 +542,6 @@ partial class IShaderGenerator
/// <param name="declaredTypes">The sequence of declared types used by the shader.</param>
/// <param name="resourceFields">The sequence of resource instance fields for the current shader.</param>
/// <param name="valueFields">The sequence of value instance fields for the current shader.</param>
/// <param name="delegateInstanceFields">The sequence of delegate fields for the current shader.</param>
/// <param name="staticFields">The sequence of static fields referenced 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>
@@ -558,7 +555,6 @@ partial class IShaderGenerator
ImmutableArray<(string Name, string Definition)> declaredTypes,
ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields,
ImmutableArray<(string Name, string HlslType)> valueFields,
ImmutableArray<string> delegateInstanceFields,
ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers,
ImmutableArray<(string Signature, string Definition)> processedMethods,
@@ -768,8 +764,7 @@ partial class IShaderGenerator
isSamplerUsed,
declaredTypes.Select(static t => t.Name).ToImmutableArray(),
definedConstants.Select(static c => c.Name).ToImmutableArray(),
processedMethods.Select(static m => m.Signature).ToImmutableArray(),
delegateInstanceFields);
processedMethods.Select(static m => m.Signature).ToImmutableArray());
}
/// <summary>
@@ -1,97 +0,0 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.__Internals;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
partial class IShaderGenerator
{
/// <inheritdoc/>
partial class GetDispatchId
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
/// </summary>
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(ImmutableArray<string> delegateFieldNames)
{
// This code produces a method declaration as follows:
//
// readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId()
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("GetDispatchId"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.WithBody(GetShaderHashCodeBody(delegateFieldNames));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
/// </summary>
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
private static BlockSyntax GetShaderHashCodeBody(ImmutableArray<string> delegateFieldNames)
{
if (delegateFieldNames.Length == 0)
{
// return 0;
return
Block(ReturnStatement(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))));
}
List<StatementSyntax> blockStatements = new(4)
{
// global::System.HashCode hashCode = default;
LocalDeclarationStatement(
VariableDeclaration(IdentifierName("global::System.HashCode"))
.AddVariables(
VariableDeclarator(Identifier("hashCode"))
.WithInitializer(EqualsValueClause(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword))))))
};
foreach (string fieldName in delegateFieldNames)
{
// hashCode.Add(delegateField.Method);
blockStatements.Add(ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("Add")))
.AddArgumentListArguments(Argument(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(fieldName),
IdentifierName("Method"))))));
}
// return hashCode.ToHashCode();
blockStatements.Add(ReturnStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("ToHashCode")))));
return Block(blockStatements);
}
}
}
-31
ファイルの表示
@@ -1,31 +0,0 @@
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
partial class IShaderGenerator
{
/// <summary>
/// A helper with all logic to generate the <c>GetDispatchId</c> method.
/// </summary>
private static partial class GetDispatchId
{
/// <summary>
/// Extracts the names of all instance fields of a <see cref="System.Delegate"/> type.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The names of all <see cref="System.Delegate"/> instance fields within <paramref name="structDeclarationSymbol"/>.</returns>
public static ImmutableArray<string> GetInfo(INamedTypeSymbol structDeclarationSymbol)
{
return
structDeclarationSymbol
.GetMembers()
.OfType<IFieldSymbol>()
.Where(static member => member is { Type: INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }, IsImplicitlyDeclared: false })
.Select(static member => member.Name)
.ToImmutableArray();
}
}
}
-10
ファイルの表示
@@ -36,13 +36,11 @@ partial class IShaderGenerator
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <returns>The thread ids for the precompiled shader, if available.</returns>
public static ThreadIdsInfo GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
bool isDynamicShader,
bool supportsDynamicShaders)
{
// Try to get the attribute that controls shader precompilation (has to be present when ComputeSharp.Dynamic is not referenced)
@@ -107,14 +105,6 @@ partial class IShaderGenerator
threadsZ = explicitThreadsZ;
}
// If the current shader is dynamic, emit a diagnostic error
if (isDynamicShader)
{
diagnostics.Add(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol);
return new(true, 0, 0, 0);
}
// Ensure the bytecode generation is disabled if any errors are present. This step is done last to ensure that
// all available diagnostics are still emitted correctly before reaching this point, instead of being disabled.
if (diagnostics.Count > 0)
-21
ファイルの表示
@@ -56,11 +56,6 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
using ImmutableArrayBuilder<DiagnosticInfo> diagnostics = new();
// GetDispatchId() info
ImmutableArray<string> dispatchIdInfo = GetDispatchId.GetInfo(typeSymbol);
token.ThrowIfCancellationRequested();
// LoadDispatchData() info
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
diagnostics,
@@ -93,14 +88,12 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
ThreadIdsInfo threadIds = LoadBytecode.GetInfo(
diagnostics,
typeSymbol,
!hlslSourceInfo.Delegates.IsEmpty,
IsDynamicCompilationSupported(context.SemanticModel.Compilation));
token.ThrowIfCancellationRequested();
return new ShaderInfo(
Hierarchy: HierarchyInfo.From(typeSymbol),
DispatchId: new DispatchIdInfo(dispatchIdInfo),
DispatchData: new DispatchDataInfo(
shaderType,
fieldInfos,
@@ -118,20 +111,6 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
shaderInfoWithErrors
.Select(static (item, _) => item.Diagnostcs));
// Get the GetDispatchId() info (hierarchy and dispatch id info)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchIdInfo DispatchId)> dispatchIdInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.DispatchId));
// Generate the GetDispatchId() methods
context.RegisterSourceOutput(dispatchIdInfo, static (context, item) =>
{
MethodDeclarationSyntax getDispatchIdMethod = GetDispatchId.GetSyntax(item.DispatchId.Delegates);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getDispatchIdMethod, addSkipLocalsInitAttribute: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetDispatchId)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the LoadDispatchData() info (hierarchy and dispatch data info)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo DispatchData)> dispatchDataInfo =
shaderInfoWithErrors
-9
ファイルの表示
@@ -1,9 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model representing gathered info on a shader dispatch id.
/// </summary>
/// <param name="Delegates">The list of delegate field names for the shader.</param>
internal sealed record DispatchIdInfo(EquatableArray<string> Delegates);
+1 -3
ファイルの表示
@@ -18,7 +18,6 @@ namespace ComputeSharp.SourceGenerators.Models;
/// <param name="DefinedTypes">The names of declared types.</param>
/// <param name="DefinedConstants">The names of defined constants.</param>
/// <param name="MethodSignatures">The signatures for captured methods.</param>
/// <param name="Delegates">The list of delegate fields.</param>
internal sealed record HlslShaderSourceInfo(
string HeaderAndThreadsX,
string ThreadsY,
@@ -32,5 +31,4 @@ internal sealed record HlslShaderSourceInfo(
bool IsSamplerUsed,
EquatableArray<string> DefinedTypes,
EquatableArray<string> DefinedConstants,
EquatableArray<string> MethodSignatures,
EquatableArray<string> Delegates);
EquatableArray<string> MethodSignatures);
-2
ファイルの表示
@@ -7,7 +7,6 @@ namespace ComputeSharp.SourceGenerators.Models;
/// A model representing all necessary info for a full generation pass for a shader.
/// </summary>
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
/// <param name="DispatchId">The gathered dispatch id for the shader type.</param>
/// <param name="DispatchData">The gathered shader dispatch data.</param>
/// <param name="DispatchMetadata">The gathered shader dispatch metadata.</param>
/// <param name="HlslShaderSource">The processed HLSL source for the shader.</param>
@@ -15,7 +14,6 @@ namespace ComputeSharp.SourceGenerators.Models;
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record ShaderInfo(
HierarchyInfo Hierarchy,
DispatchIdInfo DispatchId,
DispatchDataInfo DispatchData,
DispatchMetadataInfo DispatchMetadata,
HlslShaderSourceInfo HlslShaderSource,
-8
ファイルの表示
@@ -10,14 +10,6 @@ namespace ComputeSharp.__Internals;
[Obsolete("This interface is not intended to be used directly by user code")]
public interface IShader
{
/// <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>
+1 -1
ファイルの表示
@@ -35,7 +35,7 @@ internal static class PipelineDataLoader<T>
/// <returns>The <see cref="PipelineData"/> instance for a given shader.</returns>
public static unsafe PipelineData GetPipelineData(GraphicsDevice device, int threadsX, int threadsY, int threadsZ, ref T shader)
{
ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, threadsZ);
ShaderKey key = new(threadsX, threadsY, threadsZ);
lock (ShadersCache)
{
+2 -10
ファイルの表示
@@ -8,11 +8,6 @@ namespace ComputeSharp.Shaders.Models;
/// </summary>
internal readonly struct ShaderKey : IEquatable<ShaderKey>
{
/// <summary>
/// The hashcode of the current shader type.
/// </summary>
private readonly int id;
/// <summary>
/// The number of iterations to run on the X axis.
/// </summary>
@@ -31,14 +26,12 @@ internal readonly struct ShaderKey : IEquatable<ShaderKey>
/// <summary>
/// Creates a new <see cref="ShaderKey"/> instance with the specified parameters.
/// </summary>
/// <param name="id">The hashcode of the current shader type.</param>
/// <param name="threadsX">The number of iterations to run on the X axis.</param>
/// <param name="threadsY">The number of iterations to run on the Y axis.</param>
/// <param name="threadsZ">The number of iterations to run on the Z axis.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ShaderKey(int id, int threadsX, int threadsY, int threadsZ)
public ShaderKey(int threadsX, int threadsY, int threadsZ)
{
this.id = id;
this.threadsX = threadsX;
this.threadsY = threadsY;
this.threadsZ = threadsZ;
@@ -49,7 +42,6 @@ internal readonly struct ShaderKey : IEquatable<ShaderKey>
public bool Equals(ShaderKey other)
{
return
this.id == other.id &&
this.threadsX == other.threadsX &&
this.threadsY == other.threadsY &&
this.threadsZ == other.threadsZ;
@@ -65,6 +57,6 @@ internal readonly struct ShaderKey : IEquatable<ShaderKey>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
return HashCode.Combine(this.id, this.threadsX, this.threadsY, this.threadsZ);
return HashCode.Combine(this.threadsX, this.threadsY, this.threadsZ);
}
}
@@ -10,7 +10,6 @@
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Dynamic\ComputeSharp.Dynamic.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
</ItemGroup>
</Project>
+9 -8
ファイルの表示
@@ -5,11 +5,11 @@ float[] numbers = Enumerable.Range(0, 128).Select(i => (float)i).ToArray();
using GraphicsDevice device = GraphicsDevice.GetDefault();
using ReadWriteBuffer<float> buffer = device.AllocateReadWriteBuffer(numbers);
device.For(buffer.Length, new ApplyFunctionShader(buffer, AddHalf));
device.For(buffer.Length, new ApplyFunctionShader(buffer));
foreach (ref float number in numbers.AsSpan())
{
number = AddHalf(number);
number = ApplyFunctionShader.AddHalf(number);
}
float[] result = buffer.ToArray();
@@ -21,18 +21,19 @@ if (!numbers.SequenceEqual(result))
Console.WriteLine("Test passed successfully!");
// See https://github.com/Sergio0694/ComputeSharp/issues/374
[ShaderMethod]
static float AddHalf(float input) => input + 0.5f;
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct ApplyFunctionShader : IComputeShader
{
private readonly ReadWriteBuffer<float> sourceTexture;
private readonly Func<float, float> func;
public static float AddHalf(float input)
{
return input + 0.5f;
}
public void Execute()
{
this.sourceTexture[ThreadIds.X] = this.func(this.sourceTexture[ThreadIds.X]);
this.sourceTexture[ThreadIds.X] = AddHalf(this.sourceTexture[ThreadIds.X]);
}
}
-78
ファイルの表示
@@ -1,78 +0,0 @@
using System;
using ComputeSharp.__Internals;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#pragma warning disable CS0618
namespace ComputeSharp.Tests.Internals;
[TestClass]
[TestCategory("ShaderHashCode")]
public partial class ShaderHashCodeTests
{
public partial struct Shader1 : IComputeShader
{
public float A;
public ReadWriteBuffer<float> B;
public void Execute()
{
this.B[0] = this.A;
}
}
[TestMethod]
public void ShaderWithNoCapturedDelegates()
{
float value = 10;
using ReadWriteBuffer<float> buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer<float>(1);
Shader1 shader1 = new() { A = value, B = buffer };
int hash1 = ((IShader)shader1).GetDispatchId();
int hash2 = ((IShader)shader1).GetDispatchId();
Assert.IsTrue(hash1 == hash2);
Shader1 shader2 = new() { A = value, B = buffer };
int hash3 = ((IShader)shader2).GetDispatchId();
Assert.IsTrue(hash1 == hash3);
}
public partial struct Shader2 : IComputeShader
{
public float A;
public ReadWriteBuffer<float> B;
public Func<float, float> F;
public void Execute()
{
this.B[0] = this.F(this.A);
}
}
[TestMethod]
public void ShaderWithCapturedDelegates()
{
Func<float, float> f = static x => x * x;
using ReadWriteBuffer<float> buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer<float>(1);
Shader2 shader1 = new() { A = 1, B = buffer, F = f };
int hash1 = ((IShader)shader1).GetDispatchId();
int hash2 = ((IShader)shader1).GetDispatchId();
Assert.IsTrue(hash1 == hash2);
f = static x => x + 1;
Shader2 shader2 = new() { A = 1, B = buffer, F = f };
int hash3 = ((IShader)shader2).GetDispatchId();
Assert.IsFalse(hash1 == hash3);
}
}
-35
ファイルの表示
@@ -1481,41 +1481,6 @@ public class DiagnosticsTests
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0042", "CMPS0047");
}
[TestMethod]
public void EmbeddedBytecodeWithDynamicShader()
{
const string source = """
using System;
using ComputeSharp;
namespace ComputeSharp
{
public interface IComputeShader { }
public class ReadWriteBuffer<T> { }
public class EmbeddedBytecodeAttribute : Attribute
{
public EmbeddedBytecodeAttribute(int threadsX, int threadsY, int threadsZ) { }
}
}
namespace MyFancyApp.Sample
{
[EmbeddedBytecode(8, 8, 1)]
public struct MyShader : IComputeShader
{
public ReadWriteBuffer<float> buffer;
public Action action;
public void Execute()
{
}
}
}
""";
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0043");
}
[TestMethod]
[DataRow(-1, 1, 1)]
[DataRow(1, -1, 1)]
-251
ファイルの表示
@@ -1,251 +0,0 @@
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()
{
this.buffer[ThreadIds.X] = this.activation(ThreadIds.X);
}
}
public static class Activations
{
[ShaderMethod]
public static int Square(int x)
{
return x * x;
}
[ShaderMethod]
public static int AddOne(int x)
{
return x + 1;
}
// Missing attribute
public static int Identity(int x)
{
return x;
}
[ShaderMethod]
public static int FunctionWithConstants(int x)
{
return (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()
{
this.buffer[ThreadIds.X] = this.f2(this.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()
{
this.buffer[ThreadIds.X] = MagicNumber + this.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()
{
this.buffer[ThreadIds.X] = this.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()
{
this.buffer[ThreadIds.X] = Activations.AddOne(ThreadIds.X) + this.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));
}
}
}