From 124645fde152a3e4a8a93e0929f7b86bbe0f484d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 17 Nov 2020 13:37:58 +0100 Subject: [PATCH] Added TerraFX shader runner --- src/ComputeSharp.Shaders/ShaderRunner2{T}.cs | 204 ++++++++++++++++++ .../Translation/Models/CachedShader2{T}.cs | 42 ++++ 2 files changed, 246 insertions(+) create mode 100644 src/ComputeSharp.Shaders/ShaderRunner2{T}.cs create mode 100644 src/ComputeSharp.Shaders/Translation/Models/CachedShader2{T}.cs diff --git a/src/ComputeSharp.Shaders/ShaderRunner2{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner2{T}.cs new file mode 100644 index 00000000..f1a4d0d1 --- /dev/null +++ b/src/ComputeSharp.Shaders/ShaderRunner2{T}.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Commands; +using ComputeSharp.Shaders.Extensions; +using ComputeSharp.Shaders.Renderer; +using ComputeSharp.Shaders.Renderer.Models; +using ComputeSharp.Shaders.Translation; +using ComputeSharp.Shaders.Translation.Interop; +using ComputeSharp.Shaders.Translation.Models; +using TerraFX.Interop; +using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; + +namespace ComputeSharp.Shaders +{ + /// + /// A with helper methods to support . + /// This type is primarily needed to avoid having fields being repeated per generic instantiation. + /// + internal static class ShaderRunner2 + { + /// + /// A thread-safe map of reusable GPU buffers for captured locals. + /// + [ThreadStatic] + private static ConditionalWeakTable>? variablesBuffers; + + /// + /// Gets the reusable instance for a shader invocation. + /// + /// The to use to run the shader. + /// The reusable instance to populate. + [Pure] + public static ConstantBuffer2 GetVariablesBuffer(GraphicsDevice2 device) + { + ConditionalWeakTable> map = variablesBuffers ??= new(); + + return map.GetValue(device, gpu => new ConstantBuffer2(gpu, 4096)); + } + } + + /// + /// A responsible for performing all the necessary operations to compile and run a compute shader. + /// + /// The type of compute shader to run. + internal static class ShaderRunner2 + where T : struct, IComputeShader + { + /// + /// The mapping used to cache and reuse compiled shaders. + /// + private static readonly Dictionary> ShadersCache = new(); + + /// + /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// + /// The to use to run the shader. + /// 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. + /// The input instance representing the compute shader to run. + public static void Run(GraphicsDevice2 device, int x, int y, int z, in T shader) + { + // Calculate the optimized thread num values + int threadsX, threadsY = 1, threadsZ = 1; + if (y == 1 && z == 1) threadsX = (int)device.WavefrontSize; + else if (z == 1) threadsX = threadsY = 8; + else threadsX = threadsY = threadsZ = 4; + + Run(device, x, y, z, threadsX, threadsY, threadsZ, shader); + } + + /// + /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// + /// The to use to run the shader. + /// 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. + /// The number of threads in each thread group for the X axis. + /// The number of threads in each thread group for the Y axis. + /// The number of threads in each thread group for the Z axis. + /// The input instance representing the compute shader to run. + public static void Run( + GraphicsDevice2 device, + int x, int y, int z, + int threadsX, int threadsY, int threadsZ, + in T shader) + { + // Create the shader key + ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ); + CachedShader2 shaderData; + PipelineData? pipelineData; + + lock (ShadersCache) + { + // Get or preload the shader + if (!ShadersCache.TryGetValue(key, out shaderData)) + { + LoadShader(threadsX, threadsY, threadsZ, shader, out shaderData); + + // Cache for later use + ShadersCache.Add(key, shaderData); + } + + // Create the reusable pipeline state + if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineData)) + { + CreatePipelineData(device, shaderData, out pipelineData); + } + } + + // Create the commands list and set the pipeline state + using CommandList2 commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + commandList.SetPipelineData(pipelineData); + + // Extract the dispatch data for the shader invocation + using DispatchData2 dispatchData = shaderData.Loader.GetDispatchData(shader, x, y, z); + + // Load the captured buffers + ReadOnlySpan resources = dispatchData.Resources; + + for (int i = 0; i < resources.Length; i++) + { + commandList.SetComputeRootDescriptorTable(i + 1, resources[i]); + } + + // Initialize the loop targets and the captured values + ConstantBuffer2 variablesBuffer = ShaderRunner2.GetVariablesBuffer(device); + + variablesBuffer.SetData(dispatchData.Variables); + + commandList.SetComputeRootDescriptorTable(0, variablesBuffer.D3D12GpuDescriptorHandle); + + // Calculate the dispatch values + int + groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1), + groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1), + groupsZ = Math.DivRem(z, threadsZ, out int modZ) + (modZ == 0 ? 0 : 1); + + // Dispatch and wait for completion + commandList.Dispatch(groupsX, groupsY, groupsZ); + commandList.ExecuteAndWaitForCompletion(); + } + + /// + /// Loads a shader with the specified parameters. + /// + /// The number of threads in each thread group for the X axis. + /// The number of threads in each thread group for the Y axis. + /// The number of threads in each thread group for the Z axis. + /// The input instance representing the compute shader to run. + /// The instance to return with the cached shader data. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader2 shaderData) + { + // Load the input shader + ShaderLoader2 shaderLoader = ShaderLoader2.Load(shader); + + // Render the loaded shader + string shaderSource = ShaderRenderer.Instance.Render(new ShaderInfo + { + BuffersList = shaderLoader.HslsBuffersInfo, + FieldsList = shaderLoader.FieldsInfo, + NumThreadsX = threadsX, + NumThreadsY = threadsY, + NumThreadsZ = threadsZ, + ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName, + ShaderBody = shaderLoader.MethodBody, + FunctionsList = shaderLoader.FunctionsInfo, + LocalFunctionsList = shaderLoader.LocalFunctionsInfo + }); + + // Compile the loaded shader to HLSL bytecode + IDxcBlobObject shaderBytecode = new(ShaderCompiler2.CompileShader(shaderSource)); + + // Get the cached shader data + shaderData = new CachedShader2(shaderLoader, shaderBytecode); + } + + /// + /// Creates and caches a instance for a given shader. + /// + /// The to use to run the shader. + /// The instance with the data on the loaded shader. + /// The resulting instance to use to run the shader. + [MethodImpl(MethodImplOptions.NoInlining)] + private static unsafe void CreatePipelineData(GraphicsDevice2 device, in CachedShader2 shaderData, out PipelineData pipelineData) + { + using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12DescriptorRanges1); + + D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new((ID3DBlob*)shaderData.Bytecode.DxcBlob); + + using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), d3D12ShaderBytecode); + + pipelineData = new PipelineData(d3D12RootSignature.Move(), d3D12PipelineState.Move()); + + shaderData.CachedPipelines.Add(device, pipelineData); + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/Models/CachedShader2{T}.cs b/src/ComputeSharp.Shaders/Translation/Models/CachedShader2{T}.cs new file mode 100644 index 00000000..2e87756c --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/Models/CachedShader2{T}.cs @@ -0,0 +1,42 @@ +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Commands; +using ComputeSharp.Shaders.Translation.Interop; + +namespace ComputeSharp.Shaders.Translation.Models +{ + /// + /// A that contains info on a cached shader. + /// + /// The type of compute shader in use. + internal readonly struct CachedShader2 + where T : struct, IComputeShader + { + /// + /// The instance with the shader metadata. + /// + public readonly ShaderLoader2 Loader; + + /// + /// The compiled shader bytecode. + /// + public readonly IDxcBlobObject Bytecode; + + /// + /// The map of cached instances for each GPU in use. + /// + public readonly ConditionalWeakTable CachedPipelines; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance with the shader metadata. + /// The compiled shader bytecode. + public CachedShader2(ShaderLoader2 loader, IDxcBlobObject bytecode) + { + Loader = loader; + Bytecode = bytecode; + CachedPipelines = new(); + } + } +}