Merge pull request #650 from Sergio0694/dev/primary-constructors-net8

Support primary constructor parameters for D2D shaders
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-11-20 21:10:36 +01:00
コミット 832e148b67
26ファイル変更
+1840 -1330

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

@@ -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;
/// <inheritdoc/>
partial class D2DPixelShaderDescriptorGenerator
{
/// <inheritdoc/>
partial class ConstantBuffer
{
/// <summary>
/// Writes the <c>LoadConstantBuffer</c> method.
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteLoadConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
writer.WriteLine($"static unsafe void global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.LoadConstantBuffer<TLoader>(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<byte>(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));");
}
}
}
/// <summary>
/// Writes the <c>CreateFromConstantBuffer</c> method.
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteCreateFromConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
writer.WriteLine("/// <inheritdoc/>");
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<byte> 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<global::ComputeSharp.D2D1.Generated.ConstantBuffer>(data);");
writer.WriteLine();
writer.WriteLine("return global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.ToManaged(in buffer);");
}
}
/// <summary>
/// Registers a callback to generate additional types, if needed.
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> 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(
D2D1ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> 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($"""/// <summary>""");
writer.WriteLine($"""/// A type representing the constant buffer native layout for <see cref="{fullyQualifiedTypeName}"/>.""");
writer.WriteLine($"""/// </summary>""");
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($"""/// <summary>""");
writer.WriteLine($"""/// A type containing marshalling logic for shaders of type <see cref="{fullyQualifiedTypeName}"/>.""");
writer.WriteLine($"""/// </summary>""");
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($"""/// <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="SourceGeneration.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}()");
}
}
}
@@ -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
{
/// <summary>
/// A helper with all logic to generate the <c>LoadConstantBuffer</c> method.
/// A helper with all logic to generate the <c>ConstantBuffer</c> methods and additional types.
/// </summary>
private static partial class LoadConstantBuffer
private static partial class ConstantBuffer
{
/// <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>
@@ -28,71 +35,87 @@ partial class D2DPixelShaderDescriptorGenerator
/// <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>
/// <returns>The sequence of <see cref="FieldInfo"/> instances for all captured resources and values.</returns>
public static ImmutableArray<FieldInfo> GetInfo(
/// <param name="fields">The sequence of <see cref="FieldInfo"/> instances for all captured values.</param>
public static void GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
Compilation compilation,
ITypeSymbol structDeclarationSymbol,
out int constantBufferSizeInBytes)
out int constantBufferSizeInBytes,
out ImmutableArray<FieldInfo> fields)
{
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
static IEnumerable<FieldInfo> GetCapturedFieldInfos(
static void GetInfo(
Compilation compilation,
ITypeSymbol currentTypeSymbol,
ImmutableArray<string> fieldPath,
StrongBox<int> rawDataOffset)
ImmutableArray<FieldPathPart> fieldPath,
ref int rawDataOffset,
ImmutableArrayBuilder<FieldInfo> fields)
{
bool isFirstField = true;
foreach (
IFieldSymbol fieldSymbol in
from fieldSymbol in currentTypeSymbol.GetMembers().OfType<IFieldSymbol>()
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<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
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<int> rawDataOffsetAsBox = new();
int rawDataOffset = 0;
// Traverse all shader fields and gather info, and update the tracking offsets
ImmutableArray<FieldInfo> fieldInfos = GetCapturedFieldInfos(
compilation,
structDeclarationSymbol,
ImmutableArray<string>.Empty,
rawDataOffsetAsBox).ToImmutableArray();
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 = 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;
/// <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>
@@ -114,7 +172,7 @@ partial class D2DPixelShaderDescriptorGenerator
/// <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<string> fieldPath,
ImmutableArray<FieldPathPart> fieldPath,
string typeName,
ref int rawDataOffset)
{
@@ -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;
/// <inheritdoc/>
partial class D2DPixelShaderDescriptorGenerator
{
/// <inheritdoc/>
partial class CreateFromConstantBuffer
{
/// <summary>
/// Writes the <c>CreateFromConstantBuffer</c> method.
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
writer.WriteLine("/// <inheritdoc/>");
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<byte> 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<byte, global::ComputeSharp.D2D1.Generated.ConstantBuffer>(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<<PRIMITIVE_TYPE_NAME>, <ROW_TYPE_NAME>>(ref (*&shader.<FIELD_PATH>).M11) = buffer.<CONSTANT_BUFFER_ROW_0_PATH>;
// Unsafe.As<<PRIMITIVE_TYPE_NAME>, <ROW_TYPE_NAME>>(ref (*&shader.<FIELD_PATH>).M21) = buffer.<CONSTANT_BUFFER_ROW_1_PATH>;
// ...
// Unsafe.As<<PRIMITIVE_TYPE_NAME>, <ROW_TYPE_NAME>>(ref (*&shader.<FIELD_PATH>).MN1) = buffer.<CONSTANT_BUFFER_ROW_N_PATH>;
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;");
}
}
}
}
@@ -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)
+27 -13
ファイルの表示
@@ -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<IFieldSymbol>())
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<IFieldSymbol>())
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(
@@ -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");
}
/// <summary>
@@ -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)
@@ -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;
/// <inheritdoc/>
partial class D2DPixelShaderDescriptorGenerator
{
/// <inheritdoc/>
partial class LoadConstantBuffer
{
/// <summary>
/// Writes the <c>LoadConstantBuffer</c> method.
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
writer.WriteLine($"static unsafe void global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.LoadConstantBuffer<TLoader>(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.<CONSTANT_BUFFER_ROW_0_PATH> = Unsafe.As<<PRIMITIVE_TYPE_NAME>, <ROW_TYPE_NAME>>(ref Unsafe.AsRef(in shader.<FIELD_PATH>).M11);
// buffer.<CONSTANT_BUFFER_ROW_1_PATH> = Unsafe.As<<PRIMITIVE_TYPE_NAME>, <ROW_TYPE_NAME>>(ref Unsafe.AsRef(in shader.<FIELD_PATH>).M21);
// ...
// buffer.<CONSTANT_BUFFER_ROW_N_PATH> = Unsafe.As<<PRIMITIVE_TYPE_NAME>, <ROW_TYPE_NAME>>(ref Unsafe.AsRef(in shader.<FIELD_PATH>).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<byte>(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));");
}
}
}
/// <summary>
/// Registers a callback to generate an additional type, if needed.
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> 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 RegisterAdditionalTypeSyntax(
D2D1ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> 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($$"""/// <summary>""");
writer.WriteLine($$"""/// A type representing the constant buffer native layout for <see cref="{{fullyQualifiedTypeName}}"/>.""");
writer.WriteLine($$"""/// </summary>""");
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($$"""/// <inheritdoc cref="{{fullyQualifiedTypeName}}.{{string.Join(".", primitive.FieldPath)}}"/>""");
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($$"""/// <inheritdoc cref="{{fullyQualifiedTypeName}}.{{string.Join(".", primitive.FieldPath)}}"/>""");
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($$"""/// <summary>Row {j} of <see cref="{{fullyQualifiedTypeName}}.{{string.Join(".", matrix.FieldPath)}}"/>.</summary>""");
writer.WriteLine($$"""[FieldOffset({{matrix.Offsets[j]}})]""");
writer.WriteLine($$"""public {{rowTypeName}} {{fieldNamePrefix}}_{{j}};""");
}
break;
}
});
}
}
callbacks.Add(Callback);
}
}
}
@@ -47,7 +47,7 @@ partial class D2DPixelShaderDescriptorGenerator
return;
}
usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
_ = usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
}
/// <summary>
+7 -6
ファイルの表示
@@ -82,12 +82,13 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene
using ImmutableArrayBuilder<DiagnosticInfo> diagnostics = new();
// LoadDispatchData() info
ImmutableArray<FieldInfo> fieldInfos = LoadConstantBuffer.GetInfo(
// Constant buffer info
ConstantBuffer.GetInfo(
diagnostics,
context.SemanticModel.Compilation,
typeSymbol,
out int constantBufferSizeInBytes);
out int constantBufferSizeInBytes,
out ImmutableArray<FieldInfo> 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<IndentedTextWriter.Callback<D2D1ShaderInfo>> additionalTypes = new();
using ImmutableHashSetBuilder<string> 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);
+26 -3
ファイルの表示
@@ -7,7 +7,7 @@ namespace ComputeSharp.SourceGeneration.Models;
/// </summary>
/// <param name="FieldPath">The path of the field with respect to the shader instance.</param>
/// <param name="TypeName">The full metadata name for the primitive type.</param>
internal abstract record FieldInfo(EquatableArray<string> FieldPath, string TypeName)
internal abstract record FieldInfo(EquatableArray<FieldPathPart> FieldPath, string TypeName)
{
/// <summary>
/// A captured primitive value (either a scalar, a vector, or a linear matrix).
@@ -15,7 +15,7 @@ internal abstract record FieldInfo(EquatableArray<string> FieldPath, string Type
/// <param name="FieldPath"><inheritdoc cref="FieldInfo(EquatableArray{string}, string)" path="/param[@name='FieldPath']/node()"/></param>
/// <param name="TypeName"><inheritdoc cref="FieldInfo(EquatableArray{string}, string)" path="/param[@name='TypeName']/node()"/></param>
/// <param name="Offset">The byte offset of the value within the root signature.</param>
public sealed record Primitive(EquatableArray<string> FieldPath, string TypeName, int Offset) : FieldInfo(FieldPath, TypeName);
public sealed record Primitive(EquatableArray<FieldPathPart> FieldPath, string TypeName, int Offset) : FieldInfo(FieldPath, TypeName);
/// <summary>
/// A captured non linear matrix value.
@@ -27,10 +27,33 @@ internal abstract record FieldInfo(EquatableArray<string> FieldPath, string Type
/// <param name="Columns">The number of columns in the matrix.</param>
/// <param name="Offsets">The sequence of byte offsets for each row within the root signature.</param>
public sealed record NonLinearMatrix(
EquatableArray<string> FieldPath,
EquatableArray<FieldPathPart> FieldPath,
string TypeName,
string ElementName,
int Rows,
int Columns,
EquatableArray<int> Offsets) : FieldInfo(FieldPath, TypeName);
}
/// <summary>
/// A model for a part of a field path, ie. the name of the immediate parent field, and whether it's accessible.
/// </summary>
/// <param name="Name">The name of the immediate parent field to access (or self).</param>
/// <param name="UnspeakableName">The unspeakable name of the field, if present.</param>
internal abstract record FieldPathPart(string Name, string? UnspeakableName)
{
/// <summary>
/// A model for a leaf part of a field path.
/// </summary>
/// <param name="Name"><inheritdoc cref="FieldPathPart(string, string?)" path="/param[@name='Name']/node()"/></param>
/// <param name="UnspeakableName"><inheritdoc cref="FieldPathPart(string, string?)" path="/param[@name='UnspeakableName']/node()"/></param>
public sealed record Leaf(string Name, string? UnspeakableName) : FieldPathPart(Name, UnspeakableName);
/// <summary>
/// A model for a nested field part path (ie. going through a nested struct type).
/// </summary>
/// <param name="Name"><inheritdoc cref="FieldPathPart(string, string?)" path="/param[@name='Name']/node()"/></param>
/// <param name="UnspeakableName"><inheritdoc cref="FieldPathPart(string, string?)" path="/param[@name='UnspeakableName']/node()"/></param>
/// <param name="TypeName">The fully qualified type name of the containing type.</param>
public sealed record Nested(string Name, string? UnspeakableName, string TypeName) : FieldPathPart(Name, UnspeakableName);
}
+5 -2
ファイルの表示
@@ -49,10 +49,13 @@ internal static class ISymbolExtensions
/// Gets the fully qualified name for a given symbol.
/// </summary>
/// <param name="symbol">The input <see cref="ISymbol"/> instance.</param>
/// <param name="includeGlobal">Whether to include the <c>global::</c> prefix.</param>
/// <returns>The fully qualified name for <paramref name="symbol"/>.</returns>
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);
}
/// <summary>
-45
ファイルの表示
@@ -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());
}
/// <summary>
/// Writes a new line into the target writer depending on an input condition.
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="condition">The condition to use to decide whether or not to write a new line.</param>
public static void WriteLineIf(this IndentedTextWriter writer, bool condition)
{
if (condition)
{
writer.WriteLine();
}
}
/// <summary>
/// Writes a new line into the target writer depending on an input condition.
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="content">The content to write.</param>
/// <param name="condition">The condition to use to decide whether or not to write a new line.</param>
public static void WriteLineIf(this IndentedTextWriter writer, string content, bool condition)
{
if (condition)
{
writer.WriteLine(content);
}
}
/// <summary>
/// Writes a new line into the target writer depending on an input condition.
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="handler">The interpolated string handler with content to write.</param>
/// <param name="condition">The condition to use to decide whether or not to write a new line.</param>
public static void WriteLineIf(
this IndentedTextWriter writer,
[InterpolatedStringHandlerArgument(nameof(writer))] ref IndentedTextWriter.WriteInterpolatedStringHandler handler,
bool condition)
{
if (condition)
{
writer.WriteLine(ref handler);
}
}
/// <summary>
/// Writes a series of members separated by one line between each of them.
/// </summary>
+2 -2
ファイルの表示
@@ -44,9 +44,9 @@ internal struct ImmutableHashSetBuilder<T> : IDisposable
}
/// <inheritdoc cref="ImmutableArray{T}.Builder.Add(T)"/>
public readonly void Add(T item)
public readonly bool Add(T item)
{
_ = this.set!.Add(item);
return this.set!.Add(item);
}
/// <summary>
+164 -1
ファイルの表示
@@ -177,11 +177,55 @@ internal sealed class IndentedTextWriter : IDisposable
_ = this;
}
/// <summary>
/// Writes content to the underlying buffer depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void WriteIf(bool condition, string content, bool isMultiline = false)
{
if (condition)
{
Write(content.AsSpan(), isMultiline);
}
}
/// <summary>
/// Writes content to the underlying buffer depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void WriteIf(bool condition, ReadOnlySpan<char> content, bool isMultiline = false)
{
if (condition)
{
Write(content, isMultiline);
}
}
/// <summary>
/// Writes content to the underlying buffer depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="handler">The interpolated string handler with content to write.</param>
public void WriteIf(bool condition, [InterpolatedStringHandlerArgument("", nameof(condition))] ref WriteIfInterpolatedStringHandler handler)
{
_ = this;
}
/// <summary>
/// Writes a line to the underlying buffer.
/// </summary>
public void WriteLine()
/// <param name="skipIfPresent">Indicates whether to skip adding the line if there already is one.</param>
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();
}
/// <summary>
/// Writes a line to the underlying buffer depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="skipIfPresent">Indicates whether to skip adding the line if there already is one.</param>
public void WriteLineIf(bool condition, bool skipIfPresent = false)
{
if (condition)
{
WriteLine(skipIfPresent);
}
}
/// <summary>
/// Writes content to the underlying buffer and appends a trailing new line depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void WriteLineIf(bool condition, string content, bool isMultiline = false)
{
if (condition)
{
WriteLine(content.AsSpan(), isMultiline);
}
}
/// <summary>
/// Writes content to the underlying buffer and appends a trailing new line depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void WriteLineIf(bool condition, ReadOnlySpan<char> content, bool isMultiline = false)
{
if (condition)
{
Write(content, isMultiline);
WriteLine();
}
}
/// <summary>
/// Writes content to the underlying buffer and appends a trailing new line depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="handler">The interpolated string handler with content to write.</param>
public void WriteLineIf(bool condition, [InterpolatedStringHandlerArgument("", nameof(condition))] ref WriteIfInterpolatedStringHandler handler)
{
if (condition)
{
WriteLine();
}
}
/// <inheritdoc/>
public override string ToString()
{
@@ -351,4 +450,68 @@ internal sealed class IndentedTextWriter : IDisposable
}
}
}
/// <summary>
/// Provides a handler used by the language compiler to conditionally append interpolated strings into <see cref="IndentedTextWriter"/> instances.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[InterpolatedStringHandler]
public readonly ref struct WriteIfInterpolatedStringHandler
{
/// <summary>The associated <see cref="WriteInterpolatedStringHandler"/> to use.</summary>
private readonly WriteInterpolatedStringHandler handler;
/// <summary>Creates a handler used to append an interpolated string into a <see cref="StringBuilder"/>.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
/// <param name="writer">The associated <see cref="IndentedTextWriter"/> to which to append.</param>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="shouldAppend">A value indicating whether formatting should proceed.</param>
/// <remarks>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.</remarks>
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;
}
}
/// <inheritdoc cref="WriteInterpolatedStringHandler.AppendLiteral(string)"/>
public void AppendLiteral(string value)
{
this.handler.AppendLiteral(value);
}
/// <inheritdoc cref="WriteInterpolatedStringHandler.AppendFormatted(string?)"/>
public void AppendFormatted(string? value)
{
this.handler.AppendFormatted(value);
}
/// <inheritdoc cref="WriteInterpolatedStringHandler.AppendFormatted(ReadOnlySpan{char})"/>
public void AppendFormatted(ReadOnlySpan<char> value)
{
this.handler.AppendFormatted(value);
}
/// <inheritdoc cref="WriteInterpolatedStringHandler.AppendFormatted{T}(T)"/>
public void AppendFormatted<T>(T value)
{
this.handler.AppendFormatted(value);
}
/// <inheritdoc cref="WriteInterpolatedStringHandler.AppendFormatted{T}(T, string?)"/>
public void AppendFormatted<T>(T value, string? format)
{
this.handler.AppendFormatted(value, format);
}
}
}
+9 -2
ファイルの表示
@@ -118,9 +118,16 @@ internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName,
using ImmutableArrayBuilder<char> 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());
@@ -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<byte, uint>(ref span[0]) = (uint)x;");
writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref span[4]) = (uint)y;");
writer.WriteLineIf("global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref span[8]) = (uint)z;", !info.IsPixelShaderLike);
writer.WriteLineIf(!info.IsPixelShaderLike, "global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(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<byte, global::ComputeSharp.Bool>(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<byte, global::{primitive.TypeName}>(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 <FIELD_PATH>));
writer.WriteLine(
$"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As<global::{matrix.TypeName}, {rowTypeName}>(" +
$"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):
@@ -43,7 +43,7 @@ partial class ComputeShaderDescriptorGenerator
static void GetInfo(
Compilation compilation,
ITypeSymbol currentTypeSymbol,
ImmutableArray<string> fieldPath,
ImmutableArray<FieldPathPart> fieldPath,
ref int resourceOffset,
ref int rawDataOffset,
ImmutableArrayBuilder<FieldInfo> 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<string>.Empty,
ImmutableArray<FieldPathPart>.Empty,
ref resourceOffset,
ref rawDataOffset,
fieldBuilder,
@@ -144,7 +145,7 @@ partial class ComputeShaderDescriptorGenerator
/// <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<string> fieldPath,
ImmutableArray<FieldPathPart> fieldPath,
string typeName,
ref int rawDataOffset)
{
@@ -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)
@@ -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)
+5 -8
ファイルの表示
@@ -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);
}
/// <summary>
@@ -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);
}
/// <summary>
@@ -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);
}
/// <summary>
@@ -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));
}
/// <summary>
@@ -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);
}
/// <summary>
+6 -8
ファイルの表示
@@ -121,11 +121,10 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
/// </summary>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
internal readonly unsafe void Run<T>(int x, ref T shader)
internal readonly unsafe void Run<T>(int x, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor<T>
{
Run(x, 1, 1, ref shader);
Run(x, 1, 1, in shader);
}
/// <summary>
@@ -134,11 +133,10 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
internal readonly unsafe void Run<T>(int x, int y, ref T shader)
internal readonly unsafe void Run<T>(int x, int y, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor<T>
{
Run(x, y, 1, ref shader);
Run(x, y, 1, in shader);
}
/// <summary>
@@ -149,7 +147,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
internal readonly unsafe void Run<T>(int x, int y, int z, ref T shader)
internal readonly unsafe void Run<T>(int x, int y, int z, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor<T>
{
default(InvalidOperationException).ThrowIf(this.device is null);
@@ -189,7 +187,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
/// <typeparam name="TPixel">The type of pixel to work on.</typeparam>
/// <param name="texture">The target texture to invoke the pixel shader upon.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the pixel shader to run.</param>
internal readonly unsafe void Run<T, TPixel>(IReadWriteNormalizedTexture2D<TPixel> texture, ref T shader)
internal readonly unsafe void Run<T, TPixel>(IReadWriteNormalizedTexture2D<TPixel> texture, in T shader)
where T : struct, IComputeShader<TPixel>, IComputeShaderDescriptor<T>
where TPixel : unmanaged
{
+5 -7
ファイルの表示
@@ -487,7 +487,7 @@ public static class ComputeContextExtensions
public static void For<T>(this in ComputeContext context, int x, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor<T>
{
context.Run(x, ref Unsafe.AsRef(in shader));
context.Run(x, in shader);
}
/// <summary>
@@ -501,7 +501,7 @@ public static class ComputeContextExtensions
public static void For<T>(this in ComputeContext context, int x, int y, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor<T>
{
context.Run(x, y, ref Unsafe.AsRef(in shader));
context.Run(x, y, in shader);
}
/// <summary>
@@ -516,7 +516,7 @@ public static class ComputeContextExtensions
public static void For<T>(this in ComputeContext context, int x, int y, int z, in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor<T>
{
context.Run(x, y, z, ref Unsafe.AsRef(in shader));
context.Run(x, y, z, in shader);
}
/// <summary>
@@ -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));
}
/// <summary>
@@ -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);
}
/// <summary>
ファイル差分が大きすぎるため表示されません。 差分を読み込み
+2
ファイルの表示
@@ -64,6 +64,7 @@ public partial class D2D1ReflectionServicesTests
[D2DRequiresScenePosition]
[D2DShaderProfile(D2D1ShaderProfile.PixelShader41)]
[D2DGeneratedPixelShaderDescriptor]
[AutoConstructor]
internal readonly partial struct ReflectedShader : ID2D1PixelShader
{
private readonly float2 offset;
@@ -127,6 +128,7 @@ public partial class D2D1ReflectionServicesTests
[D2DInputCount(1)]
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
[D2DGeneratedPixelShaderDescriptor]
[AutoConstructor]
internal readonly partial struct ReflectedShaderWithDoubleOperations : ID2D1PixelShader
{
private readonly double amount;
+4 -11
ファイルの表示
@@ -574,7 +574,7 @@ public partial class D2D1ResourceTextureManagerTests
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<CopyFromResourceTexture1DShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
CopyFromResourceTexture1DShader shader = new(width);
CopyFromResourceTexture1DShader shader = new();
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader);
@@ -626,8 +626,6 @@ public partial class D2D1ResourceTextureManagerTests
[AutoConstructor]
internal partial struct CopyFromResourceTexture1DShader : ID2D1PixelShader
{
private int width;
[D2DResourceTextureIndex(0)]
private D2D1ResourceTexture1D<float> source;
@@ -663,7 +661,7 @@ public partial class D2D1ResourceTextureManagerTests
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<CopyFromResourceTexture2DShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
CopyFromResourceTexture2DShader shader = new(width, height);
CopyFromResourceTexture2DShader shader = new();
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader);
@@ -735,7 +733,7 @@ public partial class D2D1ResourceTextureManagerTests
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<CopyFromResourceTexture2DShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
CopyFromResourceTexture2DShader shader = new(width, height);
CopyFromResourceTexture2DShader shader = new();
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader);
@@ -796,9 +794,6 @@ public partial class D2D1ResourceTextureManagerTests
[AutoConstructor]
internal partial struct CopyFromResourceTexture2DShader : ID2D1PixelShader
{
private int width;
private int height;
[D2DResourceTextureIndex(0)]
private D2D1ResourceTexture2D<float> source;
@@ -839,7 +834,7 @@ public partial class D2D1ResourceTextureManagerTests
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<CopyFromResourceTexture3DShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
CopyFromResourceTexture3DShader shader = new(width, height, depth);
CopyFromResourceTexture3DShader shader = new(height);
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader);
@@ -903,9 +898,7 @@ public partial class D2D1ResourceTextureManagerTests
[AutoConstructor]
internal partial struct CopyFromResourceTexture3DShader : ID2D1PixelShader
{
private int width;
private int height;
private int depth;
[D2DResourceTextureIndex(0)]
private D2D1ResourceTexture3D<float> source;