Move constant buffer info gathering logic too
このコミットが含まれているのは:
1 親
545f4b6ca4
コミット
4c5bd8a9da
7ファイル変更
+273
-254
検索条件に一致するファイルはありません
+361
@@ -0,0 +1,361 @@
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ConstantBufferSyntaxProcessor
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of generator to include in the generated code.
|
||||
/// </summary>
|
||||
private static string? generatorName;
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to generate additional types, if needed.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInfo">The type of model providing the necessary info.</typeparam>
|
||||
/// <param name="generatorName">The name of generator to include in the generated code.</param>
|
||||
/// <param name="info">The input <typeparamref name="TInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
|
||||
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
|
||||
public static void RegisterAdditionalTypesSyntax<TInfo>(
|
||||
string generatorName,
|
||||
TInfo info,
|
||||
ImmutableArrayBuilder<IndentedTextWriter.Callback<TInfo>> callbacks,
|
||||
ImmutableHashSetBuilder<string> usingDirectives)
|
||||
where TInfo : class, IConstantBufferInfo
|
||||
{
|
||||
// Store the generator name for later. This avoids needing closures for each callback below.
|
||||
// It is assumed that all calls to this method will have the same argument in each assembly.
|
||||
ConstantBufferSyntaxProcessor.generatorName = generatorName;
|
||||
|
||||
// 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(TInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName();
|
||||
|
||||
writer.WriteLine($"""/// <summary>""");
|
||||
writer.WriteLine($"""/// A type representing the constant buffer native layout for <see cref="{fullyQualifiedTypeName}"/>.""");
|
||||
writer.WriteLine($"""/// </summary>""");
|
||||
writer.WriteGeneratedAttributes(ConstantBufferSyntaxProcessor.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(TInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName();
|
||||
|
||||
writer.WriteLine($"""/// <summary>""");
|
||||
writer.WriteLine($"""/// A type containing marshalling logic for shaders of type <see cref="{fullyQualifiedTypeName}"/>.""");
|
||||
writer.WriteLine($"""/// </summary>""");
|
||||
writer.WriteGeneratedAttributes(ConstantBufferSyntaxProcessor.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($"""/// <summary>""");
|
||||
writer.WriteLine($"""/// Marshals native constant buffer data to managed <see cref="{fullyQualifiedTypeName}"/> instances.""");
|
||||
writer.WriteLine($"""/// </summary>""");
|
||||
writer.WriteLine($"""/// <param name="buffer">The input native constant buffer.</param>""");
|
||||
writer.WriteLine($"""/// <returns>The marshalled <see cref="{fullyQualifiedTypeName}"/> instance.</returns>""");
|
||||
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($"""/// <summary>""");
|
||||
writer.WriteLine($"""/// Marshals managed <see cref="{fullyQualifiedTypeName}"/> instances to native constant buffer data.""");
|
||||
writer.WriteLine($"""/// </summary>""");
|
||||
writer.WriteLine($"""/// <param name="buffer">The input native constant buffer.</param>""");
|
||||
writer.WriteLine($"""/// <returns>The marshalled <see cref="{fullyQualifiedTypeName}"/> instance.</returns>""");
|
||||
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($"""
|
||||
/// <inheritdoc cref="{containingTypeName}.{pathPart.Name}"/>
|
||||
/// <param name="shader">The input <see cref="{containingTypeName}"/> value.</param>
|
||||
/// <returns>A mutable reference to <see cref="{containingTypeName}.{pathPart.Name}"/>.</returns>
|
||||
[UnsafeAccessor(UnsafeAccessorKind.Field)]
|
||||
private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value);
|
||||
""", isMultiline: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine($"""
|
||||
/// <summary>Gets a reference to the unspeakable field "{pathPart.Name}" of type <see cref="{containingTypeName}"/>.</summary>
|
||||
/// <param name="shader">The input <see cref="{containingTypeName}"/> value.</param>
|
||||
/// <returns>A mutable reference to the unspeakable field "{pathPart.Name}".</returns>
|
||||
[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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Extensions.IndentedTextWriterExtensions"/>
|
||||
file static class IndentedTextWriterExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the XML summary for a given field.
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
/// <param name="fieldInfo">The input field to write the XML summary for.</param>
|
||||
/// <param name="fullyQualifiedTypeName">The fully qualified type name of the containing type.</param>
|
||||
public static void WriteFieldXmlSummary(this IndentedTextWriter writer, FieldInfo fieldInfo, string fullyQualifiedTypeName)
|
||||
{
|
||||
if (fieldInfo.FieldPath[0].UnspeakableName is null)
|
||||
{
|
||||
writer.WriteLine($"""/// <inheritdoc cref="{fullyQualifiedTypeName}.{fieldInfo.FieldPath[0].Name}"/>""");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine($"""/// <summary>The unspeakable field "{fieldInfo.FieldPath[0].Name}" of <see cref="{fullyQualifiedTypeName}"/>.</summary>""");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the XML remarks for a given field, if needed.
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
/// <param name="fieldInfo">The input field to write the XML remarks for, if needed.</param>
|
||||
/// <param name="row">The row for the field, if this is a matrix type.</param>
|
||||
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($"""/// <remarks>Serialized field mapping to""");
|
||||
writer.WriteIf(row is not null, $""" row {row} of""");
|
||||
writer.WriteLine($""" <see cref="{nested.TypeName}.{leaf.Name}"/>.</remarks>""");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.Write($"""/// <remarks>Serialized field mapping to""");
|
||||
writer.WriteIf(row is not null, $""" row {row} of""");
|
||||
writer.WriteLine($""" the unspeakable field "{leaf.Name}" of <see cref="{nested.TypeName}"/>.</remarks>""");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an expression to access a given field.
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
/// <param name="fieldInfo">The input field to write the expression for.</param>
|
||||
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}()");
|
||||
}
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.RegularExpressions;
|
||||
using ComputeSharp.Core.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
|
||||
/// <summary>
|
||||
/// A processor responsible for extracting info and writing syntax for the constant buffer syntax for shader types.
|
||||
/// </summary>
|
||||
internal static partial class ConstantBufferSyntaxProcessor
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see cref="Regex"/> to extract the parameter name of a primary constructor capture field.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Temporary workaround until <see href="https://github.com/dotnet/roslyn/issues/70208"/> is available.
|
||||
/// </remarks>
|
||||
private static readonly Regex PrimaryConstructorNameRegex = new("^<([^>]+)>P$", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// Explores a given type hierarchy and generates statements to load fields.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
|
||||
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
|
||||
/// <param name="fields">The sequence of <see cref="FieldInfo"/> instances for all captured values.</param>
|
||||
public static void GetInfo(
|
||||
Compilation compilation,
|
||||
ITypeSymbol structDeclarationSymbol,
|
||||
out int constantBufferSizeInBytes,
|
||||
out ImmutableArray<FieldInfo> fields)
|
||||
{
|
||||
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
|
||||
static void GetInfo(
|
||||
Compilation compilation,
|
||||
ITypeSymbol currentTypeSymbol,
|
||||
ImmutableArray<FieldPathPart> fieldPath,
|
||||
ref int rawDataOffset,
|
||||
ImmutableArrayBuilder<FieldInfo> fields)
|
||||
{
|
||||
bool isFirstField = true;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// 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 = AlignmentHelper.Pad(rawDataOffset, 16);
|
||||
|
||||
isFirstField = false;
|
||||
}
|
||||
|
||||
if (HlslKnownTypes.IsKnownHlslType(typeName))
|
||||
{
|
||||
ImmutableArray<FieldPathPart> 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
|
||||
GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(fieldPathPart), ref rawDataOffset, fields);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Setup the resource and byte offsets for tracking
|
||||
int rawDataOffset = 0;
|
||||
|
||||
using ImmutableArrayBuilder<FieldInfo> fieldBuilder = new();
|
||||
|
||||
// Traverse all shader fields and gather info, and update the tracking offsets
|
||||
GetInfo(
|
||||
compilation,
|
||||
structDeclarationSymbol,
|
||||
ImmutableArray<FieldPathPart>.Empty,
|
||||
ref rawDataOffset,
|
||||
fieldBuilder);
|
||||
|
||||
constantBufferSizeInBytes = rawDataOffset;
|
||||
fields = fieldBuilder.ToImmutable();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the field name and the accessor name for a given field.
|
||||
/// </summary>
|
||||
/// <param name="fieldSymbol">The field symbol to analyze.</param>
|
||||
/// <param name="referencedName">The name of the field that's referenced in code by users.</param>
|
||||
/// <param name="unspeakableName">The real name of the field that should be accessed, when different.</param>
|
||||
/// <returns>Whether the field is supported and the necessary info could be retrieved.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix).
|
||||
/// </summary>
|
||||
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
|
||||
/// <param name="typeName">The type name currently being read.</param>
|
||||
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
|
||||
private static FieldInfo GetHlslKnownTypeFieldInfo(
|
||||
ImmutableArray<FieldPathPart> fieldPath,
|
||||
string typeName,
|
||||
ref int rawDataOffset)
|
||||
{
|
||||
// For scalar, vector and linear matrix types, serialize the value normally.
|
||||
// Only the initial alignment needs to be considered, while data is packed.
|
||||
(int fieldSize, int fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
|
||||
|
||||
// Check if the current type is a matrix type with more than one row. In this
|
||||
// case, each row is aligned as if it was a separate array, so the start of
|
||||
// each row needs to be at a multiple of 16 bytes (a float4 register).
|
||||
if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
|
||||
{
|
||||
using ImmutableArrayBuilder<int> builder = new();
|
||||
|
||||
for (int j = 0; j < rows; j++)
|
||||
{
|
||||
int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
|
||||
|
||||
builder.Add(startingRawDataOffset);
|
||||
|
||||
rawDataOffset = startingRawDataOffset + (fieldPack * columns);
|
||||
}
|
||||
|
||||
return new FieldInfo.NonLinearMatrix(
|
||||
fieldPath,
|
||||
typeName,
|
||||
elementName!,
|
||||
rows,
|
||||
columns,
|
||||
builder.ToImmutable());
|
||||
}
|
||||
else
|
||||
{
|
||||
// Calculate the right offset with 16-bytes padding (HLSL constant buffer).
|
||||
// Since we're in a constant buffer, we need to both pad the starting offset
|
||||
// to be aligned to the packing size of the type, and also to align the initial
|
||||
// offset to ensure that values do not cross 16 bytes boundaries either.
|
||||
int startingRawDataOffset = AlignmentHelper.AlignToBoundary(
|
||||
AlignmentHelper.Pad(rawDataOffset, fieldPack),
|
||||
fieldSize,
|
||||
16);
|
||||
|
||||
rawDataOffset = startingRawDataOffset + fieldSize;
|
||||
|
||||
return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset);
|
||||
}
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする