Merge pull request #716 from Sergio0694/dev/forward-declarations

Use forward declarations for user types and all methods
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-12-14 14:51:08 +01:00
コミット 161040818f
8ファイル変更
+615 -146

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

+25 -66
ファイルの表示
@@ -97,12 +97,14 @@ partial class D2DPixelShaderDescriptorGenerator
token.ThrowIfCancellationRequested();
// Process the discovered types and constants
ImmutableArray<HlslUserType> declaredTypes = HlslDefinitionsSyntaxProcessor.GetDeclaredTypes(
HlslDefinitionsSyntaxProcessor.GetDeclaredTypes(
diagnostics,
structDeclarationSymbol,
discoveredTypes,
instanceMethods,
constructors);
constructors,
out ImmutableArray<HlslUserType> typeDeclarations,
out ImmutableArray<string> typeMethodDeclarations);
token.ThrowIfCancellationRequested();
@@ -125,11 +127,12 @@ partial class D2DPixelShaderDescriptorGenerator
// Get the HLSL source
return GetHlslSource(
definedConstants,
declaredTypes,
valueFields,
resourceTextureFields,
staticFields,
processedMethods,
typeDeclarations,
typeMethodDeclarations,
entryPoint,
inputCount,
inputSimpleIndices,
@@ -448,12 +451,13 @@ partial class D2DPixelShaderDescriptorGenerator
/// <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="declaredTypes">The sequence of declared types used by the shader.</param>
/// <param name="valueFields">The sequence of value instance fields for the current shader.</param>
/// <param name="definedConstants"><inheritdoc cref="HlslSourceHelper.WriteTopDeclarations" path="/param[@name='definedConstants']/node()"/></param>
/// <param name="valueFields"><inheritdoc cref="HlslSourceHelper.WriteCapturedFields" path="/param[@name='valueFields']/node()"/></param>
/// <param name="resourceTextureFields">The sequence of captured resource textures for the current shader.</param>
/// <param name="staticFields">The sequence of static fields referenced by the shader.</param>
/// <param name="processedMethods">The sequence of processed methods used by the shader.</param>
/// <param name="staticFields"><inheritdoc cref="HlslSourceHelper.WriteTopDeclarations" path="/param[@name='staticFields']/node()"/></param>
/// <param name="processedMethods"><inheritdoc cref="HlslSourceHelper.WriteTopDeclarations" path="/param[@name='processedMethods']/node()"/></param>
/// <param name="typeDeclarations"><inheritdoc cref="HlslSourceHelper.WriteTopDeclarations" path="/param[@name='typeDeclarations']/node()"/></param>
/// <param name="typeMethodDeclarations"><inheritdoc cref="HlslSourceHelper.WriteMethodDeclarations" path="/param[@name='typeMethodDeclarations']/node()"/></param>
/// <param name="executeMethod">The body of the entry point of the shader.</param>
/// <param name="inputCount">The number of shader inputs to declare.</param>
/// <param name="inputSimpleIndices">The indicess of the simple shader inputs.</param>
@@ -462,11 +466,12 @@ partial class D2DPixelShaderDescriptorGenerator
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
private static string GetHlslSource(
ImmutableArray<HlslConstant> definedConstants,
ImmutableArray<HlslUserType> declaredTypes,
ImmutableArray<HlslValueField> valueFields,
ImmutableArray<HlslResourceTextureField> resourceTextureFields,
ImmutableArray<HlslStaticField> staticFields,
ImmutableArray<HlslMethod> processedMethods,
ImmutableArray<HlslUserType> typeDeclarations,
ImmutableArray<string> typeMethodDeclarations,
string executeMethod,
int inputCount,
ImmutableArray<int> inputSimpleIndices,
@@ -475,17 +480,9 @@ partial class D2DPixelShaderDescriptorGenerator
{
using IndentedTextWriter writer = new();
// Header
writer.WriteLine("""
// ================================================
// AUTO GENERATED
// ================================================
// This shader was created by ComputeSharp.
// See: https://github.com/Sergio0694/ComputeSharp.
""", isMultiline: true);
HlslSourceHelper.WriteHeader(writer);
// Shader metadata
writer.WriteLine();
writer.WriteLine($"#define D2D_INPUT_COUNT {inputCount}");
foreach (int simpleInput in inputSimpleIndices)
@@ -505,41 +502,16 @@ partial class D2DPixelShaderDescriptorGenerator
writer.WriteLine("#include \"d2d1effecthelpers.hlsli\"");
writer.WriteLine();
// Define declarations
foreach (HlslConstant constant in definedConstants)
{
writer.WriteLine($"#define {constant.Name} {constant.Value}");
}
// The FXC compiler does not support type forward declarations
HlslSourceHelper.WriteTopDeclarations(
writer,
definedConstants,
staticFields,
processedMethods,
typeDeclarations,
includeTypeForwardDeclarations: false);
writer.WriteLine(skipIfPresent: true);
// Static fields
foreach (HlslStaticField field in staticFields)
{
if (field.Assignment is string assignment)
{
writer.WriteLine($"{field.TypeDeclaration} {field.Name} = {assignment};");
}
else
{
writer.WriteLine($"{field.TypeDeclaration} {field.Name};");
}
}
// Declared types
foreach (HlslUserType userType in declaredTypes)
{
writer.WriteLine(skipIfPresent: true);
writer.WriteLine(userType.Definition);
}
writer.WriteLine(skipIfPresent: true);
// Captured variables
foreach (HlslValueField valueField in valueFields)
{
writer.WriteLine($"{valueField.Type} {valueField.Name};");
}
HlslSourceHelper.WriteCapturedFields(writer, valueFields);
// Resource textures
foreach (HlslResourceTextureField field in resourceTextureFields)
@@ -549,22 +521,9 @@ partial class D2DPixelShaderDescriptorGenerator
writer.WriteLine($"SamplerState __sampler__{field.Name} : register(s{field.Index});");
}
// Forward declarations
foreach (HlslMethod method in processedMethods)
{
writer.WriteLine(skipIfPresent: true);
writer.WriteLine(method.Signature);
}
// Captured methods
foreach (HlslMethod method in processedMethods)
{
writer.WriteLine(skipIfPresent: true);
writer.WriteLine(method.Declaration);
}
HlslSourceHelper.WriteMethodDeclarations(writer, processedMethods, typeMethodDeclarations);
// Entry point
writer.WriteLine(skipIfPresent: true);
writer.WriteLine(executeMethod);
return writer.ToString();
@@ -30,6 +30,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Models\Interfaces\IConstantBufferInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\TypeAliases.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SyntaxProcessors\ConstantBufferSyntaxProcessor.Generation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\HlslSourceHelper.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SyntaxProcessors\HlslDefinitionsSyntaxProcessor.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SyntaxRewriters\HlslSourceRewriter.Tracking.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SyntaxRewriters\HlslSourceRewriter.cs" />
+146
ファイルの表示
@@ -0,0 +1,146 @@
using System.Collections.Immutable;
namespace ComputeSharp.SourceGeneration.Helpers;
/// <summary>
/// A helper type to write HLSL source.
/// </summary>
internal static class HlslSourceHelper
{
/// <summary>
/// Writes the header included at the top of each generated HLSL shader.
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteHeader(IndentedTextWriter writer)
{
writer.WriteLine("""
// ================================================
// AUTO GENERATED
// ================================================
// This shader was created by ComputeSharp.
// See: https://github.com/Sergio0694/ComputeSharp.
""", isMultiline: true);
writer.WriteLine();
}
/// <summary>
/// Writes the top declarations in each generated HLSL shader:
/// <list type="bullet">
/// <item>Defined constants.</item>
/// <item>Type forward declarations (optional).</item>
/// <item>Method forward declarations.</item>
/// <item>Static fields.</item>
/// <item>Type declarations.</item>
/// </list>
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <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="processedMethods">The sequence of processed methods used by the shader.</param>
/// <param name="typeDeclarations">The collection of declarations of all custom types.</param>
/// <param name="includeTypeForwardDeclarations">Whether to include type forward declarations (if supported).</param>
public static void WriteTopDeclarations(
IndentedTextWriter writer,
ImmutableArray<HlslConstant> definedConstants,
ImmutableArray<HlslStaticField> staticFields,
ImmutableArray<HlslMethod> processedMethods,
ImmutableArray<HlslUserType> typeDeclarations,
bool includeTypeForwardDeclarations)
{
// Define declarations
foreach (HlslConstant constant in definedConstants)
{
writer.WriteLine($"#define {constant.Name} {constant.Value}");
}
writer.WriteLine(skipIfPresent: true);
// Forward declarations of discovered types, only if supported
if (includeTypeForwardDeclarations)
{
foreach (HlslUserType userType in typeDeclarations)
{
writer.WriteLine($"struct {userType.Name};");
}
writer.WriteLine(skipIfPresent: true);
}
// Forward declarations of shader/static methods
foreach (HlslMethod method in processedMethods)
{
writer.WriteLine(skipIfPresent: true);
writer.WriteLine(method.Signature);
}
writer.WriteLine(skipIfPresent: true);
// Static fields
foreach (HlslStaticField field in staticFields)
{
if (field.Assignment is string assignment)
{
writer.WriteLine($"{field.TypeDeclaration} {field.Name} = {assignment};");
}
else
{
writer.WriteLine($"{field.TypeDeclaration} {field.Name};");
}
}
writer.WriteLine(skipIfPresent: true);
// Declared types
foreach (HlslUserType userType in typeDeclarations)
{
writer.WriteLine(skipIfPresent: true);
writer.WriteLine(userType.Definition);
}
writer.WriteLine(skipIfPresent: true);
}
/// <summary>
/// Writes the declarations for captured shader fields.
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="valueFields">The sequence of value instance fields for the current shader.</param>
public static void WriteCapturedFields(
IndentedTextWriter writer,
ImmutableArray<HlslValueField> valueFields)
{
foreach (HlslValueField valueField in valueFields)
{
writer.WriteLine($"{valueField.Type} {valueField.Name};");
}
}
/// <summary>
/// Writes all method declarations (ie. implementations of previous forward declarations).
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="processedMethods">The sequence of processed methods used by the shader.</param>
/// <param name="typeMethodDeclarations">The collection of implementations of all methods in all custom types.</param>
public static void WriteMethodDeclarations(
IndentedTextWriter writer,
ImmutableArray<HlslMethod> processedMethods,
ImmutableArray<string> typeMethodDeclarations)
{
// Method declarations for discovered types
foreach (string method in typeMethodDeclarations)
{
writer.WriteLine(skipIfPresent: true);
writer.WriteLine(method);
}
// Captured methods
foreach (HlslMethod method in processedMethods)
{
writer.WriteLine(skipIfPresent: true);
writer.WriteLine(method.Declaration);
}
writer.WriteLine(skipIfPresent: true);
}
}
@@ -143,15 +143,19 @@ internal static class HlslDefinitionsSyntaxProcessor
/// <param name="types">The sequence of discovered custom types.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constructors">The collection of discovered constructors for custom struct types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
public static ImmutableArray<HlslUserType> GetDeclaredTypes(
/// <param name="typeDeclarations">The collection of declarations of all custom types.</param>
/// <param name="methodDeclarations">The collection of implementations of all methods in all custom types.</param>
public static void GetDeclaredTypes(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
IEnumerable<INamedTypeSymbol> types,
IReadOnlyDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IReadOnlyDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors)
IReadOnlyDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
out ImmutableArray<HlslUserType> typeDeclarations,
out ImmutableArray<string> methodDeclarations)
{
using ImmutableArrayBuilder<HlslUserType> builder = new();
using ImmutableArrayBuilder<HlslUserType> typeDeclarationsBuilder = new();
using ImmutableArrayBuilder<string> methodDeclarationsBuilder = new();
IReadOnlyCollection<INamedTypeSymbol> invalidTypes;
@@ -223,11 +227,33 @@ internal static class HlslDefinitionsSyntaxProcessor
}
}
// Declare the methods of the current type
structDeclaration = structDeclaration.WithMembers(structDeclaration.Members.AddRange(GatherInstanceMethods(type, instanceMethods, constructors)));
using (ImmutableArrayBuilder<MethodDeclarationSyntax> methodDefinitions = new())
{
// Forward declarations for all methods, and implementations.
// We need these to ensure things work with arbitrary ordering.
foreach (MethodDeclarationSyntax methodDeclaration in GatherInstanceMethods(type, instanceMethods, constructors))
{
methodDefinitions.Add(methodDeclaration.AsDefinition());
// We need to normalize the whitespaces here, as this methhod declaration will not be added to
// the list of members for the struct declaration, but rather it will be written directly into
// the resulting HLSL source (as the implementation of this forward declaration). For the same
// reason, we also need to change the identifier to also include the containing type with '::'.
string methodImplementation =
methodDeclaration
.WithIdentifier(Identifier($"{structType}::{methodDeclaration.Identifier.Text}"))
.NormalizeWhitespace(eol: "\n")
.ToFullString();
methodDeclarationsBuilder.Add(methodImplementation);
}
// Add all method forward declarations to the current type
structDeclaration = structDeclaration.WithMembers(structDeclaration.Members.AddRange(methodDefinitions.AsEnumerable()));
}
// Insert the trailing ; right after the closing bracket (after normalization)
builder.Add((
typeDeclarationsBuilder.Add((
structType,
structDeclaration
.NormalizeWhitespace(eol: "\n")
@@ -241,7 +267,8 @@ internal static class HlslDefinitionsSyntaxProcessor
diagnostics.Add(InvalidDiscoveredType, structDeclarationSymbol, structDeclarationSymbol, invalidType);
}
return builder.ToImmutable();
typeDeclarations = typeDeclarationsBuilder.ToImmutable();
methodDeclarations = methodDeclarationsBuilder.ToImmutable();
}
/// <summary>
+24 -65
ファイルの表示
@@ -114,12 +114,14 @@ partial class ComputeShaderDescriptorGenerator
token.ThrowIfCancellationRequested();
// Process the discovered types and constants
ImmutableArray<HlslUserType> declaredTypes = HlslDefinitionsSyntaxProcessor.GetDeclaredTypes(
HlslDefinitionsSyntaxProcessor.GetDeclaredTypes(
diagnostics,
structDeclarationSymbol,
discoveredTypes,
instanceMethods,
constructors);
constructors,
out ImmutableArray<HlslUserType> typeDeclarations,
out ImmutableArray<string> typeMethodDeclarations);
token.ThrowIfCancellationRequested();
@@ -136,12 +138,13 @@ partial class ComputeShaderDescriptorGenerator
threadsY,
threadsZ,
definedConstants,
declaredTypes,
resourceFields,
valueFields,
staticFields,
sharedBuffers,
processedMethods,
typeDeclarations,
typeMethodDeclarations,
isComputeShader,
implicitTextureType,
isSamplerUsed,
@@ -486,13 +489,14 @@ partial class ComputeShaderDescriptorGenerator
/// <param name="threadsX">The thread ids value for the X axis.</param>
/// <param name="threadsY">The thread ids value for the Y axis.</param>
/// <param name="threadsZ">The thread ids value for the Z axis.</param>
/// <param name="definedConstants">The sequence of defined constants for the shader.</param>
/// <param name="declaredTypes">The sequence of declared types used by the shader.</param>
/// <param name="definedConstants"><inheritdoc cref="HlslSourceHelper.WriteTopDeclarations" path="/param[@name='definedConstants']/node()"/></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="staticFields">The sequence of static fields referenced by the shader.</param>
/// <param name="valueFields"><inheritdoc cref="HlslSourceHelper.WriteCapturedFields" path="/param[@name='valueFields']/node()"/></param>
/// <param name="staticFields"><inheritdoc cref="HlslSourceHelper.WriteTopDeclarations" path="/param[@name='staticFields']/node()"/></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="processedMethods"><inheritdoc cref="HlslSourceHelper.WriteTopDeclarations" path="/param[@name='processedMethods']/node()"/></param>
/// <param name="typeDeclarations"><inheritdoc cref="HlslSourceHelper.WriteTopDeclarations" path="/param[@name='typeDeclarations']/node()"/></param>
/// <param name="typeMethodDeclarations"><inheritdoc cref="HlslSourceHelper.WriteMethodDeclarations" path="/param[@name='typeMethodDeclarations']/node()"/></param>
/// <param name="isComputeShader">Whether or not the current shader type is a compute 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>
@@ -503,12 +507,13 @@ partial class ComputeShaderDescriptorGenerator
int threadsY,
int threadsZ,
ImmutableArray<HlslConstant> definedConstants,
ImmutableArray<HlslUserType> declaredTypes,
ImmutableArray<HlslResourceField> resourceFields,
ImmutableArray<HlslValueField> valueFields,
ImmutableArray<HlslStaticField> staticFields,
ImmutableArray<HlslSharedBuffer> sharedBuffers,
ImmutableArray<HlslMethod> processedMethods,
ImmutableArray<HlslUserType> typeDeclarations,
ImmutableArray<string> typeMethodDeclarations,
bool isComputeShader,
string? implicitTextureType,
bool isSamplerUsed,
@@ -516,50 +521,21 @@ partial class ComputeShaderDescriptorGenerator
{
using IndentedTextWriter writer = new();
// Header
writer.WriteLine("""
// ================================================
// AUTO GENERATED
// ================================================
// This shader was created by ComputeSharp.
// See: https://github.com/Sergio0694/ComputeSharp.
""", isMultiline: true);
HlslSourceHelper.WriteHeader(writer);
// Group size constants
writer.WriteLine();
writer.WriteLine($"#define __GroupSize__get_X {threadsX}");
writer.WriteLine($"#define __GroupSize__get_Y {threadsY}");
writer.WriteLine($"#define __GroupSize__get_Z {threadsZ}");
// Define declarations
foreach (HlslConstant constant in definedConstants)
{
writer.WriteLine($"#define {constant.Name} {constant.Value}");
}
HlslSourceHelper.WriteTopDeclarations(
writer,
definedConstants,
staticFields,
processedMethods,
typeDeclarations,
includeTypeForwardDeclarations: true);
writer.WriteLine(skipIfPresent: true);
// Static fields
foreach (HlslStaticField field in staticFields)
{
if (field.Assignment is string assignment)
{
writer.WriteLine($"{field.TypeDeclaration} {field.Name} = {assignment};");
}
else
{
writer.WriteLine($"{field.TypeDeclaration} {field.Name};");
}
}
// Declared types
foreach (HlslUserType userType in declaredTypes)
{
writer.WriteLine(skipIfPresent: true);
writer.WriteLine(userType.Definition);
}
writer.WriteLine(skipIfPresent: true);
writer.WriteLine("cbuffer _ : register(b0)");
// Captured variables
@@ -569,11 +545,7 @@ partial class ComputeShaderDescriptorGenerator
writer.WriteLine("uint __y;");
writer.WriteLineIf(isComputeShader, "uint __z;");
// User-defined values
foreach (HlslValueField valueField in valueFields)
{
writer.WriteLine($"{valueField.Type} {valueField.Name};");
}
HlslSourceHelper.WriteCapturedFields(writer, valueFields);
}
int constantBuffersCount = 1;
@@ -621,22 +593,9 @@ partial class ComputeShaderDescriptorGenerator
writer.WriteLine($"groupshared {buffer.Type} {buffer.Name} [{count}];");
}
// Forward declarations
foreach (HlslMethod method in processedMethods)
{
writer.WriteLine(skipIfPresent: true);
writer.WriteLine(method.Signature);
}
// Captured methods
foreach (HlslMethod method in processedMethods)
{
writer.WriteLine(skipIfPresent: true);
writer.WriteLine(method.Declaration);
}
HlslSourceHelper.WriteMethodDeclarations(writer, processedMethods, typeMethodDeclarations);
// Entry point
writer.WriteLine(skipIfPresent: true);
writer.WriteLine("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]");
writer.WriteLine(executeMethod);
@@ -0,0 +1,50 @@
#pragma warning disable IDE0290, CA1822
namespace ComputeSharp.D2D1.Tests.Effects;
public struct ColorWrapperUsingExternalType
{
private float4 value;
public ColorWrapperUsingExternalType(float4 color)
{
this.value = color;
}
public readonly float4 Invert()
{
ColorProcessor processor = default;
return processor.Invert(this.value);
}
public readonly float4 Invert(float4 value)
{
return new(Hlsl.Saturate(1.0f - value.RGB), 1);
}
}
public struct ColorProcessor
{
public readonly float4 Invert(float4 value)
{
ColorWrapperUsingExternalType dummy = default;
return dummy.Invert(value);
}
}
[D2DInputCount(1)]
[D2DInputSimple(0)]
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
[D2DGeneratedPixelShaderDescriptor]
public partial struct InvertWithUserTypeAndMutuallyInvokingMethods : ID2D1PixelShader
{
/// <inheritdoc/>
public float4 Execute()
{
ColorWrapperUsingExternalType wrapper = new(D2D.GetInput(0));
return wrapper.Invert();
}
}
+6
ファイルの表示
@@ -38,6 +38,12 @@ public class EffectsTests
D2D1TestRunner.RunAndCompareShader(new InvertWithUserTypeWithConstructorEffect(), null, "Landscape.png", "Landscape_Inverted.png");
}
[TestMethod]
public void InvertWithUserTypeAndMutuallyInvokingMethods()
{
D2D1TestRunner.RunAndCompareShader(new InvertWithUserTypeAndMutuallyInvokingMethods(), null, "Landscape.png", "Landscape_Inverted.png");
}
[TestMethod]
public void Pixelate()
{
+328 -7
ファイルの表示
@@ -5,7 +5,7 @@ using ComputeSharp.Interop;
using ComputeSharp.Tests.Misc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#pragma warning disable IDE0008, IDE0022, IDE0009
#pragma warning disable IDE0008, IDE0022, IDE0009, IDE0290
namespace ComputeSharp.Tests
{
@@ -722,6 +722,10 @@ namespace ComputeSharp.Tests
#define __GroupSize__get_Y 1
#define __GroupSize__get_Z 1
static void Foo(in int a, in int b, inout int c, out int d);
static void Bar(in int a, in int b, inout int c, out int d);
cbuffer _ : register(b0)
{
uint __x;
@@ -731,10 +735,6 @@ namespace ComputeSharp.Tests
RWStructuredBuffer<float> __reserved__buffer : register(u0);
static void Foo(in int a, in int b, inout int c, out int d);
static void Bar(in int a, in int b, inout int c, out int d);
static void Foo(in int a, in int b, inout int c, out int d)
{
d = 0;
@@ -805,6 +805,8 @@ namespace ComputeSharp.Tests
#define __GroupSize__get_Z 1
#define __ComputeSharp_Tests_ShaderCompilerTests_ShaderWithPartialDeclarations__a 2
static int Sum(int x, int y);
static const int b = 4;
cbuffer _ : register(b0)
@@ -816,8 +818,6 @@ namespace ComputeSharp.Tests
RWStructuredBuffer<float> __reserved__buffer : register(u0);
static int Sum(int x, int y);
static int Sum(int x, int y)
{
return x + y;
@@ -873,6 +873,327 @@ namespace ComputeSharp.Tests
return x + y;
}
}
[TestMethod]
public void ShaderWithStructMethodCallingOtherStructMethod_IsProcessedCorrectly()
{
ShaderInfo info = ReflectionServices.GetShaderInfo<ShaderWithStructMethodCallingOtherStructMethod>();
Assert.AreEqual(
"""
// ================================================
// AUTO GENERATED
// ================================================
// This shader was created by ComputeSharp.
// See: https://github.com/Sergio0694/ComputeSharp.
#define __GroupSize__get_X 64
#define __GroupSize__get_Y 1
#define __GroupSize__get_Z 1
struct ComputeSharp_Tests_ShaderCompilerTests_StructWithInstanceMethod1;
struct ComputeSharp_Tests_ShaderCompilerTests_StructWithInstanceMethod2;
struct ComputeSharp_Tests_ShaderCompilerTests_StructWithInstanceMethod1
{
int InstanceMethod();
};
struct ComputeSharp_Tests_ShaderCompilerTests_StructWithInstanceMethod2
{
int InstanceMethod();
};
cbuffer _ : register(b0)
{
uint __x;
uint __y;
uint __z;
}
RWStructuredBuffer<int> __reserved__buffer : register(u0);
int ComputeSharp_Tests_ShaderCompilerTests_StructWithInstanceMethod1::InstanceMethod()
{
ComputeSharp_Tests_ShaderCompilerTests_StructWithInstanceMethod2 bar = (ComputeSharp_Tests_ShaderCompilerTests_StructWithInstanceMethod2)0;
return bar.InstanceMethod();
}
int ComputeSharp_Tests_ShaderCompilerTests_StructWithInstanceMethod2::InstanceMethod()
{
return 42;
}
[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]
void Execute(uint3 ThreadIds : SV_DispatchThreadID)
{
if (ThreadIds.x < __x && ThreadIds.y < __y && ThreadIds.z < __z)
{
ComputeSharp_Tests_ShaderCompilerTests_StructWithInstanceMethod1 foo = (ComputeSharp_Tests_ShaderCompilerTests_StructWithInstanceMethod1)0;
__reserved__buffer[ThreadIds.x] = foo.InstanceMethod();
}
}
""",
info.HlslSource);
}
// See https://github.com/Sergio0694/ComputeSharp/issues/479
[AutoConstructor]
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
public readonly partial struct ShaderWithStructMethodCallingOtherStructMethod : IComputeShader
{
private readonly ReadWriteBuffer<int> buffer;
public void Execute()
{
StructWithInstanceMethod1 foo = default;
buffer[ThreadIds.X] = foo.InstanceMethod();
}
}
public struct StructWithInstanceMethod1
{
public int InstanceMethod()
{
StructWithInstanceMethod2 bar = default;
return bar.InstanceMethod();
}
}
public struct StructWithInstanceMethod2
{
public int InstanceMethod()
{
return 42;
}
}
[TestMethod]
public void ShaderWithAllSupportedMembers_IsProcessedCorrectly()
{
ShaderInfo info = ReflectionServices.GetShaderInfo<ShaderWithAllSupportedMembers>();
Assert.AreEqual(
"""
// ================================================
// AUTO GENERATED
// ================================================
// This shader was created by ComputeSharp.
// See: https://github.com/Sergio0694/ComputeSharp.
#define __GroupSize__get_X 64
#define __GroupSize__get_Y 1
#define __GroupSize__get_Z 1
#define __ComputeSharp_Tests_ShaderCompilerTests_ExternalContainerClass__Factor 8
#define __ComputeSharp_Tests_ShaderCompilerTests_ShaderWithAllSupportedMembers__PI 3.14
struct ComputeSharp_Tests_ShaderCompilerTests_StructType1;
struct ComputeSharp_Tests_ShaderCompilerTests_StructType2;
int InstanceMethodInShader();
static float StaticMethodInShader(float x);
static float ComputeSharp_Tests_ShaderCompilerTests_StructType1_StaticMethod(int x);
static float ComputeSharp_Tests_ShaderCompilerTests_StructType2_StaticMethod(int x);
static const float Init = abs(__ComputeSharp_Tests_ShaderCompilerTests_ShaderWithAllSupportedMembers__PI);
static int Temp;
static int ComputeSharp_Tests_ShaderCompilerTests_ExternalContainerClass_Temp;
static const float ComputeSharp_Tests_ShaderCompilerTests_ExternalContainerClass_PI2 = 3.14 * 2;
struct ComputeSharp_Tests_ShaderCompilerTests_StructType1
{
int X;
float Y;
float Combine(ComputeSharp_Tests_ShaderCompilerTests_StructType2 other);
static ComputeSharp_Tests_ShaderCompilerTests_StructType1 __ctor(int x);
void __ctor__init(int x);
};
struct ComputeSharp_Tests_ShaderCompilerTests_StructType2
{
float2 V;
float Combine(ComputeSharp_Tests_ShaderCompilerTests_StructType1 other);
};
cbuffer _ : register(b0)
{
uint __x;
uint __y;
uint __z;
int number;
float4 __reserved__vector;
}
RWStructuredBuffer<int> __reserved__buffer : register(u0);
float ComputeSharp_Tests_ShaderCompilerTests_StructType1::Combine(ComputeSharp_Tests_ShaderCompilerTests_StructType2 other)
{
return Y + other.V.y;
}
static ComputeSharp_Tests_ShaderCompilerTests_StructType1 ComputeSharp_Tests_ShaderCompilerTests_StructType1::__ctor(int x)
{
ComputeSharp_Tests_ShaderCompilerTests_StructType1 __this = (ComputeSharp_Tests_ShaderCompilerTests_StructType1)0;
__this.__ctor__init(x);
return __this;
}
void ComputeSharp_Tests_ShaderCompilerTests_StructType1::__ctor__init(int x)
{
X = x;
Y = (float)0;
}
float ComputeSharp_Tests_ShaderCompilerTests_StructType2::Combine(ComputeSharp_Tests_ShaderCompilerTests_StructType1 other)
{
return V.x + other.X;
}
int InstanceMethodInShader()
{
return (int)(number + __reserved__vector.x);
}
static float StaticMethodInShader(float x)
{
return x + 1;
}
static float ComputeSharp_Tests_ShaderCompilerTests_StructType1_StaticMethod(int x)
{
return x * 2;
}
static float ComputeSharp_Tests_ShaderCompilerTests_StructType2_StaticMethod(int x)
{
return x * 4;
}
[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]
void Execute(uint3 ThreadIds : SV_DispatchThreadID)
{
if (ThreadIds.x < __x && ThreadIds.y < __y && ThreadIds.z < __z)
{
ComputeSharp_Tests_ShaderCompilerTests_StructType1 type1 = ComputeSharp_Tests_ShaderCompilerTests_StructType1::__ctor(__ComputeSharp_Tests_ShaderCompilerTests_ExternalContainerClass__Factor);
ComputeSharp_Tests_ShaderCompilerTests_StructType2 type2 = (ComputeSharp_Tests_ShaderCompilerTests_StructType2)0;
float combine1 = type1.Combine(type2);
float combine2 = type2.Combine(type1);
combine1 += ComputeSharp_Tests_ShaderCompilerTests_StructType1_StaticMethod(Temp++);
combine2 += ComputeSharp_Tests_ShaderCompilerTests_StructType2_StaticMethod(ComputeSharp_Tests_ShaderCompilerTests_ExternalContainerClass_Temp++);
float dummy = Init + ComputeSharp_Tests_ShaderCompilerTests_ExternalContainerClass_PI2;
__reserved__buffer[ThreadIds.x] = (int)(combine1 + combine2 + dummy);
}
}
""",
info.HlslSource);
}
[AutoConstructor]
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct ShaderWithAllSupportedMembers : IComputeShader
{
private const float PI = 3.14f;
private static readonly float Init = Hlsl.Abs(PI);
private static int Temp;
private readonly ReadWriteBuffer<int> buffer;
private readonly int number;
private readonly float4 vector;
public void Execute()
{
StructType1 type1 = new(ExternalContainerClass.Factor);
StructType2 type2 = default;
float combine1 = type1.Combine(type2);
float combine2 = type2.Combine(type1);
combine1 += StructType1.StaticMethod(Temp++);
combine2 += StructType2.StaticMethod(ExternalContainerClass.Temp++);
float dummy = Init + ExternalContainerClass.PI2;
buffer[ThreadIds.X] = (int)(combine1 + combine2 + dummy);
}
public int InstanceMethodInShader()
{
return (int)(number + vector.X);
}
public static float StaticMethodInShader(float x)
{
return x + 1;
}
}
public static class ExternalContainerClass
{
public const int Factor = 8;
public static readonly float PI2 = 3.14f * 2;
public static int Temp;
}
internal struct StructType1
{
public int X;
public float Y;
public StructType1(int x)
{
X = x;
Y = default;
}
public float Combine(StructType2 other)
{
return Y + other.V.Y;
}
public float InstanceMethod()
{
StructType2 other = default;
other.V = ExternalContainerClass.PI2;
return Y + other.Combine(default) + StructType2.StaticMethod(X);
}
public static float StaticMethod(int x)
{
return x * 2;
}
}
internal struct StructType2
{
public float2 V;
public float Combine(StructType1 other)
{
return V.X + other.X;
}
public float InstanceMethod()
{
StructType1 other = new(ExternalContainerClass.Temp);
return V.X + other.Combine(default) + StructType1.StaticMethod((int)V.X);
}
public static float StaticMethod(int x)
{
return x * 4;
}
}
}
}