Merge pull request #617 from Sergio0694/dev/d3d12-generator-tweaks

Improve D3D12 generator and IShader public API
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-10-15 17:12:11 +02:00
コミット befe904d4f
19ファイル変更
+306 -256

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

@@ -96,7 +96,7 @@ partial class D2DPixelShaderDescriptorGenerator
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void AddAdditionalDataMemberUsingDirectives(D2D1ShaderInfo info, ImmutableHashSetBuilder<string> usingDirectives)
private static void AddAdditionalDataMemberUsingDirectives(D2D1ShaderInfo info, ImmutableHashSetBuilder<string> usingDirectives)
{
if (info.InputDescriptions.IsEmpty)
{
@@ -112,7 +112,7 @@ partial class D2DPixelShaderDescriptorGenerator
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional data members.</param>
public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks)
private static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks)
{
// If there are no input descriptions, there is nothing to di
if (info.InputDescriptions.IsEmpty)
+5 -24
ファイルの表示
@@ -12,21 +12,6 @@ namespace ComputeSharp.D2D1.Interop;
[StructLayout(LayoutKind.Sequential)]
public readonly struct D2D1InputDescription
{
/// <summary>
/// The index of the resource the description belongs to.
/// </summary>
private readonly int index;
/// <summary>
/// The type of filter to apply to the input texture.
/// </summary>
private readonly D2D1Filter filter;
/// <summary>
/// The mip level to retrieve from the upstream transform, if specified.
/// </summary>
private readonly int levelOfDetailCount;
/// <summary>
/// Creates a new <see cref="D2D1InputDescription"/> instance with the specified parameters.
/// </summary>
@@ -34,26 +19,22 @@ public readonly struct D2D1InputDescription
/// <param name="filter">The type of filter to apply to the input texture.</param>
public D2D1InputDescription(int index, D2D1Filter filter)
{
this.index = index;
this.filter = filter;
Index = index;
Filter = filter;
}
/// <summary>
/// Gets the index of the resource the description belongs to.
/// </summary>
public int Index => this.index;
public int Index { get; }
/// <summary>
/// Gets the type of filter to apply to the input texture.
/// </summary>
public D2D1Filter Filter => this.filter;
public D2D1Filter Filter { get; }
/// <summary>
/// Gets the mip level to retrieve from the upstream transform, if specified.
/// </summary>
public int LevelOfDetailCount
{
get => this.levelOfDetailCount;
init => this.levelOfDetailCount = value;
}
public int LevelOfDetailCount { get; init; }
}
+4 -15
ファイルの表示
@@ -8,17 +8,6 @@ namespace ComputeSharp.D2D1.Interop;
[StructLayout(LayoutKind.Sequential)]
public readonly struct D2D1ResourceTextureDescription
{
/// <summary>
/// The index of the resource texture the description belongs to.
/// </summary>
/// <remarks>See notes in <see cref="D2D1InputDescription"/> for why explicit fields are used here.</remarks>
private readonly int index;
/// <summary>
/// The number of dimensions of the resource texture the description belongs to.
/// </summary>
private readonly int dimensions;
/// <summary>
/// Creates a new <see cref="D2D1ResourceTextureDescription"/> instance with the specified parameters.
/// </summary>
@@ -26,17 +15,17 @@ public readonly struct D2D1ResourceTextureDescription
/// <param name="dimensions">The number of dimensions of the resource texture the description belongs to.</param>
public D2D1ResourceTextureDescription(int index, int dimensions)
{
this.index = index;
this.dimensions = dimensions;
Index = index;
Dimensions = dimensions;
}
/// <summary>
/// Gets the index of the resource texture the description belongs to.
/// </summary>
public int Index => this.index;
public int Index { get; }
/// <summary>
/// Gets the rank of the resource texture the description belongs to.
/// </summary>
public int Dimensions => this.dimensions;
public int Dimensions { get; }
}
+1 -1
ファイルの表示
@@ -104,7 +104,7 @@ public static class ReflectionServices
private static unsafe ShaderInfo GetNonGenericShaderInfo<T>(in T shader)
where T : struct, IShader
{
Unsafe.AsRef(in shader).BuildHlslSource(out string hlslSource);
string hlslSource = Unsafe.AsRef(in shader).HlslSource;
using ComPtr<IDxcBlob> dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(hlslSource);
+6 -11
ファイルの表示
@@ -19,17 +19,12 @@ partial class IShaderGenerator
{
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out string hlslSource)");
using (writer.WriteBlock())
{
writer.WriteLine("hlslSource =");
writer.IncreaseIndent();
writer.WriteLine("\"\"\"");
writer.Write(info.HlslInfoKey.HlslSource, isMultiline: true);
writer.WriteLine("\"\"\";");
writer.DecreaseIndent();
}
writer.WriteLine($"readonly string global::ComputeSharp.__Internals.IShader.HlslSource =>");
writer.IncreaseIndent();
writer.WriteLine("\"\"\"");
writer.Write(info.HlslInfoKey.HlslSource, isMultiline: true);
writer.WriteLine("\"\"\";");
writer.DecreaseIndent();
}
}
}
@@ -24,7 +24,7 @@ partial class IShaderGenerator
using (writer.WriteBlock())
{
writer.WriteLine($"global::System.Span<uint> span0 = stackalloc uint[{info.Root32BitConstantCount}];");
writer.WriteLine($"global::System.Span<uint> span0 = stackalloc uint[{info.ConstantBufferSizeInBytes}];");
writer.WriteLineIf($"global::System.Span<ulong> span1 = stackalloc ulong[{info.ResourceCount}];", info.ResourceCount > 0);
writer.WriteLine("ref uint r0 = ref span0[0];");
writer.WriteLineIf("ref ulong r1 = ref span1[0];", info.ResourceCount > 0);
+5 -5
ファイルの表示
@@ -27,16 +27,16 @@ partial class IShaderGenerator
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <param name="isPixelShaderLike">Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
/// <param name="root32BitConstantCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <returns>The sequence of <see cref="FieldInfo"/> instances for all captured resources and values.</returns>
public static ImmutableArray<FieldInfo> GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
ITypeSymbol structDeclarationSymbol,
bool isPixelShaderLike,
out int resourceCount,
out int root32BitConstantCount)
out int constantBufferSizeInBytes,
out int resourceCount)
{
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
static IEnumerable<FieldInfo> GetCapturedFieldInfos(
@@ -108,7 +108,7 @@ partial class IShaderGenerator
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
// enable loading all the dispatch data after reinterpreting it to a sequence of values
// of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
root32BitConstantCount = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int);
constantBufferSizeInBytes = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int);
// A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
// Loaded values in the root signature have the following costs:
@@ -118,7 +118,7 @@ partial class IShaderGenerator
// So here we check whether the current signature respects that constraint,
// and emit a build error otherwise. For more info on this, see the docs here:
// https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
int rootSignatureDwordSize = root32BitConstantCount + resourceCount;
int rootSignatureDwordSize = constantBufferSizeInBytes + resourceCount;
if (rootSignatureDwordSize > 64)
{
@@ -1,4 +1,3 @@
using System.Globalization;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGenerators.Models;
@@ -12,7 +11,31 @@ partial class IShaderGenerator
partial class LoadDispatchMetadata
{
/// <summary>
/// Writes the <c>LoadDispatchMetadata</c> method.
/// Writes the <c>ConstantBufferSize</c> property.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteConstantBufferSizeSyntax(ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine($"readonly int global::ComputeSharp.__Internals.IShader.ConstantBufferSize => {info.ConstantBufferSizeInBytes};");
}
/// <summary>
/// Writes the <c>IsStaticSamplerRequired</c> property.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteIsStaticSamplerRequiredSyntax(ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine($"readonly bool global::ComputeSharp.__Internals.IShader.IsStaticSamplerRequired => {info.IsSamplerUsed.ToString().ToLowerInvariant()};");
}
/// <summary>
/// Writes the <c>ResourceDescriptorRanges</c> property.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
@@ -20,32 +43,77 @@ partial class IShaderGenerator
{
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata<TLoader>(ref TLoader loader, out global::System.IntPtr result)");
writer.Write($"readonly global::System.ReadOnlyMemory<global::ComputeSharp.Interop.ResourceDescriptorRange> global::ComputeSharp.__Internals.IShader.ResourceDescriptorRanges => ");
using (writer.WriteBlock())
// If there are no declared resources, just return an empty collection
if (info.ResourceDescriptors.IsEmpty)
{
// Compute the total number of resources
int totalResourcesCount = info.ResourceDescriptors.Length;
writer.WriteLine("global::System.Span<byte> span0 = stackalloc byte[5];");
writer.WriteLine($"global::System.Span<global::ComputeSharp.__Internals.ResourceDescriptor> span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[{totalResourcesCount}];");
writer.WriteLine("ref byte r0 = ref span0[0];");
writer.WriteLine("ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];");
// Write the serialized shader metadata
writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<int>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {info.Root32BitConstantCount});");
writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<bool>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {info.IsSamplerUsed.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()});");
// Populate the sequence of resource descriptors
foreach (ResourceDescriptor descriptor in info.ResourceDescriptors)
{
writer.WriteLine($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));");
}
// Invoke the value delegate to create the opaque root signature handle
writer.WriteLine("loader.LoadMetadataHandle(span0, span1, out result);");
writer.WriteLine("default;");
}
else
{
writer.WriteLine("global::ComputeSharp.Generated.Data.ResourceDescriptorRanges;");
}
}
/// <summary>
/// Registers a callback to generate an additional data member, if needed.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional data members.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void RegisterAdditionalDataMemberSyntax(
ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> usingDirectives)
{
// If there are no declared resources, there is nothing to di
if (info.ResourceDescriptors.IsEmpty)
{
return;
}
usingDirectives.Add("global::System.CodeDom.Compiler");
usingDirectives.Add("global::System.Diagnostics");
usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
usingDirectives.Add("global::ComputeSharp.Interop");
// Declare the additional data type and the shared array with resource descriptor ranges
static void Callback(ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine($$"""/// <summary>""");
writer.WriteLine($$"""/// A container type for additional data needed by the shader.""");
writer.WriteLine($$"""/// </summary>""");
writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false);
writer.WriteLine($$"""file static class Data""");
using (writer.WriteBlock())
{
writer.WriteLine("""/// <summary>The singleton <see cref="ResourceDescriptorRange"/> array instance.</summary>""");
writer.WriteLine("""public static readonly ResourceDescriptorRange[] ResourceDescriptorRanges =""");
writer.WriteLine("""{""");
writer.IncreaseIndent();
// Initialize all resource descriptor ranges
writer.WriteInitializationExpressions(info.ResourceDescriptors.AsSpan(), static (description, writer) =>
{
string rangeTypeName = description.TypeId switch
{
0 => "ShaderResourceView",
1 => "UnorderedAccessView",
_ => "ConstantBufferView"
};
writer.Write($"new ResourceDescriptorRange(ResourceDescriptorRangeType.{rangeTypeName}, {description.Register})");
});
writer.DecreaseIndent();
writer.WriteLine();
writer.WriteLine("};");
}
}
callbacks.Add(Callback);
}
}
}
+4 -5
ファイルの表示
@@ -32,12 +32,11 @@ partial class IShaderGenerator
int constantBufferOffset = 1;
int readOnlyResourceOffset = 0;
int readWriteResourceOffset = 0;
int resourceOffset = 0;
// Add the implicit texture descriptor, if needed
if (isImplicitTextureUsed)
{
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++));
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++));
}
// Populate the sequence of resource descriptors
@@ -45,15 +44,15 @@ partial class IShaderGenerator
{
if (HlslKnownTypes.IsConstantBufferType(resource.TypeName))
{
descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++, resourceOffset++));
descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++));
}
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource.TypeName))
{
descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++, resourceOffset++));
descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++));
}
else
{
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++));
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++));
}
}
+9 -6
ファイルの表示
@@ -59,8 +59,8 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
diagnostics,
typeSymbol,
isPixelShaderLike,
out int resourceCount,
out int root32BitConstantCount);
out int root32BitConstantCount,
out int resourceCount);
token.ThrowIfCancellationRequested();
@@ -123,10 +123,10 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
ThreadsZ: threadsZ,
IsPixelShaderLike: isPixelShaderLike,
IsSamplerUsed: isSamplerUsed,
ConstantBufferSizeInBytes: root32BitConstantCount,
ResourceCount: resourceCount,
Fields: fieldInfos,
ResourceDescriptors: resourceDescriptors,
ResourceCount: resourceCount,
Root32BitConstantCount: root32BitConstantCount,
HlslInfoKey: hlslInfoKey,
HlslInfo: hlslInfo,
Diagnostcs: diagnostics.ToImmutable());
@@ -148,14 +148,17 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
declaredMembers.Add(LoadBytecode.WriteThreadsXSyntax);
declaredMembers.Add(LoadBytecode.WriteThreadsYSyntax);
declaredMembers.Add(LoadBytecode.WriteThreadsZSyntax);
declaredMembers.Add(LoadBytecode.WriteHlslBytecodeSyntax);
declaredMembers.Add(LoadDispatchData.WriteSyntax);
declaredMembers.Add(LoadDispatchMetadata.WriteConstantBufferSizeSyntax);
declaredMembers.Add(LoadDispatchMetadata.WriteIsStaticSamplerRequiredSyntax);
declaredMembers.Add(LoadDispatchMetadata.WriteSyntax);
declaredMembers.Add(BuildHlslSource.WriteSyntax);
declaredMembers.Add(LoadBytecode.WriteHlslBytecodeSyntax);
declaredMembers.Add(LoadDispatchData.WriteSyntax);
using ImmutableArrayBuilder<IndentedTextWriter.Callback<ShaderInfo>> additionalTypes = new();
using ImmutableHashSetBuilder<string> usingDirectives = new();
LoadDispatchMetadata.RegisterAdditionalDataMemberSyntax(item, additionalTypes, usingDirectives);
LoadBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
using IndentedTextWriter writer = new();
+2 -3
ファイルの表示
@@ -4,6 +4,5 @@ namespace ComputeSharp.SourceGenerators.Models;
/// A resource descriptor for a captured resource in a shader.
/// </summary>
/// <param name="TypeId">The type id for the resource.</param>
/// <param name="RegisterOffset">The offset of the resource in its containing register.</param>
/// <param name="Offset">The offset of the resource descriptor in the shader root signature.</param>
internal sealed record ResourceDescriptor(int TypeId, int RegisterOffset, int Offset);
/// <param name="Register">The register offset for the resource descriptor.</param>
internal sealed record ResourceDescriptor(int TypeId, int Register);
+4 -4
ファイルの表示
@@ -12,10 +12,10 @@ namespace ComputeSharp.SourceGenerators.Models;
/// <param name="ThreadsZ">The thread ids value for the Z axis.</param>
/// <param name="IsPixelShaderLike">Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.</param>
/// <param name="IsSamplerUsed">Whether or not the static sampler is used.</param>
/// /// <param name="ConstantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <param name="ResourceCount">The total number of captured resources in the shader.</param>
/// <param name="Fields">The description on shader instance fields.</param>
/// <param name="ResourceDescriptors">The sequence of resource descriptors for the shader.</param>
/// <param name="ResourceCount">The total number of captured resources in the shader.</param>
/// <param name="Root32BitConstantCount">The size of the shader root signature, in 32 bit constants.</param>
/// <param name="HlslInfoKey">The key with processed info on the shader.</param>
/// <param name="HlslInfo">The value with processed info on the shader.</param>
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
@@ -26,10 +26,10 @@ internal sealed record ShaderInfo(
int ThreadsZ,
bool IsPixelShaderLike,
bool IsSamplerUsed,
int ConstantBufferSizeInBytes,
int ResourceCount,
EquatableArray<FieldInfo> Fields,
EquatableArray<ResourceDescriptor> ResourceDescriptors,
int ResourceCount,
int Root32BitConstantCount,
HlslBytecodeInfoKey HlslInfoKey,
HlslBytecodeInfo HlslInfo,
EquatableArray<DiagnosticInfo> Diagnostcs);
-20
ファイルの表示
@@ -1,20 +0,0 @@
using System;
using System.ComponentModel;
namespace ComputeSharp.__Internals;
/// <summary>
/// A base <see langword="interface"/> representing a metadatadata loader for a shader being dispatched.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This interface is not intended to be used directly by user code")]
public interface IDispatchMetadataLoader
{
/// <summary>
/// Loads an opaque metadata handle from the given shader metadata.
/// </summary>
/// <param name="serializedMetadata">The serialized metadata for the current shader.</param>
/// <param name="resourceDescriptors">The sequence of resource descriptors for the current shader.</param>
/// <param name="result">The resulting opaque metadata handle.</param>
void LoadMetadataHandle(ReadOnlySpan<byte> serializedMetadata, ReadOnlySpan<ResourceDescriptor> resourceDescriptors, out IntPtr result);
}
+29 -19
ファイルの表示
@@ -1,5 +1,6 @@
using System;
using System.ComponentModel;
using ComputeSharp.Interop;
namespace ComputeSharp.__Internals;
@@ -25,6 +26,34 @@ public interface IShader
/// </summary>
int ThreadsZ { get; }
/// <summary>
/// Gets the size in bytes of the constant buffer for the current shader.
/// </summary>
/// <remarks>
/// Constant buffer data is bound to shaders via 32 bit root constants, and loaded before dispatching via
/// <see href="https://learn.microsoft.com/windows/win32/api/d3d12/nf-d3d12-id3d12graphicscommandlist-setcomputeroot32bitconstants"><c>ID3D12GraphicsCommandList::SetComputeRoot32BitConstants</c></see>,
/// so the size must be a multiple of 4.
/// </remarks>
int ConstantBufferSize { get; }
/// <summary>
/// Gets whether the shader requires a static sampler being declared and initialized.
/// </summary>
/// <remarks>
/// When requested, a static sampler with linear sampling and mirror addressing will be bound to <c>register(s)</c>.
/// </remarks>
bool IsStaticSamplerRequired { get; }
/// <summary>
/// Gets the resource descriptor ranges for all resources that should be bound to this shader.
/// </summary>
ReadOnlyMemory<ResourceDescriptorRange> ResourceDescriptorRanges { get; }
/// <summary>
/// Gets the HLSL source code for the current shader instance.
/// </summary>
string HlslSource { get; }
/// <summary>
/// Gets the HLSL bytecode for the current shader.
/// </summary>
@@ -43,23 +72,4 @@ public interface IShader
[Obsolete("This method is not intended to be called directly by user code")]
void LoadDispatchData<TLoader>(ref TLoader loader, GraphicsDevice device, int x, int y, int z)
where TLoader : struct, IDispatchDataLoader;
/// <summary>
/// Loads an opaque metadata handle from the metadata of the current shader.
/// </summary>
/// <typeparam name="TLoader">The type of data loader being used.</typeparam>
/// <param name="loader">The <typeparamref name="TLoader"/> instance to use to load the data.</param>
/// <param name="result">The resulting opaque metadata handle.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
void LoadDispatchMetadata<TLoader>(ref TLoader loader, out IntPtr result)
where TLoader : struct, IDispatchMetadataLoader;
/// <summary>
/// Builds the HLSL source code for the current shader instance.
/// </summary>
/// <param name="hlslSource">The resulting HLSL source.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
void BuildHlslSource(out string hlslSource);
}
+38
ファイルの表示
@@ -0,0 +1,38 @@
using System.Runtime.InteropServices;
namespace ComputeSharp.Interop;
/// <summary>
/// A type containing info on a descriptor for a given D3D12 shader resource range.
/// </summary>
/// <remarks>
/// This type exposes a subset of values from
/// <see href="https://learn.microsoft.com/windows/win32/api/d3d12/ns-d3d12-d3d12_descriptor_range1"><c>D3D12_DESCRIPTOR_RANGE1</c></see>.
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
public readonly struct ResourceDescriptorRange
{
/// <summary>
/// Creates a new <see cref="ResourceDescriptorRange"/> instance with the specified parameters.
/// </summary>
/// <param name="type">The type of the descriptor range.</param>
/// <param name="register">The shader register in the range.</param>
public ResourceDescriptorRange(ResourceDescriptorRangeType type, uint register)
{
Type = type;
Register = register;
}
/// <summary>
/// Gets the type of the descriptor range.
/// </summary>
public ResourceDescriptorRangeType Type { get; }
/// <summary>
/// Gets the shader register in the range.
/// </summary>
/// <remarks>
/// For example, for shader-resource views (SRVs), 3 maps to <c>register(t3)</c> in HLSL.
/// </remarks>
public uint Register { get; }
}
+28
ファイルの表示
@@ -0,0 +1,28 @@
using static TerraFX.Interop.DirectX.D3D12_DESCRIPTOR_RANGE_TYPE;
namespace ComputeSharp.Interop;
/// <summary>
/// A type containing info on a descriptor type for a given D3D12 shader resource range.
/// </summary>
/// <remarks>
/// This type exposes the available values in
/// <see href="https://learn.microsoft.com/windows/win32/api/d3d12/ne-d3d12-d3d12_descriptor_range_type"><c>D3D12_DESCRIPTOR_RANGE_TYPE</c></see>.
/// </remarks>
public enum ResourceDescriptorRangeType
{
/// <summary>
/// Specifies a range of SRVs.
/// </summary>
ShaderResourceView = D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
/// <summary>
/// Specifies a range of unordered-access views (UAVs).
/// </summary>
UnorderedAccessView = D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
/// <summary>
/// Specifies a range of constant-buffer views (CBVs).
/// </summary>
ConstantBufferView = D3D12_DESCRIPTOR_RANGE_TYPE_CBV
}
-50
ファイルの表示
@@ -1,50 +0,0 @@
using System;
using System.ComponentModel;
using TerraFX.Interop.DirectX;
using static TerraFX.Interop.DirectX.D3D12_DESCRIPTOR_RANGE_FLAGS;
#pragma warning disable IDE0052, IDE1006, CS0414
namespace ComputeSharp.__Internals;
/// <summary>
/// An opaque type describing a captured resource to be used in a shader.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This type is not intended to be used directly by user code")]
public struct ResourceDescriptor
{
/// <inheritdoc cref="D3D12_DESCRIPTOR_RANGE1.RangeType"/>
private D3D12_DESCRIPTOR_RANGE_TYPE RangeType;
/// <inheritdoc cref="D3D12_DESCRIPTOR_RANGE1.NumDescriptors"/>
private uint NumDescriptors;
/// <inheritdoc cref="D3D12_DESCRIPTOR_RANGE1.BaseShaderRegister"/>
private uint BaseShaderRegister;
/// <inheritdoc cref="D3D12_DESCRIPTOR_RANGE1.RegisterSpace"/>
private uint RegisterSpace;
/// <inheritdoc cref="D3D12_DESCRIPTOR_RANGE1.Flags"/>
private D3D12_DESCRIPTOR_RANGE_FLAGS Flags;
/// <inheritdoc cref="D3D12_DESCRIPTOR_RANGE1.OffsetInDescriptorsFromTableStart"/>
private uint OffsetInDescriptorsFromTableStart;
/// <summary>
/// Initializes a new <see cref="ResourceDescriptor"/> instance.
/// </summary>
/// <param name="type">The type of resource to create the descriptor for.</param>
/// <param name="offset">The offset in the resource from the start of the shader mapping.</param>
/// <param name="descriptor">The resulting <see cref="ResourceDescriptor"/> instance.</param>
public static void Create(int type, uint offset, out ResourceDescriptor descriptor)
{
descriptor.RangeType = (D3D12_DESCRIPTOR_RANGE_TYPE)type;
descriptor.NumDescriptors = 1;
descriptor.BaseShaderRegister = offset;
descriptor.RegisterSpace = 0;
descriptor.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE;
descriptor.OffsetInDescriptorsFromTableStart = D3D12.D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
}
}
-46
ファイルの表示
@@ -1,46 +0,0 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Shaders.Extensions;
using ComputeSharp.__Internals;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#pragma warning disable CS0618
namespace ComputeSharp.Shaders.Dispatching;
/// <summary>
/// A data loader for compute shaders.
/// </summary>
internal readonly unsafe struct ShaderDispatchMetadataLoader : IDispatchMetadataLoader
{
/// <summary>
/// The <see cref="ID3D12Device"/> object in use.
/// </summary>
private readonly ID3D12Device* d3D12Device;
/// <summary>
/// Creates a new <see cref="ShaderDispatchMetadataLoader"/> instance.
/// </summary>
/// <param name="d3D12Device">The <see cref="ID3D12Device"/> object to use.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ShaderDispatchMetadataLoader(ID3D12Device* d3D12Device)
{
this.d3D12Device = d3D12Device;
}
/// <inheritdoc/>
public unsafe void LoadMetadataHandle(ReadOnlySpan<byte> serializedMetadata, ReadOnlySpan<ResourceDescriptor> resourceDescriptors, out IntPtr result)
{
default(ArgumentException).ThrowIf(serializedMetadata.Length != 5, nameof(serializedMetadata));
fixed (IntPtr* p = &result)
{
*(ComPtr<ID3D12RootSignature>*)p = this.d3D12Device->CreateRootSignature(
MemoryMarshal.Read<int>(serializedMetadata),
MemoryMarshal.Cast<ResourceDescriptor, D3D12_DESCRIPTOR_RANGE1>(resourceDescriptors),
MemoryMarshal.Read<bool>(serializedMetadata.Slice(4)));
}
}
}
+75 -19
ファイルの表示
@@ -1,10 +1,12 @@
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using ComputeSharp.Shaders.Dispatching;
using ComputeSharp.Shaders.Extensions;
using ComputeSharp.Interop;
using ComputeSharp.__Internals;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using static TerraFX.Interop.DirectX.D3D12_DESCRIPTOR_RANGE_FLAGS;
#pragma warning disable CS0618
@@ -14,7 +16,7 @@ namespace ComputeSharp.Shaders.Loading;
/// A <see langword="class"/> responsible for performing all the necessary operations to compile and load shader data.
/// </summary>
/// <typeparam name="T">The type of compute shader to load.</typeparam>
internal static class PipelineDataLoader<T>
internal static unsafe class PipelineDataLoader<T>
where T : struct, IShader
{
/// <summary>
@@ -37,29 +39,17 @@ internal static class PipelineDataLoader<T>
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <returns>The resulting <see cref="PipelineData"/> instance to use to run the shader.</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe PipelineData CreatePipelineData(GraphicsDevice device)
private static PipelineData CreatePipelineData(GraphicsDevice device)
{
PipelineData pipelineData;
using (ComPtr<ID3D12RootSignature> d3D12RootSignature = default)
using (ComPtr<ID3D12PipelineState> d3D12PipelineState = default)
{
ShaderDispatchMetadataLoader metadataLoader = new(device.D3D12Device);
CreateD3D12RootSignature(device.D3D12Device, d3D12RootSignature.GetAddressOf());
CreateD3D12PipelineState(device.D3D12Device, d3D12RootSignature.Get(), d3D12PipelineState.GetAddressOf());
Unsafe.SkipInit(out T shader);
shader.LoadDispatchMetadata(ref metadataLoader, out *(IntPtr*)&d3D12RootSignature);
ReadOnlyMemory<byte> hlslBytecode = shader.HlslBytecode;
fixed (byte* hlslBytecodePtr = hlslBytecode.Span)
{
D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new(hlslBytecodePtr, (nuint)hlslBytecode.Length);
using ComPtr<ID3D12PipelineState> d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), d3D12ShaderBytecode);
pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get());
}
pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get());
}
// Add the pipeline to the cache for this type
@@ -70,4 +60,70 @@ internal static class PipelineDataLoader<T>
return pipelineData;
}
/// <summary>
/// Creates a D3D12 root signature for the current shader type.
/// </summary>
/// <param name="d3D12Device">The target <see cref="ID3D12Device"/> to use to create the root signature.</param>
/// <param name="d3D12RootSignature">The allocated <see cref="ID3D12RootSignature"/> instance.</param>
private static void CreateD3D12RootSignature(ID3D12Device* d3D12Device, ID3D12RootSignature** d3D12RootSignature)
{
Unsafe.SkipInit(out T shader);
ReadOnlySpan<ResourceDescriptorRange> resourceDescriptorRanges = shader.ResourceDescriptorRanges.Span;
D3D12_DESCRIPTOR_RANGE1[]? d3D12DescriptorRangesArray = null;
// Create the span and optional array of D3D12_DESCRIPTOR_RANGE1 objects
Span<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges = resourceDescriptorRanges.Length <= 8
? stackalloc D3D12_DESCRIPTOR_RANGE1[8]
: d3D12DescriptorRangesArray = ArrayPool<D3D12_DESCRIPTOR_RANGE1>.Shared.Rent(resourceDescriptorRanges.Length);
// Ensure the size has the right length to match the available descriptor ranges
d3D12DescriptorRanges = d3D12DescriptorRanges.Slice(0, resourceDescriptorRanges.Length);
// Initialize the D3D12_DESCRIPTOR_RANGE1 values from the shader descriptor ranges
for (int i = 0; i < resourceDescriptorRanges.Length; i++)
{
ref readonly ResourceDescriptorRange resourceDescriptorRange = ref resourceDescriptorRanges[i];
ref D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange = ref d3D12DescriptorRanges[i];
d3D12DescriptorRange.RangeType = (D3D12_DESCRIPTOR_RANGE_TYPE)resourceDescriptorRange.Type;
d3D12DescriptorRange.NumDescriptors = 1;
d3D12DescriptorRange.BaseShaderRegister = resourceDescriptorRange.Register;
d3D12DescriptorRange.RegisterSpace = 0;
d3D12DescriptorRange.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE;
d3D12DescriptorRange.OffsetInDescriptorsFromTableStart = D3D12.D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
}
// Create the D3D12 root signature
*d3D12RootSignature = d3D12Device->CreateRootSignature(
shader.ConstantBufferSize,
d3D12DescriptorRanges,
shader.IsStaticSamplerRequired).Get();
// Return the array to the pool if no exceptions have been thrown
if (d3D12DescriptorRangesArray is not null)
{
ArrayPool<D3D12_DESCRIPTOR_RANGE1>.Shared.Return(d3D12DescriptorRangesArray);
}
}
/// <summary>
/// Creates a D3D12 pipeline state for the current shader type.
/// </summary>
/// <param name="d3D12Device">The target <see cref="ID3D12Device"/> to use to create the root signature.</param>
/// <param name="d3D12RootSignature">The input <see cref="ID3D12RootSignature"/> value to use.</param>
/// <param name="d3D12PipelineState">The resulting <see cref="ID3D12PipelineState"/> instance.</param>
private static void CreateD3D12PipelineState(ID3D12Device* d3D12Device, ID3D12RootSignature* d3D12RootSignature, ID3D12PipelineState** d3D12PipelineState)
{
Unsafe.SkipInit(out T shader);
fixed (byte* hlslBytecodePtr = shader.HlslBytecode.Span)
{
D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new(hlslBytecodePtr, (nuint)shader.HlslBytecode.Length);
*d3D12PipelineState = d3D12Device->CreateComputePipelineState(d3D12RootSignature, d3D12ShaderBytecode);
}
}
}