diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs index eb99986f..3b4a1f00 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs @@ -97,12 +97,14 @@ partial class D2DPixelShaderDescriptorGenerator token.ThrowIfCancellationRequested(); // Process the discovered types and constants - ImmutableArray declaredTypes = HlslDefinitionsSyntaxProcessor.GetDeclaredTypes( + HlslDefinitionsSyntaxProcessor.GetDeclaredTypes( diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods, - constructors); + constructors, + out ImmutableArray typeDeclarations, + out ImmutableArray 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 /// /// Produces the series of statements to build the current HLSL source. /// - /// The sequence of defined constants for the shader. - /// The sequence of declared types used by the shader. - /// The sequence of value instance fields for the current shader. + /// + /// /// The sequence of captured resource textures for the current shader. - /// The sequence of static fields referenced by the shader. - /// The sequence of processed methods used by the shader. + /// + /// + /// + /// /// The body of the entry point of the shader. /// The number of shader inputs to declare. /// The indicess of the simple shader inputs. @@ -462,11 +466,12 @@ partial class D2DPixelShaderDescriptorGenerator /// The series of statements to build the HLSL source to compile to execute the current shader. private static string GetHlslSource( ImmutableArray definedConstants, - ImmutableArray declaredTypes, ImmutableArray valueFields, ImmutableArray resourceTextureFields, ImmutableArray staticFields, ImmutableArray processedMethods, + ImmutableArray typeDeclarations, + ImmutableArray typeMethodDeclarations, string executeMethod, int inputCount, ImmutableArray 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(); diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index 5c46397b..b858e0fa 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -30,6 +30,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/HlslSourceHelper.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/HlslSourceHelper.cs new file mode 100644 index 00000000..8aff4c3e --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/HlslSourceHelper.cs @@ -0,0 +1,146 @@ +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGeneration.Helpers; + +/// +/// A helper type to write HLSL source. +/// +internal static class HlslSourceHelper +{ + /// + /// Writes the header included at the top of each generated HLSL shader. + /// + /// The instance to write into. + 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(); + } + + /// + /// Writes the top declarations in each generated HLSL shader: + /// + /// Defined constants. + /// Type forward declarations (optional). + /// Method forward declarations. + /// Static fields. + /// Type declarations. + /// + /// + /// The instance to write into. + /// The sequence of defined constants for the shader. + /// The sequence of static fields referenced by the shader. + /// The sequence of processed methods used by the shader. + /// The collection of declarations of all custom types. + /// Whether to include type forward declarations (if supported). + public static void WriteTopDeclarations( + IndentedTextWriter writer, + ImmutableArray definedConstants, + ImmutableArray staticFields, + ImmutableArray processedMethods, + ImmutableArray 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); + } + + /// + /// Writes the declarations for captured shader fields. + /// + /// The instance to write into. + /// The sequence of value instance fields for the current shader. + public static void WriteCapturedFields( + IndentedTextWriter writer, + ImmutableArray valueFields) + { + foreach (HlslValueField valueField in valueFields) + { + writer.WriteLine($"{valueField.Type} {valueField.Name};"); + } + } + + /// + /// Writes all method declarations (ie. implementations of previous forward declarations). + /// + /// The instance to write into. + /// The sequence of processed methods used by the shader. + /// The collection of implementations of all methods in all custom types. + public static void WriteMethodDeclarations( + IndentedTextWriter writer, + ImmutableArray processedMethods, + ImmutableArray 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); + } +} diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs index 0e9cab64..f1d10d04 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs @@ -143,15 +143,19 @@ internal static class HlslDefinitionsSyntaxProcessor /// The sequence of discovered custom types. /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constructors for custom struct types. - /// A sequence of custom type definitions to add to the shader source. - public static ImmutableArray GetDeclaredTypes( + /// The collection of declarations of all custom types. + /// The collection of implementations of all methods in all custom types. + public static void GetDeclaredTypes( ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, IEnumerable types, IReadOnlyDictionary instanceMethods, - IReadOnlyDictionary constructors) + IReadOnlyDictionary constructors, + out ImmutableArray typeDeclarations, + out ImmutableArray methodDeclarations) { - using ImmutableArrayBuilder builder = new(); + using ImmutableArrayBuilder typeDeclarationsBuilder = new(); + using ImmutableArrayBuilder methodDeclarationsBuilder = new(); IReadOnlyCollection 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 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(); } /// diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs index 7a442894..fbd70b2c 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs @@ -114,12 +114,14 @@ partial class ComputeShaderDescriptorGenerator token.ThrowIfCancellationRequested(); // Process the discovered types and constants - ImmutableArray declaredTypes = HlslDefinitionsSyntaxProcessor.GetDeclaredTypes( + HlslDefinitionsSyntaxProcessor.GetDeclaredTypes( diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods, - constructors); + constructors, + out ImmutableArray typeDeclarations, + out ImmutableArray 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 /// The thread ids value for the X axis. /// The thread ids value for the Y axis. /// The thread ids value for the Z axis. - /// The sequence of defined constants for the shader. - /// The sequence of declared types used by the shader. + /// /// The sequence of resource instance fields for the current shader. - /// The sequence of value instance fields for the current shader. - /// The sequence of static fields referenced by the shader. + /// + /// /// The sequence of shared buffers declared by the shader. - /// The sequence of processed methods used by the shader. + /// + /// + /// /// Whether or not the current shader type is a compute shader. /// The type of the implicit target texture, if present. /// Whether the static sampler is used by the shader. @@ -503,12 +507,13 @@ partial class ComputeShaderDescriptorGenerator int threadsY, int threadsZ, ImmutableArray definedConstants, - ImmutableArray declaredTypes, ImmutableArray resourceFields, ImmutableArray valueFields, ImmutableArray staticFields, ImmutableArray sharedBuffers, ImmutableArray processedMethods, + ImmutableArray typeDeclarations, + ImmutableArray 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); diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/InvertWithUserTypeAndMutuallyInvokingMethods.cs b/tests/ComputeSharp.D2D1.Tests/Effects/InvertWithUserTypeAndMutuallyInvokingMethods.cs new file mode 100644 index 00000000..8a056311 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/Effects/InvertWithUserTypeAndMutuallyInvokingMethods.cs @@ -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 +{ + /// + public float4 Execute() + { + ColorWrapperUsingExternalType wrapper = new(D2D.GetInput(0)); + + return wrapper.Invert(); + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/EffectsTests.cs b/tests/ComputeSharp.D2D1.Tests/EffectsTests.cs index 22127b8c..3086cc5b 100644 --- a/tests/ComputeSharp.D2D1.Tests/EffectsTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/EffectsTests.cs @@ -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() { diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index 3041b053..5adf186b 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -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 __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 __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(); + + 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 __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 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(); + + 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 __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 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; + } + } } }