diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs
new file mode 100644
index 00000000..2d79b8a2
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs
@@ -0,0 +1,415 @@
+using System.Linq;
+using ComputeSharp.D2D1.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
+using ComputeSharp.SourceGeneration.Mappings;
+using ComputeSharp.SourceGeneration.Models;
+
+namespace ComputeSharp.D2D1.SourceGenerators;
+
+///
+partial class D2DPixelShaderDescriptorGenerator
+{
+ ///
+ partial class ConstantBuffer
+ {
+ ///
+ /// Writes the LoadConstantBuffer method.
+ ///
+ /// The input instance with gathered shader info.
+ /// The instance to write into.
+ public static void WriteLoadConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
+ {
+ string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
+
+ writer.WriteLine("/// ");
+ writer.WriteGeneratedAttributes(GeneratorName);
+ writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
+ writer.WriteLine($"static unsafe void global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.LoadConstantBuffer(in {typeName} shader, ref TLoader loader)");
+
+ using (writer.WriteBlock())
+ {
+ // If there are no fields, just load an empty buffer
+ if (info.Fields.IsEmpty)
+ {
+ writer.WriteLine("loader.LoadConstantBuffer(default);");
+ }
+ else
+ {
+ // Otherwise, pass a span into the marshalled native layout buffer
+ writer.WriteLine("global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.FromManaged(in shader, out global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer);");
+ writer.WriteLine();
+ writer.WriteLine("loader.LoadConstantBuffer(new global::System.ReadOnlySpan(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));");
+ }
+ }
+ }
+
+ ///
+ /// Writes the CreateFromConstantBuffer method.
+ ///
+ /// The input instance with gathered shader info.
+ /// The instance to write into.
+ public static void WriteCreateFromConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
+ {
+ string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
+
+ writer.WriteLine("/// ");
+ writer.WriteGeneratedAttributes(GeneratorName);
+ writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
+ writer.WriteLine($"static unsafe {typeName} global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.CreateFromConstantBuffer(global::System.ReadOnlySpan data)");
+
+ using (writer.WriteBlock())
+ {
+ // If there are no fields, just return an empty shader
+ if (info.Fields.IsEmpty)
+ {
+ writer.WriteLine("return default;");
+
+ return;
+ }
+
+ // Get a reference to the data through the generated native layout type and define the shader
+ writer.WriteLine("ref readonly global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer = ref global::System.Runtime.InteropServices.MemoryMarshal.AsRef(data);");
+ writer.WriteLine();
+ writer.WriteLine("return global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.ToManaged(in buffer);");
+ }
+ }
+
+ ///
+ /// Registers a callback to generate additional types, if needed.
+ ///
+ /// The input instance with gathered shader info.
+ /// The registered callbacks to generate additional types.
+ /// The using directives needed by the generated code.
+ public static void RegisterAdditionalTypesSyntax(
+ D2D1ShaderInfo info,
+ ImmutableArrayBuilder> callbacks,
+ ImmutableHashSetBuilder usingDirectives)
+ {
+ // If there are no fields, there is no need for a constant buffer type
+ if (info.Fields.IsEmpty)
+ {
+ return;
+ }
+
+ _ = usingDirectives.Add("global::System.CodeDom.Compiler");
+ _ = usingDirectives.Add("global::System.Diagnostics");
+ _ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
+ _ = usingDirectives.Add("global::System.Runtime.CompilerServices");
+ _ = usingDirectives.Add("global::System.Runtime.InteropServices");
+
+ // Declare the ConstantBuffer type
+ static void ConstantBufferCallback(D2D1ShaderInfo info, IndentedTextWriter writer)
+ {
+ string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName();
+
+ writer.WriteLine($"""/// """);
+ writer.WriteLine($"""/// A type representing the constant buffer native layout for .""");
+ writer.WriteLine($"""/// """);
+ writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false);
+ writer.WriteLine($"""[StructLayout(LayoutKind.Explicit, Size = {info.ConstantBufferSizeInBytes})]""");
+ writer.WriteLine($"""file struct ConstantBuffer""");
+
+ using (writer.WriteBlock())
+ {
+ // Declare fields for every mapped item from the shader layout
+ writer.WriteLineSeparatedMembers(info.Fields.AsSpan(), (field, writer) =>
+ {
+ switch (field)
+ {
+ case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive:
+
+ // Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values)
+ writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName);
+ writer.WriteFieldXmlRemarks(field);
+ writer.WriteLine($"""[FieldOffset({primitive.Offset})]""");
+ writer.WriteLine($"""public global::ComputeSharp.Bool {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};""");
+ break;
+ case FieldInfo.Primitive primitive:
+
+ // Append primitive fields of other types with their mapped names
+ writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName);
+ writer.WriteFieldXmlRemarks(field);
+ writer.WriteLine($"""[FieldOffset({primitive.Offset})]""");
+ writer.WriteLine($"""public {HlslKnownTypes.GetMappedName(primitive.TypeName)} {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};""");
+ break;
+
+ case FieldInfo.NonLinearMatrix matrix:
+ string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
+ string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name));
+
+ // Declare a field for every row of the matrix type
+ for (int j = 0; j < matrix.Rows; j++)
+ {
+ writer.WriteLineIf(j > 0);
+ writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName);
+ writer.WriteFieldXmlRemarks(field, row: j);
+ writer.WriteLine($"""[FieldOffset({matrix.Offsets[j]})]""");
+ writer.WriteLine($"""public {rowTypeName} {fieldNamePrefix}_{j};""");
+ }
+
+ break;
+ }
+ });
+ }
+ }
+
+ // Declare the ConstantBufferMarshaller type
+ static void ConstantBufferMarshallerCallback(D2D1ShaderInfo info, IndentedTextWriter writer)
+ {
+ string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName();
+
+ writer.WriteLine($"""/// """);
+ writer.WriteLine($"""/// A type containing marshalling logic for shaders of type .""");
+ writer.WriteLine($"""/// """);
+ writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false);
+ writer.WriteLine($"""file static class ConstantBufferMarshaller""");
+
+ using (writer.WriteBlock())
+ {
+ // Define the ToManaged method (native constant buffer to managed shader type)
+ writer.WriteLine($"""/// """);
+ writer.WriteLine($"""/// Marshals native constant buffer data to managed instances.""");
+ writer.WriteLine($"""/// """);
+ writer.WriteLine($"""/// The input native constant buffer.""");
+ writer.WriteLine($"""/// The marshalled instance.""");
+ writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]""");
+ writer.WriteLine($"""[SkipLocalsInit]""");
+ writer.WriteLine($"public static {fullyQualifiedTypeName} ToManaged(in ConstantBuffer buffer)");
+
+ using (writer.WriteBlock())
+ {
+ writer.WriteLine($"Unsafe.SkipInit(out {fullyQualifiedTypeName} shader);");
+ writer.WriteLine();
+
+ // Generate loading statements for each captured field
+ foreach (FieldInfo fieldInfo in info.Fields)
+ {
+ switch (fieldInfo)
+ {
+ case FieldInfo.Primitive primitive:
+
+ // Read a nested primitive value
+ writer.WriteFieldAccessExpression(fieldInfo);
+ writer.WriteLine($" = buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))};");
+ break;
+
+ case FieldInfo.NonLinearMatrix matrix:
+ string primitiveTypeName = matrix.ElementName.ToLowerInvariant();
+ string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}";
+ string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
+ string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name));
+
+ // Get a reference to the whole matrix field, just once for all rows
+ writer.WriteLine(skipIfPresent: true);
+ writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref ");
+ writer.WriteFieldAccessExpression(fieldInfo);
+ writer.WriteLine(";");
+ writer.WriteLine();
+
+ // Read all rows of a given matrix type
+ for (int j = 0; j < matrix.Rows; j++)
+ {
+ writer.WriteLine($"Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1) = buffer.{fieldNamePrefix}_{j};");
+ }
+
+ writer.WriteLine();
+ break;
+ }
+ }
+
+ writer.WriteLine(skipIfPresent: true);
+ writer.WriteLine("return shader;");
+ }
+
+ // Define the FromManaged method (managed shader type to native constant buffer)
+ writer.WriteLine();
+ writer.WriteLine($"""/// """);
+ writer.WriteLine($"""/// Marshals managed instances to native constant buffer data.""");
+ writer.WriteLine($"""/// """);
+ writer.WriteLine($"""/// The input native constant buffer.""");
+ writer.WriteLine($"""/// The marshalled instance.""");
+ writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]""");
+ writer.WriteLine($"""[SkipLocalsInit]""");
+ writer.WriteLine($"public static void FromManaged(in {fullyQualifiedTypeName} shader, out ConstantBuffer buffer)");
+
+ using (writer.WriteBlock())
+ {
+ // Generate loading statements for each captured field
+ foreach (FieldInfo fieldInfo in info.Fields)
+ {
+ switch (fieldInfo)
+ {
+ case FieldInfo.Primitive primitive:
+
+ // Assign a primitive value
+ writer.Write($"buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))} = ");
+ writer.WriteFieldAccessExpression(fieldInfo);
+ writer.WriteLine(";");
+ break;
+
+ case FieldInfo.NonLinearMatrix matrix:
+ string primitiveTypeName = matrix.ElementName.ToLowerInvariant();
+ string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}";
+ string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
+ string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name));
+
+ // Get a reference to the whole matrix field, just once for all rows
+ writer.WriteLine(skipIfPresent: true);
+ writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref ");
+ writer.WriteFieldAccessExpression(fieldInfo);
+ writer.WriteLine(";");
+ writer.WriteLine();
+
+ // Assign all rows of a given matrix type
+ for (int j = 0; j < matrix.Rows; j++)
+ {
+ writer.WriteLine($"buffer.{fieldNamePrefix}_{j} = Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1);");
+ }
+
+ writer.WriteLine();
+ break;
+ }
+ }
+ }
+
+ using ImmutableHashSetBuilder<(string ContainerType, string FieldName)> generatedAccessors = new();
+
+ // Define all field accessors. Note that these are generated regardless of the accessibility
+ // of the field they're getting the value for. This simplifies the rest of the code, and allows
+ // stripping the readonly-ness of the field references, and has no binary size impact anyway.
+ // This is because the fields are compiled to be exactly equivalent to direct field references.
+ foreach (FieldInfo fieldInfo in info.Fields)
+ {
+ for (int i = 0; i < fieldInfo.FieldPath.Length; i++)
+ {
+ FieldPathPart pathPart = fieldInfo.FieldPath[i];
+
+ // Get the friendly type name for the field:
+ // - If the part path is a nested struct, the type name is embedded
+ // - Otherwise, get the correct HLSL mapped type name for the field
+ string typeName = pathPart switch
+ {
+ FieldPathPart.Nested nested => nested.TypeName,
+ FieldPathPart.Leaf when fieldInfo.TypeName is "System.Boolean" => "global::ComputeSharp.Bool",
+ _ => HlslKnownTypes.GetMappedName(fieldInfo.TypeName)
+ };
+
+ // Get the friendly type name for the field. If this nested field is the
+ // first path, then the parent is the shader type itself. Otherwise, the
+ // container path is the type of the previous containing type of the field.
+ string containingTypeName = i == 0
+ ? fullyQualifiedTypeName
+ : ((FieldPathPart.Nested)fieldInfo.FieldPath[i - 1]).TypeName;
+
+ // Make sure to skip repeated field accessors. It's possible for some accessors to end up
+ // being required, in case a shader type had multiple fields of the same nested struct type.
+ // To avoid so, we just add the containing type and name to an hashset that we update.
+ if (!generatedAccessors.Add((containingTypeName, pathPart.Name)))
+ {
+ continue;
+ }
+
+ writer.WriteLine();
+
+ // If there is no unspeakable name, we can reference the field directly. This means we can both
+ // use that in XML docs to refer to it (and inherit the docs), and we don't need an explicit name.
+ if (pathPart.UnspeakableName is null)
+ {
+ writer.WriteLine($"""
+ ///
+ /// The input value.
+ /// A mutable reference to .
+ [UnsafeAccessor(UnsafeAccessorKind.Field)]
+ private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value);
+ """, isMultiline: true);
+ }
+ else
+ {
+ writer.WriteLine($"""
+ /// Gets a reference to the unspeakable field "{pathPart.Name}" of type .
+ /// The input value.
+ /// A mutable reference to the unspeakable field "{pathPart.Name}".
+ [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "{pathPart.UnspeakableName}")]
+ private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value);
+ """, isMultiline: true);
+ }
+ }
+ }
+ }
+ }
+
+ callbacks.Add(ConstantBufferCallback);
+ callbacks.Add(ConstantBufferMarshallerCallback);
+ }
+ }
+}
+
+///
+file static class IndentedTextWriterExtensions
+{
+ ///
+ /// Writes the XML summary for a given field.
+ ///
+ /// The instance to write into.
+ /// The input field to write the XML summary for.
+ /// The fully qualified type name of the containing type.
+ public static void WriteFieldXmlSummary(this IndentedTextWriter writer, FieldInfo fieldInfo, string fullyQualifiedTypeName)
+ {
+ if (fieldInfo.FieldPath[0].UnspeakableName is null)
+ {
+ writer.WriteLine($"""/// """);
+ }
+ else
+ {
+ writer.WriteLine($"""/// The unspeakable field "{fieldInfo.FieldPath[0].Name}" of .""");
+ }
+ }
+
+ ///
+ /// Writes the XML remarks for a given field, if needed.
+ ///
+ /// The instance to write into.
+ /// The input field to write the XML remarks for, if needed.
+ /// The row for the field, if this is a matrix type.
+ public static void WriteFieldXmlRemarks(this IndentedTextWriter writer, FieldInfo fieldInfo, int? row = null)
+ {
+ // The remarks are only needed if the field is nested
+ if (fieldInfo.FieldPath is not [.., FieldPathPart.Nested nested, FieldPathPart.Leaf leaf])
+ {
+ return;
+ }
+
+ // Write the correct remarks depending on whether the field can be referenced directly
+ if (leaf.UnspeakableName is null)
+ {
+ writer.Write($"""/// Serialized field mapping to""");
+ writer.WriteIf(row is not null, $""" row {row} of""");
+ writer.WriteLine($""" .""");
+ }
+ else
+ {
+ writer.Write($"""/// Serialized field mapping to""");
+ writer.WriteIf(row is not null, $""" row {row} of""");
+ writer.WriteLine($""" the unspeakable field "{leaf.Name}" of .""");
+ }
+ }
+
+ ///
+ /// Writes an expression to access a given field.
+ ///
+ /// The instance to write into.
+ /// The input field to write the expression for.
+ public static void WriteFieldAccessExpression(this IndentedTextWriter writer, FieldInfo fieldInfo)
+ {
+ writer.Write("shader");
+
+ // Invoke all generated field accessors to get to the target field.
+ // Because they're extension methods, we can chain them sequentially.
+ // This simplifies the formatting and makes the code easier to read.
+ foreach (FieldPathPart part in fieldInfo.FieldPath)
+ {
+ writer.Write($".{part.Name}()");
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.LoadConstantBuffer.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs
similarity index 55%
rename from src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.LoadConstantBuffer.cs
rename to src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs
index cb0e00d6..d86dbe5b 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.LoadConstantBuffer.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs
@@ -1,8 +1,7 @@
using System;
-using System.Collections.Generic;
using System.Collections.Immutable;
-using System.Linq;
-using System.Runtime.CompilerServices;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.RegularExpressions;
using ComputeSharp.Core.Helpers;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
@@ -17,10 +16,18 @@ namespace ComputeSharp.D2D1.SourceGenerators;
partial class D2DPixelShaderDescriptorGenerator
{
///
- /// A helper with all logic to generate the LoadConstantBuffer method.
+ /// A helper with all logic to generate the ConstantBuffer methods and additional types.
///
- private static partial class LoadConstantBuffer
+ private static partial class ConstantBuffer
{
+ ///
+ /// A to extract the parameter name of a primary constructor capture field.
+ ///
+ ///
+ /// Temporary workaround until is available.
+ ///
+ private static readonly Regex PrimaryConstructorNameRegex = new("^<([^>]+)>P$", RegexOptions.Compiled);
+
///
/// Explores a given type hierarchy and generates statements to load fields.
///
@@ -28,71 +35,87 @@ partial class D2DPixelShaderDescriptorGenerator
/// The input object currently in use.
/// The current shader type being explored.
/// The size of the shader constant buffer.
- /// The sequence of instances for all captured resources and values.
- public static ImmutableArray GetInfo(
+ /// The sequence of instances for all captured values.
+ public static void GetInfo(
ImmutableArrayBuilder diagnostics,
Compilation compilation,
ITypeSymbol structDeclarationSymbol,
- out int constantBufferSizeInBytes)
+ out int constantBufferSizeInBytes,
+ out ImmutableArray fields)
{
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
- static IEnumerable GetCapturedFieldInfos(
+ static void GetInfo(
Compilation compilation,
ITypeSymbol currentTypeSymbol,
- ImmutableArray fieldPath,
- StrongBox rawDataOffset)
+ ImmutableArray fieldPath,
+ ref int rawDataOffset,
+ ImmutableArrayBuilder fields)
{
bool isFirstField = true;
- foreach (
- IFieldSymbol fieldSymbol in
- from fieldSymbol in currentTypeSymbol.GetMembers().OfType()
- where fieldSymbol is { Type: INamedTypeSymbol { IsStatic: false }, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false }
- select fieldSymbol)
+ foreach (ISymbol memberSymbol in currentTypeSymbol.GetMembers())
{
+ // Only process fields of a valid shape/type
+ if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol { IsStatic: false }, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false } fieldSymbol)
+ {
+ continue;
+ }
+
// Skip fields of not accessible types (the analyzer will handle this)
if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation))
{
continue;
}
- string fieldName = fieldSymbol.Name;
+ // Try to get the name to use for the field and the accessor
+ if (!TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out string? unspeakableName))
+ {
+ continue;
+ }
+
string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName();
// The first item in each nested struct needs to be aligned to 16 bytes
if (isFirstField && fieldPath.Length > 0)
{
- rawDataOffset.Value = AlignmentHelper.Pad(rawDataOffset.Value, 16);
+ rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
isFirstField = false;
}
if (HlslKnownTypes.IsKnownHlslType(typeName))
{
- yield return GetHlslKnownTypeFieldInfo(fieldPath.Add(fieldName), typeName, ref rawDataOffset.Value);
+ ImmutableArray nestedFieldPath = fieldPath.Add(new FieldPathPart.Leaf(fieldName, unspeakableName));
+
+ fields.Add(GetHlslKnownTypeFieldInfo(nestedFieldPath, typeName, ref rawDataOffset));
}
else if (fieldSymbol.Type.IsUnmanagedType)
{
+ string nestedTypeName = fieldSymbol.Type.GetFullyQualifiedName(includeGlobal: true);
+ FieldPathPart fieldPathPart = new FieldPathPart.Nested(fieldName, unspeakableName, nestedTypeName);
+
// Custom struct type defined by the user
- foreach (FieldInfo fieldInfo in GetCapturedFieldInfos(compilation, fieldSymbol.Type, fieldPath.Add(fieldName), rawDataOffset))
- {
- yield return fieldInfo;
- }
+ GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(fieldPathPart), ref rawDataOffset, fields);
}
}
}
// Setup the resource and byte offsets for tracking
- StrongBox rawDataOffsetAsBox = new();
+ int rawDataOffset = 0;
- // Traverse all shader fields and gather info, and update the tracking offsets
- ImmutableArray fieldInfos = GetCapturedFieldInfos(
- compilation,
- structDeclarationSymbol,
- ImmutableArray.Empty,
- rawDataOffsetAsBox).ToImmutableArray();
+ using (ImmutableArrayBuilder fieldBuilder = new())
+ {
+ // Traverse all shader fields and gather info, and update the tracking offsets
+ GetInfo(
+ compilation,
+ structDeclarationSymbol,
+ ImmutableArray.Empty,
+ ref rawDataOffset,
+ fieldBuilder);
- constantBufferSizeInBytes = rawDataOffsetAsBox.Value;
+ constantBufferSizeInBytes = rawDataOffset;
+ fields = fieldBuilder.ToImmutable();
+ }
// The maximum size for a constant buffer is 64KB
const int D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT = 4096;
@@ -103,8 +126,43 @@ partial class D2DPixelShaderDescriptorGenerator
{
diagnostics.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
}
+ }
- return fieldInfos;
+ ///
+ /// Tries to get the field name and the accessor name for a given field.
+ ///
+ /// The field symbol to analyze.
+ /// The name of the field that's referenced in code by users.
+ /// The real name of the field that should be accessed, when different.
+ /// Whether the field is supported and the necessary info could be retrieved.
+ public static bool TryGetFieldAccessorName(
+ IFieldSymbol fieldSymbol,
+ [NotNullWhen(true)] out string? referencedName,
+ out string? unspeakableName)
+ {
+ // If the field can be referenced by name, we can just access it directly
+ if (fieldSymbol.CanBeReferencedByName)
+ {
+ referencedName = fieldSymbol.Name;
+ unspeakableName = null;
+
+ return true;
+ }
+
+ // If the field is a primary constructor capture field, get the original name
+ if (PrimaryConstructorNameRegex.Match(fieldSymbol.Name) is { Success: true, Groups: [_, { Value: string parameterName }] })
+ {
+ referencedName = parameterName;
+ unspeakableName = fieldSymbol.Name;
+
+ return true;
+ }
+
+ // The field is not recognized, so just invalid
+ referencedName = null;
+ unspeakableName = null;
+
+ return false;
}
///
@@ -114,7 +172,7 @@ partial class D2DPixelShaderDescriptorGenerator
/// The type name currently being read.
/// The current offset within the loaded data buffer.
private static FieldInfo GetHlslKnownTypeFieldInfo(
- ImmutableArray fieldPath,
+ ImmutableArray fieldPath,
string typeName,
ref int rawDataOffset)
{
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.CreateFromConstantBuffer.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.CreateFromConstantBuffer.Syntax.cs
deleted file mode 100644
index 00c2161f..00000000
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.CreateFromConstantBuffer.Syntax.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-using ComputeSharp.D2D1.SourceGenerators.Models;
-using ComputeSharp.SourceGeneration.Extensions;
-using ComputeSharp.SourceGeneration.Helpers;
-using ComputeSharp.SourceGeneration.Mappings;
-using ComputeSharp.SourceGeneration.Models;
-
-namespace ComputeSharp.D2D1.SourceGenerators;
-
-///
-partial class D2DPixelShaderDescriptorGenerator
-{
- ///
- partial class CreateFromConstantBuffer
- {
- ///
- /// Writes the CreateFromConstantBuffer method.
- ///
- /// The input instance with gathered shader info.
- /// The instance to write into.
- public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
- {
- string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
-
- writer.WriteLine("/// ");
- writer.WriteGeneratedAttributes(GeneratorName);
- writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
- writer.WriteLine($"static unsafe {typeName} global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.CreateFromConstantBuffer(global::System.ReadOnlySpan data)");
-
- using (writer.WriteBlock())
- {
- // If there are no fields, just return an empty shader (TODO: add length check on .NET 8)
- if (info.Fields.IsEmpty)
- {
- writer.WriteLine("return default;");
-
- return;
- }
-
- // Get a reference to the data through the generated native layout type and define the shader
- writer.WriteLine($"ref readonly global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data));");
- writer.WriteLine();
- writer.WriteLine($"{typeName} shader;");
- writer.WriteLine();
-
- // Generate loading statements for each captured field
- foreach (FieldInfo fieldInfo in info.Fields)
- {
- switch (fieldInfo)
- {
- case FieldInfo.Primitive primitive:
-
- // Read a primitive value
- writer.WriteLine($"*&shader.{string.Join(".", primitive.FieldPath)} = buffer.{string.Join("_", primitive.FieldPath)};");
- break;
-
- case FieldInfo.NonLinearMatrix matrix:
- string primitiveTypeName = matrix.ElementName.ToLowerInvariant();
- string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
- string fieldPath = string.Join(".", matrix.FieldPath);
- string fieldNamePrefix = string.Join("_", matrix.FieldPath);
-
- // Read all rows of a given matrix type:
- //
- // Unsafe.As<, >(ref (*&shader.).M11) = buffer.;
- // Unsafe.As<, >(ref (*&shader.).M21) = buffer.;
- // ...
- // Unsafe.As<, >(ref (*&shader.).MN1) = buffer.;
- for (int j = 0; j < matrix.Rows; j++)
- {
- writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref (*&shader.{fieldPath}).M{j + 1}1) = buffer.{fieldNamePrefix}_{j};");
- }
-
- break;
- }
- }
-
- // Return the populated shader
- writer.WriteLine();
- writer.WriteLine("return shader;");
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.Syntax.cs
index fe88365a..836ddd60 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.Syntax.cs
@@ -85,13 +85,13 @@ partial class D2DPixelShaderDescriptorGenerator
return;
}
- usingDirectives.Add("global::System");
- usingDirectives.Add("global::System.Buffers");
- usingDirectives.Add("global::System.CodeDom.Compiler");
- usingDirectives.Add("global::System.Diagnostics");
- usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
- usingDirectives.Add("global::System.Runtime.CompilerServices");
- usingDirectives.Add("global::System.Runtime.InteropServices");
+ _ = usingDirectives.Add("global::System");
+ _ = usingDirectives.Add("global::System.Buffers");
+ _ = usingDirectives.Add("global::System.CodeDom.Compiler");
+ _ = usingDirectives.Add("global::System.Diagnostics");
+ _ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
+ _ = usingDirectives.Add("global::System.Runtime.CompilerServices");
+ _ = usingDirectives.Add("global::System.Runtime.InteropServices");
// Declare the HlslBytecodeMemoryManager custom memory manager type
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs
index 5e8b1864..5415f5f3 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs
@@ -108,9 +108,16 @@ partial class D2DPixelShaderDescriptorGenerator
using ImmutableArrayBuilder<(string, string)> values = new();
using ImmutableArrayBuilder<(string, string, int)> resourceTextures = new();
- foreach (IFieldSymbol fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
+ foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers())
{
- if (fieldSymbol.IsStatic)
+ // Skip constants and static fields, we only care about instance ones here
+ if (memberSymbol is not IFieldSymbol { IsConst: false, IsStatic: false } fieldSymbol)
+ {
+ continue;
+ }
+
+ // Try to get the actual field name
+ if (!ConstantBuffer.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _))
{
continue;
}
@@ -118,7 +125,7 @@ partial class D2DPixelShaderDescriptorGenerator
// Captured fields must be named type symbols
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol)
{
- diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
+ diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldName, fieldSymbol.Type);
continue;
}
@@ -126,7 +133,7 @@ partial class D2DPixelShaderDescriptorGenerator
string metadataName = typeSymbol.GetFullyQualifiedMetadataName();
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
- _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
+ _ = HlslKnownKeywords.TryGetMappedName(fieldName, out string? mapping);
// Handle resource textures as a special case
if (HlslKnownTypes.IsResourceTextureType(metadataName))
@@ -140,7 +147,7 @@ partial class D2DPixelShaderDescriptorGenerator
diagnostics.Add(
InvalidResourceTextureElementType,
fieldSymbol,
- fieldSymbol.Name,
+ fieldName,
structDeclarationSymbol,
fieldSymbol.Type);
}
@@ -155,7 +162,7 @@ partial class D2DPixelShaderDescriptorGenerator
_ = attributeData.TryGetConstructorArgument(0, out index);
}
- resourceTextures.Add((mapping ?? fieldSymbol.Name, typeName, index));
+ resourceTextures.Add((mapping ?? fieldName, typeName, index));
}
else if (typeSymbol.IsUnmanagedType)
{
@@ -166,11 +173,11 @@ partial class D2DPixelShaderDescriptorGenerator
types.Add(typeSymbol);
}
- values.Add((mapping ?? fieldSymbol.Name, typeName));
+ values.Add((mapping ?? fieldName, typeName));
}
else
{
- diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol);
+ diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldName, typeSymbol);
}
}
@@ -395,14 +402,21 @@ partial class D2DPixelShaderDescriptorGenerator
StructDeclarationSyntax structDeclaration = StructDeclaration(structType);
// Declare the fields of the current type
- foreach (IFieldSymbol field in type.GetMembers().OfType())
+ foreach (ISymbol memberSymbol in type.GetMembers())
{
- if (field.IsStatic)
+ // Once again, skip constants and staticv fields
+ if (memberSymbol is not IFieldSymbol { IsConst: false, IsStatic: false } fieldSymbol)
{
continue;
}
- INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
+ // Try to get the actual field name
+ if (!ConstantBuffer.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _))
+ {
+ continue;
+ }
+
+ INamedTypeSymbol fieldType = (INamedTypeSymbol)fieldSymbol.Type;
// Convert the name to the fully qualified HLSL version
if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullyQualifiedMetadataName(), out string? mappedType))
@@ -411,9 +425,9 @@ partial class D2DPixelShaderDescriptorGenerator
}
// Get the field name as a valid HLSL identifier
- if (!HlslKnownKeywords.TryGetMappedName(field.Name, out string? mappedName))
+ if (!HlslKnownKeywords.TryGetMappedName(fieldName, out string? mappedName))
{
- mappedName = field.Name;
+ mappedName = fieldName;
}
structDeclaration = structDeclaration.AddMembers(
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.Syntax.cs
index ce1f1096..ca098146 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.Syntax.cs
@@ -53,9 +53,9 @@ partial class D2DPixelShaderDescriptorGenerator
return;
}
- usingDirectives.Add("global::System.CodeDom.Compiler");
- usingDirectives.Add("global::System.Diagnostics");
- usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
+ _ = usingDirectives.Add("global::System.CodeDom.Compiler");
+ _ = usingDirectives.Add("global::System.Diagnostics");
+ _ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
AddAdditionalDataMemberUsingDirectives(info, usingDirectives);
ResourceTextureDescriptions.AddAdditionalDataMemberUsingDirectives(info, usingDirectives);
@@ -103,8 +103,8 @@ partial class D2DPixelShaderDescriptorGenerator
return;
}
- usingDirectives.Add("global::ComputeSharp.D2D1");
- usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
+ _ = usingDirectives.Add("global::ComputeSharp.D2D1");
+ _ = usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
}
///
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputTypes.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputTypes.Syntax.cs
index 0829cdc5..5ed34b34 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputTypes.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputTypes.Syntax.cs
@@ -50,14 +50,14 @@ partial class D2DPixelShaderDescriptorGenerator
return;
}
- usingDirectives.Add("global::System");
- usingDirectives.Add("global::System.Buffers");
- usingDirectives.Add("global::System.CodeDom.Compiler");
- usingDirectives.Add("global::System.Diagnostics");
- usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
- usingDirectives.Add("global::System.Runtime.CompilerServices");
- usingDirectives.Add("global::System.Runtime.InteropServices");
- usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
+ _ = usingDirectives.Add("global::System");
+ _ = usingDirectives.Add("global::System.Buffers");
+ _ = usingDirectives.Add("global::System.CodeDom.Compiler");
+ _ = usingDirectives.Add("global::System.Diagnostics");
+ _ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
+ _ = usingDirectives.Add("global::System.Runtime.CompilerServices");
+ _ = usingDirectives.Add("global::System.Runtime.InteropServices");
+ _ = usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
// Declare the InputTypesMemoryManager custom memory manager type
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.LoadConstantBuffer.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.LoadConstantBuffer.Syntax.cs
deleted file mode 100644
index 4a7d6503..00000000
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.LoadConstantBuffer.Syntax.cs
+++ /dev/null
@@ -1,157 +0,0 @@
-using ComputeSharp.D2D1.SourceGenerators.Models;
-using ComputeSharp.SourceGeneration.Extensions;
-using ComputeSharp.SourceGeneration.Helpers;
-using ComputeSharp.SourceGeneration.Mappings;
-using ComputeSharp.SourceGeneration.Models;
-
-namespace ComputeSharp.D2D1.SourceGenerators;
-
-///
-partial class D2DPixelShaderDescriptorGenerator
-{
- ///
- partial class LoadConstantBuffer
- {
- ///
- /// Writes the LoadConstantBuffer method.
- ///
- /// The input instance with gathered shader info.
- /// The instance to write into.
- public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
- {
- string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
-
- writer.WriteLine("/// ");
- writer.WriteGeneratedAttributes(GeneratorName);
- writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
- writer.WriteLine($"static unsafe void global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.LoadConstantBuffer(in {typeName} shader, ref TLoader loader)");
-
- using (writer.WriteBlock())
- {
- // If there are no fields, just load an empty buffer
- if (info.Fields.IsEmpty)
- {
- writer.WriteLine("loader.LoadConstantBuffer(default);");
- }
- else
- {
- writer.WriteLine("global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer;");
- writer.WriteLine();
-
- // Generate loading statements for each captured field
- foreach (FieldInfo fieldInfo in info.Fields)
- {
- switch (fieldInfo)
- {
- case FieldInfo.Primitive primitive:
-
- // Assign a primitive value
- writer.WriteLine($"buffer.{string.Join("_", primitive.FieldPath)} = shader.{string.Join(".", primitive.FieldPath)};");
- break;
-
- case FieldInfo.NonLinearMatrix matrix:
- string primitiveTypeName = matrix.ElementName.ToLowerInvariant();
- string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
- string fieldPath = string.Join(".", matrix.FieldPath);
- string fieldNamePrefix = string.Join("_", matrix.FieldPath);
-
- // Assign all rows of a given matrix type:
- //
- // buffer. = Unsafe.As<, >(ref Unsafe.AsRef(in shader.).M11);
- // buffer. = Unsafe.As<, >(ref Unsafe.AsRef(in shader.).M21);
- // ...
- // buffer. = Unsafe.As<, >(ref Unsafe.AsRef(in shader.).MN1);
- for (int j = 0; j < matrix.Rows; j++)
- {
- writer.WriteLine($"buffer.{fieldNamePrefix}_{j} = global::System.Runtime.CompilerServices.Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in shader.{fieldPath}).M{j + 1}1);");
- }
-
- break;
- }
- }
-
- writer.WriteLine();
- writer.WriteLine("loader.LoadConstantBuffer(new global::System.ReadOnlySpan(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));");
- }
- }
- }
-
- ///
- /// Registers a callback to generate an additional type, if needed.
- ///
- /// The input instance with gathered shader info.
- /// The registered callbacks to generate additional types.
- /// The using directives needed by the generated code.
- public static void RegisterAdditionalTypeSyntax(
- D2D1ShaderInfo info,
- ImmutableArrayBuilder> callbacks,
- ImmutableHashSetBuilder usingDirectives)
- {
- // If there are no fields, there is no need for a constant buffer type
- if (info.Fields.IsEmpty)
- {
- return;
- }
-
- usingDirectives.Add("global::System.CodeDom.Compiler");
- usingDirectives.Add("global::System.Diagnostics");
- usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
- usingDirectives.Add("global::System.Runtime.InteropServices");
-
- // Declare the ConstantBuffer type
- static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
- {
- string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName();
-
- writer.WriteLine($$"""/// """);
- writer.WriteLine($$"""/// A type representing the constant buffer native layout for .""");
- writer.WriteLine($$"""/// """);
- writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false);
- writer.WriteLine($$"""[StructLayout(LayoutKind.Explicit, Size = {{info.ConstantBufferSizeInBytes}})]""");
- writer.WriteLine($$"""file struct ConstantBuffer""");
-
- using (writer.WriteBlock())
- {
- // Declare fields for every mapped item from the shader layout
- writer.WriteLineSeparatedMembers(info.Fields.AsSpan(), (field, writer) =>
- {
- switch (field)
- {
- case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive:
-
- // Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values)
- writer.WriteLine($$"""/// """);
- writer.WriteLine($$"""[FieldOffset({{primitive.Offset}})]""");
- writer.WriteLine($$"""public global::ComputeSharp.Bool {{string.Join("_", primitive.FieldPath)}};""");
- break;
- case FieldInfo.Primitive primitive:
-
- // Append primitive fields of other types with their mapped names
- writer.WriteLine($$"""/// """);
- writer.WriteLine($$"""[FieldOffset({{primitive.Offset}})]""");
- writer.WriteLine($$"""public {{HlslKnownTypes.GetMappedName(primitive.TypeName)}} {{string.Join("_", primitive.FieldPath)}};""");
- break;
-
- case FieldInfo.NonLinearMatrix matrix:
- string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
- string fieldNamePrefix = string.Join("_", matrix.FieldPath);
-
- // Declare a field for every row of the matrix type
- for (int j = 0; j < matrix.Rows; j++)
- {
- writer.WriteLineIf(j > 0);
- writer.WriteLine($$"""/// Row {j} of .""");
- writer.WriteLine($$"""[FieldOffset({{matrix.Offsets[j]}})]""");
- writer.WriteLine($$"""public {{rowTypeName}} {{fieldNamePrefix}}_{{j}};""");
- }
-
- break;
- }
- });
- }
- }
-
- callbacks.Add(Callback);
- }
- }
-}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ResourceTextureDescriptions.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ResourceTextureDescriptions.Syntax.cs
index 1ec6ee18..218a00ae 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ResourceTextureDescriptions.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ResourceTextureDescriptions.Syntax.cs
@@ -47,7 +47,7 @@ partial class D2DPixelShaderDescriptorGenerator
return;
}
- usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
+ _ = usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
}
///
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs
index 089fb533..5f6d96c4 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs
@@ -82,12 +82,13 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene
using ImmutableArrayBuilder diagnostics = new();
- // LoadDispatchData() info
- ImmutableArray fieldInfos = LoadConstantBuffer.GetInfo(
+ // Constant buffer info
+ ConstantBuffer.GetInfo(
diagnostics,
context.SemanticModel.Compilation,
typeSymbol,
- out int constantBufferSizeInBytes);
+ out int constantBufferSizeInBytes,
+ out ImmutableArray fieldInfos);
token.ThrowIfCancellationRequested();
@@ -226,13 +227,13 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene
declaredMembers.Add(HlslBytecode.WriteCompileOptionsSyntax);
declaredMembers.Add(HlslSource.WriteSyntax);
declaredMembers.Add(HlslBytecode.WriteHlslBytecodeSyntax);
- declaredMembers.Add(CreateFromConstantBuffer.WriteSyntax);
- declaredMembers.Add(LoadConstantBuffer.WriteSyntax);
+ declaredMembers.Add(ConstantBuffer.WriteCreateFromConstantBufferSyntax);
+ declaredMembers.Add(ConstantBuffer.WriteLoadConstantBufferSyntax);
using ImmutableArrayBuilder> additionalTypes = new();
using ImmutableHashSetBuilder usingDirectives = new();
- LoadConstantBuffer.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
+ ConstantBuffer.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives);
InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Models/FieldInfo.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Models/FieldInfo.cs
index 10da8292..0463030c 100644
--- a/src/ComputeSharp.SourceGeneration.Hlsl/Models/FieldInfo.cs
+++ b/src/ComputeSharp.SourceGeneration.Hlsl/Models/FieldInfo.cs
@@ -7,7 +7,7 @@ namespace ComputeSharp.SourceGeneration.Models;
///
/// The path of the field with respect to the shader instance.
/// The full metadata name for the primitive type.
-internal abstract record FieldInfo(EquatableArray FieldPath, string TypeName)
+internal abstract record FieldInfo(EquatableArray FieldPath, string TypeName)
{
///
/// A captured primitive value (either a scalar, a vector, or a linear matrix).
@@ -15,7 +15,7 @@ internal abstract record FieldInfo(EquatableArray FieldPath, string Type
///
///
/// The byte offset of the value within the root signature.
- public sealed record Primitive(EquatableArray FieldPath, string TypeName, int Offset) : FieldInfo(FieldPath, TypeName);
+ public sealed record Primitive(EquatableArray FieldPath, string TypeName, int Offset) : FieldInfo(FieldPath, TypeName);
///
/// A captured non linear matrix value.
@@ -27,10 +27,33 @@ internal abstract record FieldInfo(EquatableArray FieldPath, string Type
/// The number of columns in the matrix.
/// The sequence of byte offsets for each row within the root signature.
public sealed record NonLinearMatrix(
- EquatableArray FieldPath,
+ EquatableArray FieldPath,
string TypeName,
string ElementName,
int Rows,
int Columns,
EquatableArray Offsets) : FieldInfo(FieldPath, TypeName);
+}
+
+///
+/// A model for a part of a field path, ie. the name of the immediate parent field, and whether it's accessible.
+///
+/// The name of the immediate parent field to access (or self).
+/// The unspeakable name of the field, if present.
+internal abstract record FieldPathPart(string Name, string? UnspeakableName)
+{
+ ///
+ /// A model for a leaf part of a field path.
+ ///
+ ///
+ ///
+ public sealed record Leaf(string Name, string? UnspeakableName) : FieldPathPart(Name, UnspeakableName);
+
+ ///
+ /// A model for a nested field part path (ie. going through a nested struct type).
+ ///
+ ///
+ ///
+ /// The fully qualified type name of the containing type.
+ public sealed record Nested(string Name, string? UnspeakableName, string TypeName) : FieldPathPart(Name, UnspeakableName);
}
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs
index 52063552..a7c58ed1 100644
--- a/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs
+++ b/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs
@@ -49,10 +49,13 @@ internal static class ISymbolExtensions
/// Gets the fully qualified name for a given symbol.
///
/// The input instance.
+ /// Whether to include the global:: prefix.
/// The fully qualified name for .
- public static string GetFullyQualifiedName(this ISymbol symbol)
+ public static string GetFullyQualifiedName(this ISymbol symbol, bool includeGlobal = false)
{
- return symbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat);
+ return includeGlobal
+ ? symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
+ : symbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat);
}
///
diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs
index 59765261..575c1c9d 100644
--- a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs
+++ b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Runtime.CompilerServices;
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGeneration.Extensions;
@@ -66,50 +65,6 @@ internal static class IndentedTextWriterExtensions
writer.WriteLineIf(usingDirectives.Any());
}
- ///
- /// Writes a new line into the target writer depending on an input condition.
- ///
- /// The instance to write into.
- /// The condition to use to decide whether or not to write a new line.
- public static void WriteLineIf(this IndentedTextWriter writer, bool condition)
- {
- if (condition)
- {
- writer.WriteLine();
- }
- }
-
- ///
- /// Writes a new line into the target writer depending on an input condition.
- ///
- /// The instance to write into.
- /// The content to write.
- /// The condition to use to decide whether or not to write a new line.
- public static void WriteLineIf(this IndentedTextWriter writer, string content, bool condition)
- {
- if (condition)
- {
- writer.WriteLine(content);
- }
- }
-
- ///
- /// Writes a new line into the target writer depending on an input condition.
- ///
- /// The instance to write into.
- /// The interpolated string handler with content to write.
- /// The condition to use to decide whether or not to write a new line.
- public static void WriteLineIf(
- this IndentedTextWriter writer,
- [InterpolatedStringHandlerArgument(nameof(writer))] ref IndentedTextWriter.WriteInterpolatedStringHandler handler,
- bool condition)
- {
- if (condition)
- {
- writer.WriteLine(ref handler);
- }
- }
-
///
/// Writes a series of members separated by one line between each of them.
///
diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs
index e96aa224..fe6a92a7 100644
--- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs
+++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs
@@ -44,9 +44,9 @@ internal struct ImmutableHashSetBuilder : IDisposable
}
///
- public readonly void Add(T item)
+ public readonly bool Add(T item)
{
- _ = this.set!.Add(item);
+ return this.set!.Add(item);
}
///
diff --git a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs
index e9b26bf9..d095a16c 100644
--- a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs
+++ b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs
@@ -177,11 +177,55 @@ internal sealed class IndentedTextWriter : IDisposable
_ = this;
}
+ ///
+ /// Writes content to the underlying buffer depending on an input condition.
+ ///
+ /// The condition to use to decide whether or not to write content.
+ /// The content to write.
+ /// Whether the input content is multiline.
+ public void WriteIf(bool condition, string content, bool isMultiline = false)
+ {
+ if (condition)
+ {
+ Write(content.AsSpan(), isMultiline);
+ }
+ }
+
+ ///
+ /// Writes content to the underlying buffer depending on an input condition.
+ ///
+ /// The condition to use to decide whether or not to write content.
+ /// The content to write.
+ /// Whether the input content is multiline.
+ public void WriteIf(bool condition, ReadOnlySpan content, bool isMultiline = false)
+ {
+ if (condition)
+ {
+ Write(content, isMultiline);
+ }
+ }
+
+ ///
+ /// Writes content to the underlying buffer depending on an input condition.
+ ///
+ /// The condition to use to decide whether or not to write content.
+ /// The interpolated string handler with content to write.
+ public void WriteIf(bool condition, [InterpolatedStringHandlerArgument("", nameof(condition))] ref WriteIfInterpolatedStringHandler handler)
+ {
+ _ = this;
+ }
+
///
/// Writes a line to the underlying buffer.
///
- public void WriteLine()
+ /// Indicates whether to skip adding the line if there already is one.
+ public void WriteLine(bool skipIfPresent = false)
{
+ if (skipIfPresent && this.builder.WrittenSpan is [.., '\n', '\n'])
+ {
+ return;
+ }
+
this.builder.Add(DefaultNewLine);
}
@@ -215,6 +259,61 @@ internal sealed class IndentedTextWriter : IDisposable
WriteLine();
}
+ ///
+ /// Writes a line to the underlying buffer depending on an input condition.
+ ///
+ /// The condition to use to decide whether or not to write content.
+ /// Indicates whether to skip adding the line if there already is one.
+ public void WriteLineIf(bool condition, bool skipIfPresent = false)
+ {
+ if (condition)
+ {
+ WriteLine(skipIfPresent);
+ }
+ }
+
+ ///
+ /// Writes content to the underlying buffer and appends a trailing new line depending on an input condition.
+ ///
+ /// The condition to use to decide whether or not to write content.
+ /// The content to write.
+ /// Whether the input content is multiline.
+ public void WriteLineIf(bool condition, string content, bool isMultiline = false)
+ {
+ if (condition)
+ {
+ WriteLine(content.AsSpan(), isMultiline);
+ }
+ }
+
+ ///
+ /// Writes content to the underlying buffer and appends a trailing new line depending on an input condition.
+ ///
+ /// The condition to use to decide whether or not to write content.
+ /// The content to write.
+ /// Whether the input content is multiline.
+ public void WriteLineIf(bool condition, ReadOnlySpan content, bool isMultiline = false)
+ {
+ if (condition)
+ {
+ Write(content, isMultiline);
+ WriteLine();
+ }
+ }
+
+ ///
+ /// Writes content to the underlying buffer and appends a trailing new line depending on an input condition.
+ ///
+ /// The condition to use to decide whether or not to write content.
+ /// The interpolated string handler with content to write.
+ public void WriteLineIf(bool condition, [InterpolatedStringHandlerArgument("", nameof(condition))] ref WriteIfInterpolatedStringHandler handler)
+ {
+ if (condition)
+ {
+ WriteLine();
+ }
+ }
+
///
public override string ToString()
{
@@ -351,4 +450,68 @@ internal sealed class IndentedTextWriter : IDisposable
}
}
}
+
+ ///
+ /// Provides a handler used by the language compiler to conditionally append interpolated strings into instances.
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [InterpolatedStringHandler]
+ public readonly ref struct WriteIfInterpolatedStringHandler
+ {
+ /// The associated to use.
+ private readonly WriteInterpolatedStringHandler handler;
+
+ /// Creates a handler used to append an interpolated string into a .
+ /// The number of constant characters outside of interpolation expressions in the interpolated string.
+ /// The number of interpolation expressions in the interpolated string.
+ /// The associated to which to append.
+ /// The condition to use to decide whether or not to write content.
+ /// A value indicating whether formatting should proceed.
+ /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.
+ public WriteIfInterpolatedStringHandler(int literalLength, int formattedCount, IndentedTextWriter writer, bool condition, out bool shouldAppend)
+ {
+ if (condition)
+ {
+ this.handler = new WriteInterpolatedStringHandler(literalLength, formattedCount, writer);
+
+ shouldAppend = true;
+ }
+ else
+ {
+ this.handler = default;
+
+ shouldAppend = false;
+ }
+ }
+
+ ///
+ public void AppendLiteral(string value)
+ {
+ this.handler.AppendLiteral(value);
+ }
+
+ ///
+ public void AppendFormatted(string? value)
+ {
+ this.handler.AppendFormatted(value);
+ }
+
+ ///
+ public void AppendFormatted(ReadOnlySpan value)
+ {
+ this.handler.AppendFormatted(value);
+ }
+
+ ///
+ public void AppendFormatted(T value)
+ {
+ this.handler.AppendFormatted(value);
+ }
+
+ ///
+ public void AppendFormatted(T value, string? format)
+ {
+ this.handler.AppendFormatted(value, format);
+ }
+ }
}
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs
index 50c8d05f..5127fbcd 100644
--- a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs
+++ b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs
@@ -118,9 +118,16 @@ internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName,
using ImmutableArrayBuilder fullyQualifiedTypeName = new();
fullyQualifiedTypeName.AddRange("global::".AsSpan());
- fullyQualifiedTypeName.AddRange(Namespace.AsSpan());
- for (int i = Hierarchy.Length - 1; i >= 0; i--)
+ if (Namespace.Length > 0)
+ {
+ fullyQualifiedTypeName.AddRange(Namespace.AsSpan());
+ fullyQualifiedTypeName.Add('.');
+ }
+
+ fullyQualifiedTypeName.AddRange(Hierarchy[^1].QualifiedName.AsSpan());
+
+ for (int i = Hierarchy.Length - 2; i >= 0; i--)
{
fullyQualifiedTypeName.Add('.');
fullyQualifiedTypeName.AddRange(Hierarchy[i].QualifiedName.AsSpan());
diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.Syntax.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.Syntax.cs
index 87ed9c4d..ccdd6076 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.Syntax.cs
+++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.Syntax.cs
@@ -1,3 +1,4 @@
+using System.Linq;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
@@ -32,7 +33,7 @@ partial class ComputeShaderDescriptorGenerator
// Append the statements for the dispatch ranges
writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.As(ref span[0]) = (uint)x;");
writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.As(ref span[4]) = (uint)y;");
- writer.WriteLineIf("global::System.Runtime.CompilerServices.Unsafe.As(ref span[8]) = (uint)z;", !info.IsPixelShaderLike);
+ writer.WriteLineIf(!info.IsPixelShaderLike, "global::System.Runtime.CompilerServices.Unsafe.As(ref span[8]) = (uint)z;");
// Generate loading statements for each captured field
foreach (FieldInfo fieldInfo in info.Fields)
@@ -44,19 +45,19 @@ partial class ComputeShaderDescriptorGenerator
// Read a boolean value and cast it to Bool first, which will apply the correct size expansion
writer.WriteLine(
$"global::System.Runtime.CompilerServices.Unsafe.As(ref span[{primitive.Offset}]) = " +
- $"(global::ComputeSharp.Bool)shader.{string.Join(".", primitive.FieldPath)};");
+ $"(global::ComputeSharp.Bool)shader.{string.Join(".", primitive.FieldPath.Select(static path => path.Name))};");
break;
case FieldInfo.Primitive primitive:
// Read a primitive value and serialize it into the target buffer
writer.WriteLine(
$"global::System.Runtime.CompilerServices.Unsafe.As(ref span[{primitive.Offset}]) = " +
- $"shader.{string.Join(".", primitive.FieldPath)};");
+ $"shader.{string.Join(".", primitive.FieldPath.Select(static path => path.Name))};");
break;
case FieldInfo.NonLinearMatrix matrix:
string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
- string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0";
+ string rowLocalName = $"__{string.Join("_", matrix.FieldPath.Select(static path => path.Name))}__row0";
// Declare a local to index into individual rows. This will generate:
//
@@ -64,7 +65,7 @@ partial class ComputeShaderDescriptorGenerator
// ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in ));
writer.WriteLine(
$"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(" +
- $"ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in shader.{string.Join(".", matrix.FieldPath)}));");
+ $"ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in shader.{string.Join(".", matrix.FieldPath.Select(static path => path.Name))}));");
// Generate the loading code for each individual row, with proper alignment.
// This will result in the following (assuming Float2x3 m):
diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.cs
index c9c25e3f..01105349 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.cs
+++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.cs
@@ -43,7 +43,7 @@ partial class ComputeShaderDescriptorGenerator
static void GetInfo(
Compilation compilation,
ITypeSymbol currentTypeSymbol,
- ImmutableArray fieldPath,
+ ImmutableArray fieldPath,
ref int resourceOffset,
ref int rawDataOffset,
ImmutableArrayBuilder fields,
@@ -82,12 +82,13 @@ partial class ComputeShaderDescriptorGenerator
}
else if (HlslKnownTypes.IsKnownHlslType(typeName))
{
- fields.Add(GetHlslKnownTypeFieldInfo(fieldPath.Add(fieldName), typeName, ref rawDataOffset));
+ // TODO: share the logic and fix the field path parts
+ fields.Add(GetHlslKnownTypeFieldInfo(fieldPath.Add(new FieldPathPart.Leaf(fieldName, null)), typeName, ref rawDataOffset));
}
else if (fieldSymbol.Type.IsUnmanagedType)
{
// Custom struct type defined by the user
- GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(fieldName), ref resourceOffset, ref rawDataOffset, fields, resources);
+ GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(new FieldPathPart.Leaf(fieldName, null)), ref resourceOffset, ref rawDataOffset, fields, resources);
}
}
}
@@ -104,7 +105,7 @@ partial class ComputeShaderDescriptorGenerator
GetInfo(
compilation,
structDeclarationSymbol,
- ImmutableArray.Empty,
+ ImmutableArray.Empty,
ref resourceOffset,
ref rawDataOffset,
fieldBuilder,
@@ -144,7 +145,7 @@ partial class ComputeShaderDescriptorGenerator
/// The type name currently being read.
/// The current offset within the loaded data buffer.
private static FieldInfo GetHlslKnownTypeFieldInfo(
- ImmutableArray fieldPath,
+ ImmutableArray fieldPath,
string typeName,
ref int rawDataOffset)
{
diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.Syntax.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.Syntax.cs
index 15b1ee5c..c8a1a0ca 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.Syntax.cs
+++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.Syntax.cs
@@ -50,13 +50,13 @@ partial class ComputeShaderDescriptorGenerator
return;
}
- usingDirectives.Add("global::System");
- usingDirectives.Add("global::System.Buffers");
- usingDirectives.Add("global::System.CodeDom.Compiler");
- usingDirectives.Add("global::System.Diagnostics");
- usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
- usingDirectives.Add("global::System.Runtime.CompilerServices");
- usingDirectives.Add("global::System.Runtime.InteropServices");
+ _ = usingDirectives.Add("global::System");
+ _ = usingDirectives.Add("global::System.Buffers");
+ _ = usingDirectives.Add("global::System.CodeDom.Compiler");
+ _ = usingDirectives.Add("global::System.Diagnostics");
+ _ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
+ _ = usingDirectives.Add("global::System.Runtime.CompilerServices");
+ _ = usingDirectives.Add("global::System.Runtime.InteropServices");
// Declare the HlslBytecodeMemoryManager custom memory manager type
static void Callback(ShaderInfo info, IndentedTextWriter writer)
diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.Syntax.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.Syntax.cs
index 56e237c1..015c91a2 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.Syntax.cs
+++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.Syntax.cs
@@ -49,10 +49,10 @@ partial class ComputeShaderDescriptorGenerator
return;
}
- usingDirectives.Add("global::System.CodeDom.Compiler");
- usingDirectives.Add("global::System.Diagnostics");
- usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
- usingDirectives.Add("global::ComputeSharp.Interop");
+ _ = usingDirectives.Add("global::System.CodeDom.Compiler");
+ _ = usingDirectives.Add("global::System.Diagnostics");
+ _ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
+ _ = usingDirectives.Add("global::ComputeSharp.Interop");
// Declare the additional data type and the shared array with resource descriptor ranges
static void Callback(ShaderInfo info, IndentedTextWriter writer)
diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs
index b0ebb8fd..837d4357 100644
--- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs
+++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs
@@ -1,5 +1,4 @@
using System;
-using System.Runtime.CompilerServices;
using ComputeSharp.Descriptors;
using ComputeSharp.Interop;
@@ -24,7 +23,7 @@ public static partial class GraphicsDeviceExtensions
using ComputeContext context = device.CreateComputeContext();
- context.Run(x, ref Unsafe.AsRef(in shader));
+ context.Run(x, in shader);
}
///
@@ -42,7 +41,7 @@ public static partial class GraphicsDeviceExtensions
using ComputeContext context = device.CreateComputeContext();
- context.Run(x, y, ref Unsafe.AsRef(in shader));
+ context.Run(x, y, in shader);
}
///
@@ -61,7 +60,7 @@ public static partial class GraphicsDeviceExtensions
using ComputeContext context = device.CreateComputeContext();
- context.Run(x, y, z, ref Unsafe.AsRef(in shader));
+ context.Run(x, y, z, in shader);
}
///
@@ -80,9 +79,7 @@ public static partial class GraphicsDeviceExtensions
using ComputeContext context = device.CreateComputeContext();
- Unsafe.SkipInit(out T shader);
-
- context.Run(texture, ref shader);
+ context.Run(texture, default(T));
}
///
@@ -102,7 +99,7 @@ public static partial class GraphicsDeviceExtensions
using ComputeContext context = device.CreateComputeContext();
- context.Run(texture, ref Unsafe.AsRef(in shader));
+ context.Run(texture, in shader);
}
///
diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs
index cc50e76b..bd978e18 100644
--- a/src/ComputeSharp/Shaders/ComputeContext.cs
+++ b/src/ComputeSharp/Shaders/ComputeContext.cs
@@ -121,11 +121,10 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
///
/// The number of iterations to run on the X axis.
/// The input instance representing the compute shader to run.
- internal readonly unsafe void Run(int x, ref T shader)
+ internal readonly unsafe void Run(int x, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor
{
-
- Run(x, 1, 1, ref shader);
+ Run(x, 1, 1, in shader);
}
///
@@ -134,11 +133,10 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
/// The number of iterations to run on the X axis.
/// The number of iterations to run on the Y axis.
/// The input instance representing the compute shader to run.
- internal readonly unsafe void Run(int x, int y, ref T shader)
+ internal readonly unsafe void Run(int x, int y, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor
{
-
- Run(x, y, 1, ref shader);
+ Run(x, y, 1, in shader);
}
///
@@ -149,7 +147,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
/// The number of iterations to run on the Y axis.
/// The number of iterations to run on the Z axis.
/// The input instance representing the compute shader to run.
- internal readonly unsafe void Run(int x, int y, int z, ref T shader)
+ internal readonly unsafe void Run(int x, int y, int z, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor
{
default(InvalidOperationException).ThrowIf(this.device is null);
@@ -189,7 +187,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
/// The type of pixel to work on.
/// The target texture to invoke the pixel shader upon.
/// The input instance representing the pixel shader to run.
- internal readonly unsafe void Run(IReadWriteNormalizedTexture2D texture, ref T shader)
+ internal readonly unsafe void Run(IReadWriteNormalizedTexture2D texture, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor
where TPixel : unmanaged
{
diff --git a/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs b/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs
index 8e38f4a6..be26aeca 100644
--- a/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs
+++ b/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs
@@ -487,7 +487,7 @@ public static class ComputeContextExtensions
public static void For(this in ComputeContext context, int x, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor
{
- context.Run(x, ref Unsafe.AsRef(in shader));
+ context.Run(x, in shader);
}
///
@@ -501,7 +501,7 @@ public static class ComputeContextExtensions
public static void For(this in ComputeContext context, int x, int y, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor
{
- context.Run(x, y, ref Unsafe.AsRef(in shader));
+ context.Run(x, y, in shader);
}
///
@@ -516,7 +516,7 @@ public static class ComputeContextExtensions
public static void For(this in ComputeContext context, int x, int y, int z, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor
{
- context.Run(x, y, z, ref Unsafe.AsRef(in shader));
+ context.Run(x, y, z, in shader);
}
///
@@ -532,9 +532,7 @@ public static class ComputeContextExtensions
{
default(ArgumentNullException).ThrowIfNull(texture);
- Unsafe.SkipInit(out T shader);
-
- context.Run(texture, ref shader);
+ context.Run(texture, default(T));
}
///
@@ -551,7 +549,7 @@ public static class ComputeContextExtensions
{
default(ArgumentNullException).ThrowIfNull(texture);
- context.Run(texture, ref Unsafe.AsRef(in shader));
+ context.Run(texture, in shader);
}
///
diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs
index 15524477..2f2a43ff 100644
--- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs
+++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs
@@ -1,41 +1,108 @@
using System;
using System.Buffers;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
+using ComputeSharp;
+using ComputeSharp.D2D1;
using ComputeSharp.D2D1.Interop;
using ComputeSharp.D2D1.Tests.Effects;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-#pragma warning disable IDE0059, IDE0044
+#pragma warning disable IDE0059, IDE0161, IDE0044
-namespace ComputeSharp.D2D1.Tests;
-
-[TestClass]
-[TestCategory("D2D1PixelShader")]
-public partial class D2D1PixelShaderTests
+[D2DInputCount(0)]
+[D2DGeneratedPixelShaderDescriptor]
+[AutoConstructor]
+internal readonly partial struct ShaderWithScalarVectorAndMatrixTypes_Global : ID2D1PixelShader
{
- [TestMethod]
- public void GetInputCount()
+ public readonly int x;
+ public readonly int y;
+ public readonly int z;
+ public readonly float2x3 f2x3;
+ public readonly int a;
+ public readonly int1x3 i1x3;
+ public readonly double2 d2;
+ public readonly int c;
+ public readonly int1x2 i1x2;
+ public readonly int2x2 i2x2;
+ public readonly int d;
+
+ public float4 Execute()
{
- Assert.AreEqual(D2D1PixelShader.GetInputCount(), 1);
- Assert.AreEqual(D2D1PixelShader.GetInputCount(), 1);
- Assert.AreEqual(D2D1PixelShader.GetInputCount(), 0);
- Assert.AreEqual(D2D1PixelShader.GetInputCount(), 7);
+ return 0;
}
+}
- [TestMethod]
- public void GetInputTypes_NoInputs()
+[AutoConstructor]
+public readonly partial struct FieldsContainer1_Global
+{
+ public readonly int1x2 i1x2;
+ public readonly int2x2 i2x2;
+ public readonly int d;
+}
+
+[AutoConstructor]
+public readonly partial struct FieldsContainer2_Global
+{
+ public readonly int z;
+ public readonly float2x3 f2x3;
+ public readonly int a;
+ public readonly FieldsContainer3_Global container3;
+}
+
+[AutoConstructor]
+public readonly partial struct FieldsContainer3_Global
+{
+ public readonly int1x3 i1x3;
+ public readonly double2 d2;
+}
+
+[D2DInputCount(0)]
+[D2DGeneratedPixelShaderDescriptor]
+[AutoConstructor]
+internal readonly partial struct ShaderWithScalarVectorAndMatrixTypesInNestedStructs_Global : ID2D1PixelShader
+{
+ public readonly int x;
+ public readonly int y;
+ public readonly FieldsContainer2_Global container2;
+ public readonly int c;
+ public readonly FieldsContainer1_Global container1;
+
+ public float4 Execute()
{
- ReadOnlyMemory inputTypes = D2D1PixelShader.GetInputTypes();
-
- Assert.AreEqual(0, inputTypes.Length);
- Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(inputTypes, out MemoryManager? _));
+ return 0;
}
+}
- [TestMethod]
- public void GetInputTypes_MultipleInputs()
+namespace ComputeSharp.D2D1.Tests
+{
+ [TestClass]
+ [TestCategory("D2D1PixelShader")]
+ public partial class D2D1PixelShaderTests
{
- CollectionAssert.AreEqual(new[]
+ [TestMethod]
+ public void GetInputCount()
{
+ Assert.AreEqual(D2D1PixelShader.GetInputCount(), 1);
+ Assert.AreEqual(D2D1PixelShader.GetInputCount(), 1);
+ Assert.AreEqual(D2D1PixelShader.GetInputCount(), 0);
+ Assert.AreEqual(D2D1PixelShader.GetInputCount(), 7);
+ }
+
+ [TestMethod]
+ public void GetInputTypes_NoInputs()
+ {
+ ReadOnlyMemory inputTypes = D2D1PixelShader.GetInputTypes();
+
+ Assert.AreEqual(0, inputTypes.Length);
+ Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(inputTypes, out MemoryManager? _));
+ }
+
+ [TestMethod]
+ public void GetInputTypes_MultipleInputs()
+ {
+ CollectionAssert.AreEqual(new[]
+ {
D2D1PixelShaderInputType.Simple,
D2D1PixelShaderInputType.Complex,
D2D1PixelShaderInputType.Simple,
@@ -44,968 +111,1022 @@ public partial class D2D1PixelShaderTests
D2D1PixelShaderInputType.Complex,
D2D1PixelShaderInputType.Simple
}, D2D1PixelShader.GetInputTypes().ToArray());
- }
-
- [TestMethod]
- public void GetInputTypes_SameManager()
- {
- ReadOnlyMemory inputTypes1 = D2D1PixelShader.GetInputTypes();
-
- Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(inputTypes1, out MemoryManager? memoryManager1));
-
- ReadOnlyMemory inputTypes2 = D2D1PixelShader.GetInputTypes();
-
- Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(inputTypes2, out MemoryManager? memoryManager2));
- Assert.AreSame(memoryManager1, memoryManager2);
- }
-
- [D2DInputCount(7)]
- [D2DInputSimple(0)]
- [D2DInputSimple(2)]
- [D2DInputComplex(1)]
- [D2DInputComplex(3)]
- [D2DInputComplex(5)]
- [D2DInputSimple(6)]
- [D2DGeneratedPixelShaderDescriptor]
- internal partial struct ShaderWithMultipleInputs : ID2D1PixelShader
- {
- public Float4 Execute()
- {
- return 0;
}
- }
- [TestMethod]
- public void GetOutputBufferPrecision()
- {
- Assert.AreEqual(D2D1PixelShader.GetOutputBufferPrecision(), D2D1BufferPrecision.Unknown);
- Assert.AreEqual(D2D1PixelShader.GetOutputBufferPrecision(), D2D1BufferPrecision.UInt16Normalized);
- Assert.AreEqual(D2D1PixelShader.GetOutputBufferPrecision(), D2D1BufferPrecision.Unknown);
- Assert.AreEqual(D2D1PixelShader.GetOutputBufferPrecision(), D2D1BufferPrecision.UInt8NormalizedSrgb);
- }
-
- [TestMethod]
- public void GetOutputBufferChannelDepth()
- {
- Assert.AreEqual(D2D1PixelShader.GetOutputBufferChannelDepth(), D2D1ChannelDepth.Default);
- Assert.AreEqual(D2D1PixelShader.GetOutputBufferChannelDepth(), D2D1ChannelDepth.Default);
- Assert.AreEqual(D2D1PixelShader.GetOutputBufferChannelDepth(), D2D1ChannelDepth.Four);
- Assert.AreEqual(D2D1PixelShader.GetOutputBufferChannelDepth(), D2D1ChannelDepth.One);
- }
-
- [D2DInputCount(0)]
- [D2DGeneratedPixelShaderDescriptor]
- internal partial struct EmptyShader : ID2D1PixelShader
- {
- public Float4 Execute()
+ [TestMethod]
+ public void GetInputTypes_SameManager()
{
- return 0;
- }
- }
+ ReadOnlyMemory inputTypes1 = D2D1PixelShader.GetInputTypes();
- [D2DInputCount(0)]
- [D2DOutputBuffer(D2D1BufferPrecision.UInt16Normalized)]
- [D2DGeneratedPixelShaderDescriptor]
- internal partial struct OnlyBufferPrecisionShader : ID2D1PixelShader
- {
- public Float4 Execute()
+ Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(inputTypes1, out MemoryManager? memoryManager1));
+
+ ReadOnlyMemory inputTypes2 = D2D1PixelShader.GetInputTypes();
+
+ Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(inputTypes2, out MemoryManager? memoryManager2));
+ Assert.AreSame(memoryManager1, memoryManager2);
+ }
+
+ [D2DInputCount(7)]
+ [D2DInputSimple(0)]
+ [D2DInputSimple(2)]
+ [D2DInputComplex(1)]
+ [D2DInputComplex(3)]
+ [D2DInputComplex(5)]
+ [D2DInputSimple(6)]
+ [D2DGeneratedPixelShaderDescriptor]
+ internal partial struct ShaderWithMultipleInputs : ID2D1PixelShader
{
- return 0;
+ public Float4 Execute()
+ {
+ return 0;
+ }
}
- }
- [D2DInputCount(0)]
- [D2DOutputBuffer(D2D1ChannelDepth.Four)]
- [D2DGeneratedPixelShaderDescriptor]
- internal partial struct OnlyChannelDepthShader : ID2D1PixelShader
- {
- public Float4 Execute()
+ [TestMethod]
+ public void GetOutputBufferPrecision()
{
- return 0;
+ Assert.AreEqual(D2D1PixelShader.GetOutputBufferPrecision(), D2D1BufferPrecision.Unknown);
+ Assert.AreEqual(D2D1PixelShader.GetOutputBufferPrecision(), D2D1BufferPrecision.UInt16Normalized);
+ Assert.AreEqual(D2D1PixelShader.GetOutputBufferPrecision(), D2D1BufferPrecision.Unknown);
+ Assert.AreEqual(D2D1PixelShader.GetOutputBufferPrecision(), D2D1BufferPrecision.UInt8NormalizedSrgb);
}
- }
- [D2DInputCount(0)]
- [D2DOutputBuffer(D2D1BufferPrecision.UInt8NormalizedSrgb, D2D1ChannelDepth.One)]
- [D2DGeneratedPixelShaderDescriptor]
- internal partial struct CustomBufferOutputShader : ID2D1PixelShader
- {
- public Float4 Execute()
+ [TestMethod]
+ public void GetOutputBufferChannelDepth()
{
- return 0;
+ Assert.AreEqual(D2D1PixelShader.GetOutputBufferChannelDepth(), D2D1ChannelDepth.Default);
+ Assert.AreEqual(D2D1PixelShader.GetOutputBufferChannelDepth(), D2D1ChannelDepth.Default);
+ Assert.AreEqual(D2D1PixelShader.GetOutputBufferChannelDepth(), D2D1ChannelDepth.Four);
+ Assert.AreEqual(D2D1PixelShader.GetOutputBufferChannelDepth(), D2D1ChannelDepth.One);
}
- }
- [TestMethod]
- public void GetInputDescriptions_Empty()
- {
- Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
-
- Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
- }
-
- [TestMethod]
- public void GetInputDescriptions_Custom()
- {
- ReadOnlyMemory inputDescriptions = D2D1PixelShader.GetInputDescriptions();
-
- Assert.AreEqual(inputDescriptions.Length, 5);
-
- ReadOnlySpan span = inputDescriptions.Span;
-
- Assert.AreEqual(span[0].Index, 0);
- Assert.AreEqual(span[0].Filter, D2D1Filter.MinPointMagLinearMipPoint);
- Assert.AreEqual(span[0].LevelOfDetailCount, 0);
-
- Assert.AreEqual(span[1].Index, 1);
- Assert.AreEqual(span[1].Filter, D2D1Filter.Anisotropic);
- Assert.AreEqual(span[1].LevelOfDetailCount, 0);
-
- Assert.AreEqual(span[2].Index, 2);
- Assert.AreEqual(span[2].Filter, D2D1Filter.MinLinearMagPointMinLinear);
- Assert.AreEqual(span[2].LevelOfDetailCount, 4);
-
- Assert.AreEqual(span[3].Index, 5);
- Assert.AreEqual(span[3].Filter, D2D1Filter.MinMagPointMipLinear);
- Assert.AreEqual(span[3].LevelOfDetailCount, 0);
-
- Assert.AreEqual(span[4].Index, 6);
- Assert.AreEqual(span[4].Filter, D2D1Filter.MinPointMagMipLinear);
- Assert.AreEqual(span[4].LevelOfDetailCount, 3);
- }
-
- [D2DInputCount(7)]
- [D2DInputSimple(0)]
- [D2DInputSimple(2)]
- [D2DInputComplex(1)]
- [D2DInputComplex(3)]
- [D2DInputComplex(5)]
- [D2DInputSimple(6)]
- [D2DInputDescription(0, D2D1Filter.MinPointMagLinearMipPoint)]
- [D2DInputDescription(1, D2D1Filter.Anisotropic)]
- [D2DInputDescription(2, D2D1Filter.MinLinearMagPointMinLinear, LevelOfDetailCount = 4)]
- [D2DInputDescription(5, D2D1Filter.MinMagPointMipLinear)]
- [D2DInputDescription(6, D2D1Filter.MinPointMagMipLinear, LevelOfDetailCount = 3)]
- [D2DGeneratedPixelShaderDescriptor]
- internal partial struct ShaderWithInputDescriptions : ID2D1PixelShader
- {
- public Float4 Execute()
+ [D2DInputCount(0)]
+ [D2DGeneratedPixelShaderDescriptor]
+ internal partial struct EmptyShader : ID2D1PixelShader
{
- return 0;
+ public Float4 Execute()
+ {
+ return 0;
+ }
}
- }
- [TestMethod]
- public void GetResourceTextureDescriptions_Empty()
- {
- Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
-
- Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
- Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
- }
-
- [TestMethod]
- public void GetResourceTextureDescriptions_Custom()
- {
- ReadOnlyMemory resourceTextureDescriptions = D2D1PixelShader.GetResourceTextureDescriptions();
-
- Assert.AreEqual(resourceTextureDescriptions.Length, 4);
-
- ReadOnlySpan span = resourceTextureDescriptions.Span;
-
- Assert.AreEqual(span[0].Index, 4);
- Assert.AreEqual(span[0].Dimensions, 1);
-
- Assert.AreEqual(span[1].Index, 5);
- Assert.AreEqual(span[1].Dimensions, 2);
-
- Assert.AreEqual(span[2].Index, 6);
- Assert.AreEqual(span[2].Dimensions, 3);
-
- Assert.AreEqual(span[3].Index, 7);
- Assert.AreEqual(span[3].Dimensions, 2);
- }
-
- [TestMethod]
- public void GetResourceTextureCount_IsCorrect()
- {
- Assert.AreEqual(0, D2D1PixelShader.GetResourceTextureCount());
- Assert.AreEqual(1, D2D1PixelShader.GetResourceTextureCount());
- Assert.AreEqual(4, D2D1PixelShader.GetResourceTextureCount());
- }
-
- [D2DInputCount(4)]
- [D2DInputSimple(0)]
- [D2DInputSimple(2)]
- [D2DInputComplex(1)]
- [D2DInputComplex(3)]
- [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
- [D2DGeneratedPixelShaderDescriptor]
- [AutoConstructor]
- internal partial struct ShaderWithoutResourceTextures : ID2D1PixelShader
- {
- public Float4 Execute()
+ [D2DInputCount(0)]
+ [D2DOutputBuffer(D2D1BufferPrecision.UInt16Normalized)]
+ [D2DGeneratedPixelShaderDescriptor]
+ internal partial struct OnlyBufferPrecisionShader : ID2D1PixelShader
{
- return 0;
+ public Float4 Execute()
+ {
+ return 0;
+ }
}
- }
- [D2DInputCount(0)]
- [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
- [D2DGeneratedPixelShaderDescriptor]
- [AutoConstructor]
- internal partial struct ShaderWithJustOneResourceTextures : ID2D1PixelShader
- {
- [D2DResourceTextureIndex(0)]
- D2D1ResourceTexture1D myTexture;
-
- public Float4 Execute()
+ [D2DInputCount(0)]
+ [D2DOutputBuffer(D2D1ChannelDepth.Four)]
+ [D2DGeneratedPixelShaderDescriptor]
+ internal partial struct OnlyChannelDepthShader : ID2D1PixelShader
{
- return this.myTexture.Sample(0);
+ public Float4 Execute()
+ {
+ return 0;
+ }
}
- }
- [D2DInputCount(4)]
- [D2DInputSimple(0)]
- [D2DInputSimple(2)]
- [D2DInputComplex(1)]
- [D2DInputComplex(3)]
- [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
- [D2DGeneratedPixelShaderDescriptor]
- [AutoConstructor]
- internal partial struct ShaderWithResourceTextures : ID2D1PixelShader
- {
- float number;
-
- [D2DResourceTextureIndex(4)]
- D2D1ResourceTexture1D myTexture1;
-
- [D2DResourceTextureIndex(5)]
- D2D1ResourceTexture2D myTexture2;
-
- [D2DResourceTextureIndex(6)]
- D2D1ResourceTexture3D myTexture3;
-
- [D2DResourceTextureIndex(7)]
- D2D1ResourceTexture2D myTexture4;
-
- public Float4 Execute()
+ [D2DInputCount(0)]
+ [D2DOutputBuffer(D2D1BufferPrecision.UInt8NormalizedSrgb, D2D1ChannelDepth.One)]
+ [D2DGeneratedPixelShaderDescriptor]
+ internal partial struct CustomBufferOutputShader : ID2D1PixelShader
{
- float4 pixel1 = this.myTexture1[0];
- float4 pixel2 = this.myTexture1.Sample(0.4f);
- float4 pixel3 = this.myTexture2[0, 1];
- float4 pixel4 = this.myTexture2.Sample(0.4f, 0.3f);
- float4 pixel5 = this.myTexture3[0, 1, 2];
- float4 pixel6 = this.myTexture3.Sample(0.4f, 0.5f, 0.6f);
- float number1 = this.myTexture4[0, 2];
- float number2 = this.myTexture4.Sample(0.4f, 0.6f);
-
- return 0;
+ public Float4 Execute()
+ {
+ return 0;
+ }
}
- }
- [TestMethod]
- public void GetBytecode_FromDynamicBytecode()
- {
- ReadOnlyMemory bytecode = D2D1PixelShader.LoadBytecode();
-
- Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? _));
- Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment segment));
- Assert.AreEqual(0, segment.Offset);
- Assert.IsTrue(segment.Count > 0);
- }
-
- [D2DInputCount(0)]
- [D2DGeneratedPixelShaderDescriptor]
- internal readonly partial struct ShaderWithoutEmbeddedBytecode : ID2D1PixelShader
- {
- public float4 Execute()
+ [TestMethod]
+ public void GetInputDescriptions_Empty()
{
- return 0;
+ Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
+
+ Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetInputDescriptions().Length, 0);
}
- }
- [TestMethod]
- public void GetBytecode_FromEmbeddedBytecode()
- {
- // Bytecode with no parameters
- ReadOnlyMemory bytecode = D2D1PixelShader.LoadBytecode();
-
- Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? manager));
- Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
-
- // Matching shader profile
- bytecode = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader40Level91);
-
- Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
-
- // Matching compile options
- bytecode = D2D1PixelShader.LoadBytecode(D2D1CompileOptions.Default | D2D1CompileOptions.EnableLinking);
-
- Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
-
- // Matching shader profile and compile options
- bytecode = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader40Level91, D2D1CompileOptions.Default | D2D1CompileOptions.EnableLinking);
-
- Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
-
- // Incorrect profile
- bytecode = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader50);
-
- Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? _));
- Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment segment));
- Assert.AreEqual(0, segment.Offset);
- Assert.IsTrue(segment.Count > 0);
-
- // Incorrect options
- bytecode = D2D1PixelShader.LoadBytecode(D2D1CompileOptions.Default | D2D1CompileOptions.EnableStrictness);
-
- Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? _));
- Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out segment));
- Assert.AreEqual(0, segment.Offset);
- Assert.IsTrue(segment.Count > 0);
- }
-
- [TestMethod]
- [ExpectedException(typeof(ArgumentException))]
- public void GetBytecode_FromEmbeddedBytecode_WithPackMatrixColumnMajor()
- {
- _ = D2D1PixelShader.LoadBytecode(D2D1CompileOptions.Default | D2D1CompileOptions.PackMatrixColumnMajor);
- }
-
- [TestMethod]
- [ExpectedException(typeof(ArgumentException))]
- public void GetBytecode_FromEmbeddedBytecode_WithTargetProfileAndPackMatrixColumnMajor()
- {
- _ = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader40Level91, D2D1CompileOptions.Default | D2D1CompileOptions.PackMatrixColumnMajor);
- }
-
- [D2DInputCount(3)]
- [D2DInputSimple(0)]
- [D2DInputSimple(1)]
- [D2DInputSimple(2)]
- [D2DShaderProfile(D2D1ShaderProfile.PixelShader40Level91)]
- [D2DGeneratedPixelShaderDescriptor]
- internal readonly partial struct ShaderWithEmbeddedBytecode : ID2D1PixelShader
- {
- public float4 Execute()
+ [TestMethod]
+ public void GetInputDescriptions_Custom()
{
- float4 dst = D2D.GetInput(0);
- float4 src = D2D.GetInput(1);
- float4 srcMask = D2D.GetInput(2);
- float4 result = ((1 - srcMask) * dst) + (srcMask * src);
+ ReadOnlyMemory inputDescriptions = D2D1PixelShader.GetInputDescriptions();
- return result;
+ Assert.AreEqual(inputDescriptions.Length, 5);
+
+ ReadOnlySpan span = inputDescriptions.Span;
+
+ Assert.AreEqual(span[0].Index, 0);
+ Assert.AreEqual(span[0].Filter, D2D1Filter.MinPointMagLinearMipPoint);
+ Assert.AreEqual(span[0].LevelOfDetailCount, 0);
+
+ Assert.AreEqual(span[1].Index, 1);
+ Assert.AreEqual(span[1].Filter, D2D1Filter.Anisotropic);
+ Assert.AreEqual(span[1].LevelOfDetailCount, 0);
+
+ Assert.AreEqual(span[2].Index, 2);
+ Assert.AreEqual(span[2].Filter, D2D1Filter.MinLinearMagPointMinLinear);
+ Assert.AreEqual(span[2].LevelOfDetailCount, 4);
+
+ Assert.AreEqual(span[3].Index, 5);
+ Assert.AreEqual(span[3].Filter, D2D1Filter.MinMagPointMipLinear);
+ Assert.AreEqual(span[3].LevelOfDetailCount, 0);
+
+ Assert.AreEqual(span[4].Index, 6);
+ Assert.AreEqual(span[4].Filter, D2D1Filter.MinPointMagMipLinear);
+ Assert.AreEqual(span[4].LevelOfDetailCount, 3);
}
- }
- [TestMethod]
- public void GetBytecode_FromEmbeddedBytecode_WithCompileOptions()
- {
- // Bytecode with no parameters
- ReadOnlyMemory bytecode = D2D1PixelShader.LoadBytecode();
-
- Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? manager));
- Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
-
- // Bytecode with all output parameters
- ReadOnlyMemory bytecode2 = D2D1PixelShader.LoadBytecode(out D2D1ShaderProfile shaderProfile, out D2D1CompileOptions compileOptions);
-
- // The bytecode is the same
- Assert.IsTrue(bytecode.Span == bytecode2.Span);
- Assert.AreEqual(shaderProfile, D2D1ShaderProfile.PixelShader40Level91);
- Assert.AreEqual(compileOptions, D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PackMatrixRowMajor);
-
- // Matching compile options
- bytecode = D2D1PixelShader.LoadBytecode(D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2);
-
- Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
-
- // Matching shader profile and compile options
- bytecode = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader40Level91, D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2);
-
- Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
- }
-
- [D2DInputCount(3)]
- [D2DInputSimple(0)]
- [D2DInputSimple(1)]
- [D2DInputSimple(2)]
- [D2DShaderProfile(D2D1ShaderProfile.PixelShader40Level91)]
- [D2DCompileOptions(D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2)]
- [D2DGeneratedPixelShaderDescriptor]
- internal readonly partial struct ShaderWithEmbeddedBytecodeAndCompileOptions : ID2D1PixelShader
- {
- public float4 Execute()
+ [D2DInputCount(7)]
+ [D2DInputSimple(0)]
+ [D2DInputSimple(2)]
+ [D2DInputComplex(1)]
+ [D2DInputComplex(3)]
+ [D2DInputComplex(5)]
+ [D2DInputSimple(6)]
+ [D2DInputDescription(0, D2D1Filter.MinPointMagLinearMipPoint)]
+ [D2DInputDescription(1, D2D1Filter.Anisotropic)]
+ [D2DInputDescription(2, D2D1Filter.MinLinearMagPointMinLinear, LevelOfDetailCount = 4)]
+ [D2DInputDescription(5, D2D1Filter.MinMagPointMipLinear)]
+ [D2DInputDescription(6, D2D1Filter.MinPointMagMipLinear, LevelOfDetailCount = 3)]
+ [D2DGeneratedPixelShaderDescriptor]
+ internal partial struct ShaderWithInputDescriptions : ID2D1PixelShader
{
- float4 dst = D2D.GetInput(0);
- float4 src = D2D.GetInput(1);
- float4 srcMask = D2D.GetInput(2);
- float4 result = ((1 - srcMask) * dst) + (srcMask * src);
-
- return result;
+ public Float4 Execute()
+ {
+ return 0;
+ }
}
- }
- [TestMethod]
- public void LoadBytecode_VerifyEffectiveValues_ExplicitShaderProfile()
- {
- _ = D2D1PixelShader.LoadBytecode(out D2D1ShaderProfile shaderProfile, out D2D1CompileOptions compileOptions);
-
- Assert.AreEqual(shaderProfile, D2D1ShaderProfile.PixelShader40Level91);
- Assert.AreEqual(compileOptions, D2D1CompileOptions.Default | D2D1CompileOptions.EnableLinking);
-
- _ = D2D1PixelShader.LoadBytecode(out shaderProfile, out compileOptions);
-
- // This shader has a complex input, so it can't support shader linking
- Assert.AreEqual(shaderProfile, D2D1ShaderProfile.PixelShader40Level91);
- Assert.AreEqual(compileOptions, D2D1CompileOptions.Default);
- }
-
- [D2DInputCount(1)]
- [D2DInputSimple(0)]
- [D2DShaderProfile(D2D1ShaderProfile.PixelShader40Level91)]
- [D2DGeneratedPixelShaderDescriptor]
- internal readonly partial struct SimpleShaderWithExplicitShaderProfileAndNoCompileOptions : ID2D1PixelShader
- {
- public float4 Execute()
+ [TestMethod]
+ public void GetResourceTextureDescriptions_Empty()
{
- return D2D.GetInput(0);
- }
- }
+ Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
- [D2DInputCount(1)]
- [D2DInputComplex(0)]
- [D2DShaderProfile(D2D1ShaderProfile.PixelShader40Level91)]
- [D2DGeneratedPixelShaderDescriptor]
- internal readonly partial struct ComplexShaderWithExplicitShaderProfileAndNoCompileOptions : ID2D1PixelShader
- {
- public float4 Execute()
+ Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
+ Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions().Length, 0);
+ }
+
+ [TestMethod]
+ public void GetResourceTextureDescriptions_Custom()
{
- return D2D.GetInput(0);
+ ReadOnlyMemory resourceTextureDescriptions = D2D1PixelShader.GetResourceTextureDescriptions();
+
+ Assert.AreEqual(resourceTextureDescriptions.Length, 4);
+
+ ReadOnlySpan span = resourceTextureDescriptions.Span;
+
+ Assert.AreEqual(span[0].Index, 4);
+ Assert.AreEqual(span[0].Dimensions, 1);
+
+ Assert.AreEqual(span[1].Index, 5);
+ Assert.AreEqual(span[1].Dimensions, 2);
+
+ Assert.AreEqual(span[2].Index, 6);
+ Assert.AreEqual(span[2].Dimensions, 3);
+
+ Assert.AreEqual(span[3].Index, 7);
+ Assert.AreEqual(span[3].Dimensions, 2);
}
- }
- [TestMethod]
- public void LoadBytecode_VerifyEffectiveValues_ExplicitCompileOptions()
- {
- _ = D2D1PixelShader.LoadBytecode(out D2D1ShaderProfile shaderProfile, out D2D1CompileOptions compileOptions);
-
- // PS5.0 is the default, when no value is specified
- Assert.AreEqual(shaderProfile, D2D1ShaderProfile.PixelShader50);
- Assert.AreEqual(compileOptions, D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.PackMatrixRowMajor);
-
- _ = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader40, out compileOptions);
-
- Assert.AreEqual(compileOptions, D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.PackMatrixRowMajor);
- }
-
- [D2DInputCount(1)]
- [D2DInputSimple(0)]
- [D2DCompileOptions(D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.IeeeStrictness)]
- [D2DGeneratedPixelShaderDescriptor]
- internal readonly partial struct ShaderWithExplicitCompileOptionsAndNoShaderProfile : ID2D1PixelShader
- {
- public float4 Execute()
+ [TestMethod]
+ public void GetResourceTextureCount_IsCorrect()
{
- return D2D.GetInput(0);
+ Assert.AreEqual(0, D2D1PixelShader.GetResourceTextureCount());
+ Assert.AreEqual(1, D2D1PixelShader.GetResourceTextureCount());
+ Assert.AreEqual(4, D2D1PixelShader.GetResourceTextureCount());
}
- }
- [TestMethod]
- public void GetConstantBufferSize_Empty()
- {
- int size = D2D1PixelShader.GetConstantBufferSize();
-
- Assert.AreEqual(size, 0);
-
- // Repeated calls always return the same result
- size = D2D1PixelShader.GetConstantBufferSize