diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs
index f89b5aa1..79f2b1d4 100644
--- a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs
+++ b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs
@@ -155,7 +155,7 @@ namespace ComputeSharp.SourceGenerators.Extensions
return ParseTypeName(mappedName!);
}
- return ParseTypeName(typeName.Replace(".", "__"));
+ return ParseTypeName(typeName.ToHlslIdentifierName());
}
}
}
diff --git a/src/ComputeSharp.SourceGenerators/Extensions/StringExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/StringExtensions.cs
new file mode 100644
index 00000000..8a84730d
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/Extensions/StringExtensions.cs
@@ -0,0 +1,21 @@
+using System.Diagnostics.Contracts;
+
+namespace ComputeSharp.SourceGenerators.Extensions
+{
+ ///
+ /// Extension methods for types.
+ ///
+ internal static class StringExtensions
+ {
+ ///
+ /// Converts a given instance to a valid HLSL identifier name.
+ ///
+ /// The input instance to convert.
+ /// An valid HLSL identifier name from .
+ [Pure]
+ public static string ToHlslIdentifierName(this string text)
+ {
+ return text.Replace('.', '_').Replace('+', '_');
+ }
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs
index 3a29bc8d..a047f37f 100644
--- a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs
+++ b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs
@@ -75,7 +75,7 @@ namespace ComputeSharp.SourceGenerators.Extensions
return node.ReplaceNode(targetType, newType);
}
- return node.ReplaceNode(targetType, ParseTypeName(typeName.Replace(".", "__")));
+ return node.ReplaceNode(targetType, ParseTypeName(typeName.ToHlslIdentifierName()));
}
///
@@ -98,7 +98,7 @@ namespace ComputeSharp.SourceGenerators.Extensions
return ParseTypeName(mappedName!);
}
- return ParseTypeName(typeName.Replace(".", "__"));
+ return ParseTypeName(typeName.ToHlslIdentifierName());
}
///
diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs
index 9ef136f1..f26b60fc 100644
--- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs
@@ -160,72 +160,7 @@ namespace ComputeSharp.SourceGenerators
resourceOffset = 0,
rawDataOffset = sizeof(int) * 3;
- foreach (
- IFieldSymbol fieldSymbol in
- from fieldSymbol in structDeclarationSymbol.GetMembers().OfType()
- where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
- !fieldSymbol.IsConst && !fieldSymbol.IsStatic
- select fieldSymbol)
- {
- string typeName = fieldSymbol.Type.GetFullMetadataName();
-
- if (HlslKnownTypes.IsTypedResourceType(typeName))
- {
- statements.Add(ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"),
- ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)"))));
- }
- else if (HlslKnownTypes.IsKnownHlslType(typeName))
- {
- // For scalar, vector and linear matrix types, serialize the value normally.
- // Only the initial alignment needs to be considered, while data is packed.
- var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
-
- // Check if the current type is a matrix type with more than one row. In this
- // case, each row is aligned as if it was a separate array, so the start of
- // each row needs to be at a multiple of 16 bytes (a float4 register).
- if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
- {
- string
- rowTypeName = $"ComputeSharp.{elementName}{columns}",
- rowLocalName = $"__{fieldSymbol.Name}__row0";
-
- statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in shader.{fieldSymbol.Name}));"));
-
- // Generate the loading code for each individual row, with proper alignment.
- // This will result in the following (assuming Float2x3 m):
- //
- // ref Float3 __m__row0 = ref Unsafe.As(ref Unsafe.AsRef(in shader.m));
- // Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, rawDataOffset), Unsafe.Add(ref __m__row0, 0));
- // Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, rawDataOffset + 16), Unsafe.Add(ref __m__row0, 1));
- for (int j = 0; j < rows; j++)
- {
- rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
-
- statements.Add(ParseStatement($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), Unsafe.Add(ref {rowLocalName}, {j}));"));
-
- rawDataOffset += fieldPack * columns;
- }
- }
- else
- {
- // Calculate the right offset with 16-bytes padding (HLSL constant buffer).
- // Since we're in a constant buffer, we need to both pad the starting offset
- // to be aligned to the packing size of the type, and also to align the initial
- // offset to ensure that values do not cross 16 bytes boundaries either.
- rawDataOffset = AlignmentHelper.AlignToBoundary(
- AlignmentHelper.Pad(rawDataOffset, fieldPack),
- fieldSize,
- 16);
-
- statements.Add(ParseStatement($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), shader.{fieldSymbol.Name});"));
-
- rawDataOffset += fieldSize;
- }
- }
- }
+ AppendFields(structDeclarationSymbol, Array.Empty(), ref resourceOffset, ref rawDataOffset, statements);
// After all the captured fields have been processed, ansure the reported byte size for
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
@@ -239,6 +174,119 @@ namespace ComputeSharp.SourceGenerators
return statements;
}
+
+ ///
+ /// Explores a given type hierarchy and generates statements to load fields.
+ ///
+ /// The current type being explored.
+ /// The current path of the field with respect to the shader instance.
+ /// The current offset in the root table of loaded resources.
+ /// The current offset within the loaded data buffer.
+ /// The target list of statements being generated.
+ private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection statements)
+ {
+ bool isFirstField = true;
+
+ foreach (
+ IFieldSymbol fieldSymbol in
+ from fieldSymbol in currentTypeSymbol.GetMembers().OfType()
+ where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
+ !fieldSymbol.IsConst && !fieldSymbol.IsStatic
+ select fieldSymbol)
+ {
+ string typeName = fieldSymbol.Type.GetFullMetadataName();
+
+ // The first item in each nested struct needs to be aligned to 16 bytes
+ if (isFirstField && fieldPath.Count > 0)
+ {
+ rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
+
+ isFirstField = false;
+ }
+
+ if (HlslKnownTypes.IsTypedResourceType(typeName))
+ {
+ statements.Add(ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"),
+ ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)"))));
+ }
+ else if (HlslKnownTypes.IsKnownHlslType(typeName))
+ {
+ AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldSymbol.Name }), typeName, ref rawDataOffset, statements);
+ }
+ else if (fieldSymbol.Type.IsUnmanagedType)
+ {
+ // Custom struct type defined by the user
+ AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldSymbol.Name }).ToArray(), ref resourceOffset, ref rawDataOffset, statements);
+ }
+ }
+ }
+
+ ///
+ /// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix).
+ ///
+ /// The current path of the field with respect to the shader instance.
+ /// The type name currently being read.
+ /// The current offset within the loaded data buffer.
+ /// The target list of statements being generated.
+ private static void AppendHlslKnownTypeField(IEnumerable fieldPath, string typeName, ref int rawDataOffset, ICollection statements)
+ {
+ // For scalar, vector and linear matrix types, serialize the value normally.
+ // Only the initial alignment needs to be considered, while data is packed.
+ var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
+
+ // Check if the current type is a matrix type with more than one row. In this
+ // case, each row is aligned as if it was a separate array, so the start of
+ // each row needs to be at a multiple of 16 bytes (a float4 register).
+ if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
+ {
+ string
+ rowTypeName = $"ComputeSharp.{elementName}{columns}",
+ rowLocalName = $"__{string.Join("_", fieldPath)}__row0";
+
+ statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in shader.{string.Join(".", fieldPath)}));"));
+
+ // Generate the loading code for each individual row, with proper alignment.
+ // This will result in the following (assuming Float2x3 m):
+ //
+ // ref Float3 __m__row0 = ref Unsafe.As(ref Unsafe.AsRef(in shader.m));
+ // Unsafe.As(ref Unsafe.Add(ref r1, rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0);
+ // Unsafe.As(ref Unsafe.Add(ref r1, rawDataOffset + 16)) = Unsafe.Add(ref __m__row0, 1);
+ for (int j = 0; j < rows; j++)
+ {
+ rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
+
+ statements.Add(ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ParseExpression($"Unsafe.As(ref Unsafe.Add(ref r1, {rawDataOffset}))"),
+ ParseExpression($"Unsafe.Add(ref {rowLocalName}, {j})"))));
+
+ rawDataOffset += fieldPack * columns;
+ }
+ }
+ else
+ {
+ // Calculate the right offset with 16-bytes padding (HLSL constant buffer).
+ // Since we're in a constant buffer, we need to both pad the starting offset
+ // to be aligned to the packing size of the type, and also to align the initial
+ // offset to ensure that values do not cross 16 bytes boundaries either.
+ rawDataOffset = AlignmentHelper.AlignToBoundary(
+ AlignmentHelper.Pad(rawDataOffset, fieldPack),
+ fieldSize,
+ 16);
+
+ statements.Add(ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ParseExpression($"Unsafe.As(ref Unsafe.Add(ref r1, {rawDataOffset}))"),
+ ParseExpression($"shader.{string.Join(".", fieldPath)}"))));
+
+ rawDataOffset += fieldSize;
+ }
+ }
}
}
diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs
index 5ae0f717..23177ccc 100644
--- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs
@@ -161,6 +161,11 @@ namespace ComputeSharp.SourceGenerators
continue;
}
+ else if (!HlslKnownTypes.IsKnownHlslType(metadataName))
+ {
+ // Track the type if it's a custom struct
+ types.Add(typeSymbol);
+ }
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
@@ -368,7 +373,7 @@ namespace ComputeSharp.SourceGenerators
{
foreach (var constant in constantDefinitions)
{
- var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().Replace(".", "__");
+ var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
yield return new string[] { constantName, constant.Value };
@@ -384,7 +389,7 @@ namespace ComputeSharp.SourceGenerators
{
foreach (var type in HlslKnownTypes.GetCustomTypes(types))
{
- var structType = type.GetFullMetadataName().Replace(".", "__");
+ var structType = type.GetFullMetadataName().ToHlslIdentifierName();
var structDeclaration = StructDeclaration(structType);
// Declare the fields of the current type
@@ -395,7 +400,7 @@ namespace ComputeSharp.SourceGenerators
// Convert the name to the fully qualified HLSL version
if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped))
{
- mapped = fieldType.GetFullMetadataName().Replace(".", "__");
+ mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName();
}
structDeclaration = structDeclaration.AddMembers(
diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs
index cc35c9dc..812040df 100644
--- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs
+++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs
@@ -222,40 +222,47 @@ namespace ComputeSharp.SourceGenerators.Mappings
string typeName = typeSymbol.GetFullMetadataName();
- // Special case for the structured buffer types
+ // Special case for the resource types
if (IsTypedResourceType(typeName))
{
string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments.Last()).GetFullMetadataName();
// If the current type is a custom type, format it as needed
- if (!KnownHlslTypes.TryGetValue(genericArgumentName, out string? mapped))
+ if (!KnownHlslTypes.TryGetValue(genericArgumentName, out string? mappedElementType))
{
- mapped = genericArgumentName.Replace(".", "__");
+ mappedElementType = genericArgumentName.ToHlslIdentifierName();
}
// Construct the HLSL type name
return typeName switch
{
- "ComputeSharp.ConstantBuffer`1" => mapped,
- "ComputeSharp.ReadOnlyBuffer`1" => $"StructuredBuffer<{mapped}>",
- "ComputeSharp.ReadWriteBuffer`1" => $"RWStructuredBuffer<{mapped}>",
- "ComputeSharp.ReadOnlyTexture2D`1" => $"Texture2D<{mapped}>",
- "ComputeSharp.ReadOnlyTexture2D`2" => $"Texture2D",
- "ComputeSharp.ReadWriteTexture2D`1" => $"RWTexture2D<{mapped}>",
- "ComputeSharp.ReadWriteTexture2D`2" => $"RWTexture2D",
- "ComputeSharp.ReadOnlyTexture3D`1" => $"Texture3D<{mapped}>",
- "ComputeSharp.ReadOnlyTexture3D`2" => $"Texture3D",
- "ComputeSharp.ReadWriteTexture3D`1" => $"RWTexture3D<{mapped}>",
- "ComputeSharp.ReadWriteTexture3D`2" => $"RWTexture3D",
- "ComputeSharp.IReadOnlyTexture2D`1" => $"Texture2D",
- "ComputeSharp.IReadWriteTexture2D`1" => $"RWTexture2D",
- "ComputeSharp.IReadOnlyTexture3D`1" => $"Texture3D",
- "ComputeSharp.IReadWriteTexture3D`1" => $"RWTexture3D",
+ "ComputeSharp.ConstantBuffer`1" => mappedElementType,
+ "ComputeSharp.ReadOnlyBuffer`1" => $"StructuredBuffer<{mappedElementType}>",
+ "ComputeSharp.ReadWriteBuffer`1" => $"RWStructuredBuffer<{mappedElementType}>",
+ "ComputeSharp.ReadOnlyTexture2D`1" => $"Texture2D<{mappedElementType}>",
+ "ComputeSharp.ReadOnlyTexture2D`2" => $"Texture2D",
+ "ComputeSharp.ReadWriteTexture2D`1" => $"RWTexture2D<{mappedElementType}>",
+ "ComputeSharp.ReadWriteTexture2D`2" => $"RWTexture2D",
+ "ComputeSharp.ReadOnlyTexture3D`1" => $"Texture3D<{mappedElementType}>",
+ "ComputeSharp.ReadOnlyTexture3D`2" => $"Texture3D",
+ "ComputeSharp.ReadWriteTexture3D`1" => $"RWTexture3D<{mappedElementType}>",
+ "ComputeSharp.ReadWriteTexture3D`2" => $"RWTexture3D",
+ "ComputeSharp.IReadOnlyTexture2D`1" => $"Texture2D",
+ "ComputeSharp.IReadWriteTexture2D`1" => $"RWTexture2D",
+ "ComputeSharp.IReadOnlyTexture3D`1" => $"Texture3D",
+ "ComputeSharp.IReadWriteTexture3D`1" => $"RWTexture3D",
_ => throw new ArgumentException()
};
}
- return KnownHlslTypes[typeName];
+ // The captured field is of an HLSL primitive type
+ if (KnownHlslTypes.TryGetValue(typeName, out string? mappedType))
+ {
+ return mappedType;
+ }
+
+ // The captured field is of a custom struct type
+ return typeName.ToHlslIdentifierName();
}
///
@@ -273,7 +280,7 @@ namespace ComputeSharp.SourceGenerators.Mappings
return mapped;
}
- return elementTypeName.Replace(".", "__");
+ return elementTypeName.ToHlslIdentifierName();
}
///
diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs
index c82554d9..c5c5867d 100644
--- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs
+++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs
@@ -260,7 +260,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
ConstantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
- var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__");
+ var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
var constantName = $"__{ownerTypeName}__{operation.Field.Name}";
return IdentifierName(constantName);
diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
index 55579e2c..d8a70895 100644
--- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
+++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
@@ -260,7 +260,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
- var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__");
+ var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}";
return IdentifierName(constantName);
@@ -398,7 +398,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
// type as well, as they will be processed by the generator in a different path.
if (!SymbolEqualityComparer.Default.Equals(this.shaderType, method.ContainingType))
{
- var methodIdentifier = method.GetFullMetadataName().Replace(".", "__");
+ var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName();
if (!this.staticMethods.ContainsKey(method))
{
diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs
index 644bf065..b4c39a0e 100644
--- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs
+++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs
@@ -60,7 +60,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
- var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__");
+ var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}";
return IdentifierName(constantName);
diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs
index 390a4b52..d0f043c8 100644
--- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs
+++ b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs
@@ -221,13 +221,10 @@ namespace ComputeSharp.Shaders.Translation
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++));
this.totalResourceCount++;
}
- else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType) || HlslKnownTypes.IsKnownMatrixType(fieldType))
- {
- this.capturedFields.Add(fieldInfo);
- this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName));
- }
- else if (fieldInfo.GetValue(shader) is Delegate { Method: { IsStatic: true } } func)
+ else if (fieldInfo.GetValue(shader) is Delegate func)
{
+ Guard.IsTrue(func.Method.IsStatic, fieldInfo.Name, "Captured delegates must be pointing to static methods");
+
// Captured static delegates with a return type
var methodSource = ShaderMethodSourceAttribute.GetForDelegate(func);
@@ -240,7 +237,11 @@ namespace ComputeSharp.Shaders.Translation
this.definesInfo[pair.Key] = pair.Value;
}
}
- else ThrowHelper.ThrowArgumentException("Invalid captured variable");
+ else
+ {
+ this.capturedFields.Add(fieldInfo);
+ this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName));
+ }
}
}
}
diff --git a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs
index fb729401..f6b11808 100644
--- a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs
+++ b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs
@@ -10,7 +10,7 @@ namespace ComputeSharp.Tests.Internals
public partial class ShaderDataLoaderTests
{
[AutoConstructor]
- public partial struct Shader1 : IComputeShader
+ public partial struct CapturedResourceShader : IComputeShader
{
public ReadWriteBuffer _;
@@ -20,14 +20,14 @@ namespace ComputeSharp.Tests.Internals
}
[TestMethod]
- public unsafe void LoadShader1()
+ public unsafe void CapturedResource()
{
ulong* p0 = stackalloc ulong[128];
byte* p1 = stackalloc byte[256];
using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16);
- int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, new Shader1(buffer), ref *p0, ref *p1);
+ int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, new CapturedResourceShader(buffer), ref *p0, ref *p1);
Assert.AreEqual(12, size);
@@ -35,7 +35,7 @@ namespace ComputeSharp.Tests.Internals
}
[AutoConstructor]
- public partial struct Shader2 : IComputeShader
+ public partial struct MultipleResourcesAndPrimitivesShader : IComputeShader
{
public ReadWriteBuffer _0;
public ReadWriteBuffer _1;
@@ -49,7 +49,7 @@ namespace ComputeSharp.Tests.Internals
}
[TestMethod]
- public unsafe void LoadShader2()
+ public unsafe void LoadMultipleResourcesAndPrimitives()
{
ulong* p0 = stackalloc ulong[128];
byte* p1 = stackalloc byte[256];
@@ -57,7 +57,7 @@ namespace ComputeSharp.Tests.Internals
using ReadWriteBuffer buffer0 = Gpu.Default.AllocateReadWriteBuffer(16);
using ReadWriteBuffer buffer1 = Gpu.Default.AllocateReadWriteBuffer(16);
- int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, new Shader2(buffer0, buffer1, 1, 22, 77), ref *p0, ref *p1);
+ int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, new MultipleResourcesAndPrimitivesShader(buffer0, buffer1, 1, 22, 77), ref *p0, ref *p1);
Assert.AreEqual(24, size);
@@ -70,7 +70,7 @@ namespace ComputeSharp.Tests.Internals
}
[AutoConstructor]
- public partial struct Shader3 : IComputeShader
+ public partial struct ScalarAndVectorTypesShader : IComputeShader
{
public ReadWriteBuffer _;
public Float3 f3;
@@ -86,14 +86,14 @@ namespace ComputeSharp.Tests.Internals
}
[TestMethod]
- public unsafe void LoadShader3()
+ public unsafe void LoadScalarAndVectorTypes()
{
ulong* p0 = stackalloc ulong[128];
byte* p1 = stackalloc byte[256];
using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16);
- Shader3 shader = new(buffer, new(55, 44, 888), 22, 77, new(3.14, 6.28), 42, 9999);
+ ScalarAndVectorTypesShader shader = new(buffer, new(55, 44, 888), 22, 77, new(3.14, 6.28), 42, 9999);
int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1);
@@ -113,7 +113,7 @@ namespace ComputeSharp.Tests.Internals
}
[AutoConstructor]
- public partial struct Shader4 : IComputeShader
+ public partial struct ScalarVectorAndMatrixTypesShader : IComputeShader
{
public ReadWriteBuffer _;
public Float2x3 f2x3;
@@ -131,14 +131,14 @@ namespace ComputeSharp.Tests.Internals
}
[TestMethod]
- public unsafe void LoadShader4()
+ public unsafe void LoadScalarVectorAndMatrixTypes()
{
ulong* p0 = stackalloc ulong[128];
byte* p1 = stackalloc byte[256];
using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16);
- Shader4 shader = new(
+ ScalarVectorAndMatrixTypesShader shader = new(
buffer,
f2x3: new(55, 44, 888, 111, 222, 333),
a: 22,
@@ -176,5 +176,186 @@ namespace ComputeSharp.Tests.Internals
Assert.AreEqual(44, *(int*)&p1[116]);
Assert.AreEqual(9999, *(int*)&p1[120]);
}
+
+ [AutoConstructor]
+ public partial struct SimpleTypes
+ {
+ public Float2x3 f2x3;
+ public int a;
+ public Int1x3 i1x3;
+ public Double2 d2;
+ public int c;
+ public Int1x2 i1x2;
+ public Int2x2 i2x2;
+ public int d;
+ }
+
+ [AutoConstructor]
+ public partial struct FlatCustomTypeShader : IComputeShader
+ {
+ public ReadWriteBuffer _0;
+ public SimpleTypes a;
+
+ public void Execute()
+ {
+ }
+ }
+
+ [TestMethod]
+ public unsafe void LoadFlatCustomTypeShader()
+ {
+ ulong* p0 = stackalloc ulong[128];
+ byte* p1 = stackalloc byte[256];
+
+ using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16);
+
+ FlatCustomTypeShader shader = new(
+ buffer,
+ new SimpleTypes(
+ f2x3: new(55, 44, 888, 111, 222, 333),
+ a: 22,
+ i1x3: new(1, 2, 3),
+ d2: new(3.14, 6.28),
+ c: 42,
+ i1x2: new(111, 222),
+ i2x2: new(11, 22, 33, 44),
+ d: 9999));
+
+ int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1);
+
+ Assert.AreEqual(124, size);
+
+ Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr);
+
+ Assert.AreEqual(55, *(float*)&p1[16]);
+ Assert.AreEqual(44, *(float*)&p1[20]);
+ Assert.AreEqual(888, *(float*)&p1[24]);
+ Assert.AreEqual(111, *(float*)&p1[32]);
+ Assert.AreEqual(222, *(float*)&p1[36]);
+ Assert.AreEqual(333, *(float*)&p1[40]);
+ Assert.AreEqual(22, *(int*)&p1[44]);
+ Assert.AreEqual(1, *(int*)&p1[48]);
+ Assert.AreEqual(2, *(int*)&p1[52]);
+ Assert.AreEqual(3, *(int*)&p1[56]);
+ Assert.AreEqual(3.14, *(double*)&p1[64]);
+ Assert.AreEqual(6.28, *(double*)&p1[72]);
+ Assert.AreEqual(42, *(int*)&p1[80]);
+ Assert.AreEqual(111, *(int*)&p1[84]);
+ Assert.AreEqual(222, *(int*)&p1[88]);
+ Assert.AreEqual(11, *(int*)&p1[96]);
+ Assert.AreEqual(22, *(int*)&p1[100]);
+ Assert.AreEqual(33, *(int*)&p1[112]);
+ Assert.AreEqual(44, *(int*)&p1[116]);
+ Assert.AreEqual(9999, *(int*)&p1[120]);
+ }
+
+ [AutoConstructor]
+ public partial struct CustomType1
+ {
+ public Float3 a;
+ public SimpleTypes b;
+ public int c;
+ public CustomType2 d;
+ public CustomType3 e;
+ }
+
+ [AutoConstructor]
+ public partial struct CustomType2
+ {
+ public int a;
+ public Float2 b;
+ public CustomType3 c;
+ }
+
+ [AutoConstructor]
+ public partial struct CustomType3
+ {
+ public int a;
+ public Float2 b;
+ }
+
+ [AutoConstructor]
+ public partial struct NestedCustomTypesShader : IComputeShader
+ {
+ public ReadWriteBuffer _0;
+ public CustomType1 a;
+
+ public void Execute()
+ {
+ }
+ }
+
+ [TestMethod]
+ public unsafe void LoadNestedCustomTypes()
+ {
+ ulong* p0 = stackalloc ulong[128];
+ byte* p1 = stackalloc byte[256];
+
+ using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16);
+
+ NestedCustomTypesShader shader = new(
+ buffer,
+ new CustomType1(
+ a: new(3.14f, 6.28f, 123.4f),
+ b: new SimpleTypes(
+ f2x3: new(55, 44, 888, 111, 222, 333),
+ a: 22,
+ i1x3: new(1, 2, 3),
+ d2: new(3.14, 6.28),
+ c: 42,
+ i1x2: new(111, 222),
+ i2x2: new(11, 22, 33, 44),
+ d: 9999),
+ c: 42,
+ d: new CustomType2(
+ a: 1234567,
+ b: new(44.4f, 55.5f),
+ c: new CustomType3(
+ a: 7654321,
+ b: new (111.1f, 222.2f))),
+ e: new CustomType3(
+ a: 888888,
+ b: new(333.3f, 444.4f))));
+
+ int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1);
+
+ Assert.AreEqual(188, size);
+
+ Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr);
+
+ Assert.AreEqual(3.14f, *(float*)&p1[16]);
+ Assert.AreEqual(6.28f, *(float*)&p1[20]);
+ Assert.AreEqual(123.4f, *(float*)&p1[24]);
+ Assert.AreEqual(55, *(float*)&p1[32]);
+ Assert.AreEqual(44, *(float*)&p1[36]);
+ Assert.AreEqual(888, *(float*)&p1[40]);
+ Assert.AreEqual(111, *(float*)&p1[48]);
+ Assert.AreEqual(222, *(float*)&p1[52]);
+ Assert.AreEqual(333, *(float*)&p1[56]);
+ Assert.AreEqual(22, *(int*)&p1[60]);
+ Assert.AreEqual(1, *(int*)&p1[64]);
+ Assert.AreEqual(2, *(int*)&p1[68]);
+ Assert.AreEqual(3, *(int*)&p1[72]);
+ Assert.AreEqual(3.14, *(double*)&p1[80]);
+ Assert.AreEqual(6.28, *(double*)&p1[88]);
+ Assert.AreEqual(42, *(int*)&p1[96]);
+ Assert.AreEqual(111, *(int*)&p1[100]);
+ Assert.AreEqual(222, *(int*)&p1[104]);
+ Assert.AreEqual(11, *(int*)&p1[112]);
+ Assert.AreEqual(22, *(int*)&p1[116]);
+ Assert.AreEqual(33, *(int*)&p1[128]);
+ Assert.AreEqual(44, *(int*)&p1[132]);
+ Assert.AreEqual(9999, *(int*)&p1[136]);
+ Assert.AreEqual(42, *(int*)&p1[140]);
+ Assert.AreEqual(1234567, *(int*)&p1[144]);
+ Assert.AreEqual(44.4f, *(float*)&p1[148]);
+ Assert.AreEqual(55.5f, *(float*)&p1[152]);
+ Assert.AreEqual(7654321, *(int*)&p1[160]);
+ Assert.AreEqual(111.1f, *(float*)&p1[164]);
+ Assert.AreEqual(222.2f, *(float*)&p1[168]);
+ Assert.AreEqual(888888, *(int*)&p1[176]);
+ Assert.AreEqual(333.3f, *(float*)&p1[180]);
+ Assert.AreEqual(444.4f, *(float*)&p1[184]);
+ }
}
}
diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs
index 09faf240..a856dfb6 100644
--- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs
+++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs
@@ -11,11 +11,11 @@ namespace ComputeSharp.Tests
[TestMethod]
public void ReservedKeywords()
{
- ReflectionServices.GetShaderInfo(out _);
+ ReflectionServices.GetShaderInfo(out _);
}
[AutoConstructor]
- public readonly partial struct ReservedKeywords_Kernel : IComputeShader
+ public readonly partial struct ReservedKeywordsShader : IComputeShader
{
public readonly ReadWriteBuffer row_major;
public readonly float dword;
@@ -32,11 +32,11 @@ namespace ComputeSharp.Tests
[TestMethod]
public void SpecialTypeAsReturnType()
{
- ReflectionServices.GetShaderInfo(out _);
+ ReflectionServices.GetShaderInfo(out _);
}
[AutoConstructor]
- public readonly partial struct SpecialTypeAsReturnType_Kernel : IComputeShader
+ public readonly partial struct SpecialTypeAsReturnTypeShader : IComputeShader
{
public readonly ReadWriteBuffer buffer;
@@ -53,11 +53,11 @@ namespace ComputeSharp.Tests
[TestMethod]
public void LocalFunctionInExternalMethods()
{
- ReflectionServices.GetShaderInfo(out _);
+ ReflectionServices.GetShaderInfo(out _);
}
[AutoConstructor]
- public readonly partial struct LocalFunctionInExternalMethods_Kernel : IComputeShader
+ public readonly partial struct LocalFunctionInExternalMethodsShader : IComputeShader
{
public readonly ReadWriteBuffer buffer;
@@ -73,5 +73,31 @@ namespace ComputeSharp.Tests
buffer[ThreadIds.X] = Foo(ThreadIds.X);
}
}
+
+ [TestMethod]
+ public void CapturedNestedStructType()
+ {
+ ReflectionServices.GetShaderInfo(out _);
+ }
+
+ [AutoConstructor]
+ public partial struct CustomStructType
+ {
+ public Float2 a;
+ public int b;
+ }
+
+ [AutoConstructor]
+ public readonly partial struct CapturedNestedStructTypeShader : IComputeShader
+ {
+ public readonly ReadWriteBuffer buffer;
+ public readonly CustomStructType foo;
+
+ ///
+ public void Execute()
+ {
+ buffer[ThreadIds.X] *= foo.a.X + foo.b;
+ }
+ }
}
}