From b386c237420d431de6d30398e2c23c2950b8f117 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Jul 2021 15:43:44 +0200 Subject: [PATCH] Switched library code to use new data loader pattern --- .../Backend/SwapChainApplication{T}.cs | 5 +- .../PixelShaderDispatchDataLoader.cs | 61 ++++++++++++ .../Shaders/Interop/ReflectionServices.cs | 13 ++- src/ComputeSharp/Shaders/ShaderRunner{T}.cs | 22 +---- .../Translation/Models/CachedShader{T}.cs | 5 +- .../Translation/Models/DispatchData.cs | 87 ----------------- .../ShaderLoader{T}.DispatchData.cs | 97 ------------------- .../Shaders/Translation/ShaderLoader{T}.cs | 16 +-- 8 files changed, 89 insertions(+), 217 deletions(-) create mode 100644 src/ComputeSharp/Shaders/Dispatching/PixelShaderDispatchDataLoader.cs delete mode 100644 src/ComputeSharp/Shaders/Translation/Models/DispatchData.cs delete mode 100644 src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs diff --git a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs index 26f4f0cf..c6c501f3 100644 --- a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs +++ b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs @@ -1,12 +1,15 @@ using System; +using ComputeSharp.__Internals; using ComputeSharp.Interop; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; +#pragma warning disable CS0618 + namespace ComputeSharp.SwapChain.Backend { internal sealed class SwapChainApplication : Win32Application - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader { /// /// The instance used to create shaders to run. diff --git a/src/ComputeSharp/Shaders/Dispatching/PixelShaderDispatchDataLoader.cs b/src/ComputeSharp/Shaders/Dispatching/PixelShaderDispatchDataLoader.cs new file mode 100644 index 00000000..43fa5455 --- /dev/null +++ b/src/ComputeSharp/Shaders/Dispatching/PixelShaderDispatchDataLoader.cs @@ -0,0 +1,61 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.__Internals; +using TerraFX.Interop; +using System.Runtime.InteropServices; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Shaders.Dispatching +{ + /// + /// A data loader for pixel shaders. + /// + internal readonly unsafe struct PixelShaderDispatchDataLoader : IDispatchDataLoader + { + /// + /// The object in use. + /// + private readonly ID3D12GraphicsCommandList* d3D12GraphicsCommandList; + + /// + /// Creates a new instance. + /// + /// The object to use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal PixelShaderDispatchDataLoader(ID3D12GraphicsCommandList* d3D12GraphicsCommandList) + { + this.d3D12GraphicsCommandList = d3D12GraphicsCommandList; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void LoadCapturedValues(ReadOnlySpan data) + { + this.d3D12GraphicsCommandList->SetComputeRoot32BitConstants(data); + } + + /// + public void LoadCapturedResources(ReadOnlySpan data) + { + ID3D12GraphicsCommandList* d3D12GraphicsCommandList = this.d3D12GraphicsCommandList; + ref ulong resourcesRef = ref MemoryMarshal.GetReference(data); + ref D3D12_GPU_DESCRIPTOR_HANDLE startRef = ref Unsafe.As(ref resourcesRef); + ref D3D12_GPU_DESCRIPTOR_HANDLE endRef = ref Unsafe.Add(ref startRef, data.Length); + uint offset = 2; + + // Skip the first target resource, as that is loaded explicitly by the shader runner using the + // target texture passed in by the user, which is not actually captured by the shader itself. + // The target root descriptor table index is therefore 2 in this case, as it needs to skip not + // only the this implicit texture to draw on, but also the constant buffer with capture values. + while (Unsafe.IsAddressLessThan(ref startRef, ref endRef)) + { + d3D12GraphicsCommandList->SetComputeRootDescriptorTable(offset, startRef); + + startRef = ref Unsafe.Add(ref startRef, 1); + offset++; + } + } + } +} diff --git a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs index 3a83b4f0..cdc099c0 100644 --- a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs +++ b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs @@ -1,11 +1,14 @@ using System; using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; using ComputeSharp.Core.Extensions; using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Translation; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; +#pragma warning disable CS0618 + namespace ComputeSharp.Interop { /// @@ -28,7 +31,7 @@ namespace ComputeSharp.Interop /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. /// public static void GetShaderInfo(out ShaderInfo shaderInfo) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { GetNonGenericShaderInfo(default(T), out shaderInfo); } @@ -45,7 +48,7 @@ namespace ComputeSharp.Interop /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. /// public static unsafe void GetShaderInfo(in T shader, out ShaderInfo shaderInfo) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { GetNonGenericShaderInfo(in shader, out shaderInfo); } @@ -66,7 +69,7 @@ namespace ComputeSharp.Interop /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. /// public static void GetShaderInfo(out ShaderInfo shaderInfo) - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader where TPixel : unmanaged { GetNonGenericShaderInfo(default(T), out shaderInfo); @@ -85,7 +88,7 @@ namespace ComputeSharp.Interop /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. /// public static unsafe void GetShaderInfo(in T shader, out ShaderInfo shaderInfo) - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader where TPixel : unmanaged { GetNonGenericShaderInfo(in shader, out shaderInfo); @@ -98,7 +101,7 @@ namespace ComputeSharp.Interop /// The input shader to retrieve info for. /// The resulting instance. private static unsafe void GetNonGenericShaderInfo(in T shader, out ShaderInfo shaderInfo) - where T : struct + where T : struct, IShader { ShaderLoader shaderLoader = ShaderLoader.Load(in shader); diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index a9cee52b..99bbd3aa 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Commands; -using ComputeSharp.Graphics.Extensions; using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Translation; @@ -189,13 +188,12 @@ namespace ComputeSharp.Shaders // Create the shader key ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, 1); - CachedShader shaderData; PipelineData? pipelineData; lock (ShadersCache) { // Get or preload the shader - if (!ShadersCache.TryGetValue(key, out shaderData)) + if (!ShadersCache.TryGetValue(key, out CachedShader shaderData)) { LoadShader(threadsX, threadsY, 1, in shader, out shaderData); @@ -216,29 +214,15 @@ namespace ComputeSharp.Shaders commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature); commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineData.D3D12PipelineState); - // Extract the dispatch data for the shader invocation - using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in shader, x, y, 1); + ComputeShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList); - // Initialize the loop targets and the captured values - commandList.D3D12GraphicsCommandList->SetComputeRoot32BitConstants(dispatchData.Variables); + shader.LoadDispatchData(in dataLoader, device, x, y, 1); // Load the implicit output texture commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable( 1, ((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuDescriptorHandle(device)); - // Skip the last (missing) resource, as the internal counter is exceeding the number of explicit - // resources that the shader has actually captured (since it includes the target texture too). - // For the same reason, the target root descriptor table index is also offset by 2, as it needs - // to skip not only the constant buffer with capture values, but the implicit texture as well. - ReadOnlySpan resources = dispatchData.Resources[..^1]; - - for (int i = 0; i < resources.Length; i++) - { - // Load the captured buffers - commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable((uint)i + 2, resources[i]); - } - // Dispatch and wait for completion commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, 1); commandList.ExecuteAndWaitForCompletion(); diff --git a/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs b/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs index 39558fb1..8a616cb5 100644 --- a/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs +++ b/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs @@ -1,7 +1,10 @@ using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; using ComputeSharp.Graphics.Commands; using ComputeSharp.Shaders.Translation.Interop; +#pragma warning disable CS0618 + namespace ComputeSharp.Shaders.Translation.Models { /// @@ -9,7 +12,7 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// The type of compute shader in use. internal readonly struct CachedShader - where T : struct + where T : struct, IShader { /// /// The instance with the shader metadata. diff --git a/src/ComputeSharp/Shaders/Translation/Models/DispatchData.cs b/src/ComputeSharp/Shaders/Translation/Models/DispatchData.cs deleted file mode 100644 index 249a3279..00000000 --- a/src/ComputeSharp/Shaders/Translation/Models/DispatchData.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Buffers; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using TerraFX.Interop; - -namespace ComputeSharp.Shaders.Translation.Models -{ - /// - /// A that contains all the captured data to dispatch a shader. - /// - internal readonly ref struct DispatchData - { - /// - /// The array (actually values) with the captured buffers. - /// - private readonly ulong[] resourcesArray; - - /// - /// The number of values in . - /// - private readonly int resourcesCount; - - /// - /// The array with all the captured variables, with proper padding. - /// - private readonly byte[] variablesArray; - - /// - /// The actual size in bytes to use from . - /// - private readonly int variablesByteSize; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The array with the captured buffers. - /// The number of instances in . - /// The array with all the captured variables, with proper padding. - /// The actual size in bytes to use from . - public DispatchData(ulong[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) - { - this.resourcesArray = resourcesArray; - this.variablesArray = variablesArray; - this.resourcesCount = resourcesCount; - this.variablesByteSize = variablesByteSize; - } - - /// - /// Gets a with all the captured buffers. - /// - public ReadOnlySpan Resources - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); - ref D3D12_GPU_DESCRIPTOR_HANDLE r1 = ref Unsafe.As(ref r0); - - return MemoryMarshal.CreateReadOnlySpan(ref r1, this.resourcesCount); - } - } - - /// - /// Gets a with the padded data representing all the captured variables. - /// - public unsafe ReadOnlySpan Variables - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray); - ref uint r1 = ref Unsafe.As(ref r0); - int length = (int)((uint)this.variablesByteSize / sizeof(uint)); - - return MemoryMarshal.CreateReadOnlySpan(ref r1, length); - } - } - - /// - public void Dispose() - { - ArrayPool.Shared.Return(this.resourcesArray); - ArrayPool.Shared.Return(this.variablesArray); - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs deleted file mode 100644 index 95c80c19..00000000 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using ComputeSharp.__Internals; -using ComputeSharp.Shaders.Translation.Models; -using TerraFX.Interop; - -#pragma warning disable CS0419, CS0618 - -namespace ComputeSharp.Shaders.Translation -{ - /// - internal sealed partial class ShaderLoader - { - /// - /// A that loads all the captured members from a shader instance. - /// - /// The to use to run the shader. - /// The shader instance to load the data from. - /// - /// A reference to the buffer with all the captured instances. - /// This is just represented as a reference, to avoid exposing the type publicly. - /// - /// A reference to the buffer to use to store all the captured value types. - /// The returned value indicates the total number of written bytes into . - private delegate int DispatchDataLoader(GraphicsDevice device, in T shader, ref ulong r0, ref byte r1); - - /// - /// The number of captured graphics resources (buffers). - /// - private int totalResourceCount; - - /// - /// The cached instance to load dispatch data before execution. - /// - private DispatchDataLoader? dispatchDataLoader; - - /// - /// The of instances mapping the captured variables in the current shader. - /// - private readonly List capturedFields = new(); - - /// - /// Gets a new instance with all the captured data for the current shader instance. - /// - /// The to use to run the shader. - /// The input instance representing the compute shader to run. - /// The number of iterations to run on the X axis. - /// The number of iterations to run on the Y axis. - /// The number of iterations to run on the Z axis. - [Pure] - public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z) - { - // Resources and variables buffers - ulong[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); - byte[] variables = ArrayPool.Shared.Rent(256); - - ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources); - ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables); - - // Set the x, y and (optionally) z counters - Unsafe.As(ref r1) = x; - Unsafe.Add(ref Unsafe.As(ref r1), 1) = y; - - if (IsComputeShader) - { - Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; - } - - // Invoke the dynamic method to extract the captured data - int totalVariablesByteSize = this.dispatchDataLoader!(device, in shader, ref r0, ref r1); - - return new(resources, this.totalResourceCount, variables, totalVariablesByteSize); - } - - /// - /// Initializes the instance that loads the dispatch data for the current shader type. - /// - private void InitializeDispatchDataLoader() - { - // Get the generated data loader - Type[] argumentTypes = new[] { typeof(GraphicsDevice), typeof(T).MakeByRefType(), typeof(ulong).MakeByRefType(), typeof(byte).MakeByRefType() }; - Type type = typeof(T).Assembly.GetType("ComputeSharp.__Internals.DispatchDataLoader")!; - MethodInfo method = type.GetMethod("LoadDispatchData", argumentTypes)!; - - // Extract the computed count of 32 bit root constants to load - D3D12Root32BitConstantsCount = ((ComputeRoot32BitConstantsAttribute)method.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count; - - // Create a delegate from the generated shader data loader - this.dispatchDataLoader = method.CreateDelegate(); - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs index a13586e1..39434980 100644 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs @@ -19,13 +19,18 @@ namespace ComputeSharp.Shaders.Translation /// /// The type of compute shader currently in use. internal sealed partial class ShaderLoader : IShaderLoader - where T : struct + where T : struct, IShader { /// /// The associated instance for the current shader type. /// private static readonly IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType(); + /// + /// The of instances mapping the captured variables in the current shader. + /// + private readonly List capturedFields = new(); + /// /// The number of constant buffers to define in the shader. /// @@ -151,8 +156,6 @@ namespace ComputeSharp.Shaders.Translation // the input shader once to avoid allocating it multiple times while processing the shader. @this.d3D12DescriptorRanges1 = @this.LoadFieldsInfo(shader); - @this.InitializeDispatchDataLoader(); - return @this; } @@ -173,6 +176,9 @@ namespace ComputeSharp.Shaders.Translation { this.definesInfo.Add(pair.Key, pair.Value); } + + // Extract the computed count of 32 bit root constants to load + D3D12Root32BitConstantsCount = ((ComputeRoot32BitConstantsAttribute)typeof(T).GetMethod(nameof(IShader.LoadDispatchData))!.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count; } /// @@ -200,7 +206,6 @@ namespace ComputeSharp.Shaders.Translation (string hlslType, string hlslName) = Attribute.ImplicitTextureField!.Value; this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); - this.totalResourceCount++; break; } @@ -251,7 +256,6 @@ namespace ComputeSharp.Shaders.Translation this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); - this.totalResourceCount++; } else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType)) { @@ -259,7 +263,6 @@ namespace ComputeSharp.Shaders.Translation this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); - this.totalResourceCount++; } else if (HlslKnownTypes.IsReadWriteResourceType(fieldType)) { @@ -267,7 +270,6 @@ namespace ComputeSharp.Shaders.Translation this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); - this.totalResourceCount++; } else if (fieldInfo.GetValue(shader) is Delegate func) {