diff --git a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems index 3d8e7be8..0e93ea84 100644 --- a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems +++ b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems @@ -27,5 +27,6 @@ + \ No newline at end of file diff --git a/src/ComputeSharp.NetStandard/System/Threading.Tasks/TaskCompletionSource.cs b/src/ComputeSharp.NetStandard/System/Threading.Tasks/TaskCompletionSource.cs new file mode 100644 index 00000000..b90c0ddd --- /dev/null +++ b/src/ComputeSharp.NetStandard/System/Threading.Tasks/TaskCompletionSource.cs @@ -0,0 +1,15 @@ +namespace System.Threading.Tasks; + +/// +/// A polyfill type that mirrors the non-generic type on .NET 6. +/// +internal sealed class TaskCompletionSource : TaskCompletionSource +{ + /// + /// Transitions the underlying into the state. + /// + public void SetResult() + { + SetResult(null); + } +} diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 57eb469d..bfbb1376 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -22,6 +22,7 @@ + diff --git a/src/ComputeSharp/Graphics/Commands/CommandList.cs b/src/ComputeSharp/Graphics/Commands/CommandList.cs index e31c9241..61a69232 100644 --- a/src/ComputeSharp/Graphics/Commands/CommandList.cs +++ b/src/ComputeSharp/Graphics/Commands/CommandList.cs @@ -1,5 +1,6 @@ using System; using System.Runtime.CompilerServices; +using System.Threading.Tasks; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; @@ -9,7 +10,7 @@ namespace ComputeSharp.Graphics.Commands; /// /// A command list to set and execute operations on the GPU. /// -internal unsafe ref struct CommandList +internal unsafe struct CommandList : IDisposable { /// /// The instance associated with the current command list. @@ -138,7 +139,18 @@ internal unsafe ref struct CommandList this.device.ExecuteCommandList(ref this); } - /// + /// + /// Executes the commands in the current commands list, returns a . + /// + /// The to await for the operations to complete. + public ValueTask ExecuteAndWaitForCompletionAsync() + { + this.d3D12GraphicsCommandList.Get()->Close(); + + return this.device.ExecuteCommandListAsync(ref this); + } + + /// public void Dispose() { this.d3D12CommandAllocator.Dispose(); diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs new file mode 100644 index 00000000..1a1866d4 --- /dev/null +++ b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs @@ -0,0 +1,235 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using ComputeSharp.Core.Extensions; +using ComputeSharp.Graphics.Commands; +using ComputeSharp.Graphics.Commands.Interop; +using ComputeSharp.Interop; +using Microsoft.Toolkit.Diagnostics; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp; + +/// +unsafe partial class GraphicsDevice : NativeObject +{ +#if !NET6_0_OR_GREATER + /// + /// A delegate for a callback to pass to . + /// + /// The input context. + /// Whether the wait has timed out. + private delegate void WaitForSingleObjectCallbackDelegate(void* pContext, byte timedOut); + + /// + /// A cached instance wrapping . + /// + private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackWrapper = WaitForSingleObjectCallback; +#endif + + /// + /// Executes a given command list and waits for the operation to be completed. + /// + /// The input to execute. + internal void ExecuteCommandList(ref CommandList commandList) + { + ref readonly ID3D12CommandListPool commandListPool = ref Unsafe.NullRef(); + ID3D12CommandQueue* d3D12CommandQueue; + ID3D12Fence* d3D12Fence; + ref ulong d3D12FenceValue = ref Unsafe.NullRef(); + + // Get the target command queue, fence and pool for the list type + switch (commandList.D3D12CommandListType) + { + case D3D12_COMMAND_LIST_TYPE_COMPUTE: + commandListPool = ref this.computeCommandListPool; + d3D12CommandQueue = this.d3D12ComputeCommandQueue; + d3D12Fence = this.d3D12ComputeFence; + d3D12FenceValue = ref this.nextD3D12ComputeFenceValue; + break; + case D3D12_COMMAND_LIST_TYPE_COPY: + commandListPool = ref this.copyCommandListPool; + d3D12CommandQueue = this.d3D12CopyCommandQueue; + d3D12Fence = this.d3D12CopyFence; + d3D12FenceValue = ref this.nextD3D12CopyFenceValue; + break; + default: ThrowHelper.ThrowArgumentException(); return; + } + + // Execute the command list + d3D12CommandQueue->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf()); + +#if NET6_0_OR_GREATER + ulong updatedFenceValue = Interlocked.Increment(ref d3D12FenceValue); +#else + ulong updatedFenceValue = (ulong)Interlocked.Increment(ref Unsafe.As(ref d3D12FenceValue)); +#endif + + // Signal to the target fence with the updated value. Note that incrementing the + // target fence value to signal must be done after executing the command list. + d3D12CommandQueue->Signal(d3D12Fence, updatedFenceValue).Assert(); + + // If the fence value hasn't been reached, wait until the operation completes + if (updatedFenceValue > d3D12Fence->GetCompletedValue()) + { + d3D12Fence->SetEventOnCompletion(updatedFenceValue, default).Assert(); + } + + // Return the rented command list and command allocator so that they can be reused + commandListPool.Return(commandList.DetachD3D12CommandList(), commandList.DetachD3D12CommandAllocator()); + } + + /// + /// Executes a given command list and returns an awaitable for the operation to be completed. + /// + /// The input to execute. + /// The object representing the operation to wait for. + /// This method is only supported for compute operations. + internal ValueTask ExecuteCommandListAsync(ref CommandList commandList) + { + // Execute the command list + this.d3D12ComputeCommandQueue.Get()->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf()); + +#if NET6_0_OR_GREATER + ulong updatedFenceValue = Interlocked.Increment(ref this.nextD3D12ComputeFenceValue); +#else + ulong updatedFenceValue = (ulong)Interlocked.Increment(ref Unsafe.As(ref this.nextD3D12ComputeFenceValue)); +#endif + + // Signal to the target fence with the updated value. Note that incrementing the + // target fence value to signal must be done after executing the command list. + this.d3D12ComputeCommandQueue.Get()->Signal(this.d3D12ComputeFence.Get(), updatedFenceValue).Assert(); + + // If the fence value has been reached, complete synchronously + if (updatedFenceValue <= this.d3D12ComputeFence.Get()->GetCompletedValue()) + { + // Return the rented command list and command allocator so that they can be reused + this.computeCommandListPool.Return(commandList.DetachD3D12CommandList(), commandList.DetachD3D12CommandAllocator()); + +#if NET6_0_OR_GREATER + return ValueTask.CompletedTask; +#else + return new(Task.CompletedTask); +#endif + } + + // Setup the awaitable task + Task computeTask = WaitForFenceAsync( + updatedFenceValue, + this, + commandList.DetachD3D12CommandList(), + commandList.DetachD3D12CommandAllocator()); + + return new(computeTask); + } + + /// + /// A context to support . + /// + private struct CallbackContext + { + /// + /// The wrapping the object to signal completion. + /// + public GCHandle TaskCompletionSourceHandle; + + /// + /// The wrapping the instance in use. + /// + public GCHandle GraphicsDeviceHandle; + + /// + /// The used to queue the operations. + /// + public ID3D12GraphicsCommandList* D3D12GraphicsCommandList; + + /// + /// The object backing . + /// + public ID3D12CommandAllocator* D3D12CommandAllocator; + + /// + /// The event handle set when the target fence value is reached. + /// + public HANDLE EventHandle; + } + + /// + /// Asynchronously waits for a target fence value to be completed. + /// + /// The target fence value to wait for. + /// The instance executing the operations. + /// The used to queue the operations. + /// The object backing . + /// The object representing the operation to wait for. + /// This method is only supported for compute operations. + private static Task WaitForFenceAsync( + ulong d3D12FenceValue, + GraphicsDevice device, + ID3D12GraphicsCommandList* d3D12GraphicsCommandList, + ID3D12CommandAllocator* d3D12CommandAllocator) + { + HANDLE eventHandle = Windows.CreateEventW(null, Windows.FALSE, Windows.FALSE, null); + + device.d3D12ComputeFence.Get()->SetEventOnCompletion(d3D12FenceValue, eventHandle).Assert(); + + TaskCompletionSource taskCompletionSource = new(); + CallbackContext* callbackContext = (CallbackContext*)NativeMemory.Alloc((nuint)sizeof(CallbackContext)); + + callbackContext->TaskCompletionSourceHandle = GCHandle.Alloc(taskCompletionSource); + callbackContext->GraphicsDeviceHandle = GCHandle.Alloc(device); + callbackContext->D3D12GraphicsCommandList = d3D12GraphicsCommandList; + callbackContext->D3D12CommandAllocator = d3D12CommandAllocator; + callbackContext->EventHandle = eventHandle; + + HANDLE waitHandle; + + _ = Windows.RegisterWaitForSingleObject( + phNewWaitObject: &waitHandle, + hObject: eventHandle, +#if NET6_0_OR_GREATER + Callback: &WaitForSingleObjectCallback, +#else + Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackWrapper), +#endif + Context: callbackContext, + dwMilliseconds: Windows.INFINITE, + dwFlags: 0); + + return taskCompletionSource.Task; + } + + /// + /// The callback to signal the completion of a compute pipeline. + /// + /// The input context. + /// Whether the wait has timed out. + [UnmanagedCallersOnly] + private static void WaitForSingleObjectCallback(void* pContext, byte timedOut) + { + CallbackContext* callbackContext = (CallbackContext*)pContext; + + TaskCompletionSource taskCompletionSource = Unsafe.As(callbackContext->TaskCompletionSourceHandle.Target)!; + GraphicsDevice device = Unsafe.As(callbackContext->GraphicsDeviceHandle.Target)!; + ID3D12GraphicsCommandList* d3D12GraphicsCommandList = callbackContext->D3D12GraphicsCommandList; + ID3D12CommandAllocator* d3D12CommandAllocator = callbackContext->D3D12CommandAllocator; + HANDLE eventHandle = callbackContext->EventHandle; + + callbackContext->TaskCompletionSourceHandle.Free(); + callbackContext->GraphicsDeviceHandle.Free(); + + device.computeCommandListPool.Return(d3D12GraphicsCommandList, d3D12CommandAllocator); + + _ = Windows.CloseHandle(eventHandle); + + NativeMemory.Free(callbackContext); + + taskCompletionSource.SetResult(); + } +} diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index fd87c436..27fb32d7 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -1,9 +1,9 @@ using System.Diagnostics; using System.Runtime.CompilerServices; -using System.Threading; -using ComputeSharp.Core.Extensions; -using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Commands.Interop; +#if NET6_0_OR_GREATER +using ComputeSharp.Core.Extensions; +#endif using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; @@ -14,7 +14,6 @@ using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; using static TerraFX.Interop.DirectX.D3D12_FEATURE; using static TerraFX.Interop.DirectX.D3D12_FORMAT_SUPPORT1; using static TerraFX.Interop.DirectX.DXGI_ADAPTER_FLAG; - namespace ComputeSharp; /// @@ -347,58 +346,6 @@ public sealed unsafe partial class GraphicsDevice : NativeObject d3D12GraphicsCommandList->SetDescriptorHeaps(1, &d3D12DescriptorHeap); } - /// - /// Executes a given command list and waits for the operation to be completed. - /// - /// The input to execute. - internal void ExecuteCommandList(ref CommandList commandList) - { - ref readonly ID3D12CommandListPool commandListPool = ref Unsafe.NullRef(); - ID3D12CommandQueue* d3D12CommandQueue; - ID3D12Fence* d3D12Fence; - ref ulong d3D12FenceValue = ref Unsafe.NullRef(); - - // Get the target command queue, fence and pool for the list type - switch (commandList.D3D12CommandListType) - { - case D3D12_COMMAND_LIST_TYPE_COMPUTE: - commandListPool = ref this.computeCommandListPool; - d3D12CommandQueue = this.d3D12ComputeCommandQueue; - d3D12Fence = this.d3D12ComputeFence; - d3D12FenceValue = ref this.nextD3D12ComputeFenceValue; - break; - case D3D12_COMMAND_LIST_TYPE_COPY: - commandListPool = ref this.copyCommandListPool; - d3D12CommandQueue = this.d3D12CopyCommandQueue; - d3D12Fence = this.d3D12CopyFence; - d3D12FenceValue = ref this.nextD3D12CopyFenceValue; - break; - default: ThrowHelper.ThrowArgumentException(); return; - } - - // Execute the command list - d3D12CommandQueue->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf()); - -#if NET6_0_OR_GREATER - ulong updatedFenceValue = Interlocked.Increment(ref d3D12FenceValue); -#else - ulong updatedFenceValue = (ulong)Interlocked.Increment(ref Unsafe.As(ref d3D12FenceValue)); -#endif - - // Signal to the target fence with the updated value. Note that incrementing the - // target fence value to signal must be done after executing the command list. - d3D12CommandQueue->Signal(d3D12Fence, updatedFenceValue).Assert(); - - // If the fence value hasn't been reached, wait until the operation completes - if (updatedFenceValue > d3D12Fence->GetCompletedValue()) - { - d3D12Fence->SetEventOnCompletion(updatedFenceValue, default).Assert(); - } - - // Return the rented command list and command allocator so that they can be reused - commandListPool.Return(commandList.DetachD3D12CommandList(), commandList.DetachD3D12CommandAllocator()); - } - /// protected override void OnDispose() { diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs index 3ffb9935..c0be411d 100644 --- a/src/ComputeSharp/Shaders/ComputeContext.cs +++ b/src/ComputeSharp/Shaders/ComputeContext.cs @@ -1,5 +1,6 @@ using System; using System.Runtime.CompilerServices; +using System.Threading.Tasks; using ComputeSharp.__Internals; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; @@ -15,7 +16,7 @@ namespace ComputeSharp; /// /// A context to batch compute operations in a single invocation, minimizing GPU overhead. /// -public ref struct ComputeContext +public struct ComputeContext : IDisposable, IAsyncDisposable { /// /// The instance owning the current context. @@ -231,7 +232,7 @@ public ref struct ComputeContext commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, 1); } - /// + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { @@ -245,6 +246,24 @@ public ref struct ComputeContext this.commandList.ExecuteAndWaitForCompletion(); } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ValueTask DisposeAsync() + { + ThrowInvalidOperationExceptionIfDeviceIsNull(); + + if (!this.commandList.IsAllocated) + { +#if NET6_0_OR_GREATER + return ValueTask.CompletedTask; +#else + return new(Task.CompletedTask); +#endif + } + + return this.commandList.ExecuteAndWaitForCompletionAsync(); + } + /// /// Gets the current instance. /// diff --git a/src/TerraFX.Interop.Windows/TerraFX.Interop.Windows.projitems b/src/TerraFX.Interop.Windows/TerraFX.Interop.Windows.projitems index 69ea10d4..fd914b80 100644 --- a/src/TerraFX.Interop.Windows/TerraFX.Interop.Windows.projitems +++ b/src/TerraFX.Interop.Windows/TerraFX.Interop.Windows.projitems @@ -233,9 +233,11 @@ + + diff --git a/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs b/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs new file mode 100644 index 00000000..edd2d175 --- /dev/null +++ b/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs @@ -0,0 +1,18 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/synchapi.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System.Runtime.InteropServices; + +namespace TerraFX.Interop.Windows +{ + internal static unsafe partial class Windows + { + [DllImport("kernel32", ExactSpelling = true)] + public static extern BOOL RegisterWaitForSingleObject([NativeTypeName("PHANDLE")] HANDLE* phNewWaitObject, HANDLE hObject, [NativeTypeName("WAITORTIMERCALLBACK")] void* Callback, [NativeTypeName("PVOID")] void* Context, [NativeTypeName("ULONG")] uint dwMilliseconds, [NativeTypeName("ULONG")] uint dwFlags); + + [NativeTypeName("#define INFINITE 0xFFFFFFFF")] + public const uint INFINITE = 0xFFFFFFFF; + } +} diff --git a/src/TerraFX.Interop.Windows/Windows/um/handleapi/Windows.cs b/src/TerraFX.Interop.Windows/Windows/um/handleapi/Windows.cs new file mode 100644 index 00000000..3670f39e --- /dev/null +++ b/src/TerraFX.Interop.Windows/Windows/um/handleapi/Windows.cs @@ -0,0 +1,15 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/synchapi.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System.Runtime.InteropServices; + +namespace TerraFX.Interop.Windows +{ + internal static unsafe partial class Windows + { + [DllImport("kernel32", ExactSpelling = true)] + public static extern BOOL CloseHandle(HANDLE hObject); + } +} diff --git a/src/TerraFX.Interop.Windows/Windows/um/synchapi/Windows.cs b/src/TerraFX.Interop.Windows/Windows/um/synchapi/Windows.cs index 99a954d9..df33571b 100644 --- a/src/TerraFX.Interop.Windows/Windows/um/synchapi/Windows.cs +++ b/src/TerraFX.Interop.Windows/Windows/um/synchapi/Windows.cs @@ -9,6 +9,9 @@ namespace TerraFX.Interop.Windows { internal static unsafe partial class Windows { + [DllImport("kernel32", ExactSpelling = true)] + public static extern HANDLE CreateEventW([NativeTypeName("LPSECURITY_ATTRIBUTES")] SECURITY_ATTRIBUTES* lpEventAttributes, BOOL bManualReset, BOOL bInitialState, [NativeTypeName("LPCWSTR")] ushort* lpName); + [DllImport("kernel32", ExactSpelling = true)] [return: NativeTypeName("DWORD")] public static extern uint WaitForSingleObjectEx(HANDLE hHandle, [NativeTypeName("DWORD")] uint dwMilliseconds, BOOL bAlertable);