Merge pull request #336 from Sergio0694/dev/d2d1-texture-resources

Add support for D2D1 resource textures
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2022-08-09 12:19:08 +02:00
コミット a174018af9
46ファイル変更
+1444 -188

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

+45 -18
ファイルの表示
@@ -1,5 +1,4 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using ComputeSharp.Core.SourceGenerators.Models;
@@ -31,11 +30,11 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator
symbol.GetAttributes().Any(static a => a.AttributeClass?.ToDisplayString() == typeof(AutoConstructorAttribute).FullName))!;
// Get the type hierarchy and fields info
IncrementalValuesProvider<(HierarchyInfo Left, ImmutableArray<ParameterInfo> Right)> constructorInfo =
IncrementalValuesProvider<(HierarchyInfo Left, ConstructorInfo Right)> constructorInfo =
structDeclarations
.Select(static (item, token) => (Hierarchy: HierarchyInfo.From(item), Parameters: Ctor.GetData(item)))
.Where(static item => !item.Parameters.IsEmpty)
.WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer<ParameterInfo>.Default.ForImmutableArray());
.Select(static (item, token) => (Hierarchy: HierarchyInfo.From(item), Info: Ctor.GetData(item)))
.Where(static item => !item.Info.Parameters.IsEmpty)
.WithComparers(HierarchyInfo.Comparer.Default, ConstructorInfo.Comparer.Default);
// Generate the constructors
context.RegisterSourceOutput(constructorInfo, static (context, item) =>
@@ -55,23 +54,46 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator
/// Gets the sequence of <see cref="ParameterInfo"/> items for all fields in the input type.
/// </summary>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> being inspected.</param>
/// <returns>The sequence of <see cref="ParameterInfo"/> items for all fields in <paramref name="structDeclarationSymbol"/>.</returns>
public static ImmutableArray<ParameterInfo> GetData(INamedTypeSymbol structDeclarationSymbol)
/// <returns>The <see cref="ConstructorInfo"/> instance for <paramref name="structDeclarationSymbol"/>.</returns>
public static ConstructorInfo GetData(INamedTypeSymbol structDeclarationSymbol)
{
return (
from fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>()
where fieldSymbol is { IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false }
let typeName = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
select new ParameterInfo(typeName, fieldSymbol.Name)).ToImmutableArray();
ImmutableArray<ParameterInfo>.Builder parameters = ImmutableArray.CreateBuilder<ParameterInfo>();
ImmutableArray<string>.Builder defaulted = ImmutableArray.CreateBuilder<string>();
foreach (IFieldSymbol fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
// Skip fields that are not instance ones (and also ignore generated fields and fixed size buffers)
if (fieldSymbol is not { IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false })
{
continue;
}
// Check whether the field is annotated to have a special behavior
if (fieldSymbol.Type.TryGetAttributeWithFullMetadataName("ComputeSharp.AutoConstructorBehaviorAttribute", out AttributeData? usageData) &&
usageData!.ConstructorArguments is { Length: 1 } arguments &&
arguments[0].Value is (int)AutoConstructorBehavior.IgnoreAndSetToDefault)
{
defaulted.Add(fieldSymbol.Name);
}
else
{
// Track the field normally
string typeName = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
parameters.Add(new ParameterInfo(typeName, fieldSymbol.Name));
}
}
return new(parameters.ToImmutableArray(), defaulted.ToImmutableArray());
}
/// <summary>
/// Gets the <see cref="CompilationUnitSyntax"/> instance for a given type and sequence of parameters.
/// </summary>
/// <param name="hierarchyInfo">The type hierarchy info.</param>
/// <param name="parameters">The sequence of parameters to initialize.</param>
/// <param name="constructorInfo">The <see cref="ConstructorInfo"/> instance with the info for the constructor to generate.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> instance for a specified type.</returns>
public static CompilationUnitSyntax GetSyntax(HierarchyInfo hierarchyInfo, ImmutableArray<ParameterInfo> parameters)
public static CompilationUnitSyntax GetSyntax(HierarchyInfo hierarchyInfo, ConstructorInfo constructorInfo)
{
// Create the constructor declaration for the type. This will
// produce a constructor with simple initialization of all variables:
@@ -82,15 +104,20 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator
// this.b = b;
// this.c = c;
// ...
// this.ignored1 = default;
// this.ignored2 = default;
// this.ignored3 = default;
// ...
// }
ConstructorDeclarationSyntax constructorDeclaration =
ConstructorDeclaration(hierarchyInfo.Hierarchy[0].QualifiedName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters.Select(field => Parameter(Identifier(field.Name)).WithType(IdentifierName(field.Type))).ToArray())
.AddBodyStatements(parameters.Select(field => ParseStatement($"this.{field.Name} = {field.Name};")).ToArray());
.AddParameterListParameters(constructorInfo.Parameters.Select(field => Parameter(Identifier(field.Name)).WithType(IdentifierName(field.Type))).ToArray())
.AddBodyStatements(constructorInfo.Parameters.Select(field => ParseStatement($"this.{field.Name} = {field.Name};")).ToArray())
.AddBodyStatements(constructorInfo.DefaultedFields.Select(field => ParseStatement($"this.{field} = default;")).ToArray());
// Add the unsafe modifier, if needed
if (parameters.Any(static param => param.Type.Contains("*")))
if (constructorInfo.Parameters.Any(static param => param.Type.Contains("*")))
{
constructorDeclaration = constructorDeclaration.AddModifiers(Token(SyntaxKind.UnsafeKeyword));
}
+2
ファイルの表示
@@ -16,6 +16,8 @@
and to match members based on full name, so the types being in the generator assembly are not an issue.-->
<ItemGroup>
<Compile Include="..\ComputeSharp.Core\Attributes\AutoConstructorAttribute.cs" Link="ComputeSharp.Core\Attributes\AutoConstructorAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Attributes\Internals\AutoConstructorBehaviorAttribute.cs" Link="ComputeSharp.Core\Attributes\Internals\AutoConstructorBehaviorAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Attributes\Internals\AutoConstructorBehavior.cs" Link="ComputeSharp.Core\Attributes\Internals\AutoConstructorBehavior.cs" />
<Compile Include="..\ComputeSharp.Core\Exceptions\InvalidExecutionContextException.cs" Link="ComputeSharp.Core\Exceptions\InvalidExecutionContextException.cs" />
<Compile Include="..\ComputeSharp.Core\Intrinsics\Attributes\HlslIntrinsicNameAttribute.cs" Link="ComputeSharp.Core\Intrinsics\Attributes\HlslIntrinsicNameAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Intrinsics\Hlsl.cs" Link="ComputeSharp.Core\Intrinsics\Hlsl.cs" />
+36
ファイルの表示
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.Core.SourceGenerators.Models;
/// <summary>
/// A model containiing information on a constructor to generate.
/// </summary>
/// <param name="Parameters">The <see cref="ParameterInfo"/> values for the constructor.</param>
/// <param name="DefaultedFields">The names of ignored fields that should be defaulted.</param>
internal sealed record ConstructorInfo(ImmutableArray<ParameterInfo> Parameters, ImmutableArray<string> DefaultedFields)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ConstructorInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<ConstructorInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, ConstructorInfo obj)
{
hashCode.AddRange(obj.Parameters);
hashCode.AddRange(obj.DefaultedFields);
}
/// <inheritdoc/>
protected override bool AreEqual(ConstructorInfo x, ConstructorInfo y)
{
return
x.Parameters.SequenceEqual(y.Parameters) &&
x.DefaultedFields.SequenceEqual(y.DefaultedFields);
}
}
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace ComputeSharp;
/// <summary>
/// Indicates the behavior of fields annotated with <see cref="AutoConstructorBehaviorAttribute"/>.
/// </summary>
internal enum AutoConstructorBehavior
{
/// <summary>
/// Causes <see cref="AutoConstructorAttribute"/> to ignore fields and set their values to <see langword="default"/>.
/// </summary>
IgnoreAndSetToDefault
}
+24
ファイルの表示
@@ -0,0 +1,24 @@
using System;
namespace ComputeSharp;
/// <summary>
/// An attribute that indicates that a target shader type should get an automatic constructor for all fields.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)]
internal sealed class AutoConstructorBehaviorAttribute : Attribute
{
/// <summary>
/// Creates a new <see cref="AutoConstructorBehaviorAttribute"/> instance with the specified parameters.
/// </summary>
/// <param name="behavior">The <see cref="AutoConstructorBehavior"/> value for the current instance.</param>
public AutoConstructorBehaviorAttribute(AutoConstructorBehavior behavior)
{
Behavior = behavior;
}
/// <summary>
/// Gets the <see cref="AutoConstructorBehavior"/> value for the current instance.
/// </summary>
public AutoConstructorBehavior Behavior { get; }
}
+5
ファイルの表示
@@ -52,3 +52,8 @@ CMPSD2D0042 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github
CMPSD2D0043 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPSD2D0044 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPSD2D0045 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPSD2D0046 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPSD2D0047 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPSD2D0048 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPSD2D0049 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPSD2D0050 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+1
ファイルの表示
@@ -82,6 +82,7 @@
<Compile Include="..\ComputeSharp.D2D1\Interfaces\__Internals\ID2D1BytecodeLoader.cs" Link="ComputeSharp.D2D1\Interfaces\__Internals\ID2D1BytecodeLoader.cs" />
<Compile Include="..\ComputeSharp.D2D1\Interfaces\__Internals\ID2D1DispatchDataLoader.cs" Link="ComputeSharp.D2D1\Interfaces\__Internals\ID2D1DispatchDataLoader.cs" />
<Compile Include="..\ComputeSharp.D2D1\Interfaces\__Internals\ID2D1InputDescriptionsLoader.cs" Link="ComputeSharp.D2D1\Interfaces\__Internals\ID2D1InputDescriptionsLoader.cs" />
<Compile Include="..\ComputeSharp.D2D1\Interfaces\__Internals\ID2D1ResourceTextureDescriptionsLoader.cs" Link="ComputeSharp.D2D1\Interfaces\__Internals\ID2D1ResourceTextureDescriptionsLoader.cs" />
<Compile Include="..\ComputeSharp.D2D1\Interfaces\__Internals\ID2D1Shader.cs" Link="ComputeSharp.D2D1\Interfaces\__Internals\ID2D1Shader.cs" />
<Compile Include="..\ComputeSharp.D2D1\Intrinsics\D2D.cs" Link="ComputeSharp.D2D1\Intrinsics\D2D.cs" />
<Compile Include="..\ComputeSharp.D2D1\Shaders\Exceptions\FxcCompilationException.cs" Link="ComputeSharp.D2D1\Shaders\Exceptions\FxcCompilationException.cs" />
+88 -8
ファイルの表示
@@ -547,7 +547,7 @@ internal static class DiagnosticDescriptors
/// </summary>
public static readonly DiagnosticDescriptor OutOfRangeInputIndex = new DiagnosticDescriptor(
id: "CMPSD2D0039",
title: "Our of range D2D1 shader input indices",
title: "Out of range D2D1 shader input indices",
messageFormat: "The D2D1 shader of type {0} is using some out of range input indices",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
@@ -595,7 +595,7 @@ internal static class DiagnosticDescriptors
/// </summary>
public static readonly DiagnosticDescriptor OutOfRangeInputDescriptionIndex = new DiagnosticDescriptor(
id: "CMPSD2D0042",
title: "Our of range D2D1 shader input description indices",
title: "Out of range D2D1 shader input description indices",
messageFormat: "The D2D1 shader of type {0} is using some out of range input description indices",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
@@ -636,18 +636,98 @@ internal static class DiagnosticDescriptors
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for when the <c>[D2DRequiresPosition]</c> attribute is missing.
/// Gets a <see cref="DiagnosticDescriptor"/> for when the <c>[D2DRequiresScenePosition]</c> attribute is missing.
/// <para>
/// Format: <c>"The D2D1 shader of type {0} is using D2D1 APIs that require the [D2DRequiresPosition] attribute to be used (that is, D2D1.GetScenePosition() and D2D1.SampleInputAtPosition(int, float2)), but the shader type is not annotated accordingly"</c>.
/// Format: <c>"The D2D1 shader of type {0} is using D2D1 APIs that require the [D2DRequiresScenePosition] attribute to be used (that is, D2D1.GetScenePosition() and D2D1.SampleInputAtPosition(int, float2)), but the shader type is not annotated accordingly"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor MissingD2DRequiresPositionAttribute = new DiagnosticDescriptor(
public static readonly DiagnosticDescriptor MissingD2DRequiresScenePositionAttribute = new DiagnosticDescriptor(
id: "CMPSD2D0045",
title: "Missing [D2DRequiresPosition] attribute",
messageFormat: "The D2D1 shader of type {0} is using D2D1 APIs that require the [D2DRequiresPosition] attribute to be used (that is, D2D.GetScenePosition() and D2D.SampleInputAtPosition(int, float2)), but the shader type is not annotated accordingly",
title: "Missing [D2DRequiresScenePosition] attribute",
messageFormat: "The D2D1 shader of type {0} is using D2D1 APIs that require the [D2DRequiresScenePosition] attribute to be used (that is, D2D.GetScenePosition() and D2D.SampleInputAtPosition(int, float2)), but the shader type is not annotated accordingly",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A D2D1 shader using functionality that needs position info (ie. when [D2DRequiresPosition] is used, which is mandatory when calling either D2D.GetScenePosition() or D2D.SampleInputAtPosition(int, float2)) needs to be annotated accordingly.",
description: "A D2D1 shader using functionality that needs position info (ie. when [D2DRequiresScenePosition] is used, which is mandatory when calling either D2D.GetScenePosition() or D2D.SampleInputAtPosition(int, float2)) needs to be annotated accordingly.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a shader with an out of range resource texture index (or more).
/// <para>
/// Format: <c>"The D2D1 shader of type {0} is using some out of range resource texture indices"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor ResourceTextureIndexOverlappingWithInputIndex = new DiagnosticDescriptor(
id: "CMPSD2D0046",
title: "D2D1 shader resource texture indices overlapping input indices",
messageFormat: "The D2D1 shader of type {0} is using some resource texture indices that overlap with the shader input indices",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A D2D1 shader must have all the indices of its resource textures in the valid range (between the input count and 16, exclusive).",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a shader with an out of range resource texture index (or more).
/// <para>
/// Format: <c>"The D2D1 shader of type {0} is using some out of range resource texture indices"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor OutOfRangeResourceTextureIndex = new DiagnosticDescriptor(
id: "CMPSD2D0047",
title: "Out of range D2D1 shader resource texture indices",
messageFormat: "The D2D1 shader of type {0} is using some out of range resource texture indices",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A D2D1 shader must have all the indices of its resource textures in the valid range (between the input count and 16, exclusive).",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for repeated indices for D2D resource texture indices.
/// <para>
/// Format: <c>"The D2D1 shader of type {0} is using repeated indices for some of its [D2DResourceTextureIndex] attributes"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor RepeatedD2DResourceTextureIndices = new DiagnosticDescriptor(
id: "CMPSD2D0048",
title: "Repeated D2D1 shader resource texture indices",
messageFormat: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DResourceTextureIndex] attributes",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A D2D1 shader must only have unique indices for all of its [D2DResourceTextureIndex] attributes.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid use of <c>[D2DResourceTextureIndex]</c>.
/// <para>
/// Format: <c>"The field \"{0}\" (in type {1}) is using [D2DResourceTextureIndex] incorrectly (the attribute can only be used on D2D1 resource texture types, but the field is of type {2})"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidD2DResourceTextureIndexAttributeUse = new DiagnosticDescriptor(
id: "CMPSD2D0049",
title: "Invalid [D2DResourceTextureIndex] use",
messageFormat: "The field \"{0}\" (in type {1}) is using [D2DResourceTextureIndex] incorrectly (the attribute can only be used on D2D1 resource texture types, but the field is of type {2})",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A field is using [D2DResourceTextureIndex] incorrectly (the attribute can only be used on D2D1 resource texture types).",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a missing <c>[D2DResourceTextureIndex]</c>.
/// <para>
/// Format: <c>"The field \"{0}\" (in type {1}) is of a D2D1 resource texture type but is missing the [D2DResourceTextureIndex] attribute"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor MissingD2DResourceTextureIndexAttribute = new DiagnosticDescriptor(
id: "CMPSD2D0050",
title: "Missing [D2DResourceTextureIndex] attribute",
messageFormat: "The field \"{0}\" (in type {1}) is of a D2D1 resource texture type but is missing the [D2DResourceTextureIndex] attribute",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "All fields of a D2D1 resource texture type must be annotated using the [D2DResourceTextureIndex] attribute.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
}
@@ -53,11 +53,18 @@ partial class ID2D1ShaderGenerator
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// Extract information on all captured fields
GetInstanceFields(
diagnostics,
structDeclarationSymbol,
discoveredTypes,
out ImmutableArray<(string Name, string HlslType)> valueFields,
out ImmutableArray<(string Name, string HlslType, int Index)> resourceTextureFields);
// Explore the syntax tree and extract the processed info
var semanticModelProvider = new SemanticModelProvider(compilation);
var valueFields = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes);
var (entryPoint, processedMethods) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, out bool methodsNeedD2D1RequiresPosition);
var staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions, out bool fieldsNeedD2D1RequiresPosition);
var (entryPoint, processedMethods) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, out bool methodsNeedD2D1RequiresScenePosition);
var staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions, out bool fieldsNeedD2D1RequiresScenePosition);
// Process the discovered types and constants
var declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes);
@@ -67,13 +74,14 @@ partial class ID2D1ShaderGenerator
bool requiresScenePosition = GetD2DRequiresScenePositionInfo(structDeclarationSymbol);
// Emit diagnostics for incorrect scene position uses
ReportInvalidD2DRequiresPositionUse(diagnostics, structDeclarationSymbol, requiresScenePosition, methodsNeedD2D1RequiresPosition || fieldsNeedD2D1RequiresPosition);
ReportInvalidD2DRequiresScenePositionUse(diagnostics, structDeclarationSymbol, requiresScenePosition, methodsNeedD2D1RequiresScenePosition || fieldsNeedD2D1RequiresScenePosition);
// Get the HLSL source
return GetHlslSource(
definedConstants,
declaredTypes,
valueFields,
resourceTextureFields,
staticFields,
processedMethods,
entryPoint,
@@ -89,13 +97,17 @@ partial class ID2D1ShaderGenerator
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="types">The collection of currently discovered types.</param>
/// <returns>A sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</returns>
private static ImmutableArray<(string Name, string HlslType)> GetInstanceFields(
/// <param name="valueFields">The sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</param>
/// <param name="resourceTextureFields">The sequence of captured resource textures in <paramref name="structDeclarationSymbol"/>.</param>
private static void GetInstanceFields(
ImmutableArray<Diagnostic>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> types)
ICollection<INamedTypeSymbol> types,
out ImmutableArray<(string Name, string HlslType)> valueFields,
out ImmutableArray<(string Name, string HlslType, int Index)> resourceTextureFields)
{
ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>();
ImmutableArray<(string, string, int)>.Builder resourceTextures = ImmutableArray.CreateBuilder<(string, string, int)>();
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
@@ -117,10 +129,25 @@ partial class ID2D1ShaderGenerator
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
// Allowed fields must be unmanaged values
if (typeSymbol.IsUnmanagedType)
// Handle resource textures as a special case
if (HlslKnownTypes.IsResourceTextureType(metadataName))
{
// Track the type if it's a custom struct
int index = 0;
// If [D2DResourceTextureIndex] is present, get the resource texture index.
// This generator doesn't need to emit diagnostics, as that's handled separately
// by the logic handling the info gathering for LoadResourceTextureDescriptions.
if (fieldSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute", out AttributeData? attributeData))
{
_ = attributeData!.TryGetConstructorArgument(0, out index);
}
resourceTextures.Add((mapping ?? fieldSymbol.Name, typeName, index));
}
else if (typeSymbol.IsUnmanagedType)
{
// Allowed fields must be unmanaged values.
// Also, track the type if it's a custom struct.
if (!HlslKnownTypes.IsKnownHlslType(metadataName))
{
types.Add(typeSymbol);
@@ -134,7 +161,8 @@ partial class ID2D1ShaderGenerator
}
}
return values.ToImmutable();
valueFields = values.ToImmutable();
resourceTextureFields = resourceTextures.ToImmutable();
}
/// <summary>
@@ -146,7 +174,7 @@ partial class ID2D1ShaderGenerator
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="needsD2D1RequiresPosition">Whether or not the shader needs the <c>[D2DRequiresPosition]</c> annotation.</param>
/// <param name="needsD2D1RequiresScenePosition">Whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> annotation.</param>
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
ImmutableArray<Diagnostic>.Builder diagnostics,
@@ -155,11 +183,11 @@ partial class ID2D1ShaderGenerator
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
out bool needsD2D1RequiresPosition)
out bool needsD2D1RequiresScenePosition)
{
ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>();
needsD2D1RequiresPosition = false;
needsD2D1RequiresScenePosition = false;
foreach (var fieldDeclaration in structDeclaration.Members.OfType<FieldDeclarationSyntax>())
{
@@ -197,7 +225,7 @@ partial class ID2D1ShaderGenerator
string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString();
needsD2D1RequiresPosition |= staticFieldRewriter.NeedsD2DRequiresPositionAttribute;
needsD2D1RequiresScenePosition |= staticFieldRewriter.NeedsD2DRequiresScenePositionAttribute;
builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment));
}
@@ -216,7 +244,7 @@ partial class ID2D1ShaderGenerator
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="needsD2D1RequiresPosition">Whether or not the shader needs the <c>[D2DRequiresPosition]</c> annotation.</param>
/// <param name="needsD2D1RequiresScenePosition">Whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> annotation.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods) GetProcessedMethods(
ImmutableArray<Diagnostic>.Builder diagnostics,
@@ -226,7 +254,7 @@ partial class ID2D1ShaderGenerator
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
out bool needsD2D1RequiresPosition)
out bool needsD2D1RequiresScenePosition)
{
// Find all declared methods in the type
ImmutableArray<MethodDeclarationSyntax> methodDeclarations = (
@@ -237,7 +265,7 @@ partial class ID2D1ShaderGenerator
string? entryPoint = null;
ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>();
needsD2D1RequiresPosition = false;
needsD2D1RequiresScenePosition = false;
foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations)
{
@@ -267,7 +295,7 @@ partial class ID2D1ShaderGenerator
MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
// Update the position requirement
needsD2D1RequiresPosition |= shaderSourceRewriter.NeedsD2DRequiresPositionAttribute;
needsD2D1RequiresScenePosition |= shaderSourceRewriter.NeedsD2DRequiresScenePositionAttribute;
// Emit the extracted local functions first
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
@@ -412,13 +440,13 @@ partial class ID2D1ShaderGenerator
}
/// <summary>
/// Reports diagnostics for invalid uses of <c>[D2DRequiresPosition]</c> in a shader.
/// Reports diagnostics for invalid uses of <c>[D2DRequiresScenePosition]</c> in a shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="requiresScenePosition">Whether the shader type is declaring the need for scene position.</param>
/// <param name="usesPositionDependentMethods">Whether the shader is using APIs that rely on scene position.</param>
private static void ReportInvalidD2DRequiresPositionUse(
private static void ReportInvalidD2DRequiresScenePositionUse(
ImmutableArray<Diagnostic>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
bool requiresScenePosition,
@@ -426,7 +454,7 @@ partial class ID2D1ShaderGenerator
{
if (!requiresScenePosition && usesPositionDependentMethods)
{
diagnostics.Add(MissingD2DRequiresPositionAttribute, structDeclarationSymbol, structDeclarationSymbol);
diagnostics.Add(MissingD2DRequiresScenePositionAttribute, structDeclarationSymbol, structDeclarationSymbol);
}
}
@@ -446,6 +474,7 @@ partial class ID2D1ShaderGenerator
/// <param name="definedConstants">The sequence of defined constants for the shader.</param>
/// <param name="declaredTypes">The sequence of declared types used by the shader.</param>
/// <param name="valueFields">The sequence of value instance fields for the current shader.</param>
/// <param name="resourceTextureFields">The sequence of captured resource textures for the current shader.</param>
/// <param name="staticFields">The sequence of static fields referenced by the shader.</param>
/// <param name="processedMethods">The sequence of processed methods used by the shader.</param>
/// <param name="executeMethod">The body of the entry point of the shader.</param>
@@ -458,6 +487,7 @@ partial class ID2D1ShaderGenerator
ImmutableArray<(string Name, string Value)> definedConstants,
ImmutableArray<(string Name, string Definition)> declaredTypes,
ImmutableArray<(string Name, string HlslType)> valueFields,
ImmutableArray<(string Name, string HlslType, int Index)> resourceTextureFields,
ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
ImmutableArray<(string Signature, string Definition)> processedMethods,
string executeMethod,
@@ -556,6 +586,15 @@ partial class ID2D1ShaderGenerator
}
}
// Resource textures
foreach (var (fieldName, fieldType, index) in resourceTextureFields)
{
AppendLF();
AppendLineAndLF($"{fieldType} {fieldName} : register(t{index});");
AppendLineAndLF($"SamplerState __sampler__{fieldName} : register(s{index});");
}
// Forward declarations
foreach (var (forwardDeclaration, _) in processedMethods)
{
@@ -42,7 +42,7 @@ partial class ID2D1ShaderGenerator
/// </summary>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load the shader dispatch data.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(ImmutableArray<FieldInfo> fieldInfos, int constantBufferSizeInBytes)
{
// If there are no fields, just load an empty buffer
@@ -41,7 +41,7 @@ partial class ID2D1ShaderGenerator
/// Gets a sequence of statements to load the input descriptions for a given shader.
/// </summary>
/// <param name="inputDescriptions">The array of <see cref="InputDescription"/> values for all available input descriptions.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load the input descriptions data.</returns>
private static ImmutableArray<StatementSyntax> GetInputDescriptionsLoadingStatements(ImmutableArray<InputDescription> inputDescriptions)
{
// If there are no input descriptions available, just load an empty buffer
@@ -127,7 +127,7 @@ partial class ID2D1ShaderGenerator
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset + 8}))"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)inputDescription.LevelOfDetail)))));
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(inputDescription.LevelOfDetail)))));
offset += sizeof(int) * 3;
}
@@ -57,7 +57,7 @@ partial class ID2D1ShaderGenerator
inputDescriptions = ImmutableArray<InputDescription>.Empty;
// Validate the input count (ignore if invalid, this will be validated by the HLSL source generator)
// Validate the input count (ignore if invalid, this will be validated by GetInputType() generator)
if (inputCount is not (>= 0 and <= 8))
{
goto End;
@@ -0,0 +1,139 @@
using System.Collections.Immutable;
using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.SourceGenerators.Models;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.D2D1.SourceGenerators;
/// <inheritdoc/>
partial class ID2D1ShaderGenerator
{
/// <inheritoc/>
private static partial class LoadResourceTextureDescriptions
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadResourceTextureDescriptions</c> method.
/// </summary>
/// <param name="resourceTextureDescriptionsInfo">The resource texture descriptions info gathered for the current shader.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadResourceTextureDescriptions</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo)
{
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadResourceTextureDescriptions<TLoader>(ref TLoader loader)
// {
// <BODY>
// }
return
MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(LoadResourceTextureDescriptions)))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
.AddParameterListParameters(Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader")))
.WithBody(Block(GetInputDescriptionsLoadingStatements(resourceTextureDescriptionsInfo.ResourceTextureDescriptions)));
}
/// <summary>
/// Gets a sequence of statements to load the resource texture descriptions for a given shader.
/// </summary>
/// <param name="resourceTextureDescriptionsInfo">The array of <see cref="ResourceTextureDescriptionsInfo"/> values for all available resource texture descriptions.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load the resource texture descriptions data.</returns>
private static ImmutableArray<StatementSyntax> GetInputDescriptionsLoadingStatements(ImmutableArray<ResourceTextureDescription> resourceTextureDescriptionsInfo)
{
// If there are no resource texture descriptions available, just load an empty buffer
if (resourceTextureDescriptionsInfo.IsEmpty)
{
// loader.LoadResourceTextureDescriptions(default);
return
ImmutableArray.Create<StatementSyntax>(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadResourceTextureDescriptions")))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword))))));
}
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
// The size of the buffer with the resource texture descriptions is the number of resurce textures descriptions,
// times the size of each input description, which is a struct containing two int-sized fields (index and rank).
int resourceTextureDescriptionSizeInBytes = resourceTextureDescriptionsInfo.Length * sizeof(int) * 2;
// global::System.Span<byte> data = stackalloc byte[<RESOURCE_TEXTURE_DESCRIPTIONS_SIZE>];
statements.Insert(0,
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("data"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceTextureDescriptionSizeInBytes)))))))))));
// ref byte r0 = ref data[0];
statements.Insert(1,
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("data"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
int offset = 0;
// Generate loading statements for each resource texture description
foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptionsInfo)
{
// Write the index of the current resource texture description:
//
// global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET>)) = <INDEX>;
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset}))"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)resourceTextureDescription.Index)))));
// Write the rank of the current resource texture description:
//
// global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET> + 4)) = <FILTER>;
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset + 4}))"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)resourceTextureDescription.Rank)))));
offset += sizeof(int) * 2;
}
// loader.LoadInputDescriptions(data);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadResourceTextureDescriptions")))
.AddArgumentListArguments(Argument(IdentifierName("data")))));
return statements.ToImmutable();
}
}
}
@@ -0,0 +1,135 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Mappings;
using Microsoft.CodeAnalysis;
using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.D2D1.SourceGenerators;
/// <inheritdoc/>
partial class ID2D1ShaderGenerator
{
/// <summary>
/// A helper with all logic to generate the <c>LoadResourceTextureDescriptions</c> method.
/// </summary>
private static partial class LoadResourceTextureDescriptions
{
/// <summary>
/// Extracts the resource texture descriptions for the current shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="inputCount">The number of inputs for the shader.</param>
/// <param name="resourceTextureDescriptions">The produced resource texture descriptions for the shader.</param>
public static void GetInfo(
ImmutableArray<Diagnostic>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
int inputCount,
out ImmutableArray<ResourceTextureDescription> resourceTextureDescriptions)
{
ImmutableArray<(int? Index, int Rank)>.Builder resourceTextureInfos = ImmutableArray.CreateBuilder<(int?, int)>();
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
// Only look for fields of a named type symbol (diagnostics is emitted by the HLSL rewriter if it's not the case).
// We're only looking for instance fields of unmanaged types in this case (as resource textures are structs).
if (fieldSymbol is not { IsStatic: false, Type: INamedTypeSymbol { IsUnmanagedType: true } typeSymbol })
{
continue;
}
string metadataName = typeSymbol.GetFullMetadataName();
// Check that the field is a resource texture type (if not, it will be processed by the HLSL rewriter too)
if (HlslKnownTypes.IsResourceTextureType(metadataName))
{
// The type name will be ComputeSharp.D2D1.D2D1ResourceTexture1D or the 2D/3D versions
int rank = int.Parse(metadataName.Substring(metadataName.Length - 2, 1));
int? index = null;
// Get the index from the [D2DResourceTextureIndex] attribute over the field
if (fieldSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute", out AttributeData? attributeData))
{
// If the constructor argument isn't available, it means the code is invalid. Just do nothing then, as the
// user will have to fix that to get the code to compile anyway. This way the generator won't crash too.
if (attributeData!.TryGetConstructorArgument(0, out int resourceIndex))
{
index = resourceIndex;
}
}
else
{
// If the attribute is missing, emit a diagnostic
diagnostics.Add(MissingD2DResourceTextureIndexAttribute, fieldSymbol, fieldSymbol.Name, structDeclarationSymbol);
}
resourceTextureInfos.Add((index, rank));
}
}
// Extract the resource texture descriptions for the rest of the pipeline
resourceTextureDescriptions = resourceTextureInfos.Select(static info => new ResourceTextureDescription((uint)(info.Index ?? 0), (uint)info.Rank)).ToImmutableArray();
// If the input count is invalid, do nothing and avoid emitting potentially incorrect
// diagnostics based on the resource texture indices with respect to the input count.
// The GetInputType() generator has already emitted diagnostic for this error, so this
// generator can just wait for users to go back and fix that issue before proceeding.
if (inputCount is not (>= 0 and <= 8))
{
return;
}
// Validate that the resource texture indices don't overlap with the shader inputs
if (resourceTextureInfos.Any(info => info.Index < inputCount))
{
diagnostics.Add(ResourceTextureIndexOverlappingWithInputIndex, structDeclarationSymbol, structDeclarationSymbol);
return;
}
// Validate that no resource texture has an index greater than or equal to 16
if (resourceTextureInfos.Any(info => info.Index >= 16))
{
diagnostics.Add(OutOfRangeResourceTextureIndex, structDeclarationSymbol, structDeclarationSymbol);
return;
}
HashSet<int> resourceTextureIndices = new(resourceTextureInfos.Where(info => info.Index.HasValue).Select(info => info.Index!.Value));
// All input description indices must be unique
if (resourceTextureIndices.Count != resourceTextureInfos.Count)
{
diagnostics.Add(RepeatedD2DResourceTextureIndices, structDeclarationSymbol, structDeclarationSymbol);
}
}
/// <summary>
/// Gets the diagnostics for a field with invalid <c>[D2DResourceTextureIndex]</c> attribute use, if that is the case.
/// </summary>
/// <param name="fieldSymbol">The input <see cref="IFieldSymbol"/> instance to process.</param>
/// <returns>The resulting <see cref="Diagnostic"/> instance for <paramref name="fieldSymbol"/>, if needed.</returns>
public static Diagnostic? GetDiagnosticForFieldWithInvalidD2DResourceTextureIndexAttribute(IFieldSymbol fieldSymbol)
{
if (fieldSymbol.HasAttributeWithFullyQualifiedName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute"))
{
string metadataName = fieldSymbol.Type.GetFullMetadataName();
if (!HlslKnownTypes.IsResourceTextureType(metadataName))
{
return Diagnostic.Create(
InvalidD2DResourceTextureIndexAttributeUse,
fieldSymbol.Locations.FirstOrDefault(),
fieldSymbol.Name,
fieldSymbol.ContainingType,
fieldSymbol.Type);
}
}
return null;
}
}
}
+44 -6
ファイルの表示
@@ -51,9 +51,9 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
.Where(static item => IsD2D1PixelShaderType(item.Left.Symbol, item.Right))
.Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol)));
// Get the dispatch data, input types, HLSL source and embedded bytecode info. This info is computed
// on the same step as parts are shared in following sub-branches in the incremental generator pipeline.
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, HlslShaderSourceInfo Source, ImmutableArray<Diagnostic> Diagnostics)> shaderInfoWithErrors =
// Get the dispatch data, input types, resource texture descriptions, HLSL source and embedded bytecode info. This info
// is computed on the same step as parts are shared in following sub-branches in the incremental generator pipeline.
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, HlslShaderSourceInfo Source, ImmutableArray<Diagnostic> Diagnostics)> shaderInfoWithErrors =
shaderDeclarations
.Combine(context.CompilationProvider)
.Select(static (item, token) =>
@@ -81,6 +81,15 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
InputTypesInfo inputTypesInfo = new(inputTypes);
// Get the resource texture info for LoadResourceTextureDescriptions()
LoadResourceTextureDescriptions.GetInfo(
diagnostics,
item.Left.Symbol,
inputCount,
out ImmutableArray<ResourceTextureDescription> resourceTextureDescriptions);
ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo = new(resourceTextureDescriptions);
// Get HLSL source for BuildHlslSource()
string hlslSource = BuildHlslSource.GetHlslSource(
diagnostics,
@@ -111,6 +120,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
item.Left.Hierarchy,
dispatchDataInfo,
inputTypesInfo,
resourceTextureDescriptionsInfo,
sourceInfo,
diagnostics.ToImmutableArray());
});
@@ -128,10 +138,10 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
context.ReportDiagnostics(d2DCompileOptionsAtAssemblyLevelErrors.Select(static (item, token) => item));
// Filter all items to enable caching at a coarse level, and remove diagnostics
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, HlslShaderSourceInfo Source)> shaderInfo =
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, HlslShaderSourceInfo Source)> shaderInfo =
shaderInfoWithErrors
.Select(static (item, token) => (item.Hierarchy, item.Dispatch, item.InputTypes, item.Source))
.WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default, InputTypesInfo.Comparer.Default, EqualityComparer<HlslShaderSourceInfo>.Default);
.Select(static (item, token) => (item.Hierarchy, item.Dispatch, item.InputTypes, item.ResourceTextureDescriptions, item.Source))
.WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default, InputTypesInfo.Comparer.Default, ResourceTextureDescriptionsInfo.Comparer.Default, EqualityComparer<HlslShaderSourceInfo>.Default);
// Filter items to enable caching for the input count methods
IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo =
@@ -163,6 +173,21 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetInputType)}", compilationUnit.GetText(Encoding.UTF8));
});
// Get a filtered sequence to enable caching
IncrementalValuesProvider<(HierarchyInfo Hierarchy, ResourceTextureDescriptionsInfo ResourceTextureDescriptions)> resourceTextureDescriptionsInfo =
shaderInfo
.Select(static (item, token) => (item.Hierarchy, item.ResourceTextureDescriptions))
.WithComparers(HierarchyInfo.Comparer.Default, ResourceTextureDescriptionsInfo.Comparer.Default);
// Generate the LoadResourceTextureDescriptions() methods
context.RegisterSourceOutput(resourceTextureDescriptionsInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
{
MethodDeclarationSyntax getInputTypeMethod = LoadResourceTextureDescriptions.GetSyntax(item.Left.ResourceTextureDescriptions);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadResourceTextureDescriptions)}", compilationUnit.GetText(Encoding.UTF8));
});
// Get a filtered sequence to enable caching
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch)> dispatchDataInfo =
shaderInfo
@@ -355,5 +380,18 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetPixelOptions)}", compilationUnit.GetText(Encoding.UTF8));
});
// Get all diagnostics for invalid [D2DResourceTextureIndex] uses
IncrementalValuesProvider<Diagnostic> invalidD2DResourceTextureIndexUseErrors =
context.SyntaxProvider
.CreateSyntaxProvider(
static (node, _) => node is FieldDeclarationSyntax { AttributeLists.Count: > 0 },
static (context, _) => ((FieldDeclarationSyntax)context.Node).Declaration.Variables.Select(v => (IFieldSymbol)context.SemanticModel.GetDeclaredSymbol(v)!))
.SelectMany(static (item, _) => item)
.Select(static (item, token) => LoadResourceTextureDescriptions.GetDiagnosticForFieldWithInvalidD2DResourceTextureIndexAttribute(item))
.Where(static diagnostic => diagnostic is not null)!;
// Output the diagnostics
context.ReportDiagnostics(invalidD2DResourceTextureIndexUseErrors);
}
}
+3 -3
ファイルの表示
@@ -12,11 +12,11 @@ partial class HlslKnownMethods
{
/// <summary>
/// Checks whether or not a method name (previous matched with <see cref="TryGetMappedName(string, out string?)"/>
/// needs the <c>[D2DRequiresPosition]</c> annotation on its containing shader in order to be used.
/// needs the <c>[D2DRequiresScenePosition]</c> annotation on its containing shader in order to be used.
/// </summary>
/// <param name="name">The fully qualified metadata name.</param>
/// <returns>Whether the method needs the <c>[D2DRequiresPosition]</c> annotation.</returns>
public static bool NeedsD2DRequiresPositionAttribute(string name)
/// <returns>Whether the method needs the <c>[D2DRequiresScenePosition]</c> annotation.</returns>
public static bool NeedsD2DRequiresScenePositionAttribute(string name)
{
return name is "ComputeSharp.D2D1.D2D.GetScenePosition" or "ComputeSharp.D2D1.D2D.SampleInputAtPosition";
}
+44
ファイルの表示
@@ -0,0 +1,44 @@
using System.Collections.Generic;
namespace ComputeSharp.SourceGeneration.Mappings;
/// <inheritdoc/>
partial class HlslKnownProperties
{
/// <inheritdoc/>
private static partial IReadOnlyDictionary<string, string> BuildKnownResourceIndexers()
{
return new Dictionary<string, string>
{
[$"ComputeSharp.D2D1.D2D1ResourceTexture2D.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.D2D1.D2D1ResourceTexture3D.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3"
};
}
/// <inheritdoc/>
private static partial IReadOnlyDictionary<string, string?> BuildKnownResourceSamplers()
{
return new Dictionary<string, string?>
{
[$"ComputeSharp.D2D1.D2D1ResourceTexture1D.this[{typeof(float).FullName}]"] = null,
[$"ComputeSharp.D2D1.D2D1ResourceTexture2D.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2",
[$"ComputeSharp.D2D1.D2D1ResourceTexture2D.this[{typeof(Float2).FullName}]"] = null,
[$"ComputeSharp.D2D1.D2D1ResourceTexture3D.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
[$"ComputeSharp.D2D1.D2D1ResourceTexture3D.this[{typeof(Float3).FullName}]"] = null
};
}
/// <inheritdoc/>
private static partial IReadOnlyDictionary<string, (int Rank, int Axis)> BuildKnownSizeAccessors()
{
return new Dictionary<string, (int, int)>
{
["ComputeSharp.D2D1.D2D1ResourceTexture1D.Width"] = (1, 0),
["ComputeSharp.D2D1.D2D1ResourceTexture2D.Width"] = (2, 0),
["ComputeSharp.D2D1.D2D1ResourceTexture2D.Height"] = (2, 1),
["ComputeSharp.D2D1.D2D1ResourceTexture3D.Width"] = (3, 0),
["ComputeSharp.D2D1.D2D1ResourceTexture3D.Height"] = (3, 1),
["ComputeSharp.D2D1.D2D1ResourceTexture3D.Depth"] = (3, 2)
};
}
}
+30 -1
ファイルの表示
@@ -1,4 +1,5 @@
using ComputeSharp.SourceGeneration.Extensions;
using System;
using ComputeSharp.SourceGeneration.Extensions;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGeneration.Mappings;
@@ -6,11 +7,39 @@ namespace ComputeSharp.SourceGeneration.Mappings;
/// <inheritdoc/>
partial class HlslKnownTypes
{
/// <summary>
/// Checks whether or not a given type name matches a resource texture type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a readonly typed resource type.</returns>
public static bool IsResourceTextureType(string typeName)
{
return typeName switch
{
"ComputeSharp.D2D1.D2D1ResourceTexture1D" or
"ComputeSharp.D2D1.D2D1ResourceTexture2D" or
"ComputeSharp.D2D1.D2D1ResourceTexture3D" => true,
_ => false
};
}
/// <inheritdoc/>
public static partial string GetMappedName(INamedTypeSymbol typeSymbol)
{
string typeName = typeSymbol.GetFullMetadataName();
// Special case for resource texture types
if (IsResourceTextureType(typeName))
{
return typeName switch
{
"ComputeSharp.D2D1.D2D1ResourceTexture1D" => "Texture1D",
"ComputeSharp.D2D1.D2D1ResourceTexture2D" => "Texture2D",
"ComputeSharp.D2D1.D2D1ResourceTexture3D" => "Texture3D",
_ => throw new ArgumentException()
};
}
// The captured field is of an HLSL primitive type
if (KnownHlslTypes.TryGetValue(typeName, out string? mappedType))
{
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
/// <summary>
/// A model representing an input description for a shader.
/// </summary>
/// <param name="Index">The index of the input resource the description if for.</param>
/// <param name="Index">The index of the input resource the description is for.</param>
/// <param name="Filter">The input filter to use.</param>
/// <param name="LevelOfDetail">The level of detail to use.</param>
internal sealed record InputDescription(uint Index, D2D1Filter Filter, int LevelOfDetail);
+1 -1
ファイルの表示
@@ -8,7 +8,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing gathered input descriptions for a shader.
/// </summary>
/// <param name="InputDescriptions">The input types for a given shader.</param>
/// <param name="InputDescriptions">The input descriptions for a given shader.</param>
internal sealed record InputDescriptionsInfo(ImmutableArray<InputDescription> InputDescriptions)
{
/// <summary>
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing a resource texture description for a shader.
/// </summary>
/// <param name="Index">The index of the resource texture resource the description is for.</param>
/// <param name="Rank">The rank of the resource texture.</param>
internal sealed record ResourceTextureDescription(uint Index, uint Rank);
+31
ファイルの表示
@@ -0,0 +1,31 @@
using System;
using System.Collections.Immutable;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing gathered resource texture descriptions for a shader.
/// </summary>
/// <param name="ResourceTextureDescriptions">The resource textures for the current shader.</param>
internal sealed record ResourceTextureDescriptionsInfo(ImmutableArray<ResourceTextureDescription> ResourceTextureDescriptions)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ResourceTextureDescriptionsInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<ResourceTextureDescriptionsInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, ResourceTextureDescriptionsInfo obj)
{
hashCode.AddRange(obj.ResourceTextureDescriptions);
}
/// <inheritdoc/>
protected override bool AreEqual(ResourceTextureDescriptionsInfo x, ResourceTextureDescriptionsInfo y)
{
return x.ResourceTextureDescriptions.SequenceEqual(y.ResourceTextureDescriptions);
}
}
}
+36 -2
ファイルの表示
@@ -66,9 +66,9 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
}
/// <summary>
/// Gets whether or not the shader needs the <c>[D2DRequiresPosition]</c> attribute.
/// Gets whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> attribute.
/// </summary>
public bool NeedsD2DRequiresPositionAttribute { get; protected set; }
public bool NeedsD2DRequiresScenePositionAttribute { get; protected set; }
/// <inheritdoc/>
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
@@ -247,6 +247,40 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
{
string propertyName = operation.Property.GetFullMetadataName();
// Rewrite texture resource indices taking individual indices a vector argument, as per HLSL spec.
// For instance: texture[ThreadIds.X, ThreadIds.Y] will be rewritten as texture[int2(ThreadIds.X, ThreadIds.Y)].
if (HlslKnownProperties.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping))
{
var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments));
return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index))));
}
// Rewrite texture resource sampled accesses, if needed
if (HlslKnownProperties.TryGetMappedResourceSamplerAccessType(propertyName, out mapping))
{
// Get the syntax for the argument syntax transformation as described above
ArgumentSyntax coordinateSyntax = mapping switch
{
not null => Argument(InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments))),
null => updatedNode.ArgumentList.Arguments[0]
};
string fieldName = (operation.Instance as IFieldReferenceOperation)?.Member.Name ?? "";
_ = HlslKnownKeywords.TryGetMappedName(fieldName, out string? mapped);
// Transform an indexer syntax into a sampling call with the implicit static linear sampler.
// For instance: texture[uv] will be rewritten as texture.Sample(__sampler__texture, uv).
return
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
updatedNode.Expression,
IdentifierName("Sample")))
.AddArgumentListArguments(Argument(IdentifierName($"__sampler__{mapped ?? fieldName}")), coordinateSyntax);
}
// If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite
// the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01.
if (HlslKnownProperties.IsKnownMatrixIndexer(propertyName))
+53 -3
ファイルの表示
@@ -264,6 +264,56 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter
false => updatedNode.WithName(IdentifierName(mapping!))
};
}
// If the current member access is an access to any of the size properties in the available
// resource types (either buffer or texture types), then rewrite the subtree to transform the
// property access into an invocation of an autogenerated static helper method to get the target
// dimension for the buffer in use. The helper method is added to the list of static helpers.
if (operation is IPropertyReferenceOperation propertyOperation &&
HlslKnownProperties.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis))
{
IMethodSymbol key = propertyOperation.Property.GetMethod!;
if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax))
{
INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.For(node).GetTypeInfo(node.Expression).Type!;
string resourceName = HlslKnownTypes.GetMappedName(resourceType);
// Create a static method to get a specified dimension for a target resource type.
// The method will automatically create the necessary number of temporary variables
// depending on the rank of the input resource (eg. 2 for Texture2D<T> resources).
// For instance, this code will generate the following tree for Texture2D<float>.Width:
//
// static int __get_Dimension0(Texture2D<float> texture)
// {
// uint _0, _1;
// texture.GetDimensions(_0, _1);
//
// return _0;
// }
methodSyntax =
MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}")
.AddModifiers(Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters(
Parameter(Identifier("resource"))
.WithType(IdentifierName(resourceName)))
.WithBody(Block(
LocalDeclarationStatement(
VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword)))
.AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())),
ExpressionStatement(
InvocationExpression(MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("resource"),
IdentifierName("GetDimensions")))
.AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())),
ReturnStatement(IdentifierName("_" + axis))));
this.staticMethods.Add(key, methodSyntax);
}
return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression));
}
}
return updatedNode;
@@ -285,10 +335,10 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter
// For instance: Math.Abs(expr) => abs(expr).
if (HlslKnownMethods.TryGetMappedName(metadataName, out string? mapping))
{
// Track whether the method needs [D2DRequiresPosition]
if (HlslKnownMethods.NeedsD2DRequiresPositionAttribute(metadataName))
// Track whether the method needs [D2DRequiresScenePosition]
if (HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName))
{
NeedsD2DRequiresPositionAttribute = true;
NeedsD2DRequiresScenePositionAttribute = true;
}
return updatedNode.WithExpression(ParseExpression(mapping!));
+2 -2
ファイルの表示
@@ -99,9 +99,9 @@ internal sealed class StaticFieldRewriter : HlslSourceRewriter
// Rewrite HLSL intrinsic methods
if (HlslKnownMethods.TryGetMappedName(metadataName, out string? mapping))
{
if (HlslKnownMethods.NeedsD2DRequiresPositionAttribute(metadataName))
if (HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName))
{
NeedsD2DRequiresPositionAttribute = true;
NeedsD2DRequiresScenePositionAttribute = true;
}
return updatedNode.WithExpression(ParseExpression(mapping!));
差分なしでファイル名を変更。
差分なしでファイル名を変更。
+28
ファイルの表示
@@ -0,0 +1,28 @@
using System;
namespace ComputeSharp.D2D1;
/// <summary>
/// An attribute for resource fields in a D2D1 shader indicating the index of the D2D1 resource texture.
/// This is needed to bind an input resource in a shader to the correct input. Using this attribute is mandatory.
/// </summary>
/// <remarks>
/// <para>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1effectauthor/nf-d2d1effectauthor-id2d1drawinfo-setresourcetexture"/>.</para>
/// </remarks>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public sealed class D2DResourceTextureIndexAttribute : Attribute
{
/// <summary>
/// Creates a new instance of the <see cref="D2DResourceTextureIndexAttribute"/> type with the specified arguments.
/// </summary>
/// <param name="index">The index of the annotated resource field.</param>
public D2DResourceTextureIndexAttribute(int index)
{
Index = index;
}
/// <summary>
/// Gets the index of the annotated resource field.
/// </summary>
public int Index { get; }
}
@@ -0,0 +1,18 @@
using System;
using System.ComponentModel;
namespace ComputeSharp.D2D1.__Internals;
/// <summary>
/// A base <see langword="interface"/> representing a loader for resource texture descriptions in a D2D1 shader.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This interface is not intended to be used directly by user code")]
public interface ID2D1ResourceTextureDescriptionsLoader
{
/// <summary>
/// Loads the available resource texture descriptions for the shader.
/// </summary>
/// <param name="data">The sequence of serialized resource texture descriptions.</param>
void LoadResourceTextureDescriptions(ReadOnlySpan<byte> data);
}
+10
ファイルの表示
@@ -55,6 +55,16 @@ public interface ID2D1Shader
void LoadInputDescriptions<TLoader>(ref TLoader loader)
where TLoader : struct, ID2D1InputDescriptionsLoader;
/// <summary>
/// Loads the resource texture descriptions for the shader, if any.
/// </summary>
/// <typeparam name="TLoader">The type of resource texture descriptions loader being used.</typeparam>
/// <param name="loader">The <typeparamref name="TLoader"/> instance to use to load the resource texture descriptions.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be used directly by user code")]
void LoadResourceTextureDescriptions<TLoader>(ref TLoader loader)
where TLoader : struct, ID2D1ResourceTextureDescriptionsLoader;
/// <summary>
/// Gets the output buffer precision and depth for the shader.
/// </summary>
+31
ファイルの表示
@@ -0,0 +1,31 @@
using ComputeSharp.Exceptions;
namespace ComputeSharp.D2D1;
/// <summary>
/// A <see langword="struct"/> representing a <see cref="Float4"/> readonly 1D texture stored on GPU memory.
/// This can be used from D2D1 pixel shaders to be able to pass arbitrary inputs to them.
/// </summary>
[AutoConstructorBehavior(AutoConstructorBehavior.IgnoreAndSetToDefault)]
public readonly struct D2D1ResourceTexture1D
{
/// <summary>
/// Gets the width of the current texture.
/// </summary>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public int Width => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture1D)}.{nameof(Width)}");
/// <summary>
/// Gets a single <see cref="Float4"/> value from the current readonly texture.
/// </summary>
/// <param name="x">The horizontal offset of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref readonly Float4 this[int x] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}[{typeof(int)}]");
/// <summary>
/// Gets a single <see cref="Float4"/> value from the current readonly texture with linear sampling.
/// </summary>
/// <param name="u">The horizontal normalized offset of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref readonly Float4 this[float u] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}[{typeof(float)}]");
}
+53
ファイルの表示
@@ -0,0 +1,53 @@
using ComputeSharp.Exceptions;
namespace ComputeSharp.D2D1;
/// <summary>
/// A <see langword="struct"/> representing a <see cref="Float4"/> readonly 2D texture stored on GPU memory.
/// This can be used from D2D1 pixel shaders to be able to pass arbitrary inputs to them.
/// </summary>
[AutoConstructorBehavior(AutoConstructorBehavior.IgnoreAndSetToDefault)]
public readonly struct D2D1ResourceTexture2D
{
/// <summary>
/// Gets the width of the current texture.
/// </summary>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public int Width => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}.{nameof(Width)}");
/// <summary>
/// Gets the height of the current texture.
/// </summary>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public int Height => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}.{nameof(Height)}");
/// <summary>
/// Gets a single <see cref="Float4"/> value from the current readonly texture.
/// </summary>
/// <param name="x">The horizontal offset of the value to get.</param>
/// <param name="y">The vertical offset of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref readonly Float4 this[int x, int y] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}[{typeof(int)}, {typeof(int)}]");
/// <summary>
/// Gets a single <see cref="Float4"/> value from the current readonly texture.
/// </summary>
/// <param name="xy">The coordinates of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref readonly Float4 this[Int2 xy] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}[{typeof(Int2)}]");
/// <summary>
/// Gets a single <see cref="Float4"/> value from the current readonly texture with linear sampling.
/// </summary>
/// <param name="u">The horizontal normalized offset of the value to get.</param>
/// <param name="v">The vertical normalized offset of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref readonly Float4 this[float u, float v] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}[{typeof(float)}, {typeof(float)}]");
/// <summary>
/// Gets a single <see cref="Float4"/> value from the current readonly texture with linear sampling.
/// </summary>
/// <param name="uv">The normalized coordinates of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref readonly Float4 this[Float2 uv] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture2D)}[{typeof(Float2)}]");
}
+61
ファイルの表示
@@ -0,0 +1,61 @@
using ComputeSharp.Exceptions;
namespace ComputeSharp.D2D1;
/// <summary>
/// A <see langword="struct"/> representing a <see cref="Float4"/> readonly 3D texture stored on GPU memory.
/// This can be used from D2D1 pixel shaders to be able to pass arbitrary inputs to them.
/// </summary>
[AutoConstructorBehavior(AutoConstructorBehavior.IgnoreAndSetToDefault)]
public readonly struct D2D1ResourceTexture3D
{
/// <summary>
/// Gets the width of the current texture.
/// </summary>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public int Width => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}.{nameof(Width)}");
/// <summary>
/// Gets the height of the current texture.
/// </summary>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public int Height => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}.{nameof(Height)}");
/// <summary>
/// Gets the depth of the current texture.
/// </summary>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public int Depth => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}.{nameof(Depth)}");
/// <summary>
/// Gets a single <see cref="Float4"/> value from the current readonly texture.
/// </summary>
/// <param name="x">The horizontal offset of the value to get.</param>
/// <param name="y">The vertical offset of the value to get.</param>
/// <param name="z">The depthwise offset of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref readonly Float4 this[int x, int y, int z] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}[{typeof(int)}, {typeof(int)}, {typeof(int)}]");
/// <summary>
/// Gets a single <see cref="Float4"/> value from the current readonly texture.
/// </summary>
/// <param name="xyz">The coordinates of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref readonly Float4 this[Int3 xyz] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}[{typeof(Int3)}]");
/// <summary>
/// Gets a single <see cref="Float4"/> value from the current readonly texture with linear sampling.
/// </summary>
/// <param name="u">The horizontal normalized offset of the value to get.</param>
/// <param name="v">The vertical normalized offset of the value to get.</param>
/// <param name="w">The depthwise offset of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref readonly Float4 this[float u, float v, float w] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}[{typeof(float)}, {typeof(float)}, {typeof(float)}]");
/// <summary>
/// Gets a single <see cref="Float4"/> value from the current readonly texture with linear sampling.
/// </summary>
/// <param name="uvw">The normalized coordinates of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref readonly Float4 this[Float3 uvw] => throw new InvalidExecutionContextException($"{typeof(D2D1ResourceTexture3D)}[{typeof(Float3)}]");
}
+1 -3
ファイルの表示
@@ -1,6 +1,4 @@
using System;
namespace ComputeSharp.D2D1.Interop;
namespace ComputeSharp.D2D1.Interop;
/// <summary>
/// A type containing info on a description for a given D2D1 pixel shader input resource.
+17
ファイルの表示
@@ -214,6 +214,23 @@ public static class D2D1PixelShader
return inputDescriptionsLoader.GetResultingInputDescriptions();
}
/// <summary>
/// Gets the available resource texture descriptions for a D2D1 pixel shader.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader to get the resource texture descriptions for.</typeparam>
/// <returns>A <see cref="ReadOnlyMemory{T}"/> with the available resource texture descriptions for the shader.</returns>
public static ReadOnlyMemory<D2D1ResourceTextureDescription> GetResourceTextureDescriptions<T>()
where T : unmanaged, ID2D1PixelShader
{
D2D1ByteArrayResourceTextureDescriptionsLoader resourceTextureDescriptionsLoader = default;
Unsafe.SkipInit(out T shader);
shader.LoadResourceTextureDescriptions(ref resourceTextureDescriptionsLoader);
return resourceTextureDescriptionsLoader.GetResultingResourceTextureDescriptions();
}
/// <summary>
/// Gets the buffer precision for the output buffer of a D2D1 pixel shader.
/// </summary>
+28
ファイルの表示
@@ -0,0 +1,28 @@
namespace ComputeSharp.D2D1.Interop;
/// <summary>
/// A type containing info on a description for a given D2D1 pixel shader resource resource.
/// </summary>
public readonly struct D2D1ResourceTextureDescription
{
/// <summary>
/// Creates a new <see cref="D2D1ResourceTextureDescription"/> instance with the specified parameters.
/// </summary>
/// <param name="index">The index of the resource texture the description belongs to.</param>
/// <param name="rank">The rank of the resource texture the description belongs to.</param>
internal D2D1ResourceTextureDescription(int index, int rank)
{
Index = index;
Rank = rank;
}
/// <summary>
/// Gets the index of the resource texture the description belongs to.
/// </summary>
public int Index { get; }
/// <summary>
/// Gets the rank of the resource texture the description belongs to.
/// </summary>
public int Rank { get; }
}
+1 -1
ファイルの表示
@@ -22,7 +22,7 @@ internal unsafe struct D2D1BufferSizeDispatchDataLoader : ID2D1DispatchDataLoade
/// </summary>
/// <returns>The size of the constant buffer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetConstantBufferSize()
private int GetConstantBufferSize()
{
return this.size;
}
+1 -2
ファイルの表示
@@ -3,7 +3,6 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.Interop;
using TerraFX.Interop.DirectX;
#pragma warning disable CS0618
@@ -15,7 +14,7 @@ namespace ComputeSharp.D2D1.Shaders.Loaders;
internal struct D2D1ByteArrayInputDescriptionsLoader : ID2D1InputDescriptionsLoader
{
/// <summary>
/// The <see cref="ID2D1DrawInfo"/> object in use.
/// The resulting <see cref="D2D1InputDescription"/> array.
/// </summary>
private D2D1InputDescription[]? inputDescriptions;
@@ -0,0 +1,36 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.Interop;
#pragma warning disable CS0618
namespace ComputeSharp.D2D1.Shaders.Loaders;
/// <summary>
/// A resource texture descriptions loader for D2D1 pixel shaders.
/// </summary>
internal struct D2D1ByteArrayResourceTextureDescriptionsLoader : ID2D1ResourceTextureDescriptionsLoader
{
/// <summary>
/// The resulting <see cref="D2D1ResourceTextureDescription"/> array.
/// </summary>
private D2D1ResourceTextureDescription[]? resourceTextureDescriptions;
/// <summary>
/// Gets the resulting resource texture descriptions.
/// </summary>
/// <returns>A <see cref="D2D1ResourceTextureDescription"/> array with the available resource texture descriptions.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public D2D1ResourceTextureDescription[] GetResultingResourceTextureDescriptions()
{
return this.resourceTextureDescriptions!;
}
/// <inheritdoc/>
void ID2D1ResourceTextureDescriptionsLoader.LoadResourceTextureDescriptions(ReadOnlySpan<byte> data)
{
this.resourceTextureDescriptions = MemoryMarshal.Cast<byte, D2D1ResourceTextureDescription>(data).ToArray();
}
}
+76
ファイルの表示
@@ -209,6 +209,39 @@ internal static partial class HlslKnownProperties
select $"{typeof(MatrixIndex).FullName}.{name}").ToImmutableHashSet();
}
/// <summary>
/// The mapping of supported known indexers to HLSL resource type names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownResourceIndexers = BuildKnownResourceIndexers();
/// <summary>
/// Builds the mapping of supported known indexers to HLSL resource type names.
/// </summary>
/// <returns>The mapping of supported known indexers to HLSL resource type names.</returns>
private static partial IReadOnlyDictionary<string, string> BuildKnownResourceIndexers();
/// <summary>
/// The mapping of supported known samplers to HLSL resource type names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string?> KnownResourceSamplers = BuildKnownResourceSamplers();
/// <summary>
/// Builds the mapping of supported known samplers to HLSL resource type names.
/// </summary>
/// <returns>The mapping of supported known samplers to HLSL resource type names.</returns>
private static partial IReadOnlyDictionary<string, string?> BuildKnownResourceSamplers();
/// <summary>
/// The mapping of supported known size accessors for HLSL resource types.
/// </summary>
private static readonly IReadOnlyDictionary<string, (int Rank, int Axis)> KnownSizeAccessors = BuildKnownSizeAccessors();
/// <summary>
/// Builds the mapping of supported known size accessors for HLSL resource types.
/// </summary>
/// <returns>The mapping of supported known size accessors for HLSL resource types.</returns>
private static partial IReadOnlyDictionary<string, (int Rank, int Axis)> BuildKnownSizeAccessors();
/// <summary>
/// Checks whether or not a given property fullname matches a matrix swizzled indexer.
/// </summary>
@@ -239,4 +272,47 @@ internal static partial class HlslKnownProperties
{
return KnownProperties.TryGetValue(name, out mapped);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible indexer resource type name for the input indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="mapped">The mapped type name, if one is found.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader for the given indexer.</returns>
public static bool TryGetMappedResourceIndexerTypeName(string name, out string? mapped)
{
return KnownResourceIndexers.TryGetValue(name, out mapped);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible sampler resource type name for the input indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="mapped">The mapped type name, if one is found.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader for the given sampler.</returns>
public static bool TryGetMappedResourceSamplerAccessType(string name, out string? mapped)
{
return KnownResourceSamplers.TryGetValue(name, out mapped);
}
/// <summary>
/// Tries to get the mapped rank and axis for a given indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="rank">The resulting indexer rank, if found.</param>
/// <param name="axis">The resulting indexer axis, if found.</param>
/// <returns>Whether or not a rank and axis could be resolved by the input indexer name.</returns>
public static bool TryGetAccessorRankAndAxis(string name, out int rank, out int axis)
{
if (KnownSizeAccessors.TryGetValue(name, out var info))
{
(rank, axis) = info;
return true;
}
(rank, axis) = default((int, int));
return false;
}
}
+23
ファイルの表示
@@ -8,6 +8,29 @@ namespace ComputeSharp.SourceGeneration.Extensions;
/// </summary>
internal static class AttributeDataExtensions
{
/// <summary>
/// Tries to get a constructor argument at a given index from the input <see cref="AttributeData"/> instance.
/// </summary>
/// <typeparam name="T">The type of constructor argument to retrieve.</typeparam>
/// <param name="attributeData">The target <see cref="AttributeData"/> instance to get the argument from.</param>
/// <param name="index">The index of the argument to try to retrieve.</param>
/// <param name="result">The resulting argument, if it was found.</param>
/// <returns>Whether or not an argument of type <typeparamref name="T"/> at position <paramref name="index"/> was found.</returns>
public static bool TryGetConstructorArgument<T>(this AttributeData attributeData, int index, out T? result)
{
if (attributeData.ConstructorArguments.Length >= index + 1 &&
attributeData.ConstructorArguments[index].Value is T argument)
{
result = argument;
return true;
}
result = default;
return false;
}
/// <summary>
/// Tries to get a given named argument value from an <see cref="AttributeData"/> instance, if present.
/// </summary>
+21
ファイルの表示
@@ -134,6 +134,27 @@ internal static class ISymbolExtensions
return symbol.GetFullMetadataName().Replace('`', '-').Replace('+', '.');
}
/// <summary>
/// Checks whether or not a given symbol has an attribute with the specified full name.
/// </summary>
/// <param name="symbol">The input <see cref="ISymbol"/> instance to check.</param>
/// <param name="name">The attribute name to look for.</param>
/// <returns>Whether or not <paramref name="symbol"/> has an attribute with the specified name.</returns>
public static bool HasAttributeWithFullyQualifiedName(this ISymbol symbol, string name)
{
ImmutableArray<AttributeData> attributes = symbol.GetAttributes();
foreach (AttributeData attribute in attributes)
{
if (attribute.AttributeClass?.HasFullyQualifiedName(name) == true)
{
return true;
}
}
return false;
}
/// <summary>
/// Tries to get an attribute with the specified full metadata name.
/// </summary>
+96
ファイルの表示
@@ -69,6 +69,32 @@ internal static class IncrementalValuesProviderExtensions
return source.WithComparer(new Comparer<T1, T2, T3, T4>(comparer1, comparer2, comparer3, comparer4));
}
/// <summary>
/// Creates a new <see cref="IncrementalValuesProvider{TValues}"/> instance with a gven pair of comparers.
/// </summary>
/// <typeparam name="T1">The type of first items in each tuple.</typeparam>
/// <typeparam name="T2">The type of second items in each tuple.</typeparam>
/// <typeparam name="T3">The type of third items in each tuple.</typeparam>
/// <typeparam name="T4">The type of fourth items in each tuple.</typeparam>
/// <typeparam name="T5">The type of fourth items in each tuple.</typeparam>
/// <param name="source">The input <see cref="IncrementalValuesProvider{TValues}"/> instance.</param>
/// <param name="comparer1">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T1"/> items.</param>
/// <param name="comparer2">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T2"/> items.</param>
/// <param name="comparer3">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T3"/> items.</param>
/// <param name="comparer4">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T4"/> items.</param>
/// <param name="comparer5">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T5"/> items.</param>
/// <returns>An <see cref="IncrementalValuesProvider{TValues}"/> with the specified comparers applied to each item.</returns>
public static IncrementalValuesProvider<(T1, T2, T3, T4, T5)> WithComparers<T1, T2, T3, T4, T5>(
this IncrementalValuesProvider<(T1, T2, T3, T4, T5)> source,
IEqualityComparer<T1> comparer1,
IEqualityComparer<T2> comparer2,
IEqualityComparer<T3> comparer3,
IEqualityComparer<T4> comparer4,
IEqualityComparer<T5> comparer5)
{
return source.WithComparer(new Comparer<T1, T2, T3, T4, T5>(comparer1, comparer2, comparer3, comparer4, comparer5));
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for a value tuple.
/// </summary>
@@ -224,4 +250,74 @@ internal static class IncrementalValuesProviderExtensions
this.comparer4.GetHashCode(obj.Item4));
}
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for a value tuple.
/// </summary>
public sealed class Comparer<T1, T2, T3, T4, T5> : IEqualityComparer<(T1, T2, T3, T4, T5)>
{
/// <summary>
/// The <typeparamref name="T1"/> comparer.
/// </summary>
private readonly IEqualityComparer<T1> comparer1;
/// <summary>
/// The <typeparamref name="T2"/> comparer.
/// </summary>
private readonly IEqualityComparer<T2> comparer2;
/// <summary>
/// The <typeparamref name="T3"/> comparer.
/// </summary>
private readonly IEqualityComparer<T3> comparer3;
/// <summary>
/// The <typeparamref name="T4"/> comparer.
/// </summary>
private readonly IEqualityComparer<T4> comparer4;
/// <summary>
/// The <typeparamref name="T5"/> comparer.
/// </summary>
private readonly IEqualityComparer<T5> comparer5;
/// <summary>
/// Creates a new <see cref="Comparer{T1, T2, T3, T4, T5}"/> instance with the specified parameters.
/// </summary>
/// <param name="comparer1">The <typeparamref name="T1"/> comparer.</param>
/// <param name="comparer2">The <typeparamref name="T2"/> comparer.</param>
/// <param name="comparer3">The <typeparamref name="T3"/> comparer.</param>
/// <param name="comparer4">The <typeparamref name="T4"/> comparer.</param>
/// <param name="comparer5">The <typeparamref name="T5"/> comparer.</param>
public Comparer(IEqualityComparer<T1> comparer1, IEqualityComparer<T2> comparer2, IEqualityComparer<T3> comparer3, IEqualityComparer<T4> comparer4, IEqualityComparer<T5> comparer5)
{
this.comparer1 = comparer1;
this.comparer2 = comparer2;
this.comparer3 = comparer3;
this.comparer4 = comparer4;
this.comparer5 = comparer5;
}
/// <inheritdoc/>
public bool Equals((T1, T2, T3, T4, T5) x, (T1, T2, T3, T4, T5) y)
{
return
this.comparer1.Equals(x.Item1, y.Item1) &&
this.comparer2.Equals(x.Item2, y.Item2) &&
this.comparer3.Equals(x.Item3, y.Item3) &&
this.comparer4.Equals(x.Item4, y.Item4) &&
this.comparer5.Equals(x.Item5, y.Item5);
}
/// <inheritdoc/>
public int GetHashCode((T1, T2, T3, T4, T5) obj)
{
return HashCode.Combine(
this.comparer1.GetHashCode(obj.Item1),
this.comparer2.GetHashCode(obj.Item2),
this.comparer3.GetHashCode(obj.Item3),
this.comparer4.GetHashCode(obj.Item4),
this.comparer5.GetHashCode(obj.Item5));
}
}
}
+67 -107
ファイルの表示
@@ -8,75 +8,78 @@ namespace ComputeSharp.SourceGeneration.Mappings;
/// <inheritdoc/>
partial class HlslKnownProperties
{
/// <summary>
/// The mapping of supported known indexers to HLSL resource type names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownResourceIndexers = new Dictionary<string, string>
/// <inheritdoc/>
private static partial IReadOnlyDictionary<string, string> BuildKnownResourceIndexers()
{
[$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.IReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.IReadWriteNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.IReadWriteNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3"
};
return new Dictionary<string, string>
{
[$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.IReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.IReadWriteNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.IReadWriteNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3"
};
}
/// <summary>
/// The mapping of supported known samplers to HLSL resource type names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string?> KnownResourceSamplers = new Dictionary<string, string?>
/// <inheritdoc/>
private static partial IReadOnlyDictionary<string, string?> BuildKnownResourceSamplers()
{
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2",
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(Float2).FullName}]"] = null,
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2",
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float2).FullName}]"] = null,
[$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2",
[$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(Float2).FullName}]"] = null,
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(Float3).FullName}]"] = null,
[$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
[$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(Float3).FullName}]"] = null,
[$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
[$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(Float3).FullName}]"] = null
};
return new Dictionary<string, string?>
{
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2",
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(Float2).FullName}]"] = null,
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2",
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float2).FullName}]"] = null,
[$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2",
[$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(Float2).FullName}]"] = null,
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(Float3).FullName}]"] = null,
[$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
[$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(Float3).FullName}]"] = null,
[$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
[$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(Float3).FullName}]"] = null
};
}
/// <summary>
/// The mapping of supported known size accessors for HLSL resource types.
/// </summary>
private static readonly IReadOnlyDictionary<string, (int Rank, int Axis)> KnownSizeAccessors = new Dictionary<string, (int, int)>
/// <inheritdoc/>
private static partial IReadOnlyDictionary<string, (int Rank, int Axis)> BuildKnownSizeAccessors()
{
["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0),
["ComputeSharp.Resources.Texture2D`1.Width"] = (2, 0),
["ComputeSharp.Resources.Texture2D`1.Height"] = (2, 1),
["ComputeSharp.Resources.Texture3D`1.Width"] = (3, 0),
["ComputeSharp.Resources.Texture3D`1.Height"] = (3, 1),
["ComputeSharp.Resources.Texture3D`1.Depth"] = (3, 2),
["ComputeSharp.IReadOnlyTexture2D`1.Width"] = (2, 0),
["ComputeSharp.IReadOnlyTexture2D`1.Height"] = (2, 1),
["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0),
["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1),
["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2),
["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Width"] = (2, 0),
["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Height"] = (2, 1),
["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Width"] = (3, 0),
["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Height"] = (3, 1),
["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Depth"] = (3, 2),
["ComputeSharp.IReadWriteNormalizedTexture2D`1.Width"] = (2, 0),
["ComputeSharp.IReadWriteNormalizedTexture2D`1.Height"] = (2, 1),
["ComputeSharp.IReadWriteNormalizedTexture3D`1.Width"] = (3, 0),
["ComputeSharp.IReadWriteNormalizedTexture3D`1.Height"] = (3, 1),
["ComputeSharp.IReadWriteNormalizedTexture3D`1.Depth"] = (3, 2)
};
return new Dictionary<string, (int, int)>
{
["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0),
["ComputeSharp.Resources.Texture2D`1.Width"] = (2, 0),
["ComputeSharp.Resources.Texture2D`1.Height"] = (2, 1),
["ComputeSharp.Resources.Texture3D`1.Width"] = (3, 0),
["ComputeSharp.Resources.Texture3D`1.Height"] = (3, 1),
["ComputeSharp.Resources.Texture3D`1.Depth"] = (3, 2),
["ComputeSharp.IReadOnlyTexture2D`1.Width"] = (2, 0),
["ComputeSharp.IReadOnlyTexture2D`1.Height"] = (2, 1),
["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0),
["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1),
["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2),
["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Width"] = (2, 0),
["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Height"] = (2, 1),
["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Width"] = (3, 0),
["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Height"] = (3, 1),
["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Depth"] = (3, 2),
["ComputeSharp.IReadWriteNormalizedTexture2D`1.Width"] = (2, 0),
["ComputeSharp.IReadWriteNormalizedTexture2D`1.Height"] = (2, 1),
["ComputeSharp.IReadWriteNormalizedTexture3D`1.Width"] = (3, 0),
["ComputeSharp.IReadWriteNormalizedTexture3D`1.Height"] = (3, 1),
["ComputeSharp.IReadWriteNormalizedTexture3D`1.Depth"] = (3, 2)
};
}
/// <inheritdoc/>
static partial void AddKnownProperties(IDictionary<string, string> knownProperties)
@@ -175,47 +178,4 @@ partial class HlslKnownProperties
}
}
}
/// <summary>
/// Tries to get the mapped HLSL-compatible indexer resource type name for the input indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="mapped">The mapped type name, if one is found.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader for the given indexer.</returns>
public static bool TryGetMappedResourceIndexerTypeName(string name, out string? mapped)
{
return KnownResourceIndexers.TryGetValue(name, out mapped);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible sampler resource type name for the input indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="mapped">The mapped type name, if one is found.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader for the given sampler.</returns>
public static bool TryGetMappedResourceSamplerAccessType(string name, out string? mapped)
{
return KnownResourceSamplers.TryGetValue(name, out mapped);
}
/// <summary>
/// Tries to get the mapped rank and axis for a given indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="rank">The resulting indexer rank, if found.</param>
/// <param name="axis">The resulting indexer axis, if found.</param>
/// <returns>Whether or not a rank and axis could be resolved by the input indexer name.</returns>
public static bool TryGetAccessorRankAndAxis(string name, out int rank, out int axis)
{
if (KnownSizeAccessors.TryGetValue(name, out var info))
{
(rank, axis) = info;
return true;
}
(rank, axis) = default((int, int));
return false;
}
}
+4 -4
ファイルの表示
@@ -41,7 +41,7 @@ partial class HlslKnownTypes
"ComputeSharp.ConstantBuffer`1" or
"ComputeSharp.ReadOnlyBuffer`1" or
"ComputeSharp.ReadWriteBuffer`1" => true,
_ => false,
_ => false
};
}
@@ -63,7 +63,7 @@ partial class HlslKnownTypes
"ComputeSharp.IReadOnlyTexture3D`1" => true,
"ComputeSharp.IReadOnlyNormalizedTexture2D`1" or
"ComputeSharp.IReadOnlyNormalizedTexture3D`1" => true,
_ => false,
_ => false
};
}
@@ -83,7 +83,7 @@ partial class HlslKnownTypes
"ComputeSharp.ReadWriteTexture3D`2" or
"ComputeSharp.IReadWriteNormalizedTexture2D`1" or
"ComputeSharp.IReadWriteNormalizedTexture3D`1" => true,
_ => false,
_ => false
};
}
@@ -113,7 +113,7 @@ partial class HlslKnownTypes
"ComputeSharp.IReadWriteNormalizedTexture2D`1" or
"ComputeSharp.IReadOnlyNormalizedTexture3D`1" or
"ComputeSharp.IReadWriteNormalizedTexture3D`1" => true,
_ => false,
_ => false
};
}
+67
ファイルの表示
@@ -169,6 +169,73 @@ public partial class D2D1PixelShaderTests
}
}
[TestMethod]
public unsafe void GetResourceTextureDescriptions_Empty()
{
Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions<CheckerboardClipEffect>().Length, 0);
Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions<InvertEffect>().Length, 0);
Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions<InvertWithThresholdEffect>().Length, 0);
Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions<PixelateEffect.Shader>().Length, 0);
Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions<ZonePlateEffect>().Length, 0);
Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions<ShaderWithMultipleInputs>().Length, 0);
Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions<EmptyShader>().Length, 0);
Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions<OnlyBufferPrecisionShader>().Length, 0);
Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions<OnlyChannelDepthShader>().Length, 0);
Assert.AreEqual(D2D1PixelShader.GetResourceTextureDescriptions<CustomBufferOutputShader>().Length, 0);
}
[TestMethod]
public unsafe void GetResourceTextureDescriptions_Custom()
{
ReadOnlyMemory<D2D1ResourceTextureDescription> resourceTextureDescriptions = D2D1PixelShader.GetResourceTextureDescriptions<ShaderWithResourceTextures>();
Assert.AreEqual(resourceTextureDescriptions.Length, 3);
ReadOnlySpan<D2D1ResourceTextureDescription> span = resourceTextureDescriptions.Span;
Assert.AreEqual(span[0].Index, 5);
Assert.AreEqual(span[0].Rank, 1);
Assert.AreEqual(span[1].Index, 6);
Assert.AreEqual(span[1].Rank, 2);
Assert.AreEqual(span[2].Index, 7);
Assert.AreEqual(span[2].Rank, 3);
}
[D2DInputCount(4)]
[D2DInputSimple(0)]
[D2DInputSimple(2)]
[D2DInputComplex(1)]
[D2DInputComplex(3)]
[AutoConstructor]
partial struct ShaderWithResourceTextures : ID2D1PixelShader
{
float number;
[D2DResourceTextureIndex(5)]
D2D1ResourceTexture1D myTexture1;
[D2DResourceTextureIndex(6)]
D2D1ResourceTexture2D myTexture2;
[D2DResourceTextureIndex(7)]
D2D1ResourceTexture3D myTexture3;
public Float4 Execute()
{
float4 pixel1 = myTexture1[0];
float4 pixel2 = myTexture1[0.4f];
float4 pixel3 = myTexture2[0, 1];
float4 pixel4 = myTexture2[0.4f, 0.3f];
float4 pixel5 = myTexture3[0, 1, 2];
float4 pixel6 = myTexture3[0.4f, 0.5f, 0.6f];
return 0;
}
}
[TestMethod]
public unsafe void GetBytecode_FromEmbeddedBytecode()
{