diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index 09cf2fd2..9d0b99e0 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -37,6 +37,11 @@ namespace ComputeSharp.Shaders Run(device, x, y, z, threadsX, threadsY, threadsZ, action); } + /// + /// The mapping used to cache and reuse compiled shaders + /// + private static readonly Dictionary<(Type type, int ThreadsX, int ThreadsY, int ThreadsZ), (ShaderLoader Loader, ShaderBytecode Bytecode)> ShadersCache = new Dictionary<(Type, int, int, int), (ShaderLoader, ShaderBytecode)>(); + /// /// Compiles and runs the input shader on a target instance, with the specified parameters /// @@ -60,42 +65,51 @@ namespace ComputeSharp.Shaders groupsY = y / threadsY + (y % threadsY == 0 ? 0 : 1), groupsZ = z / threadsZ + (z % threadsZ == 0 ? 0 : 1); - // Load the input shader - ShaderLoader shaderLoader = ShaderLoader.Load(action); - - // Render the loaded shader - ShaderInfo shaderInfo = new ShaderInfo + // Try to get the cache shader + var key = (action.Method.DeclaringType, threadsX, threadsY, threadsZ); + if (!ShadersCache.TryGetValue(key, out var shaderData)) { - BuffersList = shaderLoader.BuffersList, - FieldsList = shaderLoader.FieldsList, - NumThreadsX = threadsX, - NumThreadsY = threadsY, - NumThreadsZ = threadsZ, - ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName, - ShaderBody = shaderLoader.MethodBody - }; - string shaderSource = ShaderRenderer.Instance.Render(shaderInfo); + // Load the input shader + ShaderLoader shaderLoader = ShaderLoader.Load(action); - // Compile the loaded shader to HLSL bytecode - ShaderBytecode shaderBytecode = ShaderCompiler.Instance.CompileShader(shaderSource); + // Render the loaded shader + ShaderInfo shaderInfo = new ShaderInfo + { + BuffersList = shaderLoader.BuffersList, + FieldsList = shaderLoader.FieldsList, + NumThreadsX = threadsX, + NumThreadsY = threadsY, + NumThreadsZ = threadsZ, + ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName, + ShaderBody = shaderLoader.MethodBody + }; + string shaderSource = ShaderRenderer.Instance.Render(shaderInfo); + + // Compile the loaded shader to HLSL bytecode + ShaderBytecode shaderBytecode = ShaderCompiler.Instance.CompileShader(shaderSource); + + // Cache for later use + shaderData = (shaderLoader, shaderBytecode); + ShadersCache.Add(key, shaderData); + } // Create the root signature for the pipeline and get the pipeline state - RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, shaderLoader.RootParameters); + RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, shaderData.Loader.RootParameters); RootSignature rootSignature = device.CreateRootSignature(rootSignatureDescription); - PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode); + PipelineState pipelineState = new PipelineState(device, rootSignature, shaderData.Bytecode); // Create the commands list and set the pipeline state using CommandList commandList = new CommandList(device, CommandListType.Compute); commandList.SetPipelineState(pipelineState); // Load the captured buffers - foreach (var buffer in shaderLoader.Buffers) + foreach (var buffer in shaderData.Loader.GetBuffers(action)) { commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource); } // Initialize the loop targets - IReadOnlyList variables = new object[] { (uint)x, (uint)y, (uint)z }.Concat(shaderLoader.FieldValuesList).ToArray(); + IReadOnlyList variables = new object[] { (uint)x, (uint)y, (uint)z }.Concat(shaderData.Loader.GetVariables(action)).ToArray(); using GraphicsResource variablesBuffer = device.AllocateConstantBufferFromReflectedValues(variables); commandList.SetComputeRootDescriptorTable(0, variablesBuffer); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 3ac67495..4bbb7a80 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -26,21 +26,6 @@ namespace ComputeSharp.Shaders.Translation /// private readonly Action Action; - /// - /// The closure for the field - /// - private readonly Type ShaderType; - - /// - /// The closure instance for the field - /// - private readonly object ShaderInstance; - - /// - /// The sequence of fields in the targeted closure - /// - private readonly IReadOnlyList ShaderFields; - /// /// Creates a new with the specified parameters /// @@ -49,21 +34,39 @@ namespace ComputeSharp.Shaders.Translation { Action = action; ShaderType = action.Method.DeclaringType; - ShaderInstance = action.Target; - ShaderFields = ShaderType.GetFields().ToArray(); } + /// + /// Gets the closure for the field + /// + public Type ShaderType { get; } + /// /// Gets the array for the current shader /// public RootParameter[] RootParameters { get; private set; } - private readonly List<(int, GraphicsResource)> _Buffers = new List<(int, GraphicsResource)>(); + /// + /// The of instances mapping the captured buffers in the current shader + /// + private readonly List _BufferFields = new List(); /// /// Gets the ordered collection of buffers used as fields in the current shader /// - public IReadOnlyList<(int Index, GraphicsResource Resource)> Buffers => _Buffers; + /// The to use to build the shader + public IEnumerable<(int Index, GraphicsResource Resource)> GetBuffers(Action action) => _BufferFields.Select((field, i) => (i + 1, (GraphicsResource)field.GetValue(action.Target))); + + /// + /// The of instances mapping the captured scalar/vector variables in the current shader + /// + private readonly List _VariableFields = new List(); + + /// + /// Gets the collection of values of the captured fields for the current shader + /// + /// The to use to build the shader + public IEnumerable GetVariables(Action action) => _VariableFields.Select(field => field.GetValue(action.Target)); private readonly List _BuffersList = new List(); @@ -79,13 +82,6 @@ namespace ComputeSharp.Shaders.Translation /// public IReadOnlyList FieldsList => _FieldsList; - private readonly List _FieldValuesList = new List(); - - /// - /// Gets the collection of values of the captured fields for the current shader - /// - public IReadOnlyList FieldValuesList => _FieldValuesList; - /// /// Gets the name of the variable used as input for the shader method /// @@ -117,7 +113,8 @@ namespace ComputeSharp.Shaders.Translation /// private void LoadFieldsInfo() { - if (ShaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body"); + IReadOnlyList shaderFields = ShaderType.GetFields().ToArray(); + if (shaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body"); List descriptorRanges = new List(); int constantBuffersCount = 0; @@ -128,19 +125,18 @@ namespace ComputeSharp.Shaders.Translation descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount++)); // Inspect the captured fields - foreach (FieldInfo fieldInfo in ShaderFields) + foreach (FieldInfo fieldInfo in shaderFields) { Type fieldType = fieldInfo.FieldType; string fieldName = fieldInfo.Name; - object fieldValue = fieldInfo.GetValue(ShaderInstance); // Constant buffer if (HlslKnownTypes.IsConstantBufferType(fieldType)) { descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount)); - // Reference to the underlying buffer - _Buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue)); + // Track the buffer field + _BufferFields.Add(fieldInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); _BuffersList.Add(new ConstantBufferFieldInfo(typeName, fieldName, constantBuffersCount++)); @@ -150,8 +146,8 @@ namespace ComputeSharp.Shaders.Translation // Root parameter for a readonly buffer descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, readOnlyBuffersCount)); - // Reference to the underlying buffer - _Buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue)); + // Track the buffer field + _BufferFields.Add(fieldInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _BuffersList.Add(new ReadOnlyBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++)); @@ -161,8 +157,8 @@ namespace ComputeSharp.Shaders.Translation // Root parameter for a read write buffer descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, readWriteBuffersCount)); - // Reference to the underlying buffer - _Buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue)); + // Track the buffer field + _BufferFields.Add(fieldInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _BuffersList.Add(new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++)); @@ -170,7 +166,7 @@ namespace ComputeSharp.Shaders.Translation else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) { // Register the captured field - _FieldValuesList.Add(fieldValue); + _VariableFields.Add(fieldInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _FieldsList.Add(new CapturedFieldInfo(typeName, fieldName)); }