using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Commands; using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Renderer; 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 ShaderRunner { /// /// 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 ConstantBuffer GetVariablesBuffer(GraphicsDevice device) { ConditionalWeakTable> map = variablesBuffers ??= new(); return map.GetValue(device, static gpu => new(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 ShaderRunner 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(GraphicsDevice 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, in 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( GraphicsDevice device, int x, int y, int z, int threadsX, int threadsY, int threadsZ, in T shader) { device.ThrowIfDisposed(); // Create the shader key ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(in shader), threadsX, threadsY, threadsZ); CachedShader shaderData; PipelineData? pipelineData; lock (ShadersCache) { // Get or preload the shader if (!ShadersCache.TryGetValue(key, out shaderData)) { LoadShader(threadsX, threadsY, threadsZ, in 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 CommandList commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE); commandList.SetPipelineData(pipelineData); // Extract the dispatch data for the shader invocation using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in 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 ConstantBuffer variablesBuffer = ShaderRunner.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 CachedShader shaderData) { // Load the input shader ShaderLoader shaderLoader = ShaderLoader.Load(in shader); // Render the loaded shader using var shaderSource = HlslShaderRenderer.Render(threadsX, threadsY, threadsZ, shaderLoader); // Compile the loaded shader to HLSL bytecode IDxcBlobObject shaderBytecode = new(ShaderCompiler.CompileShader(shaderSource.WrittenSpan)); // Get the cached shader data shaderData = new CachedShader(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(GraphicsDevice device, in CachedShader shaderData, out PipelineData pipelineData) { using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12DescriptorRanges1); using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.Bytecode.D3D12ShaderBytecode); pipelineData = new PipelineData(d3D12RootSignature.Move(), d3D12PipelineState.Move()); shaderData.CachedPipelines.Add(device, pipelineData); } } }