using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.Graphics.Buffers; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Models; using TerraFX.Interop; namespace ComputeSharp.Shaders.Translation { /// internal sealed partial class ShaderLoader2 { /// /// A that loads all the captured members from a shader instance. /// /// The shader instance to load the data from. /// A reference to the buffer with all the captured instances. /// A reference to the buffer to use to store all the captured value types. private delegate void DispatchDataLoader(in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1); /// /// The number of captured graphics resources (buffers). /// private int totalResourceCount; /// /// The size in bytes of the buffer with the captured variables. /// /// Initially set to 3 values for X, Y and Z threads counts. private int totalVariablesByteSize = 3 * sizeof(int); /// /// 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 capturedMembers = new(); /// /// Gets a new instance with all the captured data for the current shader instance. /// /// 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 DispatchData2 GetDispatchData(in T shader, int x, int y, int z) { // Resources and variables buffers D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); byte[] variables = ArrayPool.Shared.Rent(this.totalVariablesByteSize); ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources); ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables); // Set the x, y and z counters Unsafe.As(ref r1) = x; Unsafe.Add(ref Unsafe.As(ref r1), 1) = y; Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; // Invoke the dynamic method to extract the captured data this.dispatchDataLoader!(shader, ref r0, ref r1); return new DispatchData2(resources, this.totalResourceCount, variables, this.totalVariablesByteSize); } /// /// Builds a new instance that loads the dispatch data for the current shader type. /// private void BuildDispatchDataLoader() { this.dispatchDataLoader = DynamicMethod.New(il => { foreach (ReadableMember member in this.capturedMembers) { if (HlslKnownTypes.IsKnownBufferType(member.MemberType)) { // Load the offset address into the resource buffers il.Emit(OpCodes.Ldarg_1); if (totalResourceCount > 0) { il.EmitAddOffset(this.totalResourceCount); } il.Emit(OpCodes.Ldarg_0); il.EmitReadMember(member); // Access Buffer.D3D12GpuDescriptorHandle FieldInfo gpuDescriptorInfo = member.MemberType.GetField( nameof(Buffer2.D3D12GpuDescriptorHandle), BindingFlags.NonPublic | BindingFlags.Instance)!; il.EmitReadMember(gpuDescriptorInfo); il.EmitStoreToAddress(member.MemberType); this.totalResourceCount++; } else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || HlslKnownTypes.IsKnownVectorType(member.MemberType)) { // Calculate the right offset with 16-bytes padding (HLSL constant buffer) int size = member.MemberType == typeof(bool) ? sizeof(uint) : Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL if (this.totalVariablesByteSize % 16 > 16 - size) { this.totalVariablesByteSize += 16 - this.totalVariablesByteSize % 16; } // Load the target address into the variables buffer il.Emit(OpCodes.Ldarg_2); il.EmitAddOffset(totalVariablesByteSize); this.totalVariablesByteSize += size; } else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}"); // Load the reference to the input delegate if the member is not static if (!member.IsStatic) { il.Emit(OpCodes.Ldarg_0); } // Read the current member and store it to the target address il.EmitReadMember(member); il.EmitStoreToAddress(member.MemberType); } il.Emit(OpCodes.Ret); }); } } }