From 80a2dc50aa32eb3afc97e01f31b2e8c48fea551b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 2 Jul 2022 03:53:16 +0200 Subject: [PATCH 01/64] Add DeviceLostReason enum type --- src/ComputeSharp/Graphics/DeviceLostReason.cs | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/ComputeSharp/Graphics/DeviceLostReason.cs diff --git a/src/ComputeSharp/Graphics/DeviceLostReason.cs b/src/ComputeSharp/Graphics/DeviceLostReason.cs new file mode 100644 index 00000000..3161ec7e --- /dev/null +++ b/src/ComputeSharp/Graphics/DeviceLostReason.cs @@ -0,0 +1,41 @@ +namespace ComputeSharp; + +/// +/// Indicates a reason a instance was lost. +/// +public enum DeviceLostReason +{ + /// + /// The application's device failed due to badly formed commands sent by the application. + /// This is an design-time issue that should be investigated and fixed. + /// + DeviceHung = unchecked((int)0x887A0006), + + /// + /// The video card has been physically removed from the system, or a driver upgrade for + /// the video card has occurred. The application should destroy and recreate the device. + /// + DeviceRemoved = unchecked((int)0x887A0005), + + /// + /// The device failed due to a badly formed command. This is a run-time issue. + /// The application should destroy and recreate the device. + /// + DeviceReset = unchecked((int)0x887A0007), + + /// + /// The driver encountered a problem and was put into the device removed state. + /// + DriverInternalError = unchecked((int)0x887A0020), + + /// + /// The application provided invalid parameter data. + /// This must be debugged and fixed before the application is released. + /// + InvalidCall = unchecked((int)0x887A0001), + + /// + /// The device was lost for an unspecified reason. + /// + UnspecifiedError = unchecked((int)0x80004005) +} From b81c140107870874a05c68f7c6462fd94c6d4d50 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 2 Jul 2022 03:53:34 +0200 Subject: [PATCH 02/64] Add GraphicsDevice.DeviceLost event --- src/ComputeSharp/Graphics/GraphicsDevice.cs | 79 ++++++++++++++++++++- 1 file changed, 78 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 616a888a..457c1eb6 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -1,5 +1,7 @@ -using System.Diagnostics; +using System; +using System.Diagnostics; using System.Runtime.CompilerServices; +using System.Threading; using CommunityToolkit.Diagnostics; using ComputeSharp.Graphics.Commands.Interop; #if NET6_0_OR_GREATER @@ -14,6 +16,7 @@ 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; /// @@ -84,6 +87,30 @@ public sealed unsafe partial class GraphicsDevice : NativeObject private ComPtr pool; #endif + /// + /// The reason the device was removed, if any. + /// + private HRESULT deviceRemovedReason; + + /// + /// Raised whenever the device is lost. + /// + /// + /// + /// "Device lost" refers to a situation where the GPU graphics device becomes unusable for further operations. This can occur + /// due to GPU hardware malfunction, driver bugs, driver software updates, or switching the app from one GPU to another. + /// + /// + /// A lost device can no longer be used, and any attempt to do so will throw an exception. To recover from + /// this situation, the app must create a new device and then recreate all its graphics resources. + /// + /// + /// This event will only be raised at most once for a given instance. Additionally, + /// the event is raised asynchronously with respect to the device being lost, and on a thread pool thread. + /// + /// + public event EventHandler? DeviceLost; + /// /// Creates a new instance for the input . /// @@ -346,6 +373,56 @@ public sealed unsafe partial class GraphicsDevice : NativeObject d3D12GraphicsCommandList->SetDescriptorHeaps(1, &d3D12DescriptorHeap); } + /// + /// Raises the event if needed. + /// + internal void RaiseDeviceLostEventIfNeeded() + { + if (IsDisposed) + { + return; + } + + // If the current device removed reason is not S_OK, it means the event + // has already been raised (but the device will keep reporting that reason). + // In that case, do nothing to avoid raising it again while the device is alive. + if (Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason)) != S.S_OK) + { + return; + } + + HRESULT result = this.d3D12Device.Get()->GetDeviceRemovedReason(); + + // Only raise the event once, and store the device removed reason to track it + if (Interlocked.CompareExchange( + ref Unsafe.As(ref this.deviceRemovedReason), + (int)result, + S.S_OK) == S.S_OK) + { + ThreadPool.QueueUserWorkItem(static state => ((GraphicsDevice)state!).RaiseDeviceLostEvent(), this); + } + } + + /// + /// Raises the event. + /// + private void RaiseDeviceLostEvent() + { + HRESULT result = Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason)); + + DeviceLostReason reason = (int)result switch + { + DXGI.DXGI_ERROR_DEVICE_HUNG => DeviceLostReason.DeviceHung, + DXGI.DXGI_ERROR_DEVICE_REMOVED => DeviceLostReason.DeviceRemoved, + DXGI.DXGI_ERROR_DEVICE_RESET => DeviceLostReason.DeviceReset, + DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR => DeviceLostReason.DriverInternalError, + DXGI.DXGI_ERROR_INVALID_CALL => DeviceLostReason.InvalidCall, + _ => DeviceLostReason.UnspecifiedError + }; + + DeviceLost?.Invoke(this, reason); + } + /// protected override void OnDispose() { From 7ed91b32d96ebb6a893070a4a2eb876fc26d6992 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 2 Jul 2022 03:53:51 +0200 Subject: [PATCH 03/64] Add logic to raise GraphicsDevice.DeviceLost in case of errors --- .../Extensions/Interop/HResultExtensions.cs | 21 ++++++++++++++++++- .../Helpers/DeviceHelper.ID3D12InfoQueue.cs | 21 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs index 403dc0ba..010957c9 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs @@ -39,7 +39,26 @@ internal static class HResultExtensions { if (result < 0) { - ThrowHelper.ThrowWin32Exception(result); + // This method just throws the exception from the helper below, which includes the + // additional logic for the device lost events. This structure ensures this method + // only has a single basic block, so it can be identified as a throw helper and + // imported properly, which results in better codegen. + static void RaiseDeviceLostEventsAndThrowWin32Exception(int result) + { + throw RaiseDeviceLostEventsAndGetWin32Exception(result); + } + + // Raises all device lost events, if needed, and then creates the Win32Exception to throw. + // This method is never inlined, which is needed to make handling the throw helper easier. + [MethodImpl(MethodImplOptions.NoInlining)] + static Win32Exception RaiseDeviceLostEventsAndGetWin32Exception(int result) + { + DeviceHelper.RaiseAllDeviceLostEventsIfNeeded(); + + return new Win32Exception(result); + } + + RaiseDeviceLostEventsAndThrowWin32Exception(result); } } else diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs index 6a818106..dff79a89 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs @@ -180,4 +180,25 @@ partial class DeviceHelper return hasErrorsOrWarnings; } + + /// + /// Raises the event if needed, on all existing devices. + /// + public static void RaiseAllDeviceLostEventsIfNeeded() + { + lock (DevicesCache) + { + foreach (GraphicsDevice device in DevicesCache.Values) + { + // Check whether the device was lost, and raise the event once. This method will + // queue the event being raised on a thread pool thread, which is crucial to avoid + // invoking the handlers while taking a lock on the devices cache. Doing so would + // lead to issues if a handler tried to synchronously create a new device, which would + // take the same lock (it's reentrant) and then add the new device to the cache. Then + // once this method resumed, the collection would be invalid, and the foreach loop + // would throw an exception on the next iteration. This will prevent that from happening. + device.RaiseDeviceLostEventIfNeeded(); + } + } + } } From 2317ac8423911fc63c7c31cd4b59d6db11b7c274 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 2 Jul 2022 13:25:05 +0200 Subject: [PATCH 04/64] Remove unnecessary references from DisableDynamicCompilation tests --- ...omputeSharp.Tests.DisableDynamicCompilation.csproj | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/tests/ComputeSharp.Tests.DisableDynamicCompilation/ComputeSharp.Tests.DisableDynamicCompilation.csproj b/tests/ComputeSharp.Tests.DisableDynamicCompilation/ComputeSharp.Tests.DisableDynamicCompilation.csproj index 7f7bae0f..9200052c 100644 --- a/tests/ComputeSharp.Tests.DisableDynamicCompilation/ComputeSharp.Tests.DisableDynamicCompilation.csproj +++ b/tests/ComputeSharp.Tests.DisableDynamicCompilation/ComputeSharp.Tests.DisableDynamicCompilation.csproj @@ -11,7 +11,6 @@ - @@ -21,16 +20,6 @@ - - - - - - - $(NoWarn);CS0649 - - From 15682c44e652003d1ceb5c7ed9cdf58080a1e63f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 2 Jul 2022 13:58:09 +0200 Subject: [PATCH 05/64] Ensure DeviceLost event is also raised in debug mode --- .../Graphics/Extensions/Interop/HResultExtensions.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs index 010957c9..1e4f4099 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs @@ -71,11 +71,15 @@ internal static class HResultExtensions if (result < 0) { + DeviceHelper.RaiseAllDeviceLostEventsIfNeeded(); + ThrowHelper.ThrowWin32Exception(result); } if (hasErrorsOrWarnings) { + DeviceHelper.RaiseAllDeviceLostEventsIfNeeded(); + ThrowHelper.ThrowWin32Exception("Warning or error detected by ID3D12InfoQueue."); } } From ea81ce27f93b5ffa2a85d60011d0833c1c158430 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 2 Jul 2022 14:09:40 +0200 Subject: [PATCH 06/64] Add device lost unit tests --- ComputeSharp.sln | 15 ++++ .../ComputeSharp.Tests.DeviceLost.csproj | 34 +++++++ .../DeviceLostTests.cs | 88 +++++++++++++++++++ 3 files changed, 137 insertions(+) create mode 100644 tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj create mode 100644 tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 06fd1a98..54268e97 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -122,6 +122,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ComputeSharp.NuGet", "Compu tests\ComputeSharp.NuGet\Program.cs = tests\ComputeSharp.NuGet\Program.cs EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Tests.DeviceLost", "tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj", "{5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -444,6 +446,18 @@ Global {14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|ARM64.Build.0 = Release|Any CPU {14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|x64.ActiveCfg = Release|Any CPU {14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|x64.Build.0 = Release|Any CPU + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Debug|ARM64.Build.0 = Debug|Any CPU + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Debug|x64.ActiveCfg = Debug|Any CPU + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Debug|x64.Build.0 = Debug|Any CPU + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Release|Any CPU.Build.0 = Release|Any CPU + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Release|ARM64.ActiveCfg = Release|Any CPU + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Release|ARM64.Build.0 = Release|Any CPU + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Release|x64.ActiveCfg = Release|Any CPU + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -475,6 +489,7 @@ Global {CBA545B4-31EF-4E9F-A1A8-2A1290B54046} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} {C0B903AA-F32C-4760-B4B6-199AC4FE1C5A} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} {E3403F19-A0D8-4317-8A54-322C7A13F2A2} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} + {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj b/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj new file mode 100644 index 00000000..8fe2d777 --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj @@ -0,0 +1,34 @@ + + + + net472;netcoreapp3.1;net6.0 + false + AnyCPU;x64;ARM64 + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs new file mode 100644 index 00000000..6f830d1f --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs @@ -0,0 +1,88 @@ +using System.ComponentModel; +using System.Threading.Tasks; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests.DeviceLost; + +[TestClass] +[TestCategory("DeviceLost")] +public partial class DeviceLostTests +{ + [CombinatorialTestMethod] + [AllDevices] + public async Task DeviceLost_RaiseEvent(Device device) + { + GraphicsDevice graphicsDevice = device.Get(); + + bool win32ExceptionThrown = false; + TaskCompletionSource<(object? Sender, DeviceLostReason Reason)> tcs = new(); + + // Register the device lost callback + graphicsDevice.DeviceLost += (s, e) => tcs.SetResult((s, e)); + + try + { + using ReadOnlyBuffer bufferA = graphicsDevice.AllocateReadOnlyBuffer(128); + using ReadWriteBuffer bufferB = graphicsDevice.AllocateReadWriteBuffer(128); + + graphicsDevice.For(128, new ComputeShaderGettingStuck(bufferA, bufferB, 12345678, 87654321, 42)); + + // The shader above will always hang, but it's not guaranteed that the DirectX runtime will detect + // the error right when executing that command. As such, we can force it to be detected by running + // any other command after that. At this point the device is lost, so any operation will fail. + graphicsDevice.For(128, new ComputeShaderGettingStuck(bufferA, bufferB, 2, 2, 42)); + } + catch (Win32Exception) + { + win32ExceptionThrown = true; + } + + // The previous shader must hang and cause an exception + Assert.IsTrue(win32ExceptionThrown); + + // Wait up to a second for the event to be raised (it's raised asynchronously on a thread pool thread) + await Task.WhenAny(tcs.Task, Task.Delay(1000)); + + // Ensure the event has been raised, and get the results + Assert.IsTrue(tcs.Task.IsCompleted); + Assert.AreEqual(tcs.Task.Status, TaskStatus.RanToCompletion); + + (object? sender, DeviceLostReason reason) = tcs.Task.Result; + + Assert.IsNotNull(sender); + Assert.AreSame(sender, graphicsDevice); + Assert.IsTrue(reason is DeviceLostReason.DeviceHung or DeviceLostReason.DeviceReset); + } + + [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] + internal readonly partial struct ComputeShaderGettingStuck : IComputeShader + { + private readonly ReadOnlyBuffer bufferA; + private readonly ReadWriteBuffer bufferB; + private readonly float a; + private readonly float b; + private readonly int target; + + /// + public void Execute() + { + if (ThreadIds.X == target) + { + for (float x = 0; x < a; x += 0.1f) + { + for (float y = 0; y < b; y += 0.1f) + { + bufferB[ThreadIds.X] += bufferA[ThreadIds.X] * x * y; + } + } + } + else + { + bufferB[ThreadIds.X] = bufferA[ThreadIds.X]; + } + } + } +} From 0a75a7f83ce60838acd741ae7b578209fd15b1b3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 2 Jul 2022 14:12:57 +0200 Subject: [PATCH 07/64] Enable device lost tests in CI pipeline --- .github/workflows/dotnet.yml | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index e307114c..3bf304b2 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -145,6 +145,32 @@ jobs: run: dotnet test tests\ComputeSharp.Tests.SourceGenerators\ComputeSharp.Tests.SourceGenerators.csproj -v n -l "console;verbosity=detailed" shell: cmd + # Run all the DX12 device lost unit tests (run the separately to minimize issues) + run-dx12-device-list-tests: + if: success() + needs: [build-solution-debug, build-solution-release] + runs-on: windows-2022 + steps: + - name: Git checkout + uses: actions/checkout@v2 + - name: Setup .NET Core 3.1 SDK + uses: actions/setup-dotnet@v1 + with: + dotnet-version: 3.1.x + - name: Setup .NET 6 SDK + uses: actions/setup-dotnet@v1 + with: + dotnet-version: 6.0.x + - name: Run ComputeSharp.Tests.DeviceLost (.NET 6) + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj -c Release -f net6.0 -v n -l "console;verbosity=detailed" + shell: cmd + - name: Run ComputeSharp.Tests.DeviceLost (.NET Core 3.1) + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj -c Release -f netcoreapp3.1 /p:Platform=x64 -v n -l "console;verbosity=detailed" + shell: cmd + - name: Run ComputeSharp.Tests.DeviceLost (.NET Framework 4.7.2) + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj -c Release -f net472 /p:Platform=x64 -v n -l "console;verbosity=detailed" + shell: cmd + # Run all the D2D1 unit tests (referencing ComputeSharp.D2D1) run-d2d1-tests: if: success() @@ -368,7 +394,7 @@ jobs: # Publish the packages to GitHub packages publish-nightlies-github: - needs: [run-dx12-tests, run-d2d1-tests, run-dx12-samples, verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs] + needs: [run-dx12-tests, run-dx12-device-list-tests, run-d2d1-tests, run-dx12-samples, verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs] runs-on: windows-2022 if: ${{github.event_name == 'push'}} steps: @@ -384,7 +410,7 @@ jobs: # Publish the packages to Azure DevOps publish-nightlies-azure-devops: - needs: [run-dx12-tests, run-d2d1-tests, run-dx12-samples, verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs] + needs: [run-dx12-tests, run-dx12-device-list-tests, run-d2d1-tests, run-dx12-samples, verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs] runs-on: windows-2022 if: ${{github.event_name == 'push'}} steps: From ab8ca32770e5d393a30cd4ff4cc1da8be62228ea Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 2 Jul 2022 15:37:06 +0200 Subject: [PATCH 08/64] Add missing Assert() calls when submitting GPU work --- src/ComputeSharp/Graphics/Commands/CommandList.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp/Graphics/Commands/CommandList.cs b/src/ComputeSharp/Graphics/Commands/CommandList.cs index 61a69232..28494e84 100644 --- a/src/ComputeSharp/Graphics/Commands/CommandList.cs +++ b/src/ComputeSharp/Graphics/Commands/CommandList.cs @@ -1,6 +1,7 @@ using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; +using ComputeSharp.Core.Extensions; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; @@ -134,7 +135,7 @@ internal unsafe struct CommandList : IDisposable /// public void ExecuteAndWaitForCompletion() { - this.d3D12GraphicsCommandList.Get()->Close(); + this.d3D12GraphicsCommandList.Get()->Close().Assert(); this.device.ExecuteCommandList(ref this); } @@ -145,7 +146,7 @@ internal unsafe struct CommandList : IDisposable /// The to await for the operations to complete. public ValueTask ExecuteAndWaitForCompletionAsync() { - this.d3D12GraphicsCommandList.Get()->Close(); + this.d3D12GraphicsCommandList.Get()->Close().Assert(); return this.device.ExecuteCommandListAsync(ref this); } From 5cb00a8924a899b538db0b6a55093125a9fec6bd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 2 Jul 2022 16:17:33 +0200 Subject: [PATCH 09/64] Fix use-after-free with ID3D12InfoQueue messages --- .../Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs index dff79a89..38bc3787 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs @@ -160,17 +160,17 @@ partial class DeviceHelper { builder.Append($"[Description]: \"{new string(message->pDescription)}\""); } + + if (message->Severity is D3D12_MESSAGE_SEVERITY_ERROR or D3D12_MESSAGE_SEVERITY_CORRUPTION or D3D12_MESSAGE_SEVERITY_WARNING) + { + hasErrorsOrWarnings = true; + } } finally { NativeMemory.Free(message); } - if (message->Severity is D3D12_MESSAGE_SEVERITY_ERROR or D3D12_MESSAGE_SEVERITY_CORRUPTION or D3D12_MESSAGE_SEVERITY_WARNING) - { - hasErrorsOrWarnings = true; - } - Trace.WriteLine(builder); } From 041956b8545826bd3acd2b26e54efdba28330ecb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 3 Jul 2022 20:15:16 +0200 Subject: [PATCH 10/64] Switch device lost detection to fence signal callback --- .../Extensions/Interop/HResultExtensions.cs | 25 +--- .../Graphics/GraphicsDevice.DeviceLost.cs | 136 ++++++++++++++++++ .../Graphics/GraphicsDevice.Execute.cs | 12 +- src/ComputeSharp/Graphics/GraphicsDevice.cs | 68 +++------ .../Helpers/DeviceHelper.ID3D12InfoQueue.cs | 21 --- .../Graphics/Interop/NativeObject.cs | 5 +- .../Windows/um/WinBase/Windows.cs | 3 + .../DeviceLostTests.cs | 12 +- 8 files changed, 168 insertions(+), 114 deletions(-) create mode 100644 src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs index 1e4f4099..403dc0ba 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs @@ -39,26 +39,7 @@ internal static class HResultExtensions { if (result < 0) { - // This method just throws the exception from the helper below, which includes the - // additional logic for the device lost events. This structure ensures this method - // only has a single basic block, so it can be identified as a throw helper and - // imported properly, which results in better codegen. - static void RaiseDeviceLostEventsAndThrowWin32Exception(int result) - { - throw RaiseDeviceLostEventsAndGetWin32Exception(result); - } - - // Raises all device lost events, if needed, and then creates the Win32Exception to throw. - // This method is never inlined, which is needed to make handling the throw helper easier. - [MethodImpl(MethodImplOptions.NoInlining)] - static Win32Exception RaiseDeviceLostEventsAndGetWin32Exception(int result) - { - DeviceHelper.RaiseAllDeviceLostEventsIfNeeded(); - - return new Win32Exception(result); - } - - RaiseDeviceLostEventsAndThrowWin32Exception(result); + ThrowHelper.ThrowWin32Exception(result); } } else @@ -71,15 +52,11 @@ internal static class HResultExtensions if (result < 0) { - DeviceHelper.RaiseAllDeviceLostEventsIfNeeded(); - ThrowHelper.ThrowWin32Exception(result); } if (hasErrorsOrWarnings) { - DeviceHelper.RaiseAllDeviceLostEventsIfNeeded(); - ThrowHelper.ThrowWin32Exception("Warning or error detected by ID3D12InfoQueue."); } } diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs new file mode 100644 index 00000000..e5f077f7 --- /dev/null +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -0,0 +1,136 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using ComputeSharp.Core.Extensions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp; + +/// +unsafe partial class GraphicsDevice +{ +#if !NET6_0_OR_GREATER + /// + /// A cached instance wrapping . + /// + private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackForRegisterDeviceLostCallbackWrapper = WaitForSingleObjectCallbackForWaitForFenceAsync; +#endif + + /// + /// Raises the event if needed. + /// + private void QueueRaiseDeviceLostEventIfNeeded() + { + if (IsDisposed) + { + return; + } + + // If the current device removed reason is not S_OK, it means the event + // has already been raised (but the device will keep reporting that reason). + // In that case, do nothing to avoid raising it again while the device is alive. + if (Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason)) != S.S_OK) + { + return; + } + + HRESULT result = this.d3D12Device.Get()->GetDeviceRemovedReason(); + + // Only raise the event once, and store the device removed reason to track it + if (result != S.S_OK && + Interlocked.CompareExchange( + ref Unsafe.As(ref this.deviceRemovedReason), + (int)result, + S.S_OK) == S.S_OK) + { + QueueRaiseDeviceLostEvent(); + } + } + + /// + /// Queues the event being raised on the thread pool. + /// + private void QueueRaiseDeviceLostEvent() + { + static void RaiseDeviceLostEvent(GraphicsDevice device) + { + HRESULT result = Volatile.Read(ref Unsafe.As(ref device.deviceRemovedReason)); + + DeviceLostReason reason = (int)result switch + { + DXGI.DXGI_ERROR_DEVICE_HUNG => DeviceLostReason.DeviceHung, + DXGI.DXGI_ERROR_DEVICE_REMOVED => DeviceLostReason.DeviceRemoved, + DXGI.DXGI_ERROR_DEVICE_RESET => DeviceLostReason.DeviceReset, + DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR => DeviceLostReason.DriverInternalError, + DXGI.DXGI_ERROR_INVALID_CALL => DeviceLostReason.InvalidCall, + _ => DeviceLostReason.UnspecifiedError + }; + + device.DeviceLost?.Invoke(device, reason); + } + + ThreadPool.QueueUserWorkItem(static state => RaiseDeviceLostEvent((GraphicsDevice)state!), this); + } + + /// + /// Registers a callback to notify whenever the current device is lost. + /// + /// The current instance. + /// The resulting used as callback state. + /// The resulting device lost event for the callback. + private static void RegisterDeviceLostCallback(GraphicsDevice device, out GCHandle deviceHandle, out HANDLE deviceRemovedEvent) + { + HANDLE eventHandle = Windows.CreateEventW(null, Windows.FALSE, Windows.FALSE, null); + + // Whenever a device is lost, for any reason, all fences are signaled to the highest value. + // As such, a fence event with a value of ulong.MaxValue can act as a device lost callback. + device.d3D12ComputeFence.Get()->SetEventOnCompletion(ulong.MaxValue, eventHandle).Assert(); + + GCHandle handle = deviceHandle = GCHandle.Alloc(device, GCHandleType.Weak); + HANDLE waitHandle; + + _ = Windows.RegisterWaitForSingleObject( + phNewWaitObject: &waitHandle, + hObject: eventHandle, +#if NET6_0_OR_GREATER + Callback: &WaitForSingleObjectCallbackForRegisterDeviceLostCallback, +#else + Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackForRegisterDeviceLostCallbackWrapper), +#endif + Context: (void*)(IntPtr)handle, + dwMilliseconds: Windows.INFINITE, + dwFlags: 0); + + deviceRemovedEvent = waitHandle; + } + + /// + /// Unregisters a callback setup by . + /// + /// The current instance. + private static void UnregisterDeviceLostCallback(GraphicsDevice device) + { + _ = Windows.UnregisterWait(device.deviceRemovedEvent); + _ = Windows.CloseHandle(device.deviceRemovedEvent); + + device.deviceHandle.Free(); + } + + /// + /// The callback to signal a device lost event. + /// + /// The input context. + /// Whether the wait has timed out. + [UnmanagedCallersOnly] + private static void WaitForSingleObjectCallbackForRegisterDeviceLostCallback(void* pContext, byte timedOut) + { + GraphicsDevice device = Unsafe.As(GCHandle.FromIntPtr((IntPtr)pContext).Target!); + + device.QueueRaiseDeviceLostEventIfNeeded(); + } +} diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs index 6d2a3ac5..8f17e00f 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs @@ -31,9 +31,9 @@ unsafe partial class GraphicsDevice private delegate void WaitForSingleObjectCallbackDelegate(void* pContext, byte timedOut); /// - /// A cached instance wrapping . + /// A cached instance wrapping . /// - private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackWrapper = WaitForSingleObjectCallback; + private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackForWaitForFenceAsyncWrapper = WaitForSingleObjectCallbackForWaitForFenceAsync; #endif /// @@ -131,7 +131,7 @@ unsafe partial class GraphicsDevice } /// - /// A context to support . + /// A context to support . /// private struct CallbackContext { @@ -195,9 +195,9 @@ unsafe partial class GraphicsDevice phNewWaitObject: &waitHandle, hObject: eventHandle, #if NET6_0_OR_GREATER - Callback: &WaitForSingleObjectCallback, + Callback: &WaitForSingleObjectCallbackForWaitForFenceAsync, #else - Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackWrapper), + Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackForWaitForFenceAsyncWrapper), #endif Context: callbackContext, dwMilliseconds: Windows.INFINITE, @@ -212,7 +212,7 @@ unsafe partial class GraphicsDevice /// The input context. /// Whether the wait has timed out. [UnmanagedCallersOnly] - private static void WaitForSingleObjectCallback(void* pContext, byte timedOut) + private static void WaitForSingleObjectCallbackForWaitForFenceAsync(void* pContext, byte timedOut) { CallbackContext* callbackContext = (CallbackContext*)pContext; diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 457c1eb6..2abc731f 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -1,7 +1,7 @@ using System; using System.Diagnostics; using System.Runtime.CompilerServices; -using System.Threading; +using System.Runtime.InteropServices; using CommunityToolkit.Diagnostics; using ComputeSharp.Graphics.Commands.Interop; #if NET6_0_OR_GREATER @@ -87,6 +87,16 @@ public sealed unsafe partial class GraphicsDevice : NativeObject private ComPtr pool; #endif + /// + /// A weak to the current instance (used to support the device lost callback). + /// + private GCHandle deviceHandle; + + /// + /// The wait event for the device removed. + /// + private HANDLE deviceRemovedEvent; + /// /// The reason the device was removed, if any. /// @@ -153,6 +163,10 @@ public sealed unsafe partial class GraphicsDevice : NativeObject this.pool = this.allocator.Get()->CreatePoolForCacheCoherentUMA(); } #endif + + this.deviceRemovedReason = S.S_OK; + + RegisterDeviceLostCallback(this, out this.deviceHandle, out this.deviceRemovedEvent); } /// @@ -373,56 +387,6 @@ public sealed unsafe partial class GraphicsDevice : NativeObject d3D12GraphicsCommandList->SetDescriptorHeaps(1, &d3D12DescriptorHeap); } - /// - /// Raises the event if needed. - /// - internal void RaiseDeviceLostEventIfNeeded() - { - if (IsDisposed) - { - return; - } - - // If the current device removed reason is not S_OK, it means the event - // has already been raised (but the device will keep reporting that reason). - // In that case, do nothing to avoid raising it again while the device is alive. - if (Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason)) != S.S_OK) - { - return; - } - - HRESULT result = this.d3D12Device.Get()->GetDeviceRemovedReason(); - - // Only raise the event once, and store the device removed reason to track it - if (Interlocked.CompareExchange( - ref Unsafe.As(ref this.deviceRemovedReason), - (int)result, - S.S_OK) == S.S_OK) - { - ThreadPool.QueueUserWorkItem(static state => ((GraphicsDevice)state!).RaiseDeviceLostEvent(), this); - } - } - - /// - /// Raises the event. - /// - private void RaiseDeviceLostEvent() - { - HRESULT result = Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason)); - - DeviceLostReason reason = (int)result switch - { - DXGI.DXGI_ERROR_DEVICE_HUNG => DeviceLostReason.DeviceHung, - DXGI.DXGI_ERROR_DEVICE_REMOVED => DeviceLostReason.DeviceRemoved, - DXGI.DXGI_ERROR_DEVICE_RESET => DeviceLostReason.DeviceReset, - DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR => DeviceLostReason.DriverInternalError, - DXGI.DXGI_ERROR_INVALID_CALL => DeviceLostReason.InvalidCall, - _ => DeviceLostReason.UnspecifiedError - }; - - DeviceLost?.Invoke(this, reason); - } - /// protected override void OnDispose() { @@ -440,6 +404,8 @@ public sealed unsafe partial class GraphicsDevice : NativeObject this.pool.Dispose(); this.allocator.Dispose(); #endif + + UnregisterDeviceLostCallback(this); } /// diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs index 38bc3787..313d92fa 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs @@ -180,25 +180,4 @@ partial class DeviceHelper return hasErrorsOrWarnings; } - - /// - /// Raises the event if needed, on all existing devices. - /// - public static void RaiseAllDeviceLostEventsIfNeeded() - { - lock (DevicesCache) - { - foreach (GraphicsDevice device in DevicesCache.Values) - { - // Check whether the device was lost, and raise the event once. This method will - // queue the event being raised on a thread pool thread, which is crucial to avoid - // invoking the handlers while taking a lock on the devices cache. Doing so would - // lead to issues if a handler tried to synchronously create a new device, which would - // take the same lock (it's reentrant) and then add the new device to the cache. Then - // once this method resumed, the collection would be invalid, and the foreach loop - // would throw an exception on the next iteration. This will prevent that from happening. - device.RaiseDeviceLostEventIfNeeded(); - } - } - } } diff --git a/src/ComputeSharp/Graphics/Interop/NativeObject.cs b/src/ComputeSharp/Graphics/Interop/NativeObject.cs index 28d49e0b..01cab286 100644 --- a/src/ComputeSharp/Graphics/Interop/NativeObject.cs +++ b/src/ComputeSharp/Graphics/Interop/NativeObject.cs @@ -72,6 +72,7 @@ public abstract class NativeObject : IDisposable /// /// Throws an if the current instance has been disposed. /// + /// Thrown if the current instance is disposed. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ThrowIfDisposed() { @@ -80,9 +81,9 @@ public abstract class NativeObject : IDisposable // We can't use ThrowHelper here as we only want to invoke ToString if we // are about to throw an exception. The JIT will recognize this pattern // as this method has a single basic block that always throws an exception. - void Throw() => throw new ObjectDisposedException(ToString()); + static void Throw(object self) => throw new ObjectDisposedException(self.ToString()); - Throw(); + Throw(this); } } } diff --git a/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs b/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs index edd2d175..eb881c81 100644 --- a/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs +++ b/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs @@ -12,6 +12,9 @@ namespace TerraFX.Interop.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); + [DllImport("kernel32", ExactSpelling = true)] + public static extern BOOL UnregisterWait(HANDLE WaitHandle); + [NativeTypeName("#define INFINITE 0xFFFFFFFF")] public const uint INFINITE = 0xFFFFFFFF; } diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs index 6f830d1f..49bba493 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs @@ -16,7 +16,7 @@ public partial class DeviceLostTests { GraphicsDevice graphicsDevice = device.Get(); - bool win32ExceptionThrown = false; + //bool win32ExceptionThrown = false; TaskCompletionSource<(object? Sender, DeviceLostReason Reason)> tcs = new(); // Register the device lost callback @@ -28,20 +28,12 @@ public partial class DeviceLostTests using ReadWriteBuffer bufferB = graphicsDevice.AllocateReadWriteBuffer(128); graphicsDevice.For(128, new ComputeShaderGettingStuck(bufferA, bufferB, 12345678, 87654321, 42)); - - // The shader above will always hang, but it's not guaranteed that the DirectX runtime will detect - // the error right when executing that command. As such, we can force it to be detected by running - // any other command after that. At this point the device is lost, so any operation will fail. - graphicsDevice.For(128, new ComputeShaderGettingStuck(bufferA, bufferB, 2, 2, 42)); } catch (Win32Exception) { - win32ExceptionThrown = true; + // This is not guaranteed to be thrown, but handle it just in case } - // The previous shader must hang and cause an exception - Assert.IsTrue(win32ExceptionThrown); - // Wait up to a second for the event to be raised (it's raised asynchronously on a thread pool thread) await Task.WhenAny(tcs.Task, Task.Delay(1000)); From 8a9368506bf00cc7807cc3ef299269dff6fdbf76 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 3 Jul 2022 20:20:25 +0200 Subject: [PATCH 11/64] Add device lost validation to public APIs --- .../GraphicsDeviceExtensions.Dispatching.cs | 1 + .../Graphics/GraphicsDevice.DeviceLost.cs | 22 +++++++++++++++++++ src/ComputeSharp/Graphics/GraphicsDevice.cs | 5 +++++ .../Graphics/Resources/Abstract/Buffer{T}.cs | 1 + .../Resources/Abstract/StructuredBuffer{T}.cs | 5 +++++ .../Resources/Abstract/Texture2D{T}.cs | 6 +++++ .../Resources/Abstract/Texture3D{T}.cs | 6 +++++ .../Resources/Abstract/TransferBuffer{T}.cs | 1 + .../Abstract/TransferTexture2D{T}.cs | 1 + .../Abstract/TransferTexture3D{T}.cs | 1 + .../Graphics/Resources/ConstantBuffer{T}.cs | 3 +++ .../ReadWriteTexture2D{T,TPixel}.ReadOnly.cs | 1 + .../ReadWriteTexture2D{T}.ReadOnly.cs | 1 + .../ReadWriteTexture3D{T,TPixel}.ReadOnly.cs | 1 + .../ReadWriteTexture3D{T}.ReadOnly.cs | 1 + 15 files changed, 56 insertions(+) diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs index 393fe304..47d37914 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs @@ -151,6 +151,7 @@ public static partial class GraphicsDeviceExtensions Guard.IsNotNull(device); device.ThrowIfDisposed(); + device.ThrowIfDeviceLost(); return new(device); } diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index e5f077f7..2e67481e 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -21,6 +21,28 @@ unsafe partial class GraphicsDevice private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackForRegisterDeviceLostCallbackWrapper = WaitForSingleObjectCallbackForWaitForFenceAsync; #endif + /// + /// Throws an if the current device has been lost. + /// + /// Thrown if the current device has been lost. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void ThrowIfDeviceLost() + { + // This method is called as a check before performing any operations. In order to minimize overhead, + // the GetDeviceRemovedReason() method is not called here, and the local field is just used instead. + // That field is set by the device lost callback anyway, and the extra precision of calling the API + // explicitly is not needed since there are no thread safety guarantees in this scenario anyway. + // That is, the check isn't meant to cover 100% of cases, as a device might be lost right after this + // check is performed anyway. This check is only meant to catch the common scenarios to help users. + // For the same reason, this method doesn't have to worry about raising the event either. + if (Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason)) != S.S_OK) + { + static void Throw(object self) => throw new InvalidOperationException($"The device \"{self}\" has been lost and can no longer be used."); + + Throw(this); + } + } + /// /// Raises the event if needed. /// diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 2abc731f..6e7ad77e 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -234,6 +234,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsDoublePrecisionSupportAvailable() { ThrowIfDisposed(); + ThrowIfDeviceLost(); var d3D12OptionsData = this.d3D12Device.Get()->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS); @@ -250,6 +251,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject where T : unmanaged { ThrowIfDisposed(); + ThrowIfDeviceLost(); return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D); } @@ -264,6 +266,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject where T : unmanaged { ThrowIfDisposed(); + ThrowIfDeviceLost(); return this.d3D12Device.Get()->IsDxgiFormatSupported( DXGIFormatHelper.GetForType(), @@ -280,6 +283,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject where T : unmanaged { ThrowIfDisposed(); + ThrowIfDeviceLost(); return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D); } @@ -294,6 +298,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject where T : unmanaged { ThrowIfDisposed(); + ThrowIfDeviceLost(); return this.d3D12Device.Get()->IsDxgiFormatSupported( DXGIFormatHelper.GetForType(), diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs index 4d5b5561..b830a105 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs @@ -65,6 +65,7 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource private protected Buffer(GraphicsDevice device, int length, uint elementSizeInBytes, ResourceType resourceType, AllocationMode allocationMode) { device.ThrowIfDisposed(); + device.ThrowIfDeviceLost(); if (resourceType == ResourceType.Constant) { diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs index 98c99bdf..c2693cea 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs @@ -33,6 +33,7 @@ public abstract class StructuredBuffer : Buffer internal override unsafe void CopyTo(ref T destination, int sourceOffset, int count) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -104,6 +105,7 @@ public abstract class StructuredBuffer : Buffer internal override unsafe void CopyTo(Buffer destination, int sourceOffset, int destinationOffset, int count) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -148,6 +150,7 @@ public abstract class StructuredBuffer : Buffer internal unsafe void CopyTo(ReadBackBuffer destination, int sourceOffset, int destinationOffset, int count) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -191,6 +194,7 @@ public abstract class StructuredBuffer : Buffer internal override unsafe void CopyFrom(ref T source, int offset, int length) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -266,6 +270,7 @@ public abstract class StructuredBuffer : Buffer internal unsafe void CopyFrom(UploadBuffer source, int sourceOffset, int destinationOffset, int count) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs index dacc203e..e6190b93 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs @@ -73,6 +73,7 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, AllocationMode allocationMode, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { device.ThrowIfDisposed(); + device.ThrowIfDeviceLost(); Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); @@ -169,6 +170,7 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra internal void CopyTo(ref T destination, int size, int sourceOffsetX, int sourceOffsetY, int width, int height) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -258,6 +260,7 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra internal void CopyTo(Texture2D destination, int sourceOffsetX, int sourceOffsetY, int destinationOffsetX, int destinationOffsetY, int width, int height) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -326,6 +329,7 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra internal void CopyTo(ReadBackTexture2D destination, int sourceOffsetX, int sourceOffsetY, int destinationOffsetX, int destinationOffsetY, int width, int height) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -389,6 +393,7 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra internal void CopyFrom(ref T source, int size, int destinationOffsetX, int destinationOffsetY, int width, int height) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -476,6 +481,7 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra internal void CopyFrom(UploadTexture2D source, int sourceOffsetX, int sourceOffsetY, int destinationOffsetX, int destinationOffsetY, int width, int height) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs index 70e7361d..b12dc576 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs @@ -74,6 +74,7 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra private protected Texture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType, AllocationMode allocationMode, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { device.ThrowIfDisposed(); + device.ThrowIfDeviceLost(); Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); @@ -181,6 +182,7 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra internal void CopyTo(ref T destination, int size, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int width, int height, int depth) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -279,6 +281,7 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra internal void CopyTo(Texture3D destination, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -356,6 +359,7 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra internal void CopyTo(ReadBackTexture3D destination, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -427,6 +431,7 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra internal void CopyFrom(ref T source, int size, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -523,6 +528,7 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra internal void CopyFrom(UploadTexture3D source, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs index edd1d028..8e42995a 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs @@ -45,6 +45,7 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource private protected TransferBuffer(GraphicsDevice device, int length, ResourceType resourceType, AllocationMode allocationMode) { device.ThrowIfDisposed(); + device.ThrowIfDeviceLost(); // The maximum length is set such that the aligned buffer size can't exceed uint.MaxValue Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / (uint)sizeof(T)) & ~255); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs index ec77a7af..8e546be2 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs @@ -51,6 +51,7 @@ public unsafe abstract class TransferTexture2D : NativeObject, IGraphicsResou private protected TransferTexture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, AllocationMode allocationMode) { device.ThrowIfDisposed(); + device.ThrowIfDeviceLost(); Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs index e4f48331..72201ccb 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs @@ -52,6 +52,7 @@ public unsafe abstract class TransferTexture3D : NativeObject, IGraphicsResou private protected TransferTexture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType, AllocationMode allocationMode) { device.ThrowIfDisposed(); + device.ThrowIfDeviceLost(); Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); diff --git a/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs index e08040ea..c51fca8b 100644 --- a/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs @@ -58,6 +58,7 @@ public sealed class ConstantBuffer : Buffer internal override unsafe void CopyTo(ref T destination, int offset, int length) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -84,6 +85,7 @@ public sealed class ConstantBuffer : Buffer internal override unsafe void CopyTo(Buffer destination, int sourceOffset, int destinationOffset, int length) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); @@ -118,6 +120,7 @@ public sealed class ConstantBuffer : Buffer internal override unsafe void CopyFrom(ref T source, int offset, int length) { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs index 55cb5933..dee9a948 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs @@ -25,6 +25,7 @@ partial class ReadWriteTexture2D internal IReadOnlyNormalizedTexture2D AsReadOnly() { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); ThrowIfIsNotInReadOnlyState(); diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs index fdb58dd9..12c4c5ec 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs @@ -25,6 +25,7 @@ partial class ReadWriteTexture2D public IReadOnlyTexture2D AsReadOnly() { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); ThrowIfIsNotInReadOnlyState(); diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs index 270c7135..f9e7ccfb 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs @@ -25,6 +25,7 @@ partial class ReadWriteTexture3D public IReadOnlyNormalizedTexture3D AsReadOnly() { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); ThrowIfIsNotInReadOnlyState(); diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs index 5d38517d..c825d5f7 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs @@ -25,6 +25,7 @@ partial class ReadWriteTexture3D public IReadOnlyTexture3D AsReadOnly() { GraphicsDevice.ThrowIfDisposed(); + GraphicsDevice.ThrowIfDeviceLost(); ThrowIfDisposed(); ThrowIfIsNotInReadOnlyState(); From 2aa7c70edd6c8d53a7a87b8f88e523bbcf8a4898 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jul 2022 08:13:32 +0200 Subject: [PATCH 12/64] Fix device lost unit test (using ID3D12Device5::RemoveDevice) --- .../DeviceLostTests.cs | 64 ++++++++----------- .../TerraFX.Interop.Windows/ID3D12Device5.cs | 33 ++++++++++ 2 files changed, 60 insertions(+), 37 deletions(-) create mode 100644 tests/ComputeSharp.Tests.DeviceLost/TerraFX.Interop.Windows/ID3D12Device5.cs diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs index 49bba493..a4ee66e4 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs @@ -1,8 +1,12 @@ -using System.ComponentModel; +using System; using System.Threading.Tasks; +using ComputeSharp.Interop; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using TerraFX.Interop.DirectX; + +#pragma warning disable CA1416 namespace ComputeSharp.Tests.DeviceLost; @@ -16,26 +20,15 @@ public partial class DeviceLostTests { GraphicsDevice graphicsDevice = device.Get(); - //bool win32ExceptionThrown = false; TaskCompletionSource<(object? Sender, DeviceLostReason Reason)> tcs = new(); // Register the device lost callback graphicsDevice.DeviceLost += (s, e) => tcs.SetResult((s, e)); - try - { - using ReadOnlyBuffer bufferA = graphicsDevice.AllocateReadOnlyBuffer(128); - using ReadWriteBuffer bufferB = graphicsDevice.AllocateReadWriteBuffer(128); - - graphicsDevice.For(128, new ComputeShaderGettingStuck(bufferA, bufferB, 12345678, 87654321, 42)); - } - catch (Win32Exception) - { - // This is not guaranteed to be thrown, but handle it just in case - } + RemoveDevice(graphicsDevice); // Wait up to a second for the event to be raised (it's raised asynchronously on a thread pool thread) - await Task.WhenAny(tcs.Task, Task.Delay(1000)); + await Task.WhenAny(tcs.Task, Task.Delay(100)); // Ensure the event has been raised, and get the results Assert.IsTrue(tcs.Task.IsCompleted); @@ -45,36 +38,33 @@ public partial class DeviceLostTests Assert.IsNotNull(sender); Assert.AreSame(sender, graphicsDevice); - Assert.IsTrue(reason is DeviceLostReason.DeviceHung or DeviceLostReason.DeviceReset); + Assert.AreEqual(reason, DeviceLostReason.DeviceRemoved); } - [AutoConstructor] - [EmbeddedBytecode(DispatchAxis.X)] - internal readonly partial struct ComputeShaderGettingStuck : IComputeShader + /// + /// Removes the underlying device for a given instance. + /// + /// The target instance. + private static unsafe void RemoveDevice(GraphicsDevice graphicsDevice) { - private readonly ReadOnlyBuffer bufferA; - private readonly ReadWriteBuffer bufferB; - private readonly float a; - private readonly float b; - private readonly int target; + ID3D12Device5* d3D12Device = default; + Guid d3D12Device5Guid = typeof(ID3D12Device5).GUID; - /// - public void Execute() + if (InteropServices.TryGetID3D12Device(graphicsDevice, &d3D12Device5Guid, (void**)&d3D12Device) != 0) { - if (ThreadIds.X == target) + Assert.Inconclusive(); + } + + try + { + d3D12Device->RemoveDevice(); + } + finally + { + if (d3D12Device is not null) { - for (float x = 0; x < a; x += 0.1f) - { - for (float y = 0; y < b; y += 0.1f) - { - bufferB[ThreadIds.X] += bufferA[ThreadIds.X] * x * y; - } - } + d3D12Device->Release(); } - else - { - bufferB[ThreadIds.X] = bufferA[ThreadIds.X]; - } } } } diff --git a/tests/ComputeSharp.Tests.DeviceLost/TerraFX.Interop.Windows/ID3D12Device5.cs b/tests/ComputeSharp.Tests.DeviceLost/TerraFX.Interop.Windows/ID3D12Device5.cs new file mode 100644 index 00000000..d81d75aa --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/TerraFX.Interop.Windows/ID3D12Device5.cs @@ -0,0 +1,33 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d3d12.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +#if !NET6_0_OR_GREATER + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace TerraFX.Interop.DirectX +{ + [Guid("8B4F173B-2FEA-4B80-8F58-4307191AB95D")] + public unsafe partial struct ID3D12Device5 + { + public void** lpVtbl; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[2]))((ID3D12Device5*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RemoveDevice() + { + ((delegate* unmanaged[Stdcall])(lpVtbl[58]))((ID3D12Device5*)Unsafe.AsPointer(ref this)); + } + } +} + +#endif From 90f74bd4027d523b30eb6c2f809d7b142810bccf Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jul 2022 10:45:01 +0200 Subject: [PATCH 13/64] Improve error handling in DeviceExtensions --- .../ComputeSharp.Tests/Extensions/DeviceExtensions.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/ComputeSharp.Tests/Extensions/DeviceExtensions.cs b/tests/ComputeSharp.Tests/Extensions/DeviceExtensions.cs index 3996fa5e..983083bb 100644 --- a/tests/ComputeSharp.Tests/Extensions/DeviceExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/DeviceExtensions.cs @@ -20,13 +20,20 @@ public static class DeviceExtensions GraphicsDevice? device = type switch { Device.Discrete => GraphicsDevice.QueryDevices(info => info.IsHardwareAccelerated).FirstOrDefault(), - Device.Warp => GraphicsDevice.QueryDevices(info => !info.IsHardwareAccelerated).First(), + Device.Warp => GraphicsDevice.QueryDevices(info => !info.IsHardwareAccelerated).FirstOrDefault(), _ => ThrowHelper.ThrowArgumentException("Invalid device.") }; if (device is null) { - Assert.Inconclusive(); + // If the device is null, fail only if the device was WARP (as it should always be available). + // If a dedicated device was requested instead, just report the test as inconclusive (no GPU). + switch (type) + { + case Device.Discrete: Assert.Inconclusive(); break; + case Device.Warp: Assert.Fail(); break; + } + } return device!; From 3f77e0a9b5d39496495190b8d45437826c1ef918 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jul 2022 10:45:39 +0200 Subject: [PATCH 14/64] Add more device lost unit tests --- .../DeviceLostTests.cs | 143 +++++++++++++++++- 1 file changed, 139 insertions(+), 4 deletions(-) diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs index a4ee66e4..73c4c8cb 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs @@ -12,13 +12,14 @@ namespace ComputeSharp.Tests.DeviceLost; [TestClass] [TestCategory("DeviceLost")] +[DoNotParallelize] public partial class DeviceLostTests { [CombinatorialTestMethod] [AllDevices] public async Task DeviceLost_RaiseEvent(Device device) { - GraphicsDevice graphicsDevice = device.Get(); + using GraphicsDevice graphicsDevice = device.Get(); TaskCompletionSource<(object? Sender, DeviceLostReason Reason)> tcs = new(); @@ -28,19 +29,133 @@ public partial class DeviceLostTests RemoveDevice(graphicsDevice); // Wait up to a second for the event to be raised (it's raised asynchronously on a thread pool thread) - await Task.WhenAny(tcs.Task, Task.Delay(100)); + await Task.WhenAny(tcs.Task, Task.Delay(1000)); // Ensure the event has been raised, and get the results Assert.IsTrue(tcs.Task.IsCompleted); - Assert.AreEqual(tcs.Task.Status, TaskStatus.RanToCompletion); - (object? sender, DeviceLostReason reason) = tcs.Task.Result; + (object? sender, DeviceLostReason reason) = await tcs.Task; Assert.IsNotNull(sender); Assert.AreSame(sender, graphicsDevice); Assert.AreEqual(reason, DeviceLostReason.DeviceRemoved); } + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ConstantBuffer<>))] + [Resource(typeof(ReadOnlyBuffer<>))] + [Resource(typeof(ReadWriteBuffer<>))] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_AllocateBuffer(Device device, Type bufferType) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await RemoveDeviceAsync(graphicsDevice); + + using var _ = graphicsDevice.AllocateBuffer(bufferType, 128); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture2D<>))] + [Resource(typeof(ReadWriteTexture2D<>))] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_AllocateTexture2D(Device device, Type textureType) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await RemoveDeviceAsync(graphicsDevice); + + using var _ = graphicsDevice.AllocateTexture2D(textureType, 128, 128); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture3D<>))] + [Resource(typeof(ReadWriteTexture3D<>))] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_AllocateTexture3D(Device device, Type textureType) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await RemoveDeviceAsync(graphicsDevice); + + using var _ = graphicsDevice.AllocateTexture3D(textureType, 128, 128, 3); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_IsDoublePrecisionSupportAvailable(Device device) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await RemoveDeviceAsync(graphicsDevice); + + _ = graphicsDevice.IsDoublePrecisionSupportAvailable(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_IsReadOnlyTexture2DSupportedForType(Device device) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await RemoveDeviceAsync(graphicsDevice); + + _ = graphicsDevice.IsReadOnlyTexture2DSupportedForType(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_IsReadWriteTexture2DSupportedForType(Device device) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await RemoveDeviceAsync(graphicsDevice); + + _ = graphicsDevice.IsReadWriteTexture2DSupportedForType(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_IsReadOnlyTexture3DSupportedForType(Device device) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await RemoveDeviceAsync(graphicsDevice); + + _ = graphicsDevice.IsReadOnlyTexture3DSupportedForType(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_IsReadWriteTexture3DSupportedForType(Device device) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await RemoveDeviceAsync(graphicsDevice); + + _ = graphicsDevice.IsReadWriteTexture3DSupportedForType(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_CreateComputeContext(Device device) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await RemoveDeviceAsync(graphicsDevice); + + using var _ = graphicsDevice.CreateComputeContext(); + } + /// /// Removes the underlying device for a given instance. /// @@ -67,4 +182,24 @@ public partial class DeviceLostTests } } } + + /// + /// Removes the underlying device for a given instance and waits for it to be reported. + /// + /// The target instance. + private static async Task RemoveDeviceAsync(GraphicsDevice graphicsDevice) + { + TaskCompletionSource tcs = new(); + + graphicsDevice.DeviceLost += (s, e) => tcs.SetResult(null); + + RemoveDevice(graphicsDevice); + + await Task.WhenAny(tcs.Task, Task.Delay(1000)); + + if (!tcs.Task.IsCompleted) + { + Assert.Fail(); + } + } } From b50de2528f949e21fa90be76a8e0d781d144036d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jul 2022 12:01:38 +0200 Subject: [PATCH 15/64] Fix incorrect cleanup of device lost event handle --- .../Graphics/GraphicsDevice.DeviceLost.cs | 12 +++++++++--- src/ComputeSharp/Graphics/GraphicsDevice.cs | 9 +++++++-- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index 2e67481e..f0c5149f 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -105,7 +105,12 @@ unsafe partial class GraphicsDevice /// The current instance. /// The resulting used as callback state. /// The resulting device lost event for the callback. - private static void RegisterDeviceLostCallback(GraphicsDevice device, out GCHandle deviceHandle, out HANDLE deviceRemovedEvent) + /// The resulting device lost wait handle for the callback. + private static void RegisterDeviceLostCallback( + GraphicsDevice device, + out GCHandle deviceHandle, + out HANDLE deviceRemovedEvent, + out HANDLE deviceRemovedWaitHandle) { HANDLE eventHandle = Windows.CreateEventW(null, Windows.FALSE, Windows.FALSE, null); @@ -128,7 +133,8 @@ unsafe partial class GraphicsDevice dwMilliseconds: Windows.INFINITE, dwFlags: 0); - deviceRemovedEvent = waitHandle; + deviceRemovedEvent = eventHandle; + deviceRemovedWaitHandle = waitHandle; } /// @@ -137,7 +143,7 @@ unsafe partial class GraphicsDevice /// The current instance. private static void UnregisterDeviceLostCallback(GraphicsDevice device) { - _ = Windows.UnregisterWait(device.deviceRemovedEvent); + _ = Windows.UnregisterWait(device.deviceRemovedWaitHandle); _ = Windows.CloseHandle(device.deviceRemovedEvent); device.deviceHandle.Free(); diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 6e7ad77e..66602ebd 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -93,10 +93,15 @@ public sealed unsafe partial class GraphicsDevice : NativeObject private GCHandle deviceHandle; /// - /// The wait event for the device removed. + /// The event for the device removed callback. /// private HANDLE deviceRemovedEvent; + /// + /// The wait handle for the device removed callback. + /// + private HANDLE deviceRemovedWaitHandle; + /// /// The reason the device was removed, if any. /// @@ -166,7 +171,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject this.deviceRemovedReason = S.S_OK; - RegisterDeviceLostCallback(this, out this.deviceHandle, out this.deviceRemovedEvent); + RegisterDeviceLostCallback(this, out this.deviceHandle, out this.deviceRemovedEvent, out this.deviceRemovedWaitHandle); } /// From d7a5e89dcbb5140a75d6708d0395c380ad99f425 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jul 2022 12:02:51 +0200 Subject: [PATCH 16/64] Fix race condition in GraphicsDevice GC handle cleanup --- .../Graphics/GraphicsDevice.DeviceLost.cs | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index f0c5149f..b227f950 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -143,10 +143,23 @@ unsafe partial class GraphicsDevice /// The current instance. private static void UnregisterDeviceLostCallback(GraphicsDevice device) { - _ = Windows.UnregisterWait(device.deviceRemovedWaitHandle); - _ = Windows.CloseHandle(device.deviceRemovedEvent); + // As per the UnregisterWait docs: + // "If any callback functions associated with the timer have not completed when UnregisterWait is called, + // UnregisterWait unregisters the wait on the callback functions and fails with the ERROR_IO_PENDING error code." + // To ensure the handle is always correctly disposed, there are three scenarios to take into account: + // 1) If the callback is executed first and has completed, this call will return S_OK. No additional cleanup + // is needed, as the wait callback will have already freed the handle. In that case, do nothing. + // 2) If the callback is pending, this call will return ERROR_IO_PENDING. If that happens, no additional work + // is needed in this case either, as the callback will take care of freeing the handle during execution. + // 3) If the callback has never been invoked, the handle can safely be freed. + // In all cases, the OS will take care of checking against race conditions, so no interlocked APIs are needed. + if (Windows.UnregisterWait(device.deviceRemovedWaitHandle) == S.S_OK && + device.deviceHandle.IsAllocated) + { + device.deviceHandle.Free(); + } - device.deviceHandle.Free(); + _ = Windows.CloseHandle(device.deviceRemovedEvent); } /// @@ -159,6 +172,11 @@ unsafe partial class GraphicsDevice { GraphicsDevice device = Unsafe.As(GCHandle.FromIntPtr((IntPtr)pContext).Target!); + // The handle is guaranteed to be allocated when the callback is executed. Freeing it from here + // is needed so that the cleanup upon disposal might skip it if there's a pending execution. That + // ensures the handle is always disposed, without the disposal path having to lock and wait for it. + device.deviceHandle.Free(); + device.QueueRaiseDeviceLostEventIfNeeded(); } } From c2c7613b473ade705b91dfeeac1a7796c5610f42 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jul 2022 17:04:09 +0200 Subject: [PATCH 17/64] Fix memory leak in ID3D12DescriptorHandleAllocator --- .../Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/ComputeSharp/Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs b/src/ComputeSharp/Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs index 5591aba3..02989353 100644 --- a/src/ComputeSharp/Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs +++ b/src/ComputeSharp/Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs @@ -138,5 +138,6 @@ internal unsafe struct ID3D12DescriptorHandleAllocator : IDisposable public void Dispose() { this.d3D12DescriptorHeap.Dispose(); + this.d3D12DescriptorHeapNonShaderVisible.Dispose(); } } From 6359b055009ff02d21680b770d961dbc327cb373 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jul 2022 17:04:30 +0200 Subject: [PATCH 18/64] Fix access violation on NS2.0 target due to wrong marshal method --- src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index b227f950..27266a2d 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -18,7 +18,7 @@ unsafe partial class GraphicsDevice /// /// A cached instance wrapping . /// - private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackForRegisterDeviceLostCallbackWrapper = WaitForSingleObjectCallbackForWaitForFenceAsync; + private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackForRegisterDeviceLostCallbackWrapper = WaitForSingleObjectCallbackForRegisterDeviceLostCallback; #endif /// From aa50b021447cbce2ac4e84a7e3e923e4022f3f2e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Jul 2022 15:16:03 +0200 Subject: [PATCH 19/64] Add device disposal reference counting tests --- .../ComputeSharp.Tests.DeviceLost.csproj | 10 ++ .../DeviceDisposalTests.cs | 120 ++++++++++++++++++ .../DeviceLostTests.cs | 3 +- .../Properties/AssemblyInfo.cs | 3 + 4 files changed, 134 insertions(+), 2 deletions(-) create mode 100644 tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs create mode 100644 tests/ComputeSharp.Tests.DeviceLost/Properties/AssemblyInfo.cs diff --git a/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj b/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj index 8fe2d777..ebc7641b 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj +++ b/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj @@ -18,6 +18,16 @@ + + + + + + + + $(NoWarn);CS0649 + diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs new file mode 100644 index 00000000..a132eabd --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs @@ -0,0 +1,120 @@ +using ComputeSharp.Interop; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable CA1416 + +namespace ComputeSharp.Tests.DeviceLost; + +[TestClass] +[TestCategory("DeviceDisposal")] +public class DeviceDisposalTests +{ + [CombinatorialTestMethod] + public unsafe void DeviceDisposal_GetDefault_ReferenceCounting() + { + using ComPtr d3D12Device = default; + + using (GraphicsDevice graphicsDevice = GraphicsDevice.Default) + { + InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + } + + // This test has to ensure a GraphicsDevice instance correctly destroys the underlying device + // when disposed. To verify this, we first get the underlying ID3D12Device* object, which causes + // its reference count to be incremented by 1. Assuming GraphicsDevice is working correctly, once + // it is disposed, the underlying ID3D12Device* object should have its ref count set to just 1, + // which is the one we added when doing QueryInterface on it. To verify this, we first increment + // that, and then release it to get the updated count. If everything is correct, the ref count + // we got back should be 1, with the last one just being from our own ID3D12Device* local. We + // can't just do Release() and check that, as that'd cause the ref count to just go to 0 but + // without clearing the pointer stored in the ComPtr local, which would then crash when + // going out of scope and trying to dereference that object to call Release() on it. + _ = d3D12Device.Get()->AddRef(); + + uint refCount = d3D12Device.Get()->Release(); + + Assert.AreEqual(refCount, 1u); + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void DeviceDisposal_ReferenceCounting(Device device) + { + using ComPtr d3D12Device = default; + + using (GraphicsDevice graphicsDevice = device.Get()) + { + InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + } + + _ = d3D12Device.Get()->AddRef(); + + uint refCount = d3D12Device.Get()->Release(); + + Assert.AreEqual(refCount, 1u); + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void DeviceDisposal_DisposedResources_ReferenceCounting(Device device) + { + using ComPtr d3D12Device = default; + + using (GraphicsDevice graphicsDevice = device.Get()) + { + using var r1 = graphicsDevice.AllocateConstantBuffer(128); + using var r2 = graphicsDevice.AllocateReadOnlyBuffer(128); + using var r3 = graphicsDevice.AllocateReadWriteBuffer(128); + using var r4 = graphicsDevice.AllocateReadOnlyTexture2D(128, 128); + using var r5 = graphicsDevice.AllocateReadWriteTexture2D(128, 128); + + InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + } + + _ = d3D12Device.Get()->AddRef(); + + uint refCount = d3D12Device.Get()->Release(); + + Assert.AreEqual(refCount, 1u); + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void DeviceDisposal_DisposedResourcesAfterDevice_ReferenceCounting(Device device) + { + using ComPtr d3D12Device = default; + + ConstantBuffer r1; + ReadOnlyBuffer r2; + ReadWriteBuffer r3; + ReadOnlyTexture2D r4; + ReadWriteTexture2D r5; + + using (GraphicsDevice graphicsDevice = device.Get()) + { + r1 = graphicsDevice.AllocateConstantBuffer(128); + r2 = graphicsDevice.AllocateReadOnlyBuffer(128); + r3 = graphicsDevice.AllocateReadWriteBuffer(128); + r4 = graphicsDevice.AllocateReadOnlyTexture2D(128, 128); + r5 = graphicsDevice.AllocateReadWriteTexture2D(128, 128); + + InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + } + + r1.Dispose(); + r2.Dispose(); + r3.Dispose(); + r4.Dispose(); + r5.Dispose(); + + _ = d3D12Device.Get()->AddRef(); + + uint refCount = d3D12Device.Get()->Release(); + + Assert.AreEqual(refCount, 1u); + } +} diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs index 73c4c8cb..7c0cf7d1 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs @@ -12,8 +12,7 @@ namespace ComputeSharp.Tests.DeviceLost; [TestClass] [TestCategory("DeviceLost")] -[DoNotParallelize] -public partial class DeviceLostTests +public class DeviceLostTests { [CombinatorialTestMethod] [AllDevices] diff --git a/tests/ComputeSharp.Tests.DeviceLost/Properties/AssemblyInfo.cs b/tests/ComputeSharp.Tests.DeviceLost/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..8ed86d91 --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[assembly: DoNotParallelize] From 701c88983ce70508725abc2cf2fb24a65c90aacf Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Jul 2022 16:19:08 +0200 Subject: [PATCH 20/64] Add DeviceLostReason.AccessDenied value --- src/ComputeSharp/Graphics/DeviceLostReason.cs | 23 +++++++++++++------ .../Graphics/GraphicsDevice.DeviceLost.cs | 1 + 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/ComputeSharp/Graphics/DeviceLostReason.cs b/src/ComputeSharp/Graphics/DeviceLostReason.cs index 3161ec7e..b27f1132 100644 --- a/src/ComputeSharp/Graphics/DeviceLostReason.cs +++ b/src/ComputeSharp/Graphics/DeviceLostReason.cs @@ -1,4 +1,7 @@ -namespace ComputeSharp; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp; /// /// Indicates a reason a instance was lost. @@ -9,33 +12,39 @@ public enum DeviceLostReason /// The application's device failed due to badly formed commands sent by the application. /// This is an design-time issue that should be investigated and fixed. /// - DeviceHung = unchecked((int)0x887A0006), + DeviceHung = DXGI.DXGI_ERROR_DEVICE_HUNG, /// /// The video card has been physically removed from the system, or a driver upgrade for /// the video card has occurred. The application should destroy and recreate the device. /// - DeviceRemoved = unchecked((int)0x887A0005), + DeviceRemoved = DXGI.DXGI_ERROR_DEVICE_REMOVED, /// /// The device failed due to a badly formed command. This is a run-time issue. /// The application should destroy and recreate the device. /// - DeviceReset = unchecked((int)0x887A0007), + DeviceReset = DXGI.DXGI_ERROR_DEVICE_RESET, /// /// The driver encountered a problem and was put into the device removed state. /// - DriverInternalError = unchecked((int)0x887A0020), + DriverInternalError = DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR, /// /// The application provided invalid parameter data. /// This must be debugged and fixed before the application is released. /// - InvalidCall = unchecked((int)0x887A0001), + InvalidCall = DXGI.DXGI_ERROR_INVALID_CALL, + + /// + /// The device was removed after attempting an invalid operation (eg. trying to write to the wrong swapchain buffer). + /// The application should destroy and recreate the device. This also likely indicates an application bug. + /// + AccessDenied = DXGI.DXGI_ERROR_ACCESS_DENIED, /// /// The device was lost for an unspecified reason. /// - UnspecifiedError = unchecked((int)0x80004005) + UnspecifiedError = E.E_FAIL } diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index 27266a2d..c6febdb6 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -90,6 +90,7 @@ unsafe partial class GraphicsDevice DXGI.DXGI_ERROR_DEVICE_RESET => DeviceLostReason.DeviceReset, DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR => DeviceLostReason.DriverInternalError, DXGI.DXGI_ERROR_INVALID_CALL => DeviceLostReason.InvalidCall, + DXGI.DXGI_ERROR_ACCESS_DENIED => DeviceLostReason.AccessDenied, _ => DeviceLostReason.UnspecifiedError }; From ca96337b8a8f5cfd70186ef03330e07979945ae3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Jul 2022 17:32:56 +0200 Subject: [PATCH 21/64] Add GraphicsDevice.GetDefault() declaration --- .../Graphics/GraphicsDevice.GetDevice.cs | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs index 242f51bd..41dbd338 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs @@ -20,6 +20,42 @@ partial class GraphicsDevice /// public static GraphicsDevice Default => DeviceHelper.DefaultFactory.Value; + /// + /// Gets or creates the default instance for the current machine. + /// + /// The default define is the first device supporting the required feature level that could + /// be created when enumerating the available adapters in performance order. That is, it is + /// conceptually equivalent to the first successfully created device from . + /// + /// + /// The default instance for the current machine. + /// + /// The returned is cached across multiple invocations. In order to + /// support device lost scenarios (see ) and due to how the DirectX 12 + /// runtime handles caching of device instances, this method has the following behavior: + /// + /// If no device has been created, create the default one, cache it, and return it. + /// If a cached device is available, return that. + /// If the returned device is disposed, the cache is reset. + /// + /// If is called again after that, the returned device might map to a different adapter. + /// This would be the case if the first device was lost due to the adapter being removed from the system. + /// + /// + /// There is one additional caveat to the list above: if is called, then that device is lost, then + /// the returned instance is disposed incorrectly (eg. with some existing resources not being + /// disposed, which would keep the underlying device object alive), calling again will result in + /// an exception instead of a different device being returned. That is, if enumerating adapters and trying to create a device + /// fails due to device lost (as opposed to other valid failures when trying to normally create a device), an exception will be + /// thrown instead of just skipping that adapter, because that would mean a device had been created but incorrectly disposed. + /// + /// Thrown if the target device was lost and incorrectly disposed (see remarks). + /// Thrown if no adapter could be created (this should never be the case). + public static GraphicsDevice GetDefault() + { + throw new NotImplementedException(); + } + /// /// Enumerates all the currently available devices supporting the minimum necessary feature level. /// Physical devices and integrated GPUs will be enumerated first, and the WARP device will always be last. From ea0f792ae6c520d0f4362c5fe8b7c0323f80ee27 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 16 Jul 2022 14:24:57 +0200 Subject: [PATCH 22/64] Implement GraphicsDevice.GetDefault() method --- .../Graphics/GraphicsDevice.GetDevice.cs | 2 +- .../Graphics/Helpers/DeviceHelper.Factory.cs | 39 +++++++ .../Graphics/Helpers/DeviceHelper.cs | 108 ++++++++++-------- 3 files changed, 99 insertions(+), 50 deletions(-) diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs index 41dbd338..68e678c8 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs @@ -53,7 +53,7 @@ partial class GraphicsDevice /// Thrown if no adapter could be created (this should never be the case). public static GraphicsDevice GetDefault() { - throw new NotImplementedException(); + return DeviceHelper.GetDefaultDeviceFromCacheOrCreateInstance(); } /// diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs index 8445a801..78bfce29 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Extensions; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -18,6 +19,44 @@ partial class DeviceHelper /// private static readonly Dictionary> D3D12InfoQueueMap = new(); + /// + /// The cached default instance, if any. + /// + internal static GraphicsDevice? defaultDevice; + + /// + /// Gets the cached instance or creates and caches a new one. + /// + /// The default instance. + public static unsafe GraphicsDevice GetDefaultDeviceFromCacheOrCreateInstance() + { + lock (DevicesCache) + { + do + { + GraphicsDevice? defaultDevice = DeviceHelper.defaultDevice; + + // Fast path retrieving the cached instance and returning it + if (defaultDevice is not null) + { + return defaultDevice; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static void InitializeAndAssignDefaultDevice() + { + DeviceHelper.defaultDevice = GetOrCreateDefaultDevice(); + } + + // Non inlined method to load the default device and assign it to the + // cached field. If this method returns, then the default device has + // correctly been initialized. Otherwise, the method will just throw. + InitializeAndAssignDefaultDevice(); + } + while (true); + } + } + /// /// Retrieves a instance for an object. /// diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs index d31e3065..ab635502 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs @@ -30,7 +30,7 @@ internal static partial class DeviceHelper /// /// The instance used to produce the default instance. /// - public static readonly Lazy DefaultFactory = new(GetDefaultDevice); + public static readonly Lazy DefaultFactory = new(GetOrCreateDefaultDevice); /// /// Gets the of the default device. @@ -56,7 +56,7 @@ internal static partial class DeviceHelper /// /// The default instance supporting and . /// Thrown when a default device is not available. - private static unsafe GraphicsDevice GetDefaultDevice() + private static unsafe GraphicsDevice GetOrCreateDefaultDevice() { using ComPtr d3D12Device = default; using ComPtr dxgiAdapter = default; @@ -79,6 +79,7 @@ internal static partial class DeviceHelper /// A pointer to the object used to create , or . /// A pointer to the value for the device found. /// Whether a default device was found with the requested feature level. + /// Thrown if the target device was lost and incorrectly disposed (see remarks). private static unsafe bool TryGetDefaultDevice(ID3D12Device** d3D12Device, IDXGIAdapter** dxgiAdapter, DXGI_ADAPTER_DESC1* dxgiDescription1) { using ComPtr dxgiFactory6 = default; @@ -106,60 +107,48 @@ internal static partial class DeviceHelper dxgiAdapter1.Get()->GetDesc1(dxgiDescription1).Assert(); + // Skip the WARP adapter if (dxgiDescription1->VendorId == MicrosoftVendorId && dxgiDescription1->DeviceId == WarpDeviceId) { continue; } - // Explicit paths for when a device is being retrieved or not, with special handling - // for the additional check that is required for the SM6 level. This can't be checked - // without creating a device first, so the path for when the target device pointer is - // null is useful to do an initial filtering using D3D12CreateDevice to avoid creating - // a device for adapters that would've failed at the FL11 check already. - if (d3D12Device == null) + using ComPtr d3D12DeviceCandidate = default; + + // Try to create a device for the current adapter. There are 3 possible results here: + // 1) The call succeeds. In this case the first device retrieved is the default one. + // 2) The call fails for a device lost reason. This indicates a default device was + // previously retrieved but not disposed correctly. In this case, the code throws. + // 3) The call fails for other reasons. In this case the adapter is simply skipped. + // This might be the case if an adapter doesn't support the requested feature level. + HRESULT createDeviceResult = DirectX.D3D12CreateDevice( + dxgiAdapter1.AsIUnknown().Get(), + D3D_FEATURE_LEVEL_11_0, + Windows.__uuidof(), + d3D12DeviceCandidate.GetVoidAddressOf()); + + // Check and throw if the device is a device lost state and not disposed properly + if ((int)createDeviceResult is + DXGI.DXGI_ERROR_DEVICE_HUNG or + DXGI.DXGI_ERROR_DEVICE_REMOVED or + DXGI.DXGI_ERROR_DEVICE_RESET or + DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR or + DXGI.DXGI_ERROR_INVALID_CALL or + DXGI.DXGI_ERROR_ACCESS_DENIED) { - HRESULT createDeviceResult = DirectX.D3D12CreateDevice( - dxgiAdapter1.AsIUnknown().Get(), - D3D_FEATURE_LEVEL_11_0, - Windows.__uuidof(), - null); - - if (Windows.SUCCEEDED(createDeviceResult)) - { - using ComPtr d3D12DeviceCandidate = default; - - createDeviceResult = DirectX.D3D12CreateDevice( - dxgiAdapter1.AsIUnknown().Get(), - D3D_FEATURE_LEVEL_11_0, - Windows.__uuidof(), - d3D12DeviceCandidate.GetVoidAddressOf()); - - if (Windows.SUCCEEDED(createDeviceResult) && - d3D12DeviceCandidate.Get()->IsShaderModelSupported(D3D_SHADER_MODEL_6_0)) - { - return true; - } - } + ThrowHelper.ThrowInvalidOperationException("The default device is in device lost state and has not been disposed properly."); } - else + + // Check for success, and then also filter out devices that support SM6.0. This can + // only be checked on a concrete ID3D12Device instance, so it can't be done earlier. + if (Windows.SUCCEEDED(createDeviceResult) && + d3D12DeviceCandidate.Get()->IsShaderModelSupported(D3D_SHADER_MODEL_6_0)) { - using ComPtr d3D12DeviceCandidate = default; + d3D12DeviceCandidate.CopyTo(d3D12Device); + dxgiAdapter1.CopyTo(dxgiAdapter); - HRESULT createDeviceResult = DirectX.D3D12CreateDevice( - dxgiAdapter1.AsIUnknown().Get(), - D3D_FEATURE_LEVEL_11_0, - Windows.__uuidof(), - d3D12DeviceCandidate.GetVoidAddressOf()); - - if (Windows.SUCCEEDED(createDeviceResult) && - d3D12DeviceCandidate.Get()->IsShaderModelSupported(D3D_SHADER_MODEL_6_0)) - { - d3D12DeviceCandidate.CopyTo(d3D12Device); - dxgiAdapter1.CopyTo(dxgiAdapter); - - return true; - } + return true; } } } @@ -171,6 +160,7 @@ internal static partial class DeviceHelper /// A pointer to the object used to create , or . /// A pointer to the value for the device found. /// Whether a warp device was created successfully. + /// Thrown if the target device was lost and incorrectly disposed (see remarks). private static unsafe bool TryGetWarpDevice(ID3D12Device** d3D12Device, IDXGIAdapter** dxgiAdapter, DXGI_ADAPTER_DESC1* dxgiDescription1) { using ComPtr dxgiFactory6 = default; @@ -183,14 +173,34 @@ internal static partial class DeviceHelper dxgiAdapter1.Get()->GetDesc1(dxgiDescription1).Assert(); + using ComPtr d3D12DeviceCandidate = default; + HRESULT createDeviceResult = DirectX.D3D12CreateDevice( dxgiAdapter1.AsIUnknown().Get(), D3D_FEATURE_LEVEL_11_0, Windows.__uuidof(), - (void**)d3D12Device); + d3D12DeviceCandidate.GetVoidAddressOf()); - dxgiAdapter1.CopyTo(dxgiAdapter); + if ((int)createDeviceResult is + DXGI.DXGI_ERROR_DEVICE_HUNG or + DXGI.DXGI_ERROR_DEVICE_REMOVED or + DXGI.DXGI_ERROR_DEVICE_RESET or + DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR or + DXGI.DXGI_ERROR_INVALID_CALL or + DXGI.DXGI_ERROR_ACCESS_DENIED) + { + ThrowHelper.ThrowInvalidOperationException("The default device is in device lost state and has not been disposed properly."); + } - return Windows.SUCCEEDED(createDeviceResult); + // There is no need to check for SM6.0, as it's guaranteed to be supported by Windows + if (Windows.SUCCEEDED(createDeviceResult)) + { + d3D12DeviceCandidate.CopyTo(d3D12Device); + dxgiAdapter1.CopyTo(dxgiAdapter); + + return true; + } + + return false; } } From 4e5acba69cadf02bab2ac7555c0e9794d8e4fa91 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 16 Jul 2022 14:47:29 +0200 Subject: [PATCH 23/64] Remove GraphicsDevice.Default property and APIs --- .../Blas/BlasBenchmark.cs | 20 +++++----- .../Dispatching/DispatchingBenchmark.cs | 16 ++++---- .../Processors/HlslBokehBlurProcessor.cs | 4 +- .../Processors/HlslGaussianBlurProcessor.cs | 4 +- samples/ComputeSharp.Sample.FSharp/Program.fs | 4 +- samples/ComputeSharp.Sample/Program.cs | 4 +- .../Backend/SwapChainApplication{T}.cs | 6 +-- samples/ComputeSharp.SwapChain/Program.cs | 2 +- .../Helpers/SwapChainManager.cs | 4 +- .../Graphics/GraphicsDevice.GetDevice.cs | 12 ------ .../Graphics/Helpers/DeviceHelper.cs | 24 ----------- .../Graphics/Interop/NativeObject.cs | 12 ------ tests/ComputeSharp.Dynamic.NuGet/Program.cs | 4 +- tests/ComputeSharp.NuGet/Program.cs | 4 +- tests/ComputeSharp.Pix.NuGet/Program.cs | 4 +- .../DeviceDisposalTests.cs | 2 +- .../ShaderDataLoaderTests.cs | 40 +++++++++---------- .../ShaderHashCodeTests.cs | 4 +- .../ComputeSharp.Tests/InitializationTests.cs | 12 +++--- 19 files changed, 67 insertions(+), 115 deletions(-) diff --git a/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs b/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs index 0dd6f5a4..326d0527 100644 --- a/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs @@ -100,10 +100,10 @@ public class BlasBenchmark : IDisposable B = CreateRandomArray(P); Y = CreateRandomArray(C * N * P); - BufferX = GraphicsDevice.Default.AllocateReadOnlyBuffer(X); - BufferW = GraphicsDevice.Default.AllocateReadOnlyBuffer(W); - BufferB = GraphicsDevice.Default.AllocateReadOnlyBuffer(B); - BufferY = GraphicsDevice.Default.AllocateReadWriteBuffer(Y); + BufferX = GraphicsDevice.GetDefault().AllocateReadOnlyBuffer(X); + BufferW = GraphicsDevice.GetDefault().AllocateReadOnlyBuffer(W); + BufferB = GraphicsDevice.GetDefault().AllocateReadOnlyBuffer(B); + BufferY = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(Y); Cpu(); GpuWithNoTemporaryBuffers(); @@ -140,7 +140,7 @@ public class BlasBenchmark : IDisposable [Benchmark] public void GpuWithNoTemporaryBuffers() { - BlasHelpers.FullyConnectedForwardGpu(GraphicsDevice.Default, C, N, M, P, BufferX!, BufferW!, BufferB!, BufferY!); + BlasHelpers.FullyConnectedForwardGpu(GraphicsDevice.GetDefault(), C, N, M, P, BufferX!, BufferW!, BufferB!, BufferY!); } /// @@ -149,12 +149,12 @@ public class BlasBenchmark : IDisposable [Benchmark] public void GpuWithTemporaryBuffers() { - using ReadOnlyBuffer x = GraphicsDevice.Default.AllocateReadOnlyBuffer(X!); - using ReadOnlyBuffer w = GraphicsDevice.Default.AllocateReadOnlyBuffer(W!); - using ReadOnlyBuffer b = GraphicsDevice.Default.AllocateReadOnlyBuffer(B!); - using ReadWriteBuffer y = GraphicsDevice.Default.AllocateReadWriteBuffer(Y!.Length); + using ReadOnlyBuffer x = GraphicsDevice.GetDefault().AllocateReadOnlyBuffer(X!); + using ReadOnlyBuffer w = GraphicsDevice.GetDefault().AllocateReadOnlyBuffer(W!); + using ReadOnlyBuffer b = GraphicsDevice.GetDefault().AllocateReadOnlyBuffer(B!); + using ReadWriteBuffer y = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(Y!.Length); - BlasHelpers.FullyConnectedForwardGpu(GraphicsDevice.Default, C, N, M, P, x, w, b, y); + BlasHelpers.FullyConnectedForwardGpu(GraphicsDevice.GetDefault(), C, N, M, P, x, w, b, y); y.CopyTo(Y); } diff --git a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs index e94a1e95..f7c71449 100644 --- a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs @@ -23,7 +23,7 @@ public partial class DispatchingBenchmark : IDisposable [GlobalSetup] public void Setup() { - Buffer = GraphicsDevice.Default.AllocateReadWriteBuffer(128); + Buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(128); } /// @@ -40,7 +40,7 @@ public partial class DispatchingBenchmark : IDisposable [BenchmarkCategory("SINGLE")] public void Compute_Single() { - GraphicsDevice.Default.For(64, new TestShader(Buffer!)); + GraphicsDevice.GetDefault().For(64, new TestShader(Buffer!)); } /// @@ -50,7 +50,7 @@ public partial class DispatchingBenchmark : IDisposable [BenchmarkCategory("SINGLE")] public void Compute_Single_WithContext() { - using var context = GraphicsDevice.Default.CreateComputeContext(); + using var context = GraphicsDevice.GetDefault().CreateComputeContext(); context.For(64, new TestShader(Buffer!)); } @@ -62,7 +62,7 @@ public partial class DispatchingBenchmark : IDisposable [BenchmarkCategory("SINGLE")] public async Task Compute_Single_WithContext_Async() { - await using var context = GraphicsDevice.Default.CreateComputeContext(); + await using var context = GraphicsDevice.GetDefault().CreateComputeContext(); context.For(64, new TestShader(Buffer!)); } @@ -74,8 +74,8 @@ public partial class DispatchingBenchmark : IDisposable [BenchmarkCategory("MULTIPLE")] public void Compute_Multiple() { - GraphicsDevice.Default.For(64, new TestShader(Buffer!)); - GraphicsDevice.Default.For(64, new TestShader(Buffer!)); + GraphicsDevice.GetDefault().For(64, new TestShader(Buffer!)); + GraphicsDevice.GetDefault().For(64, new TestShader(Buffer!)); } /// @@ -85,7 +85,7 @@ public partial class DispatchingBenchmark : IDisposable [BenchmarkCategory("MULTIPLE")] public void Compute_Multiple_WithContext() { - using var context = GraphicsDevice.Default.CreateComputeContext(); + using var context = GraphicsDevice.GetDefault().CreateComputeContext(); context.For(64, new TestShader(Buffer!)); context.Barrier(Buffer!); @@ -99,7 +99,7 @@ public partial class DispatchingBenchmark : IDisposable [BenchmarkCategory("MULTIPLE")] public async Task Compute_Multiple_WithContext_Async() { - await using var context = GraphicsDevice.Default.CreateComputeContext(); + await using var context = GraphicsDevice.GetDefault().CreateComputeContext(); context.For(64, new TestShader(Buffer!)); context.Barrier(Buffer!); diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs index c6372d8e..f2b1f4c7 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs @@ -26,7 +26,7 @@ public sealed partial class HlslBokehBlurProcessor : IImageProcessor /// Initializes a new instance of the class. /// public HlslBokehBlurProcessor() - : this(GraphicsDevice.Default, DefaultRadius, DefaultComponents) + : this(GraphicsDevice.GetDefault(), DefaultRadius, DefaultComponents) { } @@ -36,7 +36,7 @@ public sealed partial class HlslBokehBlurProcessor : IImageProcessor /// The size of the area to sample. /// The number of components to use to approximate the original 2D bokeh blur convolution kernel. public HlslBokehBlurProcessor(int radius, int components) - : this(GraphicsDevice.Default, radius, components) + : this(GraphicsDevice.GetDefault(), radius, components) { } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs index 95cd2a2f..b046b334 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs @@ -21,7 +21,7 @@ public sealed partial class HlslGaussianBlurProcessor : IImageProcessor /// Initializes a new instance of the class. /// public HlslGaussianBlurProcessor() - : this(GraphicsDevice.Default, DefaultSigma, 9) + : this(GraphicsDevice.GetDefault(), DefaultSigma, 9) { } @@ -30,7 +30,7 @@ public sealed partial class HlslGaussianBlurProcessor : IImageProcessor /// /// The radius value representing the size of the area to sample. public HlslGaussianBlurProcessor(int radius) - : this(GraphicsDevice.Default, radius / 3F, radius) + : this(GraphicsDevice.GetDefault(), radius / 3F, radius) { } diff --git a/samples/ComputeSharp.Sample.FSharp/Program.fs b/samples/ComputeSharp.Sample.FSharp/Program.fs index 8782690a..aa376b86 100644 --- a/samples/ComputeSharp.Sample.FSharp/Program.fs +++ b/samples/ComputeSharp.Sample.FSharp/Program.fs @@ -32,12 +32,12 @@ let main _ = let array = [| for i in 1 .. 100 -> (float32)i |] // Create the graphics buffer - use buffer = GraphicsDevice.Default.AllocateReadWriteBuffer(array) + use buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(array) let shader = new MultiplyByTwo(buffer) // Run the shader (passed by reference) - GraphicsDevice.Default.For(100, &shader) + GraphicsDevice.GetDefault().For(100, &shader) // Print the initial matrix printMatrix array 10 10 "BEFORE" diff --git a/samples/ComputeSharp.Sample/Program.cs b/samples/ComputeSharp.Sample/Program.cs index c1962f0a..64294e81 100644 --- a/samples/ComputeSharp.Sample/Program.cs +++ b/samples/ComputeSharp.Sample/Program.cs @@ -6,10 +6,10 @@ using ComputeSharp.Sample; float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray(); // Create the graphics buffer -using ReadWriteBuffer gpuBuffer = GraphicsDevice.Default.AllocateReadWriteBuffer(array); +using ReadWriteBuffer gpuBuffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(array); // Run the shader -GraphicsDevice.Default.For(100, new MultiplyByTwo(gpuBuffer)); +GraphicsDevice.GetDefault().For(100, new MultiplyByTwo(gpuBuffer)); // Print the initial matrix Formatting.PrintMatrix(array, 10, 10, "BEFORE"); diff --git a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs index 18077d7f..cc15dc39 100644 --- a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs +++ b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs @@ -90,7 +90,7 @@ internal sealed class SwapChainApplication : Win32Application // Get the underlying ID3D12Device in use fixed (ID3D12Device** d3D12Device = this.d3D12Device) { - _ = InteropServices.TryGetID3D12Device(GraphicsDevice.Default, Windows.__uuidof(), (void**)d3D12Device); + _ = InteropServices.TryGetID3D12Device(GraphicsDevice.GetDefault(), Windows.__uuidof(), (void**)d3D12Device); } // Create the direct command queue to use @@ -217,7 +217,7 @@ internal sealed class SwapChainApplication : Win32Application D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc(); // Create the 2D texture to use to generate frames to display - this.texture = GraphicsDevice.Default.AllocateReadWriteTexture2D( + this.texture = GraphicsDevice.GetDefault().AllocateReadWriteTexture2D( (int)d3D12Resource0Description.Width, (int)d3D12Resource0Description.Height); } @@ -233,7 +233,7 @@ internal sealed class SwapChainApplication : Win32Application } // Generate the new frame - GraphicsDevice.Default.ForEach(this.texture!, this.shaderFactory(time)); + GraphicsDevice.GetDefault().ForEach(this.texture!, this.shaderFactory(time)); using ComPtr d3D12Resource = default; diff --git a/samples/ComputeSharp.SwapChain/Program.cs b/samples/ComputeSharp.SwapChain/Program.cs index 0601b382..f34c3b3c 100644 --- a/samples/ComputeSharp.SwapChain/Program.cs +++ b/samples/ComputeSharp.SwapChain/Program.cs @@ -77,6 +77,6 @@ class Program { string filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Textures", $"{name}.png"); - return GraphicsDevice.Default.LoadReadOnlyTexture2D(filename); + return GraphicsDevice.GetDefault().LoadReadOnlyTexture2D(filename); } } diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 66417e4d..32af7800 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -239,7 +239,7 @@ internal sealed unsafe partial class SwapChainManager : NativeObject // Get the underlying ID3D12Device in use fixed (ID3D12Device** d3D12Device = this.d3D12Device) { - GraphicsDevice.Default.D3D12Device->QueryInterface(Win32.__uuidof(), (void**)d3D12Device).Assert(); + GraphicsDevice.GetDefault().D3D12Device->QueryInterface(Win32.__uuidof(), (void**)d3D12Device).Assert(); } // Create the direct command queue to use @@ -394,7 +394,7 @@ internal sealed unsafe partial class SwapChainManager : NativeObject // Dispose the previous texture, if present, and create the new 2D texture to use to generate frames to display this.texture?.Dispose(); - this.texture = GraphicsDevice.Default.AllocateReadWriteTexture2D((int)resizedWidth, (int)resizeHeight); + this.texture = GraphicsDevice.GetDefault().AllocateReadWriteTexture2D((int)resizedWidth, (int)resizeHeight); } } diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs index 68e678c8..e17a64dd 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs @@ -8,18 +8,6 @@ namespace ComputeSharp; /// partial class GraphicsDevice { - /// - /// Gets the default instance for the current machine. - /// This instance cannot be manually disposed - attempting to do so is safe and it will - /// not cause an exception, but it will simply do nothing and not dispose the device. - /// - /// - /// This device will always be available, even when there isn't a compatible physical GPU - /// or integrated GPU in the system in use. In that case, the WARP device will be used. - /// For more info, see . - /// - public static GraphicsDevice Default => DeviceHelper.DefaultFactory.Value; - /// /// Gets or creates the default instance for the current machine. /// diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs index ab635502..256e4eab 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs @@ -27,30 +27,6 @@ internal static partial class DeviceHelper /// private const uint WarpDeviceId = 0x8C; - /// - /// The instance used to produce the default instance. - /// - public static readonly Lazy DefaultFactory = new(GetOrCreateDefaultDevice); - - /// - /// Gets the of the default device. - /// - /// The of the default device supporting and . - /// This methods assumes that a default device is available. - public static unsafe Luid GetDefaultDeviceLuid() - { - if (DefaultFactory.IsValueCreated) - { - return DefaultFactory.Value.Luid; - } - - DXGI_ADAPTER_DESC1 dxgiDescription1; - - _ = TryGetDefaultDevice(null, null, &dxgiDescription1) || TryGetWarpDevice(null, null, &dxgiDescription1); - - return Luid.FromLUID(dxgiDescription1.AdapterLuid); - } - /// /// Gets the default instance. /// diff --git a/src/ComputeSharp/Graphics/Interop/NativeObject.cs b/src/ComputeSharp/Graphics/Interop/NativeObject.cs index 01cab286..f0310f90 100644 --- a/src/ComputeSharp/Graphics/Interop/NativeObject.cs +++ b/src/ComputeSharp/Graphics/Interop/NativeObject.cs @@ -1,7 +1,6 @@ using System; using System.Runtime.CompilerServices; using System.Threading; -using ComputeSharp.Graphics.Helpers; namespace ComputeSharp.Interop; @@ -39,17 +38,6 @@ public abstract class NativeObject : IDisposable [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { - // If the current instance is a graphics device, check that the LUID doesn't - // match the one for the default device, which is deliberately never disposed. - // This type check is inlined and then resolved at JIT time if the target instance - // is visible to the compiler. That is, if Dispose() is explicitly called on a - // sealed type that is not GraphicsDevice, this entire path will just be removed. - if (GetType() == typeof(GraphicsDevice) && - DeviceHelper.GetDefaultDeviceLuid() == Unsafe.As(this).Luid) - { - return; - } - if (Interlocked.CompareExchange(ref this.isDisposed, 1, 0) == 0) { [MethodImpl(MethodImplOptions.NoInlining)] diff --git a/tests/ComputeSharp.Dynamic.NuGet/Program.cs b/tests/ComputeSharp.Dynamic.NuGet/Program.cs index 31b654f0..7792c298 100644 --- a/tests/ComputeSharp.Dynamic.NuGet/Program.cs +++ b/tests/ComputeSharp.Dynamic.NuGet/Program.cs @@ -5,10 +5,10 @@ using ComputeSharp; float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray(); // Create the graphics buffer -using ReadWriteBuffer gpuBuffer = GraphicsDevice.Default.AllocateReadWriteBuffer(array); +using ReadWriteBuffer gpuBuffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(array); // Run the shader -GraphicsDevice.Default.For(100, new MultiplyByTwo(gpuBuffer)); +GraphicsDevice.GetDefault().For(100, new MultiplyByTwo(gpuBuffer)); // Get the data back float[] result = gpuBuffer.ToArray(); diff --git a/tests/ComputeSharp.NuGet/Program.cs b/tests/ComputeSharp.NuGet/Program.cs index 591d80de..a0b3885d 100644 --- a/tests/ComputeSharp.NuGet/Program.cs +++ b/tests/ComputeSharp.NuGet/Program.cs @@ -5,10 +5,10 @@ using ComputeSharp; float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray(); // Create the graphics buffer -using ReadWriteBuffer gpuBuffer = GraphicsDevice.Default.AllocateReadWriteBuffer(array); +using ReadWriteBuffer gpuBuffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(array); // Run the shader -GraphicsDevice.Default.For(100, new MultiplyByTwo(gpuBuffer)); +GraphicsDevice.GetDefault().For(100, new MultiplyByTwo(gpuBuffer)); // Get the data back float[] result = gpuBuffer.ToArray(); diff --git a/tests/ComputeSharp.Pix.NuGet/Program.cs b/tests/ComputeSharp.Pix.NuGet/Program.cs index c2119998..9544e448 100644 --- a/tests/ComputeSharp.Pix.NuGet/Program.cs +++ b/tests/ComputeSharp.Pix.NuGet/Program.cs @@ -5,10 +5,10 @@ using ComputeSharp; float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray(); // Create the graphics buffer -using ReadWriteBuffer gpuBuffer = GraphicsDevice.Default.AllocateReadWriteBuffer(array); +using ReadWriteBuffer gpuBuffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(array); // Run the shader -using (var context = GraphicsDevice.Default.CreateComputeContext()) +using (var context = GraphicsDevice.GetDefault().CreateComputeContext()) { context.Log("Dispatching shader"); context.BeginEvent("Dispatching event"); diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs index a132eabd..55d851f5 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs @@ -18,7 +18,7 @@ public class DeviceDisposalTests { using ComPtr d3D12Device = default; - using (GraphicsDevice graphicsDevice = GraphicsDevice.Default) + using (GraphicsDevice graphicsDevice = GraphicsDevice.GetDefault()) { InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); } diff --git a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs index 6b6274fd..4071dbb1 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs @@ -23,11 +23,11 @@ public partial class ShaderDataLoaderTests [TestMethod] public unsafe void CapturedResource() { - using ReadWriteBuffer buffer = GraphicsDevice.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); - ((IShader)new CapturedResourceShader(buffer)).LoadDispatchData(ref dataLoader, GraphicsDevice.Default, 111, 222, 333); + ((IShader)new CapturedResourceShader(buffer)).LoadDispatchData(ref dataLoader, GraphicsDevice.GetDefault(), 111, 222, 333); Assert.AreEqual(3, dataLoader.Values.Length); Assert.AreEqual(1, dataLoader.Resources.Length); @@ -55,12 +55,12 @@ public partial class ShaderDataLoaderTests [TestMethod] public unsafe void LoadMultipleResourcesAndPrimitives() { - using ReadWriteBuffer buffer0 = GraphicsDevice.Default.AllocateReadWriteBuffer(16); - using ReadWriteBuffer buffer1 = GraphicsDevice.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer buffer0 = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); + using ReadWriteBuffer buffer1 = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); - ((IShader)new MultipleResourcesAndPrimitivesShader(buffer0, buffer1, 1, 22, 77)).LoadDispatchData(ref dataLoader, GraphicsDevice.Default, 111, 222, 333); + ((IShader)new MultipleResourcesAndPrimitivesShader(buffer0, buffer1, 1, 22, 77)).LoadDispatchData(ref dataLoader, GraphicsDevice.GetDefault(), 111, 222, 333); Assert.AreEqual(6, dataLoader.Values.Length); Assert.AreEqual(2, dataLoader.Resources.Length); @@ -94,12 +94,12 @@ public partial class ShaderDataLoaderTests [TestMethod] public unsafe void LoadScalarAndVectorTypes() { - using ReadWriteBuffer buffer = GraphicsDevice.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); ScalarAndVectorTypesShader shader = new(buffer, new(55, 44, 888), 22, 77, new(3.14, 6.28), 42, 9999); - ((IShader)shader).LoadDispatchData(ref dataLoader, GraphicsDevice.Default, 111, 222, 333); + ((IShader)shader).LoadDispatchData(ref dataLoader, GraphicsDevice.GetDefault(), 111, 222, 333); Assert.AreEqual(18, dataLoader.Values.Length); Assert.AreEqual(1, dataLoader.Resources.Length); @@ -147,7 +147,7 @@ public partial class ShaderDataLoaderTests [TestMethod] public unsafe void LoadScalarVectorAndMatrixTypes() { - using ReadWriteBuffer buffer = GraphicsDevice.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); ScalarVectorAndMatrixTypesShader shader = new( @@ -161,7 +161,7 @@ public partial class ShaderDataLoaderTests i2x2: new(11, 22, 33, 44), d: 9999); - ((IShader)shader).LoadDispatchData(ref dataLoader, GraphicsDevice.Default, 111, 222, 333); + ((IShader)shader).LoadDispatchData(ref dataLoader, GraphicsDevice.GetDefault(), 111, 222, 333); Assert.AreEqual(31, dataLoader.Values.Length); Assert.AreEqual(1, dataLoader.Resources.Length); @@ -226,7 +226,7 @@ public partial class ShaderDataLoaderTests [TestMethod] public unsafe void LoadFlatCustomTypeShader() { - using ReadWriteBuffer buffer = GraphicsDevice.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); FlatCustomTypeShader shader = new( @@ -241,7 +241,7 @@ public partial class ShaderDataLoaderTests i2x2: new(11, 22, 33, 44), d: 9999)); - ((IShader)shader).LoadDispatchData(ref dataLoader, GraphicsDevice.Default, 111, 222, 333); + ((IShader)shader).LoadDispatchData(ref dataLoader, GraphicsDevice.GetDefault(), 111, 222, 333); Assert.AreEqual(31, dataLoader.Values.Length); Assert.AreEqual(1, dataLoader.Resources.Length); @@ -318,7 +318,7 @@ public partial class ShaderDataLoaderTests [TestMethod] public unsafe void LoadNestedCustomTypes() { - using ReadWriteBuffer buffer = GraphicsDevice.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); NestedCustomTypesShader shader = new( @@ -345,7 +345,7 @@ public partial class ShaderDataLoaderTests a: 888888, b: new(333.3f, 444.4f)))); - ((IShader)shader).LoadDispatchData(ref dataLoader, GraphicsDevice.Default, 111, 222, 333); + ((IShader)shader).LoadDispatchData(ref dataLoader, GraphicsDevice.GetDefault(), 111, 222, 333); Assert.AreEqual(47, dataLoader.Values.Length); Assert.AreEqual(1, dataLoader.Resources.Length); @@ -417,16 +417,16 @@ public partial class ShaderDataLoaderTests [TestMethod] public unsafe void AmbiguousNames() { - using ReadWriteBuffer a = GraphicsDevice.Default.AllocateReadWriteBuffer(16); - using ReadWriteBuffer b = GraphicsDevice.Default.AllocateReadWriteBuffer(16); - using ReadWriteBuffer c = GraphicsDevice.Default.AllocateReadWriteBuffer(16); - using ReadWriteBuffer x = GraphicsDevice.Default.AllocateReadWriteBuffer(16); - using ReadWriteBuffer y = GraphicsDevice.Default.AllocateReadWriteBuffer(16); - using ReadWriteBuffer z = GraphicsDevice.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer a = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); + using ReadWriteBuffer b = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); + using ReadWriteBuffer c = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); + using ReadWriteBuffer x = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); + using ReadWriteBuffer y = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); + using ReadWriteBuffer z = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(16); DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); - ((IShader)new AmbiguousNamesShader(a, b, c, x, y, z, 7777, 8888, 9999)).LoadDispatchData(ref dataLoader, GraphicsDevice.Default, 111, 222, 333); + ((IShader)new AmbiguousNamesShader(a, b, c, x, y, z, 7777, 8888, 9999)).LoadDispatchData(ref dataLoader, GraphicsDevice.GetDefault(), 111, 222, 333); Assert.AreEqual(6, dataLoader.Values.Length); Assert.AreEqual(6, dataLoader.Resources.Length); diff --git a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs index f90251a9..0dcc496d 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs @@ -25,7 +25,7 @@ public partial class ShaderHashCodeTests public void ShaderWithNoCapturedDelegates() { float value = 10; - using ReadWriteBuffer buffer = GraphicsDevice.Default.AllocateReadWriteBuffer(1); + using ReadWriteBuffer buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(1); Shader1 shader1 = new() { A = value, B = buffer }; @@ -58,7 +58,7 @@ public partial class ShaderHashCodeTests { Func f = static x => x * x; - using ReadWriteBuffer buffer = GraphicsDevice.Default.AllocateReadWriteBuffer(1); + using ReadWriteBuffer buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(1); Shader2 shader1 = new() { A = 1, B = buffer, F = f }; diff --git a/tests/ComputeSharp.Tests/InitializationTests.cs b/tests/ComputeSharp.Tests/InitializationTests.cs index fa703600..0b5f1496 100644 --- a/tests/ComputeSharp.Tests/InitializationTests.cs +++ b/tests/ComputeSharp.Tests/InitializationTests.cs @@ -13,7 +13,7 @@ public partial class InitializationTests [TestMethod] public void IsSupported() { - Assert.IsTrue(GraphicsDevice.Default is not null); + Assert.IsTrue(GraphicsDevice.GetDefault() is not null); } [CombinatorialTestMethod] @@ -31,11 +31,11 @@ public partial class InitializationTests [TestMethod] public void DisposeDefault() { - using var before = GraphicsDevice.Default.AllocateReadOnlyBuffer(128); + using var before = GraphicsDevice.GetDefault().AllocateReadOnlyBuffer(128); - GraphicsDevice.Default.Dispose(); + GraphicsDevice.GetDefault().Dispose(); - using var after = GraphicsDevice.Default.AllocateReadOnlyBuffer(128); + using var after = GraphicsDevice.GetDefault().AllocateReadOnlyBuffer(128); } [TestMethod] @@ -45,7 +45,7 @@ public partial class InitializationTests foreach (GraphicsDevice device in GraphicsDevice.EnumerateDevices()) { - if (i++ == 0) Assert.AreSame(GraphicsDevice.Default, device); + if (i++ == 0) Assert.AreSame(GraphicsDevice.GetDefault(), device); using ReadWriteBuffer buffer = device.AllocateReadWriteBuffer(128); @@ -64,7 +64,7 @@ public partial class InitializationTests foreach (GraphicsDevice device in GraphicsDevice.QueryDevices(info => info.DedicatedMemorySize >= 1024)) { - if (i++ == 0) Assert.AreSame(GraphicsDevice.Default, device); + if (i++ == 0) Assert.AreSame(GraphicsDevice.GetDefault(), device); using ReadWriteBuffer buffer = device.AllocateReadWriteBuffer(128); From 93c82feb983ba8f2fecc3b8197e7741c685af4b2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 16 Jul 2022 15:59:10 +0200 Subject: [PATCH 24/64] Reset default device on dispose --- src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs | 6 ++++++ tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs index 78bfce29..cd010295 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs @@ -94,6 +94,12 @@ partial class DeviceHelper { lock (DevicesCache) { + // Remove the default device from the cache, if it has been disposed + if (device == defaultDevice) + { + defaultDevice = null; + } + DevicesCache.Remove(device.Luid); if (Configuration.IsDebugOutputEnabled) diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs index 55d851f5..4622eb31 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs @@ -13,7 +13,7 @@ namespace ComputeSharp.Tests.DeviceLost; [TestCategory("DeviceDisposal")] public class DeviceDisposalTests { - [CombinatorialTestMethod] + [TestMethod] public unsafe void DeviceDisposal_GetDefault_ReferenceCounting() { using ComPtr d3D12Device = default; From d09d56c573502becb6afe0f2acdc62fba1cd91fa Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Jul 2022 01:45:27 +0200 Subject: [PATCH 25/64] Fix a NRE due to race condition in device lost callback --- .../Graphics/GraphicsDevice.DeviceLost.cs | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index c6febdb6..3bff93f2 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -119,7 +119,7 @@ unsafe partial class GraphicsDevice // As such, a fence event with a value of ulong.MaxValue can act as a device lost callback. device.d3D12ComputeFence.Get()->SetEventOnCompletion(ulong.MaxValue, eventHandle).Assert(); - GCHandle handle = deviceHandle = GCHandle.Alloc(device, GCHandleType.Weak); + GCHandle handle = GCHandle.Alloc(device, GCHandleType.Weak); HANDLE waitHandle; _ = Windows.RegisterWaitForSingleObject( @@ -130,10 +130,11 @@ unsafe partial class GraphicsDevice #else Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackForRegisterDeviceLostCallbackWrapper), #endif - Context: (void*)(IntPtr)handle, + Context: (void*)GCHandle.ToIntPtr(handle), dwMilliseconds: Windows.INFINITE, dwFlags: 0); + deviceHandle = handle; deviceRemovedEvent = eventHandle; deviceRemovedWaitHandle = waitHandle; } @@ -171,13 +172,23 @@ unsafe partial class GraphicsDevice [UnmanagedCallersOnly] private static void WaitForSingleObjectCallbackForRegisterDeviceLostCallback(void* pContext, byte timedOut) { - GraphicsDevice device = Unsafe.As(GCHandle.FromIntPtr((IntPtr)pContext).Target!); + GCHandle handle = GCHandle.FromIntPtr((IntPtr)pContext); + GraphicsDevice? device = Unsafe.As(handle.Target); - // The handle is guaranteed to be allocated when the callback is executed. Freeing it from here - // is needed so that the cleanup upon disposal might skip it if there's a pending execution. That - // ensures the handle is always disposed, without the disposal path having to lock and wait for it. - device.deviceHandle.Free(); + // Since the GCHandle is weak, it's possible that if the callback races against the finalizer thread, + // the call to UnregisterDeviceLostCallback might not be able to unregister the wait before the object + // is collected, which causes the GCHandle to return null. To guard against this, it is crucial to + // free the handle from the input context, and not by trying to get the one stored in the field on + // the target object, as that might just be null. The handle is guaranteed to be allocated when the + // callback is executed. Freeing it from here is needed so that the cleanup upon disposal might skip + // it if there's a pending execution. That ensures the handle is always disposed, without the disposal + // path having to lock and wait for it. + handle.Free(); - device.QueueRaiseDeviceLostEventIfNeeded(); + // If the device is available, then also queue the device lost event to be raised on the thread pool + if (device is not null) + { + device.QueueRaiseDeviceLostEventIfNeeded(); + } } } From 8b8ca034db9c0695d5b89eab41adde77cff499c7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Jul 2022 01:57:27 +0200 Subject: [PATCH 26/64] Skip device disposal test on .NET 6 (possible D3D12MA bug) --- tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs index 4622eb31..c2ec6e2c 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs @@ -86,6 +86,11 @@ public class DeviceDisposalTests [AllDevices] public unsafe void DeviceDisposal_DisposedResourcesAfterDevice_ReferenceCounting(Device device) { +#if NET6_0_OR_GREATER + // TODO: investigate ref count with resources disposed after device when using D3D12MA + Assert.Inconclusive(); +#endif + using ComPtr d3D12Device = default; ConstantBuffer r1; From c8c779d8275cf94b112edca27dc3ddddde8a2664 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 21 Jul 2022 00:29:24 +0200 Subject: [PATCH 27/64] Add lock to synchronize Dispose/DeviceLost logic --- .../Graphics/GraphicsDevice.DeviceLost.cs | 15 ++++++++++++++- src/ComputeSharp/Graphics/GraphicsDevice.cs | 14 +++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index 3bff93f2..931b14cb 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -61,7 +61,20 @@ unsafe partial class GraphicsDevice return; } - HRESULT result = this.d3D12Device.Get()->GetDeviceRemovedReason(); + HRESULT result; + + // Make sure to guard against concurrent accesses from the dispose logic + lock (this.d3D12DeviceLock) + { + ID3D12Device* d3D12Device = this.d3D12Device.Get(); + + if (d3D12Device is null) + { + return; + } + + result = d3D12Device->GetDeviceRemovedReason(); + } // Only raise the event once, and store the device removed reason to track it if (result != S.S_OK && diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 66602ebd..031ed041 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -107,6 +107,13 @@ public sealed unsafe partial class GraphicsDevice : NativeObject /// private HRESULT deviceRemovedReason; + /// + /// A lcok object used to synchronize accesses to between and . + /// This is needed because the device lost callback might race with a dispose call and end up trying to invoke a method on an invalid object. + /// We can't just check whether it's , as a null condition might still cause a racing thread to access a freed up object. + /// + private readonly object d3D12DeviceLock = new(); + /// /// Raised whenever the device is lost. /// @@ -402,7 +409,12 @@ public sealed unsafe partial class GraphicsDevice : NativeObject { DeviceHelper.NotifyDisposedDevice(this); - this.d3D12Device.Dispose(); + // Guard the dispose call around the native device to avoid device lost races + lock (this.d3D12DeviceLock) + { + this.d3D12Device.Dispose(); + } + this.d3D12ComputeCommandQueue.Dispose(); this.d3D12CopyCommandQueue.Dispose(); this.d3D12ComputeFence.Dispose(); From c5997d2c62cec50b9880d13ec9db8e273dc941a2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 23 Jul 2022 13:50:08 +0200 Subject: [PATCH 28/64] Add ReferenceTracker type --- .../Graphics/Interop/ReferenceTracker.cs | 204 ++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs diff --git a/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs b/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs new file mode 100644 index 00000000..b55b26c5 --- /dev/null +++ b/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs @@ -0,0 +1,204 @@ +using System; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.Interop; + +/// +/// An object acting as reference tracked for a given managed object. +/// +internal struct ReferenceTracker : IDisposable +{ + /// + /// The target object to track. + /// + private readonly ITrackedObject trackedObject; + + /// + /// An object to use to synchronize the reference tracking operations. + /// + private readonly object lockObject; + + /// + /// The number of existing reference tracking leases for . + /// + private int leasesCount; + + /// + /// Whether or not has been called on . + /// + private bool isDisposeRequested; + + /// + /// Creates a new instance with the specified paramters. + /// + /// The input tracked object to wrap. + public ReferenceTracker(ITrackedObject trackedObject) + { + this.trackedObject = trackedObject; + this.lockObject = new object(); + this.leasesCount = 0; + this.isDisposeRequested = false; + } + + /// + /// Gets a value to extend the lifetime of the tracked object. + /// + /// A object that can extend the lifetime of the tracked object. + /// Thrown if the tracked object has been disposed. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Lease GetLease() + { + Lease lease = TryGetLease(out bool leaseTaken); + + if (!leaseTaken) + { + // We can't use ThrowHelper here as we only want to invoke ToString if we + // are about to throw an exception. The JIT will recognize this pattern + // as this method has a single basic block that always throws an exception. + static void Throw(object trackedObject) => throw new ObjectDisposedException(trackedObject.ToString()); + + Throw(this.trackedObject); + } + + return lease; + } + + /// + /// Tries to get a value to extend the lifetime of the tracked object. + /// + /// Whether or not the returned value is enabled. + /// A object that can extend the lifetime of the tracked object. + public Lease TryGetLease(out bool leaseTaken) + { + bool success = true; + + lock (this.lockObject) + { + if (this.isDisposeRequested) + { + success = false; + } + else + { + this.leasesCount++; + } + } + + ITrackedObject? trackedObject; + + if (success) + { + leaseTaken = true; + trackedObject = this.trackedObject; + } + else + { + leaseTaken = false; + trackedObject = null; + } + + return new(trackedObject); + } + + /// + public void Dispose() + { + bool shouldRelease = false; + + lock (this.lockObject) + { + if (!this.isDisposeRequested) + { + this.isDisposeRequested = true; + + // Only release resources if this is the first time Dipose() has been called, and + // there are no outstanding leases. If there is one, don't do anything now. The + // tracked object will just be released once the last active lease is returned. + if (this.leasesCount == 0) + { + shouldRelease = true; + } + } + } + + if (shouldRelease) + { + this.trackedObject.DangerousRelease(); + } + } + + /// + /// Returns a given lease (ie. decrements the ref count for the tracked object). + /// + private void ReturnLease() + { + bool shouldRelease = false; + + lock (this.lockObject) + { + this.leasesCount--; + + // If Dipose() has been called and this was the last lease, release the tracked object + if (this.isDisposeRequested && this.leasesCount == 0) + { + shouldRelease = true; + } + } + + if (shouldRelease) + { + this.trackedObject.DangerousRelease(); + } + } + + /// + /// A reference tracking lease to extend the lifetime of a given tracked object while in a given scope. + /// + public struct Lease + { + /// + /// The tracked object being wrapped, if any. + /// + private ITrackedObject? trackedObject; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The input tracked object to wrap, if any. + public Lease(ITrackedObject? trackedObject) + { + this.trackedObject = trackedObject; + } + + /// + public void Dispose() + { + ITrackedObject? trackedObject = this.trackedObject; + + this.trackedObject = null; + + if (trackedObject is not null) + { + trackedObject.GetReferenceTracker().ReturnLease(); + } + } + } + + /// + /// An interface for an object being tracked by an owning object. + /// + public interface ITrackedObject + { + /// + /// Gets a reference to the owning for the object. + /// + /// A reference to the owning for the object. + ref ReferenceTracker GetReferenceTracker(); + + /// + /// Releases all resources (including unmanaged ones) for the tracked object. + /// + /// This method is guaranteed to only ever be called once for a given tracked object. + void DangerousRelease(); + } +} From 297aa7ab36dfb979509fc7494e4e56d3f338d735 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 23 Jul 2022 16:25:39 +0200 Subject: [PATCH 29/64] Switch to ReferenceTracker for all device/resource types --- .../GraphicsDeviceMismatchException.cs | 6 +- .../GraphicsDeviceExtensions.Dispatching.cs | 8 +- .../Graphics/GraphicsDevice.DeviceLost.cs | 50 +- src/ComputeSharp/Graphics/GraphicsDevice.cs | 104 ++- .../__Internals/GraphicsResourceHelper.cs | 50 +- .../Graphics/Interop/NativeObject.cs | 2 +- .../Graphics/Interop/ReferenceTracker.cs | 2 +- .../Graphics/Resources/Abstract/Buffer{T}.cs | 153 ++-- .../Resources/Abstract/StructuredBuffer{T}.cs | 419 ++++----- .../Resources/Abstract/Texture2D{T}.cs | 715 ++++++++-------- .../Resources/Abstract/Texture3D{T}.cs | 805 ++++++++++-------- .../Resources/Abstract/TransferBuffer{T}.cs | 91 +- .../Abstract/TransferTexture2D{T}.cs | 96 ++- .../Abstract/TransferTexture3D{T}.cs | 100 ++- .../Graphics/Resources/ConstantBuffer{T}.cs | 137 +-- .../ReadWriteTexture2D{T,TPixel}.ReadOnly.cs | 86 +- .../ReadWriteTexture2D{T}.ReadOnly.cs | 92 +- .../ReadWriteTexture3D{T,TPixel}.ReadOnly.cs | 86 +- .../ReadWriteTexture3D{T}.ReadOnly.cs | 86 +- 19 files changed, 1747 insertions(+), 1341 deletions(-) diff --git a/src/ComputeSharp/Graphics/Exceptions/GraphicsDeviceMismatchException.cs b/src/ComputeSharp/Graphics/Exceptions/GraphicsDeviceMismatchException.cs index 6283a35b..814a9d05 100644 --- a/src/ComputeSharp/Graphics/Exceptions/GraphicsDeviceMismatchException.cs +++ b/src/ComputeSharp/Graphics/Exceptions/GraphicsDeviceMismatchException.cs @@ -22,15 +22,15 @@ public sealed class GraphicsDeviceMismatchException : InvalidOperationException /// /// Creates a new instance from the specified parameters. /// - /// The input that was used. + /// The input that was used. /// The source instance tied to . /// The target instance that was used. /// A new instance with a formatted error message. /// - /// This method only takes a instance and the associated instance as + /// This method only takes a instance and the associated instance as /// will still be available, but without the unnecessary generic type specializations for the method. /// - private static GraphicsDeviceMismatchException Create(NativeObject resource, GraphicsDevice sourceDevice, GraphicsDevice destinationDevice) + private static GraphicsDeviceMismatchException Create(ReferenceTracker.ITrackedObject resource, GraphicsDevice sourceDevice, GraphicsDevice destinationDevice) { StringBuilder builder = new(512); diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs index 47d37914..afdae583 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs @@ -150,9 +150,11 @@ public static partial class GraphicsDeviceExtensions { Guard.IsNotNull(device); - device.ThrowIfDisposed(); - device.ThrowIfDeviceLost(); + using (device.GetReferenceTracker().GetLease()) + { + device.ThrowIfDeviceLost(); - return new(device); + return new(device); + } } } diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index 931b14cb..c0f91f06 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -48,42 +48,32 @@ unsafe partial class GraphicsDevice /// private void QueueRaiseDeviceLostEventIfNeeded() { - if (IsDisposed) + using (this.referenceTracker.TryGetLease(out bool leaseTaken)) { - return; - } - - // If the current device removed reason is not S_OK, it means the event - // has already been raised (but the device will keep reporting that reason). - // In that case, do nothing to avoid raising it again while the device is alive. - if (Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason)) != S.S_OK) - { - return; - } - - HRESULT result; - - // Make sure to guard against concurrent accesses from the dispose logic - lock (this.d3D12DeviceLock) - { - ID3D12Device* d3D12Device = this.d3D12Device.Get(); - - if (d3D12Device is null) + if (!leaseTaken) { return; } - result = d3D12Device->GetDeviceRemovedReason(); - } + // If the current device removed reason is not S_OK, it means the event + // has already been raised (but the device will keep reporting that reason). + // In that case, do nothing to avoid raising it again while the device is alive. + if (Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason)) != S.S_OK) + { + return; + } - // Only raise the event once, and store the device removed reason to track it - if (result != S.S_OK && - Interlocked.CompareExchange( - ref Unsafe.As(ref this.deviceRemovedReason), - (int)result, - S.S_OK) == S.S_OK) - { - QueueRaiseDeviceLostEvent(); + HRESULT result = this.d3D12Device.Get()->GetDeviceRemovedReason(); + + // Only raise the event once, and store the device removed reason to track it + if (result != S.S_OK && + Interlocked.CompareExchange( + ref Unsafe.As(ref this.deviceRemovedReason), + (int)result, + S.S_OK) == S.S_OK) + { + QueueRaiseDeviceLostEvent(); + } } } diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 031ed041..00d8b987 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -23,8 +23,13 @@ namespace ComputeSharp; /// A that represents an instance that can be used to run compute shaders. /// [DebuggerDisplay("{ToString(),raw}")] -public sealed unsafe partial class GraphicsDevice : NativeObject +public sealed unsafe partial class GraphicsDevice : ReferenceTracker.ITrackedObject, IDisposable { + /// + /// The owning object for the current instance. + /// + private ReferenceTracker referenceTracker; + /// /// The underlying wrapped by the current instance. /// @@ -107,13 +112,6 @@ public sealed unsafe partial class GraphicsDevice : NativeObject /// private HRESULT deviceRemovedReason; - /// - /// A lcok object used to synchronize accesses to between and . - /// This is needed because the device lost callback might race with a dispose call and end up trying to invoke a method on an invalid object. - /// We can't just check whether it's , as a null condition might still cause a racing thread to access a freed up object. - /// - private readonly object d3D12DeviceLock = new(); - /// /// Raised whenever the device is lost. /// @@ -141,6 +139,8 @@ public sealed unsafe partial class GraphicsDevice : NativeObject /// The available info for the new instance. internal GraphicsDevice(ID3D12Device* d3D12Device, IDXGIAdapter* dxgiAdapter, DXGI_ADAPTER_DESC1* dxgiDescription1) { + this.referenceTracker = new ReferenceTracker(this); + this.d3D12Device = new ComPtr(d3D12Device); this.d3D12ComputeCommandQueue = d3D12Device->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COMPUTE); @@ -181,6 +181,14 @@ public sealed unsafe partial class GraphicsDevice : NativeObject RegisterDeviceLostCallback(this, out this.deviceHandle, out this.deviceRemovedEvent, out this.deviceRemovedWaitHandle); } + /// + /// Releases unmanaged resources for the current instance. + /// + ~GraphicsDevice() + { + this.referenceTracker.Dispose(); + } + /// /// Gets the locally unique identifier for the current device. /// @@ -245,12 +253,14 @@ public sealed unsafe partial class GraphicsDevice : NativeObject /// Whether the current device supports double precision floating point operations in shaders. public bool IsDoublePrecisionSupportAvailable() { - ThrowIfDisposed(); - ThrowIfDeviceLost(); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceLost(); - var d3D12OptionsData = this.d3D12Device.Get()->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS); + var d3D12OptionsData = this.d3D12Device.Get()->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS); - return d3D12OptionsData.DoublePrecisionFloatShaderOps; + return d3D12OptionsData.DoublePrecisionFloatShaderOps; + } } /// @@ -262,10 +272,12 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadOnlyTexture2DSupportedForType() where T : unmanaged { - ThrowIfDisposed(); - ThrowIfDeviceLost(); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceLost(); - return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D); + return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D); + } } /// @@ -277,12 +289,14 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadWriteTexture2DSupportedForType() where T : unmanaged { - ThrowIfDisposed(); - ThrowIfDeviceLost(); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceLost(); - return this.d3D12Device.Get()->IsDxgiFormatSupported( - DXGIFormatHelper.GetForType(), - D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); + return this.d3D12Device.Get()->IsDxgiFormatSupported( + DXGIFormatHelper.GetForType(), + D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); + } } /// @@ -294,10 +308,12 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadOnlyTexture3DSupportedForType() where T : unmanaged { - ThrowIfDisposed(); - ThrowIfDeviceLost(); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceLost(); - return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D); + return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D); + } } /// @@ -309,12 +325,14 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadWriteTexture3DSupportedForType() where T : unmanaged { - ThrowIfDisposed(); - ThrowIfDeviceLost(); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceLost(); - return this.d3D12Device.Get()->IsDxgiFormatSupported( - DXGIFormatHelper.GetForType(), - D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); + return this.d3D12Device.Get()->IsDxgiFormatSupported( + DXGIFormatHelper.GetForType(), + D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); + } } /// @@ -405,16 +423,32 @@ public sealed unsafe partial class GraphicsDevice : NativeObject } /// - protected override void OnDispose() + public void Dispose() + { + this.referenceTracker.Dispose(); + + GC.SuppressFinalize(this); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ref ReferenceTracker GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void ReferenceTracker.ITrackedObject.DangerousRelease() { DeviceHelper.NotifyDisposedDevice(this); - // Guard the dispose call around the native device to avoid device lost races - lock (this.d3D12DeviceLock) - { - this.d3D12Device.Dispose(); - } - + this.d3D12Device.Dispose(); this.d3D12ComputeCommandQueue.Dispose(); this.d3D12CopyCommandQueue.Dispose(); this.d3D12ComputeFence.Dispose(); diff --git a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index 57b879ab..29317385 100644 --- a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -64,12 +64,14 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(buffer); - buffer.ThrowIfDisposed(); - buffer.ThrowIfDeviceMismatch(device); + using (buffer.GetReferenceTracker().GetLease()) + { + buffer.ThrowIfDeviceMismatch(device); - D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = buffer.D3D12GpuDescriptorHandle; + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = buffer.D3D12GpuDescriptorHandle; - return *(ulong*)&d3D12GpuDescriptorHandle; + return *(ulong*)&d3D12GpuDescriptorHandle; + } } /// @@ -85,12 +87,14 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - texture.ThrowIfDisposed(); - texture.ThrowIfDeviceMismatch(device); + using (texture.GetReferenceTracker().GetLease()) + { + texture.ThrowIfDeviceMismatch(device); - D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; - return *(ulong*)&d3D12GpuDescriptorHandle; + return *(ulong*)&d3D12GpuDescriptorHandle; + } } /// @@ -106,12 +110,14 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - texture.ThrowIfDisposed(); - texture.ThrowIfDeviceMismatch(device); + using (texture.GetReferenceTracker().GetLease()) + { + texture.ThrowIfDeviceMismatch(device); - D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; - return *(ulong*)&d3D12GpuDescriptorHandle; + return *(ulong*)&d3D12GpuDescriptorHandle; + } } /// @@ -196,12 +202,14 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - texture.ThrowIfDisposed(); - texture.ThrowIfDeviceMismatch(device); + using (texture.GetReferenceTracker().GetLease()) + { + texture.ThrowIfDeviceMismatch(device); - D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; - return *(ulong*)&d3D12GpuDescriptorHandle; + return *(ulong*)&d3D12GpuDescriptorHandle; + } } /// @@ -217,12 +225,14 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - texture.ThrowIfDisposed(); - texture.ThrowIfDeviceMismatch(device); + using (texture.GetReferenceTracker().GetLease()) + { + texture.ThrowIfDeviceMismatch(device); - D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; - return *(ulong*)&d3D12GpuDescriptorHandle; + return *(ulong*)&d3D12GpuDescriptorHandle; + } } /// diff --git a/src/ComputeSharp/Graphics/Interop/NativeObject.cs b/src/ComputeSharp/Graphics/Interop/NativeObject.cs index f0310f90..d96a06f9 100644 --- a/src/ComputeSharp/Graphics/Interop/NativeObject.cs +++ b/src/ComputeSharp/Graphics/Interop/NativeObject.cs @@ -7,7 +7,7 @@ namespace ComputeSharp.Interop; /// /// Base class for a class. /// -public abstract class NativeObject : IDisposable +internal abstract class NativeObject : IDisposable { /// /// Indicates whether or not the current instance has been disposed. diff --git a/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs b/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs index b55b26c5..3f26d23b 100644 --- a/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs +++ b/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs @@ -154,7 +154,7 @@ internal struct ReferenceTracker : IDisposable /// /// A reference tracking lease to extend the lifetime of a given tracked object while in a given scope. /// - public struct Lease + public struct Lease : IDisposable { /// /// The tracked object being wrapped, if any. diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs index b830a105..7ef4b0b7 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs @@ -1,4 +1,5 @@ -using System.Buffers; +using System; +using System.Buffers; using System.Runtime.CompilerServices; using CommunityToolkit.Diagnostics; using ComputeSharp.Core.Helpers; @@ -24,9 +25,14 @@ namespace ComputeSharp.Resources; /// A representing a typed buffer stored on GPU memory. /// /// The type of items stored on the buffer. -public unsafe abstract class Buffer : NativeObject, IGraphicsResource +public unsafe abstract class Buffer : ReferenceTracker.ITrackedObject, IDisposable, IGraphicsResource where T : unmanaged { + /// + /// The owning object for the current instance. + /// + private ReferenceTracker referenceTracker; + #if NET6_0_OR_GREATER /// /// The instance used to retrieve . @@ -64,63 +70,75 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource /// The allocation mode to use for the new resource. private protected Buffer(GraphicsDevice device, int length, uint elementSizeInBytes, ResourceType resourceType, AllocationMode allocationMode) { - device.ThrowIfDisposed(); - device.ThrowIfDeviceLost(); + this.referenceTracker = new ReferenceTracker(this); - if (resourceType == ResourceType.Constant) + using (device.GetReferenceTracker().GetLease()) { - Guard.IsBetweenOrEqualTo(length, 1, D3D12.D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT); - } - else - { - // The maximum length is set such that the aligned buffer size can't exceed uint.MaxValue - Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / elementSizeInBytes) & ~255); - } + device.ThrowIfDeviceLost(); - if (TypeInfo.IsDoubleOrContainsDoubles && - device.D3D12Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS).DoublePrecisionFloatShaderOps == 0) - { - UnsupportedDoubleOperationException.Throw(); - } + if (resourceType == ResourceType.Constant) + { + Guard.IsBetweenOrEqualTo(length, 1, D3D12.D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT); + } + else + { + // The maximum length is set such that the aligned buffer size can't exceed uint.MaxValue + Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / elementSizeInBytes) & ~255); + } - nint usableSizeInBytes = checked((nint)(length * elementSizeInBytes)); - nint effectiveSizeInBytes = resourceType == ResourceType.Constant ? AlignmentHelper.Pad(usableSizeInBytes, D3D12.D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT) : usableSizeInBytes; + if (TypeInfo.IsDoubleOrContainsDoubles && + device.D3D12Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS).DoublePrecisionFloatShaderOps == 0) + { + UnsupportedDoubleOperationException.Throw(); + } - SizeInBytes = usableSizeInBytes; - GraphicsDevice = device; - Length = length; + nint usableSizeInBytes = checked((nint)(length * elementSizeInBytes)); + nint effectiveSizeInBytes = resourceType == ResourceType.Constant ? AlignmentHelper.Pad(usableSizeInBytes, D3D12.D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT) : usableSizeInBytes; + + SizeInBytes = usableSizeInBytes; + GraphicsDevice = device; + Length = length; #if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, (ulong)effectiveSizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); + this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, (ulong)effectiveSizeInBytes); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); #else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, (ulong)effectiveSizeInBytes, device.IsCacheCoherentUMA); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, (ulong)effectiveSizeInBytes, device.IsCacheCoherentUMA); #endif - device.RegisterAllocatedResource(); - device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); - device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView); + device.RegisterAllocatedResource(); + device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView); - switch (resourceType) - { - case ResourceType.Constant: - device.D3D12Device->CreateConstantBufferView(this.d3D12Resource.Get(), effectiveSizeInBytes, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - break; - case ResourceType.ReadOnly: - device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), (uint)length, elementSizeInBytes, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - break; - case ResourceType.ReadWrite: - device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), (uint)length, elementSizeInBytes, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - device.D3D12Device->CreateUnorderedAccessViewForClear( - this.d3D12Resource.Get(), - DXGI_FORMAT_R32_UINT, - (uint)(usableSizeInBytes / sizeof(uint)), - this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12CpuDescriptorHandle, - this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12CpuDescriptorHandleNonShaderVisible); - break; + switch (resourceType) + { + case ResourceType.Constant: + device.D3D12Device->CreateConstantBufferView(this.d3D12Resource.Get(), effectiveSizeInBytes, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + break; + case ResourceType.ReadOnly: + device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), (uint)length, elementSizeInBytes, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + break; + case ResourceType.ReadWrite: + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), (uint)length, elementSizeInBytes, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + device.D3D12Device->CreateUnorderedAccessViewForClear( + this.d3D12Resource.Get(), + DXGI_FORMAT_R32_UINT, + (uint)(usableSizeInBytes / sizeof(uint)), + this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12CpuDescriptorHandle, + this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12CpuDescriptorHandleNonShaderVisible); + break; + } + + this.d3D12Resource.Get()->SetName(this); } + } - this.d3D12Resource.Get()->SetName(this); + /// + /// Releases unmanaged resources for the current instance. + /// + ~Buffer() + { + this.referenceTracker.Dispose(); } /// @@ -201,7 +219,28 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource internal abstract void CopyFrom(ref T source, int destinationOffset, int count); /// - protected override void OnDispose() + public void Dispose() + { + this.referenceTracker.Dispose(); + + GC.SuppressFinalize(this); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ref ReferenceTracker GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void ReferenceTracker.ITrackedObject.DangerousRelease() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER @@ -231,20 +270,24 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device) { - ThrowIfDisposed(); - ThrowIfDeviceMismatch(device); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceMismatch(device); - return ( - this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12GpuDescriptorHandle, - this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12CpuDescriptorHandleNonShaderVisible); + return ( + this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12GpuDescriptorHandle, + this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12CpuDescriptorHandleNonShaderVisible); + } } /// internal unsafe ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); - ThrowIfDeviceMismatch(device); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceMismatch(device); - return D3D12Resource; + return D3D12Resource; + } } } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs index c2693cea..be9dcddb 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs @@ -32,71 +32,72 @@ public abstract class StructuredBuffer : Buffer /// internal override unsafe void CopyTo(ref T destination, int sourceOffset, int count) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - Guard.IsBetweenOrEqualTo(count, 0, Length); - Guard.IsInRange(sourceOffset, 0, Length); - Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); - - if (GraphicsDevice.IsCacheCoherentUMA) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (GetReferenceTracker().GetLease()) { - using ID3D12ResourceMap resource = D3D12Resource->Map(); + GraphicsDevice.ThrowIfDeviceLost(); - fixed (void* destinationPointer = &destination) + Guard.IsBetweenOrEqualTo(count, 0, Length); + Guard.IsInRange(sourceOffset, 0, Length); + Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); + + if (GraphicsDevice.IsCacheCoherentUMA) { - MemoryHelper.Copy( - source: resource.Pointer, - destination: destinationPointer, - sourceElementOffset: (uint)sourceOffset, - destinationElementOffset: 0, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)count); + using ID3D12ResourceMap resource = D3D12Resource->Map(); + + fixed (void* destinationPointer = &destination) + { + MemoryHelper.Copy( + source: resource.Pointer, + destination: destinationPointer, + sourceElementOffset: (uint)sourceOffset, + destinationElementOffset: 0, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)count); + } } - } - else - { - nint byteOffset = (nint)sourceOffset * sizeof(T); - nint byteLength = count * sizeof(T); - -#if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource(null, ResourceType.ReadBack, AllocationMode.Default, (ulong)byteLength); -#else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.ReadBack, - (ulong)byteLength, - GraphicsDevice.IsCacheCoherentUMA); -#endif - - using (CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY)) + else { -#if NET6_0_OR_GREATER - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(allocation.Get()->GetResource(), 0, D3D12Resource, (ulong)byteOffset, (ulong)byteLength); -#else - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(d3D12Resource.Get(), 0, D3D12Resource, (ulong)byteOffset, (ulong)byteLength); -#endif - copyCommandList.ExecuteAndWaitForCompletion(); - } + nint byteOffset = (nint)sourceOffset * sizeof(T); + nint byteLength = count * sizeof(T); #if NET6_0_OR_GREATER - using ID3D12ResourceMap resource = allocation.Get()->GetResource()->Map(); + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource(null, ResourceType.ReadBack, AllocationMode.Default, (ulong)byteLength); #else - using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.ReadBack, + (ulong)byteLength, + GraphicsDevice.IsCacheCoherentUMA); #endif - fixed (void* destinationPointer = &destination) - { - MemoryHelper.Copy( - source: resource.Pointer, - destination: destinationPointer, - sourceElementOffset: 0, - destinationElementOffset: 0, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)count); + using (CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY)) + { +#if NET6_0_OR_GREATER + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(allocation.Get()->GetResource(), 0, D3D12Resource, (ulong)byteOffset, (ulong)byteLength); +#else + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(d3D12Resource.Get(), 0, D3D12Resource, (ulong)byteOffset, (ulong)byteLength); +#endif + copyCommandList.ExecuteAndWaitForCompletion(); + } + +#if NET6_0_OR_GREATER + using ID3D12ResourceMap resource = allocation.Get()->GetResource()->Map(); +#else + using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); +#endif + + fixed (void* destinationPointer = &destination) + { + MemoryHelper.Copy( + source: resource.Pointer, + destination: destinationPointer, + sourceElementOffset: 0, + destinationElementOffset: 0, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)count); + } } } } @@ -104,40 +105,41 @@ public abstract class StructuredBuffer : Buffer /// internal override unsafe void CopyTo(Buffer destination, int sourceOffset, int destinationOffset, int count) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - - Guard.IsBetweenOrEqualTo(count, 0, Length); - Guard.IsBetweenOrEqualTo(count, 0, destination.Length); - Guard.IsInRange(sourceOffset, 0, Length); - Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); - Guard.IsInRange(destinationOffset, 0, destination.Length); - Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); - - if (!destination.IsPaddingPresent) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (GetReferenceTracker().GetLease()) + using (destination.GetReferenceTracker().GetLease()) { - nint sourceByteOffset = (nint)sourceOffset * sizeof(T); - nint destinationByteOffset = (nint)destinationOffset * sizeof(T); - nint byteLength = count * sizeof(T); + GraphicsDevice.ThrowIfDeviceLost(); - // Directly copy the input buffer - using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); + destination.ThrowIfDeviceMismatch(GraphicsDevice); - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion( - destination.D3D12Resource, - (ulong)destinationByteOffset, - D3D12Resource, - (ulong)sourceByteOffset, - (ulong)byteLength); + Guard.IsBetweenOrEqualTo(count, 0, Length); + Guard.IsBetweenOrEqualTo(count, 0, destination.Length); + Guard.IsInRange(sourceOffset, 0, Length); + Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); + Guard.IsInRange(destinationOffset, 0, destination.Length); + Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); - copyCommandList.ExecuteAndWaitForCompletion(); + if (!destination.IsPaddingPresent) + { + nint sourceByteOffset = (nint)sourceOffset * sizeof(T); + nint destinationByteOffset = (nint)destinationOffset * sizeof(T); + nint byteLength = count * sizeof(T); + + // Directly copy the input buffer + using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); + + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion( + destination.D3D12Resource, + (ulong)destinationByteOffset, + D3D12Resource, + (ulong)sourceByteOffset, + (ulong)byteLength); + + copyCommandList.ExecuteAndWaitForCompletion(); + } + else CopyToWithCpuBuffer(destination, sourceOffset, destinationOffset, count); } - else CopyToWithCpuBuffer(destination, sourceOffset, destinationOffset, count); } /// @@ -149,114 +151,116 @@ public abstract class StructuredBuffer : Buffer /// The number of items to read. internal unsafe void CopyTo(ReadBackBuffer destination, int sourceOffset, int destinationOffset, int count) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - - Guard.IsBetweenOrEqualTo(count, 0, Length); - Guard.IsBetweenOrEqualTo(count, 0, destination.Length); - Guard.IsInRange(sourceOffset, 0, Length); - Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); - Guard.IsInRange(destinationOffset, 0, destination.Length); - Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); - - if (GraphicsDevice.IsCacheCoherentUMA) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (GetReferenceTracker().GetLease()) + using (destination.GetReferenceTracker().GetLease()) { - using ID3D12ResourceMap resource = D3D12Resource->Map(); + GraphicsDevice.ThrowIfDeviceLost(); - MemoryHelper.Copy( - source: resource.Pointer, - destination: destination.MappedData, - sourceElementOffset: (uint)sourceOffset, - destinationElementOffset: (uint)destinationOffset, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)count); - } - else - { - ulong byteDestinationOffset = (uint)destinationOffset * (uint)sizeof(T); - ulong byteOffset = (uint)sourceOffset * (uint)sizeof(T); - ulong byteLength = (uint)count * (uint)sizeof(T); + destination.ThrowIfDeviceMismatch(GraphicsDevice); - using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); + Guard.IsBetweenOrEqualTo(count, 0, Length); + Guard.IsBetweenOrEqualTo(count, 0, destination.Length); + Guard.IsInRange(sourceOffset, 0, Length); + Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); + Guard.IsInRange(destinationOffset, 0, destination.Length); + Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(destination.D3D12Resource, byteDestinationOffset, D3D12Resource, byteOffset, byteLength); - copyCommandList.ExecuteAndWaitForCompletion(); + if (GraphicsDevice.IsCacheCoherentUMA) + { + using ID3D12ResourceMap resource = D3D12Resource->Map(); + + MemoryHelper.Copy( + source: resource.Pointer, + destination: destination.MappedData, + sourceElementOffset: (uint)sourceOffset, + destinationElementOffset: (uint)destinationOffset, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)count); + } + else + { + ulong byteDestinationOffset = (uint)destinationOffset * (uint)sizeof(T); + ulong byteOffset = (uint)sourceOffset * (uint)sizeof(T); + ulong byteLength = (uint)count * (uint)sizeof(T); + + using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); + + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(destination.D3D12Resource, byteDestinationOffset, D3D12Resource, byteOffset, byteLength); + copyCommandList.ExecuteAndWaitForCompletion(); + } } } /// internal override unsafe void CopyFrom(ref T source, int offset, int length) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - Guard.IsBetweenOrEqualTo(length, 0, Length); - Guard.IsInRange(offset, 0, Length); - Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); - - if (GraphicsDevice.IsCacheCoherentUMA) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (GetReferenceTracker().GetLease()) { - using ID3D12ResourceMap resource = D3D12Resource->Map(); + GraphicsDevice.ThrowIfDeviceLost(); - fixed (void* sourcePointer = &source) + Guard.IsBetweenOrEqualTo(length, 0, Length); + Guard.IsInRange(offset, 0, Length); + Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); + + if (GraphicsDevice.IsCacheCoherentUMA) { - MemoryHelper.Copy( - source: sourcePointer, - destination: resource.Pointer, - sourceElementOffset: 0, - destinationElementOffset: (uint)offset, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)length); + using ID3D12ResourceMap resource = D3D12Resource->Map(); + + fixed (void* sourcePointer = &source) + { + MemoryHelper.Copy( + source: sourcePointer, + destination: resource.Pointer, + sourceElementOffset: 0, + destinationElementOffset: (uint)offset, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)length); + } } - } - else - { - nint byteOffset = (nint)offset * sizeof(T); - nint byteLength = length * sizeof(T); - -#if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource(null, ResourceType.Upload, AllocationMode.Default, (ulong)byteLength); -#else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.Upload, - (ulong)byteLength, - GraphicsDevice.IsCacheCoherentUMA); -#endif - -#if NET6_0_OR_GREATER - using (ID3D12ResourceMap resource = allocation.Get()->GetResource()->Map()) -#else - using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) -#endif - fixed (void* sourcePointer = &source) + else { - MemoryHelper.Copy( - source: sourcePointer, - destination: resource.Pointer, - sourceElementOffset: 0, - destinationElementOffset: 0, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)length); - } - - using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); + nint byteOffset = (nint)offset * sizeof(T); + nint byteLength = length * sizeof(T); #if NET6_0_OR_GREATER - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, (ulong)byteOffset, allocation.Get()->GetResource(), 0, (ulong)byteLength); + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource(null, ResourceType.Upload, AllocationMode.Default, (ulong)byteLength); #else - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, (ulong)byteOffset, d3D12Resource.Get(), 0, (ulong)byteLength); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.Upload, + (ulong)byteLength, + GraphicsDevice.IsCacheCoherentUMA); #endif - copyCommandList.ExecuteAndWaitForCompletion(); + +#if NET6_0_OR_GREATER + using (ID3D12ResourceMap resource = allocation.Get()->GetResource()->Map()) +#else + using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) +#endif + fixed (void* sourcePointer = &source) + { + MemoryHelper.Copy( + source: sourcePointer, + destination: resource.Pointer, + sourceElementOffset: 0, + destinationElementOffset: 0, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)length); + } + + using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); + +#if NET6_0_OR_GREATER + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, (ulong)byteOffset, allocation.Get()->GetResource(), 0, (ulong)byteLength); +#else + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, (ulong)byteOffset, d3D12Resource.Get(), 0, (ulong)byteLength); +#endif + copyCommandList.ExecuteAndWaitForCompletion(); + } } } @@ -269,44 +273,45 @@ public abstract class StructuredBuffer : Buffer /// The number of items to read. internal unsafe void CopyFrom(UploadBuffer source, int sourceOffset, int destinationOffset, int count) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - source.ThrowIfDeviceMismatch(GraphicsDevice); - source.ThrowIfDisposed(); - - Guard.IsBetweenOrEqualTo(count, 0, Length); - Guard.IsBetweenOrEqualTo(count, 0, source.Length); - Guard.IsInRange(sourceOffset, 0, source.Length); - Guard.IsLessThanOrEqualTo(sourceOffset + count, source.Length, nameof(sourceOffset)); - Guard.IsInRange(destinationOffset, 0, Length); - Guard.IsLessThanOrEqualTo(destinationOffset + count, Length, nameof(destinationOffset)); - - if (GraphicsDevice.IsCacheCoherentUMA) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (GetReferenceTracker().GetLease()) + using (source.GetReferenceTracker().GetLease()) { - using ID3D12ResourceMap resource = D3D12Resource->Map(); + GraphicsDevice.ThrowIfDeviceLost(); - MemoryHelper.Copy( - source: source.MappedData, - destination: resource.Pointer, - sourceElementOffset: (uint)sourceOffset, - destinationElementOffset: (uint)destinationOffset, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)count); - } - else - { - ulong byteSourceOffset = (uint)sourceOffset * (uint)sizeof(T); - ulong byteOffset = (uint)destinationOffset * (uint)sizeof(T); - ulong byteLength = (uint)count * (uint)sizeof(T); + source.ThrowIfDeviceMismatch(GraphicsDevice); - using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); + Guard.IsBetweenOrEqualTo(count, 0, Length); + Guard.IsBetweenOrEqualTo(count, 0, source.Length); + Guard.IsInRange(sourceOffset, 0, source.Length); + Guard.IsLessThanOrEqualTo(sourceOffset + count, source.Length, nameof(sourceOffset)); + Guard.IsInRange(destinationOffset, 0, Length); + Guard.IsLessThanOrEqualTo(destinationOffset + count, Length, nameof(destinationOffset)); - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, byteOffset, source.D3D12Resource, byteSourceOffset, byteLength); - copyCommandList.ExecuteAndWaitForCompletion(); + if (GraphicsDevice.IsCacheCoherentUMA) + { + using ID3D12ResourceMap resource = D3D12Resource->Map(); + + MemoryHelper.Copy( + source: source.MappedData, + destination: resource.Pointer, + sourceElementOffset: (uint)sourceOffset, + destinationElementOffset: (uint)destinationOffset, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)count); + } + else + { + ulong byteSourceOffset = (uint)sourceOffset * (uint)sizeof(T); + ulong byteOffset = (uint)destinationOffset * (uint)sizeof(T); + ulong byteLength = (uint)count * (uint)sizeof(T); + + using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); + + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, byteOffset, source.D3D12Resource, byteSourceOffset, byteLength); + copyCommandList.ExecuteAndWaitForCompletion(); + } } } } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs index e6190b93..b351356e 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs @@ -26,9 +26,14 @@ namespace ComputeSharp.Resources; /// A representing a typed 2D texture stored on GPU memory. /// /// The type of items stored on the texture. -public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, GraphicsResourceHelper.IGraphicsResource +public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDisposable, IGraphicsResource, GraphicsResourceHelper.IGraphicsResource where T : unmanaged { + /// + /// The owning object for the current instance. + /// + private ReferenceTracker referenceTracker; + #if NET6_0_OR_GREATER /// /// The instance used to retrieve . @@ -72,67 +77,79 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// The format support for the current texture type. private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, AllocationMode allocationMode, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { - device.ThrowIfDisposed(); - device.ThrowIfDeviceLost(); + this.referenceTracker = new ReferenceTracker(this); - Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) + using (device.GetReferenceTracker().GetLease()) { - UnsupportedTextureTypeException.ThrowForTexture2D(); - } + device.ThrowIfDeviceLost(); - GraphicsDevice = device; + Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) + { + UnsupportedTextureTypeException.ThrowForTexture2D(); + } + + GraphicsDevice = device; #if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource( - device.Pool, - resourceType, - allocationMode, - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - out this.d3D12ResourceState); + this.allocation = device.Allocator->CreateResource( + device.Pool, + resourceType, + allocationMode, + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out this.d3D12ResourceState); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); #else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource( - resourceType, - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - device.IsCacheCoherentUMA, - out this.d3D12ResourceState); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource( + resourceType, + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + device.IsCacheCoherentUMA, + out this.d3D12ResourceState); #endif - this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON - ? D3D12_COMMAND_LIST_TYPE_COPY - : D3D12_COMMAND_LIST_TYPE_COMPUTE; + this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON + ? D3D12_COMMAND_LIST_TYPE_COPY + : D3D12_COMMAND_LIST_TYPE_COMPUTE; - device.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - out this.d3D12PlacedSubresourceFootprint, - out _, - out _); + device.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out this.d3D12PlacedSubresourceFootprint, + out _, + out _); - device.RegisterAllocatedResource(); - device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + device.RegisterAllocatedResource(); + device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); - switch (resourceType) - { - case ResourceType.ReadOnly: - device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - break; - case ResourceType.ReadWrite: - device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); - break; + switch (resourceType) + { + case ResourceType.ReadOnly: + device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + break; + case ResourceType.ReadWrite: + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); + break; + } + + this.d3D12Resource.Get()->SetName(this); } + } - this.d3D12Resource.Get()->SetName(this); + /// + /// Releases unmanaged resources for the current instance. + /// + ~Texture2D() + { + this.referenceTracker.Dispose(); } /// @@ -169,20 +186,20 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// The height of the memory area to copy. internal void CopyTo(ref T destination, int size, int sourceOffsetX, int sourceOffsetY, int width, int height) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (this.referenceTracker.GetLease()) + { + GraphicsDevice.ThrowIfDeviceLost(); - ThrowIfDisposed(); + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(sourceOffsetY, 0, Height); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); + Guard.IsGreaterThanOrEqualTo(size, (nint)width * height); - Guard.IsInRange(sourceOffsetX, 0, Width); - Guard.IsInRange(sourceOffsetY, 0, Height); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - Guard.IsGreaterThanOrEqualTo(size, (nint)width * height); - - GraphicsDevice.D3D12Device->GetCopyableFootprint( + GraphicsDevice.D3D12Device->GetCopyableFootprint( DXGIFormatHelper.GetForType(), (uint)width, (uint)height, @@ -191,59 +208,60 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra out ulong totalSizeInBytes); #if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, - ResourceType.ReadBack, - AllocationMode.Default, - totalSizeInBytes); + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( + GraphicsDevice.Pool, + ResourceType.ReadBack, + AllocationMode.Default, + totalSizeInBytes); - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); + using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); #else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.ReadBack, - totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.ReadBack, + totalSizeInBytes, + GraphicsDevice.IsCacheCoherentUMA); #endif - using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) - { - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: d3D12Resource.Get(), + &d3D12PlacedSubresourceFootprintDestination, + destinationX: 0, + destinationY: 0, + destinationZ: 0, + d3D12ResourceSource: D3D12Resource, + sourceX: (uint)sourceOffsetX, + sourceY: (uint)sourceOffsetY, + sourceZ: 0, + (uint)width, + (uint)height, + depth: 1); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: d3D12Resource.Get(), - &d3D12PlacedSubresourceFootprintDestination, - destinationX: 0, - destinationY: 0, - destinationZ: 0, - d3D12ResourceSource: D3D12Resource, - sourceX: (uint)sourceOffsetX, - sourceY: (uint)sourceOffsetY, - sourceZ: 0, - (uint)width, - (uint)height, - depth: 1); + using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + fixed (void* destinationPointer = &destination) { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + MemoryHelper.Copy( + resource.Pointer, + (uint)height, + rowSizeInBytes, + d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch, + destinationPointer); } - - copyCommandList.ExecuteAndWaitForCompletion(); - } - - using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); - - fixed (void* destinationPointer = &destination) - { - MemoryHelper.Copy( - resource.Pointer, - (uint)height, - rowSizeInBytes, - d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch, - destinationPointer); } } @@ -259,61 +277,62 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// The height of the memory area to copy. internal void CopyTo(Texture2D destination, int sourceOffsetX, int sourceOffsetY, int destinationOffsetX, int destinationOffsetY, int width, int height) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - - Guard.IsInRange(sourceOffsetX, 0, Width); - Guard.IsInRange(sourceOffsetY, 0, Height); - Guard.IsInRange(destinationOffsetX, 0, destination.Width); - Guard.IsInRange(destinationOffsetY, 0, destination.Height); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(width, 1, destination.Width); - Guard.IsBetweenOrEqualTo(height, 1, destination.Height); - Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); - Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - - D3D12_COMMAND_LIST_TYPE d3D12CommandListType = - this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || - destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE - ? D3D12_COMMAND_LIST_TYPE_COMPUTE - : D3D12_COMMAND_LIST_TYPE_COPY; - - using CommandList copyCommandList = new(GraphicsDevice, d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (this.referenceTracker.GetLease()) + using (destination.referenceTracker.GetLease()) { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(sourceOffsetY, 0, Height); + Guard.IsInRange(destinationOffsetX, 0, destination.Width); + Guard.IsInRange(destinationOffsetY, 0, destination.Height); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(width, 1, destination.Width); + Guard.IsBetweenOrEqualTo(height, 1, destination.Height); + Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); + Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); + + D3D12_COMMAND_LIST_TYPE d3D12CommandListType = + this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || + destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE + ? D3D12_COMMAND_LIST_TYPE_COMPUTE + : D3D12_COMMAND_LIST_TYPE_COPY; + + using CommandList copyCommandList = new(GraphicsDevice, d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: destination.D3D12Resource, + (uint)destinationOffsetX, + (uint)destinationOffsetY, + destinationZ: 0, + d3D12ResourceSource: D3D12Resource, + (uint)sourceOffsetX, + (uint)sourceOffsetY, + sourceZ: 0, + (uint)width, + (uint)height, + 1); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } - - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: destination.D3D12Resource, - (uint)destinationOffsetX, - (uint)destinationOffsetY, - destinationZ: 0, - d3D12ResourceSource: D3D12Resource, - (uint)sourceOffsetX, - (uint)sourceOffsetY, - sourceZ: 0, - (uint)width, - (uint)height, - 1); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); } /// @@ -328,57 +347,58 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// The height of the memory area to copy. internal void CopyTo(ReadBackTexture2D destination, int sourceOffsetX, int sourceOffsetY, int destinationOffsetX, int destinationOffsetY, int width, int height) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - - Guard.IsInRange(sourceOffsetX, 0, Width); - Guard.IsInRange(sourceOffsetY, 0, Height); - Guard.IsInRange(destinationOffsetX, 0, destination.Width); - Guard.IsInRange(destinationOffsetY, 0, destination.Height); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(width, 1, destination.Width); - Guard.IsBetweenOrEqualTo(height, 1, destination.Height); - Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); - Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (this.referenceTracker.GetLease()) + using (destination.GetReferenceTracker().GetLease()) { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - } + GraphicsDevice.ThrowIfDeviceLost(); - fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintDestination = &destination.D3D12PlacedSubresourceFootprint) - { - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: destination.D3D12Resource, - d3D12PlacedSubresourceFootprintDestination, - (uint)destinationOffsetX, - (uint)destinationOffsetY, - destinationZ: 0, - d3D12ResourceSource: D3D12Resource, - (uint)sourceOffsetX, - (uint)sourceOffsetY, - sourceZ: 0, - (uint)width, - (uint)height, - 1); - } + destination.ThrowIfDeviceMismatch(GraphicsDevice); - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); - } + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(sourceOffsetY, 0, Height); + Guard.IsInRange(destinationOffsetX, 0, destination.Width); + Guard.IsInRange(destinationOffsetY, 0, destination.Height); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(width, 1, destination.Width); + Guard.IsBetweenOrEqualTo(height, 1, destination.Height); + Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); + Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - copyCommandList.ExecuteAndWaitForCompletion(); + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + } + + fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintDestination = &destination.D3D12PlacedSubresourceFootprint) + { + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: destination.D3D12Resource, + d3D12PlacedSubresourceFootprintDestination, + (uint)destinationOffsetX, + (uint)destinationOffsetY, + destinationZ: 0, + d3D12ResourceSource: D3D12Resource, + (uint)sourceOffsetX, + (uint)sourceOffsetY, + sourceZ: 0, + (uint)width, + (uint)height, + 1); + } + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); + } } /// @@ -392,80 +412,81 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// The height of the memory area to write to. internal void CopyFrom(ref T source, int size, int destinationOffsetX, int destinationOffsetY, int width, int height) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (this.referenceTracker.GetLease()) + { + GraphicsDevice.ThrowIfDeviceLost(); - ThrowIfDisposed(); + Guard.IsInRange(destinationOffsetX, 0, Width); + Guard.IsInRange(destinationOffsetY, 0, Height); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); + Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); + Guard.IsGreaterThanOrEqualTo(size, (nint)width * height); - Guard.IsInRange(destinationOffsetX, 0, Width); - Guard.IsInRange(destinationOffsetY, 0, Height); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); - Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); - Guard.IsGreaterThanOrEqualTo(size, (nint)width * height); - - GraphicsDevice.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintSource, - out ulong rowSizeInBytes, - out ulong totalSizeInBytes); + GraphicsDevice.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintSource, + out ulong rowSizeInBytes, + out ulong totalSizeInBytes); #if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, - ResourceType.Upload, - AllocationMode.Default, - totalSizeInBytes); + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( + GraphicsDevice.Pool, + ResourceType.Upload, + AllocationMode.Default, + totalSizeInBytes); - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); + using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); #else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.Upload, - totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.Upload, + totalSizeInBytes, + GraphicsDevice.IsCacheCoherentUMA); #endif - using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) - fixed (void* sourcePointer = &source) - { - MemoryHelper.Copy( - sourcePointer, - resource.Pointer, + using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) + fixed (void* sourcePointer = &source) + { + MemoryHelper.Copy( + sourcePointer, + resource.Pointer, + (uint)height, + rowSizeInBytes, + d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch); + } + + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: D3D12Resource, + destinationX: (uint)destinationOffsetX, + destinationY: (uint)destinationOffsetY, + destinationZ: 0, + d3D12ResourceSource: d3D12Resource.Get(), + &d3D12PlacedSubresourceFootprintSource, + sourceX: 0, + sourceY: 0, + sourceZ: 0, + (uint)width, (uint)height, - rowSizeInBytes, - d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch); + depth: 1); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } - - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); - } - - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: D3D12Resource, - destinationX: (uint)destinationOffsetX, - destinationY: (uint)destinationOffsetY, - destinationZ: 0, - d3D12ResourceSource: d3D12Resource.Get(), - &d3D12PlacedSubresourceFootprintSource, - sourceX: 0, - sourceY: 0, - sourceZ: 0, - (uint)width, - (uint)height, - depth: 1); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); } /// @@ -480,61 +501,83 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// The height of the memory area to write to. internal void CopyFrom(UploadTexture2D source, int sourceOffsetX, int sourceOffsetY, int destinationOffsetX, int destinationOffsetY, int width, int height) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - source.ThrowIfDeviceMismatch(GraphicsDevice); - source.ThrowIfDisposed(); - - Guard.IsInRange(sourceOffsetX, 0, source.Width); - Guard.IsInRange(sourceOffsetY, 0, source.Height); - Guard.IsInRange(destinationOffsetX, 0, Width); - Guard.IsInRange(destinationOffsetY, 0, Height); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(width, 1, source.Width); - Guard.IsBetweenOrEqualTo(height, 1, source.Height); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, source.Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, source.Height, nameof(sourceOffsetY)); - Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); - Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); - - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (this.referenceTracker.GetLease()) + using (source.GetReferenceTracker().GetLease()) { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); - } + GraphicsDevice.ThrowIfDeviceLost(); - fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintSource = &source.D3D12PlacedSubresourceFootprint) - { - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: D3D12Resource, - (uint)destinationOffsetX, - (uint)destinationOffsetY, - destinationZ: 0, - d3D12ResourceSource: source.D3D12Resource, - d3D12PlacedSubresourceFootprintSource, - (uint)sourceOffsetX, - (uint)sourceOffsetY, - sourceZ: 0, - (uint)width, - (uint)height, - depth: 1); - } + source.ThrowIfDeviceMismatch(GraphicsDevice); - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); - } + Guard.IsInRange(sourceOffsetX, 0, source.Width); + Guard.IsInRange(sourceOffsetY, 0, source.Height); + Guard.IsInRange(destinationOffsetX, 0, Width); + Guard.IsInRange(destinationOffsetY, 0, Height); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(width, 1, source.Width); + Guard.IsBetweenOrEqualTo(height, 1, source.Height); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, source.Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, source.Height, nameof(sourceOffsetY)); + Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); + Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); - copyCommandList.ExecuteAndWaitForCompletion(); + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + } + + fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintSource = &source.D3D12PlacedSubresourceFootprint) + { + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: D3D12Resource, + (uint)destinationOffsetX, + (uint)destinationOffsetY, + destinationZ: 0, + d3D12ResourceSource: source.D3D12Resource, + d3D12PlacedSubresourceFootprintSource, + (uint)sourceOffsetX, + (uint)sourceOffsetY, + sourceZ: 0, + (uint)width, + (uint)height, + depth: 1); + } + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); + } } /// - protected override void OnDispose() + public virtual void Dispose() + { + this.referenceTracker.Dispose(); + + GC.SuppressFinalize(this); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ref ReferenceTracker GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void ReferenceTracker.ITrackedObject.DangerousRelease() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER @@ -582,46 +625,54 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) { - ThrowIfDisposed(); - ThrowIfDeviceMismatch(device); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceMismatch(device); - isNormalized = DXGIFormatHelper.IsNormalizedType(); + isNormalized = DXGIFormatHelper.IsNormalizedType(); - return (this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); + return (this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); + } } /// internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); - ThrowIfDeviceMismatch(device); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceMismatch(device); - return D3D12Resource; + return D3D12Resource; + } } /// internal (D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource) { - ThrowIfDisposed(); - ThrowIfDeviceMismatch(device); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceMismatch(device); - D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState; - D3D12_RESOURCE_STATES d3D12ResourceStatesAfter = ResourceStateHelper.GetD3D12ResourceStates(resourceState); + D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState; + D3D12_RESOURCE_STATES d3D12ResourceStatesAfter = ResourceStateHelper.GetD3D12ResourceStates(resourceState); - this.d3D12ResourceState = d3D12ResourceStatesAfter; + this.d3D12ResourceState = d3D12ResourceStatesAfter; - d3D12Resource = D3D12Resource; + d3D12Resource = D3D12Resource; - return (d3D12ResourceStatesBefore, d3D12ResourceStatesAfter); + return (d3D12ResourceStatesBefore, d3D12ResourceStatesAfter); + } } /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - ThrowIfDisposed(); - ThrowIfDeviceMismatch(device); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceMismatch(device); - return D3D12GpuDescriptorHandle; + return D3D12GpuDescriptorHandle; + } } /// diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs index b12dc576..e4f5635d 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs @@ -26,9 +26,14 @@ namespace ComputeSharp.Resources; /// A representing a typed 3D texture stored on GPU memory. /// /// The type of items stored on the texture. -public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, GraphicsResourceHelper.IGraphicsResource +public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDisposable, IGraphicsResource, GraphicsResourceHelper.IGraphicsResource where T : unmanaged { + /// + /// The owning object for the current instance. + /// + private ReferenceTracker referenceTracker; + #if NET6_0_OR_GREATER /// /// The instance used to retrieve . @@ -73,71 +78,83 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// The format support for the current texture type. private protected Texture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType, AllocationMode allocationMode, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { - device.ThrowIfDisposed(); - device.ThrowIfDeviceLost(); + this.referenceTracker = new ReferenceTracker(this); - Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) + using (device.GetReferenceTracker().GetLease()) { - UnsupportedTextureTypeException.ThrowForTexture3D(); - } + device.ThrowIfDeviceLost(); - GraphicsDevice = device; + Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); + Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); + Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); + + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) + { + UnsupportedTextureTypeException.ThrowForTexture3D(); + } + + GraphicsDevice = device; #if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource( - device.Pool, - resourceType, - allocationMode, - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - out this.d3D12ResourceState); + this.allocation = device.Allocator->CreateResource( + device.Pool, + resourceType, + allocationMode, + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + (ushort)depth, + out this.d3D12ResourceState); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); #else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource( - resourceType, - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - device.IsCacheCoherentUMA, - out this.d3D12ResourceState); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource( + resourceType, + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + (ushort)depth, + device.IsCacheCoherentUMA, + out this.d3D12ResourceState); #endif - this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON - ? D3D12_COMMAND_LIST_TYPE_COPY - : D3D12_COMMAND_LIST_TYPE_COMPUTE; + this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON + ? D3D12_COMMAND_LIST_TYPE_COPY + : D3D12_COMMAND_LIST_TYPE_COMPUTE; - device.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - out this.d3D12PlacedSubresourceFootprint, - out _, - out _); + device.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + (ushort)depth, + out this.d3D12PlacedSubresourceFootprint, + out _, + out _); - device.RegisterAllocatedResource(); - device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + device.RegisterAllocatedResource(); + device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); - switch (resourceType) - { - case ResourceType.ReadOnly: - device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - break; - case ResourceType.ReadWrite: - device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); - break; + switch (resourceType) + { + case ResourceType.ReadOnly: + device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + break; + case ResourceType.ReadWrite: + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); + break; + } + + this.d3D12Resource.Get()->SetName(this); } + } - this.d3D12Resource.Get()->SetName(this); + /// + /// Releases unmanaged resources for the current instance. + /// + ~Texture3D() + { + this.referenceTracker.Dispose(); } /// @@ -181,87 +198,88 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// The depth of the memory area to copy. internal void CopyTo(ref T destination, int size, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int width, int height, int depth) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - Guard.IsInRange(sourceOffsetX, 0, Width); - Guard.IsInRange(sourceOffsetY, 0, Height); - Guard.IsInRange(sourceOffsetZ, 0, Depth); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(depth, 1, Depth); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); - Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth); - - GraphicsDevice.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintDestination, - out ulong rowSizeInBytes, - out ulong totalSizeInBytes); - -#if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, - ResourceType.ReadBack, - AllocationMode.Default, - totalSizeInBytes); - - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); -#else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.ReadBack, - totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); -#endif - - using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (this.referenceTracker.GetLease()) { - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - } + GraphicsDevice.ThrowIfDeviceLost(); - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: d3D12Resource.Get(), - &d3D12PlacedSubresourceFootprintDestination, - destinationX: 0, - destinationY: 0, - destinationZ: 0, - d3D12ResourceSource: D3D12Resource, - sourceX: (uint)sourceOffsetX, - sourceY: (uint)sourceOffsetY, - sourceZ: (ushort)sourceOffsetZ, + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(sourceOffsetY, 0, Height); + Guard.IsInRange(sourceOffsetZ, 0, Depth); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(depth, 1, Depth); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); + Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); + Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth); + + GraphicsDevice.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), (uint)width, (uint)height, - (ushort)depth); + (ushort)depth, + out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintDestination, + out ulong rowSizeInBytes, + out ulong totalSizeInBytes); - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) +#if NET6_0_OR_GREATER + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( + GraphicsDevice.Pool, + ResourceType.ReadBack, + AllocationMode.Default, + totalSizeInBytes); + + using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); +#else + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.ReadBack, + totalSizeInBytes, + GraphicsDevice.IsCacheCoherentUMA); +#endif + + using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: d3D12Resource.Get(), + &d3D12PlacedSubresourceFootprintDestination, + destinationX: 0, + destinationY: 0, + destinationZ: 0, + d3D12ResourceSource: D3D12Resource, + sourceX: (uint)sourceOffsetX, + sourceY: (uint)sourceOffsetY, + sourceZ: (ushort)sourceOffsetZ, + (uint)width, + (uint)height, + (ushort)depth); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } - copyCommandList.ExecuteAndWaitForCompletion(); - } + using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); - using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); - - fixed (void* destinationPointer = &destination) - { - MemoryHelper.Copy( - resource.Pointer, - (uint)height, - (uint)depth, - rowSizeInBytes, - d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch, - d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch * (uint)height, - destinationPointer); + fixed (void* destinationPointer = &destination) + { + MemoryHelper.Copy( + resource.Pointer, + (uint)height, + (uint)depth, + rowSizeInBytes, + d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch, + d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch * (uint)height, + destinationPointer); + } } } @@ -280,67 +298,68 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// The depth of the memory area to copy. internal void CopyTo(Texture3D destination, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - - Guard.IsInRange(sourceOffsetX, 0, Width); - Guard.IsInRange(sourceOffsetY, 0, Height); - Guard.IsInRange(sourceOffsetZ, 0, Depth); - Guard.IsInRange(destinationOffsetX, 0, destination.Width); - Guard.IsInRange(destinationOffsetY, 0, destination.Height); - Guard.IsInRange(destinationOffsetZ, 0, destination.Depth); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(depth, 1, Depth); - Guard.IsBetweenOrEqualTo(width, 1, destination.Width); - Guard.IsBetweenOrEqualTo(height, 1, destination.Height); - Guard.IsBetweenOrEqualTo(depth, 1, destination.Depth); - Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); - Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); - Guard.IsBetweenOrEqualTo(destinationOffsetZ + depth, 1, destination.Depth, nameof(destinationOffsetZ)); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); - - D3D12_COMMAND_LIST_TYPE d3D12CommandListType = - this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || - destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE - ? D3D12_COMMAND_LIST_TYPE_COMPUTE - : D3D12_COMMAND_LIST_TYPE_COPY; - - using CommandList copyCommandList = new(GraphicsDevice, d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (this.referenceTracker.GetLease()) + using (destination.referenceTracker.GetLease()) { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(sourceOffsetY, 0, Height); + Guard.IsInRange(sourceOffsetZ, 0, Depth); + Guard.IsInRange(destinationOffsetX, 0, destination.Width); + Guard.IsInRange(destinationOffsetY, 0, destination.Height); + Guard.IsInRange(destinationOffsetZ, 0, destination.Depth); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(depth, 1, Depth); + Guard.IsBetweenOrEqualTo(width, 1, destination.Width); + Guard.IsBetweenOrEqualTo(height, 1, destination.Height); + Guard.IsBetweenOrEqualTo(depth, 1, destination.Depth); + Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); + Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); + Guard.IsBetweenOrEqualTo(destinationOffsetZ + depth, 1, destination.Depth, nameof(destinationOffsetZ)); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); + Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); + + D3D12_COMMAND_LIST_TYPE d3D12CommandListType = + this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || + destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE + ? D3D12_COMMAND_LIST_TYPE_COMPUTE + : D3D12_COMMAND_LIST_TYPE_COPY; + + using CommandList copyCommandList = new(GraphicsDevice, d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: destination.D3D12Resource, + (uint)destinationOffsetX, + (uint)destinationOffsetY, + (ushort)destinationOffsetZ, + d3D12ResourceSource: D3D12Resource, + (uint)sourceOffsetX, + (uint)sourceOffsetY, + (ushort)sourceOffsetZ, + (uint)width, + (uint)height, + (ushort)depth); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } - - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: destination.D3D12Resource, - (uint)destinationOffsetX, - (uint)destinationOffsetY, - (ushort)destinationOffsetZ, - d3D12ResourceSource: D3D12Resource, - (uint)sourceOffsetX, - (uint)sourceOffsetY, - (ushort)sourceOffsetZ, - (uint)width, - (uint)height, - (ushort)depth); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); } /// @@ -358,63 +377,64 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// The depth of the memory area to copy. internal void CopyTo(ReadBackTexture3D destination, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - - Guard.IsInRange(sourceOffsetX, 0, Width); - Guard.IsInRange(sourceOffsetY, 0, Height); - Guard.IsInRange(sourceOffsetZ, 0, Depth); - Guard.IsInRange(destinationOffsetX, 0, destination.Width); - Guard.IsInRange(destinationOffsetY, 0, destination.Height); - Guard.IsInRange(destinationOffsetZ, 0, destination.Depth); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(depth, 1, Depth); - Guard.IsBetweenOrEqualTo(width, 1, destination.Width); - Guard.IsBetweenOrEqualTo(height, 1, destination.Height); - Guard.IsBetweenOrEqualTo(depth, 1, destination.Depth); - Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); - Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); - Guard.IsBetweenOrEqualTo(destinationOffsetZ + depth, 1, destination.Depth, nameof(destinationOffsetZ)); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); - - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (this.referenceTracker.GetLease()) + using (destination.GetReferenceTracker().GetLease()) { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - } + GraphicsDevice.ThrowIfDeviceLost(); - fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintDestination = &destination.D3D12PlacedSubresourceFootprint) - { - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: destination.D3D12Resource, - d3D12PlacedSubresourceFootprintDestination, - (uint)destinationOffsetX, - (uint)destinationOffsetY, - (ushort)destinationOffsetZ, - d3D12ResourceSource: D3D12Resource, - (uint)sourceOffsetX, - (uint)sourceOffsetY, - (ushort)sourceOffsetZ, - (uint)width, - (uint)height, - (ushort)depth); - } + destination.ThrowIfDeviceMismatch(GraphicsDevice); - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); - } + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(sourceOffsetY, 0, Height); + Guard.IsInRange(sourceOffsetZ, 0, Depth); + Guard.IsInRange(destinationOffsetX, 0, destination.Width); + Guard.IsInRange(destinationOffsetY, 0, destination.Height); + Guard.IsInRange(destinationOffsetZ, 0, destination.Depth); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(depth, 1, Depth); + Guard.IsBetweenOrEqualTo(width, 1, destination.Width); + Guard.IsBetweenOrEqualTo(height, 1, destination.Height); + Guard.IsBetweenOrEqualTo(depth, 1, destination.Depth); + Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); + Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); + Guard.IsBetweenOrEqualTo(destinationOffsetZ + depth, 1, destination.Depth, nameof(destinationOffsetZ)); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); + Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); - copyCommandList.ExecuteAndWaitForCompletion(); + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + } + + fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintDestination = &destination.D3D12PlacedSubresourceFootprint) + { + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: destination.D3D12Resource, + d3D12PlacedSubresourceFootprintDestination, + (uint)destinationOffsetX, + (uint)destinationOffsetY, + (ushort)destinationOffsetZ, + d3D12ResourceSource: D3D12Resource, + (uint)sourceOffsetX, + (uint)sourceOffsetY, + (ushort)sourceOffsetZ, + (uint)width, + (uint)height, + (ushort)depth); + } + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); + } } /// @@ -430,86 +450,87 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// The depth of the memory area to write to. internal void CopyFrom(ref T source, int size, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (this.referenceTracker.GetLease()) + { + GraphicsDevice.ThrowIfDeviceLost(); - ThrowIfDisposed(); + Guard.IsInRange(destinationOffsetX, 0, Width); + Guard.IsInRange(destinationOffsetY, 0, Height); + Guard.IsInRange(destinationOffsetZ, 0, Depth); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(depth, 1, Depth); + Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); + Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); + Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); + Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth); - Guard.IsInRange(destinationOffsetX, 0, Width); - Guard.IsInRange(destinationOffsetY, 0, Height); - Guard.IsInRange(destinationOffsetZ, 0, Depth); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(depth, 1, Depth); - Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); - Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); - Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); - Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth); - - GraphicsDevice.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintSource, - out ulong rowSizeInBytes, - out ulong totalSizeInBytes); + GraphicsDevice.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + (ushort)depth, + out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintSource, + out ulong rowSizeInBytes, + out ulong totalSizeInBytes); #if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, - ResourceType.Upload, - AllocationMode.Default, - totalSizeInBytes); + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( + GraphicsDevice.Pool, + ResourceType.Upload, + AllocationMode.Default, + totalSizeInBytes); - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); + using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); #else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.Upload, - totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.Upload, + totalSizeInBytes, + GraphicsDevice.IsCacheCoherentUMA); #endif - using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) - fixed (void* sourcePointer = &source) - { - MemoryHelper.Copy( - sourcePointer, - resource.Pointer, + using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) + fixed (void* sourcePointer = &source) + { + MemoryHelper.Copy( + sourcePointer, + resource.Pointer, + (uint)height, + (uint)depth, + rowSizeInBytes, + d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch, + d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch * (uint)height); + } + + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: D3D12Resource, + destinationX: (uint)destinationOffsetX, + destinationY: (uint)destinationOffsetY, + destinationZ: (ushort)destinationOffsetZ, + d3D12ResourceSource: d3D12Resource.Get(), + &d3D12PlacedSubresourceFootprintSource, + sourceX: 0, + sourceY: 0, + sourceZ: 0, + (uint)width, (uint)height, - (uint)depth, - rowSizeInBytes, - d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch, - d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch * (uint)height); + (ushort)depth); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } - - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); - } - - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: D3D12Resource, - destinationX: (uint)destinationOffsetX, - destinationY: (uint)destinationOffsetY, - destinationZ: (ushort)destinationOffsetZ, - d3D12ResourceSource: d3D12Resource.Get(), - &d3D12PlacedSubresourceFootprintSource, - sourceX: 0, - sourceY: 0, - sourceZ: 0, - (uint)width, - (uint)height, - (ushort)depth); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); } /// @@ -527,67 +548,89 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// The depth of the memory area to write to. internal void CopyFrom(UploadTexture3D source, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - source.ThrowIfDeviceMismatch(GraphicsDevice); - source.ThrowIfDisposed(); - - Guard.IsInRange(sourceOffsetX, 0, source.Width); - Guard.IsInRange(sourceOffsetY, 0, source.Height); - Guard.IsInRange(sourceOffsetZ, 0, source.Depth); - Guard.IsInRange(destinationOffsetX, 0, Width); - Guard.IsInRange(destinationOffsetY, 0, Height); - Guard.IsInRange(destinationOffsetZ, 0, Depth); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(depth, 1, Depth); - Guard.IsBetweenOrEqualTo(width, 1, source.Width); - Guard.IsBetweenOrEqualTo(height, 1, source.Height); - Guard.IsBetweenOrEqualTo(depth, 1, source.Depth); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, source.Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, source.Height, nameof(sourceOffsetY)); - Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, source.Depth, nameof(sourceOffsetZ)); - Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); - Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); - Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); - - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (this.referenceTracker.GetLease()) + using (source.GetReferenceTracker().GetLease()) { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); - } + GraphicsDevice.ThrowIfDeviceLost(); - fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintSource = &source.D3D12PlacedSubresourceFootprint) - { - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: D3D12Resource, - (uint)destinationOffsetX, - (uint)destinationOffsetY, - (ushort)destinationOffsetZ, - d3D12ResourceSource: source.D3D12Resource, - d3D12PlacedSubresourceFootprintSource, - (uint)sourceOffsetX, - (uint)sourceOffsetY, - (ushort)sourceOffsetZ, - (uint)width, - (uint)height, - (ushort)depth); - } + source.ThrowIfDeviceMismatch(GraphicsDevice); - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); - } + Guard.IsInRange(sourceOffsetX, 0, source.Width); + Guard.IsInRange(sourceOffsetY, 0, source.Height); + Guard.IsInRange(sourceOffsetZ, 0, source.Depth); + Guard.IsInRange(destinationOffsetX, 0, Width); + Guard.IsInRange(destinationOffsetY, 0, Height); + Guard.IsInRange(destinationOffsetZ, 0, Depth); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(depth, 1, Depth); + Guard.IsBetweenOrEqualTo(width, 1, source.Width); + Guard.IsBetweenOrEqualTo(height, 1, source.Height); + Guard.IsBetweenOrEqualTo(depth, 1, source.Depth); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, source.Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, source.Height, nameof(sourceOffsetY)); + Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, source.Depth, nameof(sourceOffsetZ)); + Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); + Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); + Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); - copyCommandList.ExecuteAndWaitForCompletion(); + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + } + + fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintSource = &source.D3D12PlacedSubresourceFootprint) + { + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: D3D12Resource, + (uint)destinationOffsetX, + (uint)destinationOffsetY, + (ushort)destinationOffsetZ, + d3D12ResourceSource: source.D3D12Resource, + d3D12PlacedSubresourceFootprintSource, + (uint)sourceOffsetX, + (uint)sourceOffsetY, + (ushort)sourceOffsetZ, + (uint)width, + (uint)height, + (ushort)depth); + } + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); + } } /// - protected override void OnDispose() + public virtual void Dispose() + { + this.referenceTracker.Dispose(); + + GC.SuppressFinalize(this); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ref ReferenceTracker GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void ReferenceTracker.ITrackedObject.DangerousRelease() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER @@ -635,46 +678,54 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) { - ThrowIfDisposed(); - ThrowIfDeviceMismatch(device); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceMismatch(device); - isNormalized = DXGIFormatHelper.IsNormalizedType(); + isNormalized = DXGIFormatHelper.IsNormalizedType(); - return (this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); + return (this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); + } } /// internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); - ThrowIfDeviceMismatch(device); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceMismatch(device); - return D3D12Resource; + return D3D12Resource; + } } /// internal (D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource) { - ThrowIfDisposed(); - ThrowIfDeviceMismatch(device); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceMismatch(device); - D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState; - D3D12_RESOURCE_STATES d3D12ResourceStatesAfter = ResourceStateHelper.GetD3D12ResourceStates(resourceState); + D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState; + D3D12_RESOURCE_STATES d3D12ResourceStatesAfter = ResourceStateHelper.GetD3D12ResourceStates(resourceState); - this.d3D12ResourceState = d3D12ResourceStatesAfter; + this.d3D12ResourceState = d3D12ResourceStatesAfter; - d3D12Resource = D3D12Resource; + d3D12Resource = D3D12Resource; - return (d3D12ResourceStatesBefore, d3D12ResourceStatesAfter); + return (d3D12ResourceStatesBefore, d3D12ResourceStatesAfter); + } } /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - ThrowIfDisposed(); - ThrowIfDeviceMismatch(device); + using (this.referenceTracker.GetLease()) + { + ThrowIfDeviceMismatch(device); - return D3D12GpuDescriptorHandle; + return D3D12GpuDescriptorHandle; + } } /// diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs index 8e42995a..d4583bfb 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs @@ -15,9 +15,14 @@ namespace ComputeSharp.Resources; /// A representing a typed buffer stored on CPU memory, that can be used to transfer data to/from the GPU. /// /// The type of items stored on the buffer. -public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource, IMemoryOwner +public abstract unsafe class TransferBuffer : ReferenceTracker.ITrackedObject, IGraphicsResource, IMemoryOwner where T : unmanaged { + /// + /// The owning object for the current instance. + /// + private ReferenceTracker referenceTracker; + #if NET6_0_OR_GREATER /// /// The instance used to retrieve . @@ -44,29 +49,41 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource /// The allocation mode to use for the new resource. private protected TransferBuffer(GraphicsDevice device, int length, ResourceType resourceType, AllocationMode allocationMode) { - device.ThrowIfDisposed(); - device.ThrowIfDeviceLost(); + this.referenceTracker = new ReferenceTracker(this); - // The maximum length is set such that the aligned buffer size can't exceed uint.MaxValue - Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / (uint)sizeof(T)) & ~255); + using (device.GetReferenceTracker().GetLease()) + { + device.ThrowIfDeviceLost(); - GraphicsDevice = device; - Length = length; + // The maximum length is set such that the aligned buffer size can't exceed uint.MaxValue + Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / (uint)sizeof(T)) & ~255); - ulong sizeInBytes = (uint)length * (uint)sizeof(T); + GraphicsDevice = device; + Length = length; + + ulong sizeInBytes = (uint)length * (uint)sizeof(T); #if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, sizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); + this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, sizeInBytes); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); #else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, sizeInBytes, device.IsCacheCoherentUMA); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, sizeInBytes, device.IsCacheCoherentUMA); #endif - device.RegisterAllocatedResource(); + device.RegisterAllocatedResource(); - this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; + this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; - this.d3D12Resource.Get()->SetName(this); + this.d3D12Resource.Get()->SetName(this); + } + } + + /// + /// Releases unmanaged resources for the current instance. + /// + ~TransferBuffer() + { + this.referenceTracker.Dispose(); } /// @@ -93,9 +110,10 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - ThrowIfDisposed(); - - return new MemoryManager(this).Memory; + using (this.referenceTracker.GetLease()) + { + return new MemoryManager(this).Memory; + } } } @@ -105,14 +123,36 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - ThrowIfDisposed(); - - return new(this.mappedData, Length); + using (this.referenceTracker.GetLease()) + { + return new(this.mappedData, Length); + } } } /// - protected override void OnDispose() + public void Dispose() + { + this.referenceTracker.Dispose(); + + GC.SuppressFinalize(this); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ref ReferenceTracker GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void ReferenceTracker.ITrackedObject.DangerousRelease() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER @@ -171,11 +211,12 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource /// public override MemoryHandle Pin(int elementIndex = 0) { - Guard.IsEqualTo(elementIndex, 0); + using (this.buffer.referenceTracker.GetLease()) + { + Guard.IsEqualTo(elementIndex, 0); - this.buffer.ThrowIfDisposed(); - - return new(this.buffer.mappedData); + return new(this.buffer.mappedData); + } } /// diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs index 8e546be2..cd0d9a99 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs @@ -1,4 +1,5 @@ -using System.Runtime.CompilerServices; +using System; +using System.Runtime.CompilerServices; using CommunityToolkit.Diagnostics; using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Extensions; @@ -15,9 +16,14 @@ namespace ComputeSharp.Resources; /// A representing a typed 2D texture stored on on CPU memory, that can be used to transfer data to/from the GPU. /// /// The type of items stored on the texture. -public unsafe abstract class TransferTexture2D : NativeObject, IGraphicsResource +public unsafe abstract class TransferTexture2D : ReferenceTracker.ITrackedObject, IDisposable, IGraphicsResource where T : unmanaged { + /// + /// The owning object for the current instance. + /// + private ReferenceTracker referenceTracker; + #if NET6_0_OR_GREATER /// /// The instance used to retrieve . @@ -50,39 +56,51 @@ public unsafe abstract class TransferTexture2D : NativeObject, IGraphicsResou /// The allocation mode to use for the new resource. private protected TransferTexture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, AllocationMode allocationMode) { - device.ThrowIfDisposed(); - device.ThrowIfDeviceLost(); + this.referenceTracker = new ReferenceTracker(this); - Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D)) + using (device.GetReferenceTracker().GetLease()) { - UnsupportedTextureTypeException.ThrowForTexture2D(); - } + device.ThrowIfDeviceLost(); - GraphicsDevice = device; + Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - device.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - out this.d3D12PlacedSubresourceFootprint, - out _, - out ulong totalSizeInBytes); + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D)) + { + UnsupportedTextureTypeException.ThrowForTexture2D(); + } + + GraphicsDevice = device; + + device.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out this.d3D12PlacedSubresourceFootprint, + out _, + out ulong totalSizeInBytes); #if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, totalSizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); + this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, totalSizeInBytes); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); #else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, totalSizeInBytes, device.IsCacheCoherentUMA); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, totalSizeInBytes, device.IsCacheCoherentUMA); #endif - device.RegisterAllocatedResource(); + device.RegisterAllocatedResource(); - this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; + this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; - this.d3D12Resource.Get()->SetName(this); + this.d3D12Resource.Get()->SetName(this); + } + } + + /// + /// Releases unmanaged resources for the current instance. + /// + ~TransferTexture2D() + { + this.referenceTracker.Dispose(); } /// @@ -114,14 +132,36 @@ public unsafe abstract class TransferTexture2D : NativeObject, IGraphicsResou [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - ThrowIfDisposed(); - - return new(this.mappedData, Width, Height, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); + using (this.referenceTracker.GetLease()) + { + return new(this.mappedData, Width, Height, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); + } } } /// - protected override void OnDispose() + public void Dispose() + { + this.referenceTracker.Dispose(); + + GC.SuppressFinalize(this); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ref ReferenceTracker GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void ReferenceTracker.ITrackedObject.DangerousRelease() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs index 72201ccb..da347e36 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs @@ -1,4 +1,5 @@ -using System.Runtime.CompilerServices; +using System; +using System.Runtime.CompilerServices; using CommunityToolkit.Diagnostics; using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Extensions; @@ -15,9 +16,14 @@ namespace ComputeSharp.Resources; /// A representing a typed 3D texture stored on on CPU memory, that can be used to transfer data to/from the GPU. /// /// The type of items stored on the texture. -public unsafe abstract class TransferTexture3D : NativeObject, IGraphicsResource +public unsafe abstract class TransferTexture3D : ReferenceTracker.ITrackedObject, IDisposable, IGraphicsResource where T : unmanaged { + /// + /// The owning object for the current instance. + /// + private ReferenceTracker referenceTracker; + #if NET6_0_OR_GREATER /// /// The instance used to retrieve . @@ -51,41 +57,53 @@ public unsafe abstract class TransferTexture3D : NativeObject, IGraphicsResou /// The allocation mode to use for the new resource. private protected TransferTexture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType, AllocationMode allocationMode) { - device.ThrowIfDisposed(); - device.ThrowIfDeviceLost(); + this.referenceTracker = new ReferenceTracker(this); - Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D)) + using (device.GetReferenceTracker().GetLease()) { - UnsupportedTextureTypeException.ThrowForTexture3D(); - } + device.ThrowIfDeviceLost(); - GraphicsDevice = device; + Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); + Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); + Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - device.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - out this.d3D12PlacedSubresourceFootprint, - out _, - out ulong totalSizeInBytes); + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D)) + { + UnsupportedTextureTypeException.ThrowForTexture3D(); + } + + GraphicsDevice = device; + + device.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + (ushort)depth, + out this.d3D12PlacedSubresourceFootprint, + out _, + out ulong totalSizeInBytes); #if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, totalSizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); + this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, totalSizeInBytes); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); #else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, totalSizeInBytes, device.IsCacheCoherentUMA); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, totalSizeInBytes, device.IsCacheCoherentUMA); #endif - device.RegisterAllocatedResource(); + device.RegisterAllocatedResource(); - this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; + this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; - this.d3D12Resource.Get()->SetName(this); + this.d3D12Resource.Get()->SetName(this); + } + } + + /// + /// Releases unmanaged resources for the current instance. + /// + ~TransferTexture3D() + { + this.referenceTracker.Dispose(); } /// @@ -122,14 +140,36 @@ public unsafe abstract class TransferTexture3D : NativeObject, IGraphicsResou [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - ThrowIfDisposed(); - - return new(this.mappedData, Width, Height, Depth, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); + using (this.referenceTracker.GetLease()) + { + return new(this.mappedData, Width, Height, Depth, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); + } } } /// - protected override void OnDispose() + public void Dispose() + { + this.referenceTracker.Dispose(); + + GC.SuppressFinalize(this); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ref ReferenceTracker GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void ReferenceTracker.ITrackedObject.DangerousRelease() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER diff --git a/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs index c51fca8b..2958f74e 100644 --- a/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs @@ -57,89 +57,92 @@ public sealed class ConstantBuffer : Buffer /// internal override unsafe void CopyTo(ref T destination, int offset, int length) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - Guard.IsBetweenOrEqualTo(length, 0, Length); - Guard.IsInRange(offset, 0, Length); - Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); - - using ID3D12ResourceMap resource = D3D12Resource->Map(); - - fixed (void* destinationPointer = &destination) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (GetReferenceTracker().GetLease()) { - MemoryHelper.Copy( - source: resource.Pointer, - destination: destinationPointer, - sourceElementOffset: (uint)offset, - destinationElementOffset: 0, - sourceElementPitchInBytes: (uint)GetPaddedSize(), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)length); + GraphicsDevice.ThrowIfDeviceLost(); + + Guard.IsBetweenOrEqualTo(length, 0, Length); + Guard.IsInRange(offset, 0, Length); + Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); + + using ID3D12ResourceMap resource = D3D12Resource->Map(); + + fixed (void* destinationPointer = &destination) + { + MemoryHelper.Copy( + source: resource.Pointer, + destination: destinationPointer, + sourceElementOffset: (uint)offset, + destinationElementOffset: 0, + sourceElementPitchInBytes: (uint)GetPaddedSize(), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)length); + } } } /// internal override unsafe void CopyTo(Buffer destination, int sourceOffset, int destinationOffset, int length) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - - Guard.IsBetweenOrEqualTo(length, 0, Length); - Guard.IsBetweenOrEqualTo(length, 0, destination.Length); - Guard.IsInRange(sourceOffset, 0, Length); - Guard.IsLessThanOrEqualTo(sourceOffset + length, Length, nameof(sourceOffset)); - Guard.IsInRange(destinationOffset, 0, destination.Length); - Guard.IsLessThanOrEqualTo(destinationOffset + length, destination.Length, nameof(destinationOffset)); - - if (destination is ConstantBuffer buffer) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (GetReferenceTracker().GetLease()) + using (destination.GetReferenceTracker().GetLease()) { - using ID3D12ResourceMap sourceMap = D3D12Resource->Map(); - using ID3D12ResourceMap destinationMap = buffer.D3D12Resource->Map(); + GraphicsDevice.ThrowIfDeviceLost(); - MemoryHelper.Copy( - source: sourceMap.Pointer, - destination: destinationMap.Pointer, - sourceElementOffset: (uint)sourceOffset, - destinationElementOffset: (uint)destinationOffset, - sourceElementPitchInBytes: (uint)GetPaddedSize(), - destinationElementPitchInBytes: (uint)GetPaddedSize(), - count: (uint)length); + destination.ThrowIfDeviceMismatch(GraphicsDevice); + + Guard.IsBetweenOrEqualTo(length, 0, Length); + Guard.IsBetweenOrEqualTo(length, 0, destination.Length); + Guard.IsInRange(sourceOffset, 0, Length); + Guard.IsLessThanOrEqualTo(sourceOffset + length, Length, nameof(sourceOffset)); + Guard.IsInRange(destinationOffset, 0, destination.Length); + Guard.IsLessThanOrEqualTo(destinationOffset + length, destination.Length, nameof(destinationOffset)); + + if (destination is ConstantBuffer buffer) + { + using ID3D12ResourceMap sourceMap = D3D12Resource->Map(); + using ID3D12ResourceMap destinationMap = buffer.D3D12Resource->Map(); + + MemoryHelper.Copy( + source: sourceMap.Pointer, + destination: destinationMap.Pointer, + sourceElementOffset: (uint)sourceOffset, + destinationElementOffset: (uint)destinationOffset, + sourceElementPitchInBytes: (uint)GetPaddedSize(), + destinationElementPitchInBytes: (uint)GetPaddedSize(), + count: (uint)length); + } + else CopyToWithCpuBuffer(destination, sourceOffset, destinationOffset, length); } - else CopyToWithCpuBuffer(destination, sourceOffset, destinationOffset, length); } /// internal override unsafe void CopyFrom(ref T source, int offset, int length) { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - - Guard.IsBetweenOrEqualTo(length, 0, Length); - Guard.IsInRange(offset, 0, Length); - Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); - - using ID3D12ResourceMap resource = D3D12Resource->Map(); - - fixed (void* sourcePointer = &source) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (GetReferenceTracker().GetLease()) { - MemoryHelper.Copy( - source: sourcePointer, - destination: resource.Pointer, - sourceElementOffset: 0, - destinationElementOffset: (uint)offset, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)GetPaddedSize(), - count: (uint)length); + GraphicsDevice.ThrowIfDeviceLost(); + + Guard.IsBetweenOrEqualTo(length, 0, Length); + Guard.IsInRange(offset, 0, Length); + Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); + + using ID3D12ResourceMap resource = D3D12Resource->Map(); + + fixed (void* sourcePointer = &source) + { + MemoryHelper.Copy( + source: sourcePointer, + destination: resource.Pointer, + sourceElementOffset: 0, + destinationElementOffset: (uint)offset, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)GetPaddedSize(), + count: (uint)length); + } } } diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs index dee9a948..35aa2d73 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs @@ -24,32 +24,34 @@ partial class ReadWriteTexture2D /// internal IReadOnlyNormalizedTexture2D AsReadOnly() { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - ThrowIfIsNotInReadOnlyState(); - - ReadOnly? readOnlyWrapper = this.readOnlyWrapper; - - if (readOnlyWrapper is not null) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (GetReferenceTracker().GetLease()) { - return readOnlyWrapper; - } + GraphicsDevice.ThrowIfDeviceLost(); - [MethodImpl(MethodImplOptions.NoInlining)] - static ReadOnly InitializeWrapper(ReadWriteTexture2D texture) - { - return texture.readOnlyWrapper = new(texture); - } + ThrowIfIsNotInReadOnlyState(); - return InitializeWrapper(this); + ReadOnly? readOnlyWrapper = this.readOnlyWrapper; + + if (readOnlyWrapper is not null) + { + return readOnlyWrapper; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static ReadOnly InitializeWrapper(ReadWriteTexture2D texture) + { + return texture.readOnlyWrapper = new(texture); + } + + return InitializeWrapper(this); + } } /// - protected override void OnDispose() + public override void Dispose() { - base.OnDispose(); + base.Dispose(); this.readOnlyWrapper?.Dispose(); } @@ -57,8 +59,13 @@ partial class ReadWriteTexture2D /// /// A wrapper for a resource that has been temporarily transitioned to readonly. /// - private sealed unsafe class ReadOnly : NativeObject, IReadOnlyNormalizedTexture2D, GraphicsResourceHelper.IGraphicsResource + private sealed unsafe class ReadOnly : ReferenceTracker.ITrackedObject, IDisposable, IReadOnlyNormalizedTexture2D, GraphicsResourceHelper.IGraphicsResource { + /// + /// The owning object for the current instance. + /// + private ReferenceTracker referenceTracker; + /// /// The owning instance being wrapped. /// @@ -75,6 +82,7 @@ partial class ReadWriteTexture2D /// The owning instance to wrap. public ReadOnly(ReadWriteTexture2D owner) { + this.referenceTracker = new ReferenceTracker(this); this.owner = owner; owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); @@ -106,12 +114,13 @@ partial class ReadWriteTexture2D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - ThrowIfDisposed(); + using (this.referenceTracker.GetLease()) + using (this.owner.GetReferenceTracker().GetLease()) + { + this.owner.ThrowIfDeviceMismatch(device); - this.owner.ThrowIfDisposed(); - this.owner.ThrowIfDeviceMismatch(device); - - return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + } } /// @@ -123,12 +132,13 @@ partial class ReadWriteTexture2D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); + using (this.referenceTracker.GetLease()) + using (this.owner.GetReferenceTracker().GetLease()) + { + this.owner.ThrowIfDeviceMismatch(device); - this.owner.ThrowIfDisposed(); - this.owner.ThrowIfDeviceMismatch(device); - - return this.owner.D3D12Resource; + return this.owner.D3D12Resource; + } } /// @@ -138,7 +148,21 @@ partial class ReadWriteTexture2D } /// - protected override void OnDispose() + public void Dispose() + { + this.referenceTracker.Dispose(); + + GC.SuppressFinalize(this); + } + + /// + ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void ReferenceTracker.ITrackedObject.DangerousRelease() { if (this.owner.GraphicsDevice is GraphicsDevice device) { diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs index 12c4c5ec..056d8ee4 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs @@ -24,35 +24,37 @@ partial class ReadWriteTexture2D /// public IReadOnlyTexture2D AsReadOnly() { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - ThrowIfIsNotInReadOnlyState(); - - ReadOnly? readOnlyWrapper = this.readOnlyWrapper; - - if (readOnlyWrapper is not null) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (GetReferenceTracker().GetLease()) { - return readOnlyWrapper; - } + GraphicsDevice.ThrowIfDeviceLost(); - // The wrapper initialization is moved to a non inlined helper to keep the codegen of this method - // as compact as possible. If the current wrapper is not initialized, control goes directly to the - // helper that will initialize and return it, which translates to a single jump. - [MethodImpl(MethodImplOptions.NoInlining)] - static ReadOnly InitializeWrapper(ReadWriteTexture2D texture) - { - return texture.readOnlyWrapper = new(texture); - } + ThrowIfIsNotInReadOnlyState(); - return InitializeWrapper(this); + ReadOnly? readOnlyWrapper = this.readOnlyWrapper; + + if (readOnlyWrapper is not null) + { + return readOnlyWrapper; + } + + // The wrapper initialization is moved to a non inlined helper to keep the codegen of this method + // as compact as possible. If the current wrapper is not initialized, control goes directly to the + // helper that will initialize and return it, which translates to a single jump. + [MethodImpl(MethodImplOptions.NoInlining)] + static ReadOnly InitializeWrapper(ReadWriteTexture2D texture) + { + return texture.readOnlyWrapper = new(texture); + } + + return InitializeWrapper(this); + } } /// - protected override void OnDispose() + public override void Dispose() { - base.OnDispose(); + base.Dispose(); this.readOnlyWrapper?.Dispose(); } @@ -60,8 +62,13 @@ partial class ReadWriteTexture2D /// /// A wrapper for a resource that has been temporarily transitioned to readonly. /// - private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture2D, GraphicsResourceHelper.IGraphicsResource + private sealed unsafe class ReadOnly : ReferenceTracker.ITrackedObject, IDisposable, IReadOnlyTexture2D, GraphicsResourceHelper.IGraphicsResource { + /// + /// The owning object for the current instance. + /// + private ReferenceTracker referenceTracker; + /// /// The owning instance being wrapped. /// @@ -78,6 +85,7 @@ partial class ReadWriteTexture2D /// The owning instance to wrap. public ReadOnly(ReadWriteTexture2D owner) { + this.referenceTracker = new ReferenceTracker(this); this.owner = owner; owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); @@ -109,12 +117,13 @@ partial class ReadWriteTexture2D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - ThrowIfDisposed(); + using (this.referenceTracker.GetLease()) + using (this.owner.GetReferenceTracker().GetLease()) + { + this.owner.ThrowIfDeviceMismatch(device); - this.owner.ThrowIfDisposed(); - this.owner.ThrowIfDeviceMismatch(device); - - return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + } } /// @@ -126,12 +135,13 @@ partial class ReadWriteTexture2D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); + using (this.referenceTracker.GetLease()) + using (this.owner.GetReferenceTracker().GetLease()) + { + this.owner.ThrowIfDeviceMismatch(device); - this.owner.ThrowIfDisposed(); - this.owner.ThrowIfDeviceMismatch(device); - - return this.owner.D3D12Resource; + return this.owner.D3D12Resource; + } } /// @@ -141,7 +151,21 @@ partial class ReadWriteTexture2D } /// - protected override void OnDispose() + public void Dispose() + { + this.referenceTracker.Dispose(); + + GC.SuppressFinalize(this); + } + + /// + ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void ReferenceTracker.ITrackedObject.DangerousRelease() { if (this.owner.GraphicsDevice is GraphicsDevice device) { diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs index f9e7ccfb..8db4d870 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs @@ -24,32 +24,34 @@ partial class ReadWriteTexture3D /// public IReadOnlyNormalizedTexture3D AsReadOnly() { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - ThrowIfIsNotInReadOnlyState(); - - ReadOnly? readOnlyWrapper = this.readOnlyWrapper; - - if (readOnlyWrapper is not null) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (GetReferenceTracker().GetLease()) { - return readOnlyWrapper; - } + GraphicsDevice.ThrowIfDeviceLost(); - [MethodImpl(MethodImplOptions.NoInlining)] - static ReadOnly InitializeWrapper(ReadWriteTexture3D texture) - { - return texture.readOnlyWrapper = new(texture); - } + ThrowIfIsNotInReadOnlyState(); - return InitializeWrapper(this); + ReadOnly? readOnlyWrapper = this.readOnlyWrapper; + + if (readOnlyWrapper is not null) + { + return readOnlyWrapper; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static ReadOnly InitializeWrapper(ReadWriteTexture3D texture) + { + return texture.readOnlyWrapper = new(texture); + } + + return InitializeWrapper(this); + } } /// - protected override void OnDispose() + public override void Dispose() { - base.OnDispose(); + base.Dispose(); this.readOnlyWrapper?.Dispose(); } @@ -57,8 +59,13 @@ partial class ReadWriteTexture3D /// /// A wrapper for a resource that has been temporarily transitioned to readonly. /// - private sealed unsafe class ReadOnly : NativeObject, IReadOnlyNormalizedTexture3D, GraphicsResourceHelper.IGraphicsResource + private sealed unsafe class ReadOnly : ReferenceTracker.ITrackedObject, IDisposable, IReadOnlyNormalizedTexture3D, GraphicsResourceHelper.IGraphicsResource { + /// + /// The owning object for the current instance. + /// + private ReferenceTracker referenceTracker; + /// /// The owning instance being wrapped. /// @@ -75,6 +82,7 @@ partial class ReadWriteTexture3D /// The owning instance to wrap. public ReadOnly(ReadWriteTexture3D owner) { + this.referenceTracker = new ReferenceTracker(this); this.owner = owner; owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); @@ -109,12 +117,13 @@ partial class ReadWriteTexture3D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - ThrowIfDisposed(); + using (this.referenceTracker.GetLease()) + using (this.owner.GetReferenceTracker().GetLease()) + { + this.owner.ThrowIfDeviceMismatch(device); - this.owner.ThrowIfDisposed(); - this.owner.ThrowIfDeviceMismatch(device); - - return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + } } /// @@ -126,12 +135,13 @@ partial class ReadWriteTexture3D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); + using (this.referenceTracker.GetLease()) + using (this.owner.GetReferenceTracker().GetLease()) + { + this.owner.ThrowIfDeviceMismatch(device); - this.owner.ThrowIfDisposed(); - this.owner.ThrowIfDeviceMismatch(device); - - return this.owner.D3D12Resource; + return this.owner.D3D12Resource; + } } /// @@ -141,7 +151,21 @@ partial class ReadWriteTexture3D } /// - protected override void OnDispose() + public void Dispose() + { + this.referenceTracker.Dispose(); + + GC.SuppressFinalize(this); + } + + /// + ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void ReferenceTracker.ITrackedObject.DangerousRelease() { if (this.owner.GraphicsDevice is GraphicsDevice device) { diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs index c825d5f7..f4e7b075 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs @@ -24,32 +24,34 @@ partial class ReadWriteTexture3D /// public IReadOnlyTexture3D AsReadOnly() { - GraphicsDevice.ThrowIfDisposed(); - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfDisposed(); - ThrowIfIsNotInReadOnlyState(); - - ReadOnly? readOnlyWrapper = this.readOnlyWrapper; - - if (readOnlyWrapper is not null) + using (GraphicsDevice.GetReferenceTracker().GetLease()) + using (GetReferenceTracker().GetLease()) { - return readOnlyWrapper; - } + GraphicsDevice.ThrowIfDeviceLost(); - [MethodImpl(MethodImplOptions.NoInlining)] - static ReadOnly InitializeWrapper(ReadWriteTexture3D texture) - { - return texture.readOnlyWrapper = new(texture); - } + ThrowIfIsNotInReadOnlyState(); - return InitializeWrapper(this); + ReadOnly? readOnlyWrapper = this.readOnlyWrapper; + + if (readOnlyWrapper is not null) + { + return readOnlyWrapper; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static ReadOnly InitializeWrapper(ReadWriteTexture3D texture) + { + return texture.readOnlyWrapper = new(texture); + } + + return InitializeWrapper(this); + } } /// - protected override void OnDispose() + public override void Dispose() { - base.OnDispose(); + base.Dispose(); this.readOnlyWrapper?.Dispose(); } @@ -57,8 +59,13 @@ partial class ReadWriteTexture3D /// /// A wrapper for a resource that has been temporarily transitioned to readonly. /// - private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture3D, GraphicsResourceHelper.IGraphicsResource + private sealed unsafe class ReadOnly : ReferenceTracker.ITrackedObject, IDisposable, IReadOnlyTexture3D, GraphicsResourceHelper.IGraphicsResource { + /// + /// The owning object for the current instance. + /// + private ReferenceTracker referenceTracker; + /// /// The owning instance being wrapped. /// @@ -75,6 +82,7 @@ partial class ReadWriteTexture3D /// The owning instance to wrap. public ReadOnly(ReadWriteTexture3D owner) { + this.referenceTracker = new ReferenceTracker(this); this.owner = owner; owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); @@ -109,12 +117,13 @@ partial class ReadWriteTexture3D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - ThrowIfDisposed(); + using (this.referenceTracker.GetLease()) + using (this.owner.GetReferenceTracker().GetLease()) + { + this.owner.ThrowIfDeviceMismatch(device); - this.owner.ThrowIfDisposed(); - this.owner.ThrowIfDeviceMismatch(device); - - return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + } } /// @@ -126,12 +135,13 @@ partial class ReadWriteTexture3D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); + using (this.referenceTracker.GetLease()) + using (this.owner.GetReferenceTracker().GetLease()) + { + this.owner.ThrowIfDeviceMismatch(device); - this.owner.ThrowIfDisposed(); - this.owner.ThrowIfDeviceMismatch(device); - - return this.owner.D3D12Resource; + return this.owner.D3D12Resource; + } } /// @@ -141,7 +151,21 @@ partial class ReadWriteTexture3D } /// - protected override void OnDispose() + public void Dispose() + { + this.referenceTracker.Dispose(); + + GC.SuppressFinalize(this); + } + + /// + ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void ReferenceTracker.ITrackedObject.DangerousRelease() { if (this.owner.GraphicsDevice is GraphicsDevice device) { From 149a03d92b4f6b4740f0a96374142b738c56eb5a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 24 Jul 2022 14:37:10 +0200 Subject: [PATCH 30/64] Move ReferenceTracker logic to NativeObject base class --- .../Helpers/SwapChainManager.Rendering.cs | 88 ++++++++++--------- .../Helpers/SwapChainManager.cs | 2 +- .../Graphics/GraphicsDevice.DeviceLost.cs | 2 +- src/ComputeSharp/Graphics/GraphicsDevice.cs | 50 ++--------- .../Helpers/DeviceHelper.Enumerator.cs | 2 +- .../Graphics/Interop/NativeObject.cs | 80 +++++++---------- .../Graphics/Resources/Abstract/Buffer{T}.cs | 44 +--------- .../Resources/Abstract/Texture2D{T}.cs | 60 +++---------- .../Resources/Abstract/Texture3D{T}.cs | 60 +++---------- .../Resources/Abstract/TransferBuffer{T}.cs | 46 ++-------- .../Abstract/TransferTexture2D{T}.cs | 45 +--------- .../Abstract/TransferTexture3D{T}.cs | 45 +--------- .../ReadWriteTexture2D{T,TPixel}.ReadOnly.cs | 32 ++----- .../ReadWriteTexture2D{T}.ReadOnly.cs | 32 ++----- .../ReadWriteTexture3D{T,TPixel}.ReadOnly.cs | 32 ++----- .../ReadWriteTexture3D{T}.ReadOnly.cs | 32 ++----- .../Shaders/Models/ICachedShader.cs | 2 +- .../Shaders/Models/PipelineData.cs | 2 +- 18 files changed, 157 insertions(+), 499 deletions(-) diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs index 6ac85a0a..dfb1801a 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -9,14 +9,14 @@ using ComputeSharp.Uwp.Extensions; using ComputeSharp.WinUI.Extensions; #endif -#pragma warning disable CS0420 - #if WINDOWS_UWP namespace ComputeSharp.Uwp.Helpers; #else namespace ComputeSharp.WinUI.Helpers; #endif +#pragma warning disable CS0420 + /// partial class SwapChainManager { @@ -27,26 +27,27 @@ partial class SwapChainManager /// The instance to use to render frames. public async void StartRenderLoop(IFrameRequestQueue? frameRequestQueue, IShaderRunner shaderRunner) { - ThrowIfDisposed(); - - Guard.IsNotNull(shaderRunner); - - using (await this.setupSemaphore.LockAsync()) + using (GetReferenceTracker().GetLease()) { - this.renderCancellationTokenSource?.Cancel(); - - await this.renderSemaphore.WaitAsync(); + Guard.IsNotNull(shaderRunner); - Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); + using (await this.setupSemaphore.LockAsync()) + { + this.renderCancellationTokenSource?.Cancel(); - this.frameRequestQueue = frameRequestQueue; - this.shaderRunner = shaderRunner; - this.renderCancellationTokenSource = new CancellationTokenSource(); - this.renderThread = newRenderThread; - this.renderSemaphore = new SemaphoreSlim(0, 1); - this.isResizePending = true; + await this.renderSemaphore.WaitAsync(); - newRenderThread.Start(this); + Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); + + this.frameRequestQueue = frameRequestQueue; + this.shaderRunner = shaderRunner; + this.renderCancellationTokenSource = new CancellationTokenSource(); + this.renderThread = newRenderThread; + this.renderSemaphore = new SemaphoreSlim(0, 1); + this.isResizePending = true; + + newRenderThread.Start(this); + } } } @@ -55,8 +56,7 @@ partial class SwapChainManager /// public async void StopRenderLoop() { - ThrowIfDisposed(); - + using (GetReferenceTracker().GetLease()) using (await this.setupSemaphore.LockAsync()) { this.renderCancellationTokenSource?.Cancel(); @@ -69,8 +69,7 @@ partial class SwapChainManager /// Whether or not to use dynamic resolution. public async void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled) { - ThrowIfDisposed(); - + using (GetReferenceTracker().GetLease()) using (await this.setupSemaphore.LockAsync()) { // If there is a render thread currently running, stop it and restart it @@ -103,8 +102,7 @@ partial class SwapChainManager /// Whether or not to use vertical sync. public async void QueueVerticalSyncModeChange(bool isVerticalSyncEnabled) { - ThrowIfDisposed(); - + using (GetReferenceTracker().GetLease()) using (await this.setupSemaphore.LockAsync()) { // The v-sync option can be toggled on the fly when not using dynamic resolution @@ -138,12 +136,13 @@ partial class SwapChainManager /// The height of the render resolution. public void QueueResize(double width, double height) { - ThrowIfDisposed(); + using (GetReferenceTracker().GetLease()) + { + this.width = (float)width; + this.height = (float)height; - this.width = (float)width; - this.height = (float)height; - - this.isResizePending = true; + this.isResizePending = true; + } } /// @@ -153,12 +152,13 @@ partial class SwapChainManager /// The composition scale on the Y axis public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY) { - ThrowIfDisposed(); + using (GetReferenceTracker().GetLease()) + { + this.compositionScaleX = (float)compositionScaleX; + this.compositionScaleY = (float)compositionScaleY; - this.compositionScaleX = (float)compositionScaleX; - this.compositionScaleY = (float)compositionScaleY; - - this.isResizePending = true; + this.isResizePending = true; + } } /// @@ -167,11 +167,12 @@ partial class SwapChainManager /// The resolution scale factor to use. public void QueueResolutionScaleChange(double resolutionScale) { - ThrowIfDisposed(); + using (GetReferenceTracker().GetLease()) + { + this.resolutionScale = (float)resolutionScale; - this.resolutionScale = (float)resolutionScale; - - this.isResizePending = true; + this.isResizePending = true; + } } /// @@ -187,11 +188,18 @@ partial class SwapChainManager { this.dynamicResolutionScale = this.resolutionScale; - RenderLoopWithDynamicResolution(); + // These two leases are needed to ensure the manager isn't disposed while rendering is running + using (GetReferenceTracker().GetLease()) + { + RenderLoopWithDynamicResolution(); + } } else { - RenderLoop(); + using (GetReferenceTracker().GetLease()) + { + RenderLoop(); + } } this.renderStopwatch?.Stop(); diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 32af7800..c0a9e85b 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -497,7 +497,7 @@ internal sealed unsafe partial class SwapChainManager : NativeObject } /// - protected override void OnDispose() + private protected override void OnDispose() { ThreadPool.UnsafeQueueUserWorkItem(static state => { diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index c0f91f06..b44272ba 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -48,7 +48,7 @@ unsafe partial class GraphicsDevice /// private void QueueRaiseDeviceLostEventIfNeeded() { - using (this.referenceTracker.TryGetLease(out bool leaseTaken)) + using (GetReferenceTracker().TryGetLease(out bool leaseTaken)) { if (!leaseTaken) { diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 00d8b987..1e5bf383 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -23,13 +23,8 @@ namespace ComputeSharp; /// A that represents an instance that can be used to run compute shaders. /// [DebuggerDisplay("{ToString(),raw}")] -public sealed unsafe partial class GraphicsDevice : ReferenceTracker.ITrackedObject, IDisposable +public sealed unsafe partial class GraphicsDevice : NativeObject { - /// - /// The owning object for the current instance. - /// - private ReferenceTracker referenceTracker; - /// /// The underlying wrapped by the current instance. /// @@ -139,8 +134,6 @@ public sealed unsafe partial class GraphicsDevice : ReferenceTracker.ITrackedObj /// The available info for the new instance. internal GraphicsDevice(ID3D12Device* d3D12Device, IDXGIAdapter* dxgiAdapter, DXGI_ADAPTER_DESC1* dxgiDescription1) { - this.referenceTracker = new ReferenceTracker(this); - this.d3D12Device = new ComPtr(d3D12Device); this.d3D12ComputeCommandQueue = d3D12Device->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COMPUTE); @@ -181,14 +174,6 @@ public sealed unsafe partial class GraphicsDevice : ReferenceTracker.ITrackedObj RegisterDeviceLostCallback(this, out this.deviceHandle, out this.deviceRemovedEvent, out this.deviceRemovedWaitHandle); } - /// - /// Releases unmanaged resources for the current instance. - /// - ~GraphicsDevice() - { - this.referenceTracker.Dispose(); - } - /// /// Gets the locally unique identifier for the current device. /// @@ -253,7 +238,7 @@ public sealed unsafe partial class GraphicsDevice : ReferenceTracker.ITrackedObj /// Whether the current device supports double precision floating point operations in shaders. public bool IsDoublePrecisionSupportAvailable() { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceLost(); @@ -272,7 +257,7 @@ public sealed unsafe partial class GraphicsDevice : ReferenceTracker.ITrackedObj public bool IsReadOnlyTexture2DSupportedForType() where T : unmanaged { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceLost(); @@ -289,7 +274,7 @@ public sealed unsafe partial class GraphicsDevice : ReferenceTracker.ITrackedObj public bool IsReadWriteTexture2DSupportedForType() where T : unmanaged { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceLost(); @@ -308,7 +293,7 @@ public sealed unsafe partial class GraphicsDevice : ReferenceTracker.ITrackedObj public bool IsReadOnlyTexture3DSupportedForType() where T : unmanaged { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceLost(); @@ -325,7 +310,7 @@ public sealed unsafe partial class GraphicsDevice : ReferenceTracker.ITrackedObj public bool IsReadWriteTexture3DSupportedForType() where T : unmanaged { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceLost(); @@ -423,28 +408,7 @@ public sealed unsafe partial class GraphicsDevice : ReferenceTracker.ITrackedObj } /// - public void Dispose() - { - this.referenceTracker.Dispose(); - - GC.SuppressFinalize(this); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ref ReferenceTracker GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - void ReferenceTracker.ITrackedObject.DangerousRelease() + private protected override void OnDispose() { DeviceHelper.NotifyDisposedDevice(this); diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Enumerator.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Enumerator.cs index 019ef47d..87296d33 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Enumerator.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Enumerator.cs @@ -207,7 +207,7 @@ partial class DeviceHelper } /// - protected override void OnDispose() + private protected override void OnDispose() { this.dxgiFactory6.Dispose(); } diff --git a/src/ComputeSharp/Graphics/Interop/NativeObject.cs b/src/ComputeSharp/Graphics/Interop/NativeObject.cs index d96a06f9..53383848 100644 --- a/src/ComputeSharp/Graphics/Interop/NativeObject.cs +++ b/src/ComputeSharp/Graphics/Interop/NativeObject.cs @@ -1,77 +1,61 @@ using System; using System.Runtime.CompilerServices; -using System.Threading; namespace ComputeSharp.Interop; /// /// Base class for a class. /// -internal abstract class NativeObject : IDisposable +public abstract class NativeObject : IDisposable, ReferenceTracker.ITrackedObject { /// - /// Indicates whether or not the current instance has been disposed. + /// The owning object for the current instance. /// - private volatile int isDisposed; + private ReferenceTracker referenceTracker; + + /// + /// Creates a new instance. + /// + internal NativeObject() + { + this.referenceTracker = new ReferenceTracker(this); + } /// /// Releases unmanaged resources and performs other cleanup operations. /// ~NativeObject() { - if (Interlocked.CompareExchange(ref this.isDisposed, 1, 0) == 0) - { - OnDispose(); - } - } - - /// - /// Gets whether or not the current instance has already been disposed. - /// - internal bool IsDisposed - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => this.isDisposed != 0; + this.referenceTracker.Dispose(); } /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { - if (Interlocked.CompareExchange(ref this.isDisposed, 1, 0) == 0) - { - [MethodImpl(MethodImplOptions.NoInlining)] - void DisposeAndSuppressFinalize() - { - OnDispose(); + this.referenceTracker.Dispose(); - GC.SuppressFinalize(this); - } - - DisposeAndSuppressFinalize(); - } + GC.SuppressFinalize(this); } - /// - /// Releases unmanaged and (optionally) managed resources. - /// - protected abstract void OnDispose(); - - /// - /// Throws an if the current instance has been disposed. - /// - /// Thrown if the current instance is disposed. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void ThrowIfDisposed() + internal ref ReferenceTracker GetReferenceTracker() { - if (IsDisposed) - { - // We can't use ThrowHelper here as we only want to invoke ToString if we - // are about to throw an exception. The JIT will recognize this pattern - // as this method has a single basic block that always throws an exception. - static void Throw(object self) => throw new ObjectDisposedException(self.ToString()); - - Throw(this); - } + return ref this.referenceTracker; } + + /// + ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void ReferenceTracker.ITrackedObject.DangerousRelease() + { + OnDispose(); + } + + /// + private protected abstract void OnDispose(); } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs index 7ef4b0b7..1054071b 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs @@ -25,14 +25,9 @@ namespace ComputeSharp.Resources; /// A representing a typed buffer stored on GPU memory. /// /// The type of items stored on the buffer. -public unsafe abstract class Buffer : ReferenceTracker.ITrackedObject, IDisposable, IGraphicsResource +public unsafe abstract class Buffer : NativeObject, IGraphicsResource where T : unmanaged { - /// - /// The owning object for the current instance. - /// - private ReferenceTracker referenceTracker; - #if NET6_0_OR_GREATER /// /// The instance used to retrieve . @@ -70,8 +65,6 @@ public unsafe abstract class Buffer : ReferenceTracker.ITrackedObject, IDispo /// The allocation mode to use for the new resource. private protected Buffer(GraphicsDevice device, int length, uint elementSizeInBytes, ResourceType resourceType, AllocationMode allocationMode) { - this.referenceTracker = new ReferenceTracker(this); - using (device.GetReferenceTracker().GetLease()) { device.ThrowIfDeviceLost(); @@ -133,14 +126,6 @@ public unsafe abstract class Buffer : ReferenceTracker.ITrackedObject, IDispo } } - /// - /// Releases unmanaged resources for the current instance. - /// - ~Buffer() - { - this.referenceTracker.Dispose(); - } - /// public GraphicsDevice GraphicsDevice { get; } @@ -219,28 +204,7 @@ public unsafe abstract class Buffer : ReferenceTracker.ITrackedObject, IDispo internal abstract void CopyFrom(ref T source, int destinationOffset, int count); /// - public void Dispose() - { - this.referenceTracker.Dispose(); - - GC.SuppressFinalize(this); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ref ReferenceTracker GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - void ReferenceTracker.ITrackedObject.DangerousRelease() + private protected sealed override void OnDispose() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER @@ -270,7 +234,7 @@ public unsafe abstract class Buffer : ReferenceTracker.ITrackedObject, IDispo /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceMismatch(device); @@ -283,7 +247,7 @@ public unsafe abstract class Buffer : ReferenceTracker.ITrackedObject, IDispo /// internal unsafe ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceMismatch(device); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs index b351356e..48b68a5c 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs @@ -26,14 +26,9 @@ namespace ComputeSharp.Resources; /// A representing a typed 2D texture stored on GPU memory. /// /// The type of items stored on the texture. -public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDisposable, IGraphicsResource, GraphicsResourceHelper.IGraphicsResource +public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, GraphicsResourceHelper.IGraphicsResource where T : unmanaged { - /// - /// The owning object for the current instance. - /// - private ReferenceTracker referenceTracker; - #if NET6_0_OR_GREATER /// /// The instance used to retrieve . @@ -77,8 +72,6 @@ public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDi /// The format support for the current texture type. private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, AllocationMode allocationMode, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { - this.referenceTracker = new ReferenceTracker(this); - using (device.GetReferenceTracker().GetLease()) { device.ThrowIfDeviceLost(); @@ -144,14 +137,6 @@ public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDi } } - /// - /// Releases unmanaged resources for the current instance. - /// - ~Texture2D() - { - this.referenceTracker.Dispose(); - } - /// public GraphicsDevice GraphicsDevice { get; } @@ -187,7 +172,7 @@ public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDi internal void CopyTo(ref T destination, int size, int sourceOffsetX, int sourceOffsetY, int width, int height) { using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); @@ -278,8 +263,8 @@ public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDi internal void CopyTo(Texture2D destination, int sourceOffsetX, int sourceOffsetY, int destinationOffsetX, int destinationOffsetY, int width, int height) { using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (this.referenceTracker.GetLease()) - using (destination.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) + using (destination.GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); @@ -348,7 +333,7 @@ public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDi internal void CopyTo(ReadBackTexture2D destination, int sourceOffsetX, int sourceOffsetY, int destinationOffsetX, int destinationOffsetY, int width, int height) { using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) using (destination.GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); @@ -413,7 +398,7 @@ public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDi internal void CopyFrom(ref T source, int size, int destinationOffsetX, int destinationOffsetY, int width, int height) { using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); @@ -502,7 +487,7 @@ public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDi internal void CopyFrom(UploadTexture2D source, int sourceOffsetX, int sourceOffsetY, int destinationOffsetX, int destinationOffsetY, int width, int height) { using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) using (source.GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); @@ -556,28 +541,7 @@ public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDi } /// - public virtual void Dispose() - { - this.referenceTracker.Dispose(); - - GC.SuppressFinalize(this); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ref ReferenceTracker GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - void ReferenceTracker.ITrackedObject.DangerousRelease() + private protected override void OnDispose() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER @@ -625,7 +589,7 @@ public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDi /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceMismatch(device); @@ -638,7 +602,7 @@ public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDi /// internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceMismatch(device); @@ -649,7 +613,7 @@ public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDi /// internal (D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceMismatch(device); @@ -667,7 +631,7 @@ public unsafe abstract class Texture2D : ReferenceTracker.ITrackedObject, IDi /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceMismatch(device); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs index e4f5635d..2b85ba0b 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs @@ -26,14 +26,9 @@ namespace ComputeSharp.Resources; /// A representing a typed 3D texture stored on GPU memory. /// /// The type of items stored on the texture. -public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDisposable, IGraphicsResource, GraphicsResourceHelper.IGraphicsResource +public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, GraphicsResourceHelper.IGraphicsResource where T : unmanaged { - /// - /// The owning object for the current instance. - /// - private ReferenceTracker referenceTracker; - #if NET6_0_OR_GREATER /// /// The instance used to retrieve . @@ -78,8 +73,6 @@ public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDi /// The format support for the current texture type. private protected Texture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType, AllocationMode allocationMode, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { - this.referenceTracker = new ReferenceTracker(this); - using (device.GetReferenceTracker().GetLease()) { device.ThrowIfDeviceLost(); @@ -149,14 +142,6 @@ public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDi } } - /// - /// Releases unmanaged resources for the current instance. - /// - ~Texture3D() - { - this.referenceTracker.Dispose(); - } - /// public GraphicsDevice GraphicsDevice { get; } @@ -199,7 +184,7 @@ public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDi internal void CopyTo(ref T destination, int size, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int width, int height, int depth) { using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); @@ -299,8 +284,8 @@ public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDi internal void CopyTo(Texture3D destination, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (this.referenceTracker.GetLease()) - using (destination.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) + using (destination.GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); @@ -378,7 +363,7 @@ public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDi internal void CopyTo(ReadBackTexture3D destination, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) using (destination.GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); @@ -451,7 +436,7 @@ public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDi internal void CopyFrom(ref T source, int size, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); @@ -549,7 +534,7 @@ public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDi internal void CopyFrom(UploadTexture3D source, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) using (source.GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); @@ -609,28 +594,7 @@ public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDi } /// - public virtual void Dispose() - { - this.referenceTracker.Dispose(); - - GC.SuppressFinalize(this); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ref ReferenceTracker GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - void ReferenceTracker.ITrackedObject.DangerousRelease() + private protected override void OnDispose() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER @@ -678,7 +642,7 @@ public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDi /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceMismatch(device); @@ -691,7 +655,7 @@ public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDi /// internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceMismatch(device); @@ -702,7 +666,7 @@ public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDi /// internal (D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceMismatch(device); @@ -720,7 +684,7 @@ public unsafe abstract class Texture3D : ReferenceTracker.ITrackedObject, IDi /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { ThrowIfDeviceMismatch(device); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs index d4583bfb..ca7397b2 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs @@ -15,14 +15,9 @@ namespace ComputeSharp.Resources; /// A representing a typed buffer stored on CPU memory, that can be used to transfer data to/from the GPU. /// /// The type of items stored on the buffer. -public abstract unsafe class TransferBuffer : ReferenceTracker.ITrackedObject, IGraphicsResource, IMemoryOwner +public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource, IMemoryOwner where T : unmanaged { - /// - /// The owning object for the current instance. - /// - private ReferenceTracker referenceTracker; - #if NET6_0_OR_GREATER /// /// The instance used to retrieve . @@ -49,8 +44,6 @@ public abstract unsafe class TransferBuffer : ReferenceTracker.ITrackedObject /// The allocation mode to use for the new resource. private protected TransferBuffer(GraphicsDevice device, int length, ResourceType resourceType, AllocationMode allocationMode) { - this.referenceTracker = new ReferenceTracker(this); - using (device.GetReferenceTracker().GetLease()) { device.ThrowIfDeviceLost(); @@ -78,14 +71,6 @@ public abstract unsafe class TransferBuffer : ReferenceTracker.ITrackedObject } } - /// - /// Releases unmanaged resources for the current instance. - /// - ~TransferBuffer() - { - this.referenceTracker.Dispose(); - } - /// public GraphicsDevice GraphicsDevice { get; } @@ -110,7 +95,7 @@ public abstract unsafe class TransferBuffer : ReferenceTracker.ITrackedObject [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { return new MemoryManager(this).Memory; } @@ -123,7 +108,7 @@ public abstract unsafe class TransferBuffer : ReferenceTracker.ITrackedObject [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) { return new(this.mappedData, Length); } @@ -131,28 +116,7 @@ public abstract unsafe class TransferBuffer : ReferenceTracker.ITrackedObject } /// - public void Dispose() - { - this.referenceTracker.Dispose(); - - GC.SuppressFinalize(this); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ref ReferenceTracker GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - void ReferenceTracker.ITrackedObject.DangerousRelease() + private protected sealed override void OnDispose() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER @@ -211,7 +175,7 @@ public abstract unsafe class TransferBuffer : ReferenceTracker.ITrackedObject /// public override MemoryHandle Pin(int elementIndex = 0) { - using (this.buffer.referenceTracker.GetLease()) + using (this.buffer.GetReferenceTracker().GetLease()) { Guard.IsEqualTo(elementIndex, 0); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs index cd0d9a99..783b6146 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs @@ -1,5 +1,4 @@ -using System; -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using CommunityToolkit.Diagnostics; using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Extensions; @@ -16,14 +15,9 @@ namespace ComputeSharp.Resources; /// A representing a typed 2D texture stored on on CPU memory, that can be used to transfer data to/from the GPU. /// /// The type of items stored on the texture. -public unsafe abstract class TransferTexture2D : ReferenceTracker.ITrackedObject, IDisposable, IGraphicsResource +public unsafe abstract class TransferTexture2D : NativeObject, IGraphicsResource where T : unmanaged { - /// - /// The owning object for the current instance. - /// - private ReferenceTracker referenceTracker; - #if NET6_0_OR_GREATER /// /// The instance used to retrieve . @@ -56,8 +50,6 @@ public unsafe abstract class TransferTexture2D : ReferenceTracker.ITrackedObj /// The allocation mode to use for the new resource. private protected TransferTexture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, AllocationMode allocationMode) { - this.referenceTracker = new ReferenceTracker(this); - using (device.GetReferenceTracker().GetLease()) { device.ThrowIfDeviceLost(); @@ -95,14 +87,6 @@ public unsafe abstract class TransferTexture2D : ReferenceTracker.ITrackedObj } } - /// - /// Releases unmanaged resources for the current instance. - /// - ~TransferTexture2D() - { - this.referenceTracker.Dispose(); - } - /// public GraphicsDevice GraphicsDevice { get; } @@ -132,7 +116,7 @@ public unsafe abstract class TransferTexture2D : ReferenceTracker.ITrackedObj [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - using (this.referenceTracker.GetLease()) + using (this.GetReferenceTracker().GetLease()) { return new(this.mappedData, Width, Height, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); } @@ -140,28 +124,7 @@ public unsafe abstract class TransferTexture2D : ReferenceTracker.ITrackedObj } /// - public void Dispose() - { - this.referenceTracker.Dispose(); - - GC.SuppressFinalize(this); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ref ReferenceTracker GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - void ReferenceTracker.ITrackedObject.DangerousRelease() + private protected sealed override void OnDispose() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs index da347e36..29243629 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs @@ -1,5 +1,4 @@ -using System; -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using CommunityToolkit.Diagnostics; using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Extensions; @@ -16,14 +15,9 @@ namespace ComputeSharp.Resources; /// A representing a typed 3D texture stored on on CPU memory, that can be used to transfer data to/from the GPU. /// /// The type of items stored on the texture. -public unsafe abstract class TransferTexture3D : ReferenceTracker.ITrackedObject, IDisposable, IGraphicsResource +public unsafe abstract class TransferTexture3D : NativeObject, IGraphicsResource where T : unmanaged { - /// - /// The owning object for the current instance. - /// - private ReferenceTracker referenceTracker; - #if NET6_0_OR_GREATER /// /// The instance used to retrieve . @@ -57,8 +51,6 @@ public unsafe abstract class TransferTexture3D : ReferenceTracker.ITrackedObj /// The allocation mode to use for the new resource. private protected TransferTexture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType, AllocationMode allocationMode) { - this.referenceTracker = new ReferenceTracker(this); - using (device.GetReferenceTracker().GetLease()) { device.ThrowIfDeviceLost(); @@ -98,14 +90,6 @@ public unsafe abstract class TransferTexture3D : ReferenceTracker.ITrackedObj } } - /// - /// Releases unmanaged resources for the current instance. - /// - ~TransferTexture3D() - { - this.referenceTracker.Dispose(); - } - /// public GraphicsDevice GraphicsDevice { get; } @@ -140,7 +124,7 @@ public unsafe abstract class TransferTexture3D : ReferenceTracker.ITrackedObj [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - using (this.referenceTracker.GetLease()) + using (this.GetReferenceTracker().GetLease()) { return new(this.mappedData, Width, Height, Depth, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); } @@ -148,28 +132,7 @@ public unsafe abstract class TransferTexture3D : ReferenceTracker.ITrackedObj } /// - public void Dispose() - { - this.referenceTracker.Dispose(); - - GC.SuppressFinalize(this); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ref ReferenceTracker GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - void ReferenceTracker.ITrackedObject.DangerousRelease() + private protected sealed override void OnDispose() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs index 35aa2d73..014ba208 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs @@ -49,9 +49,9 @@ partial class ReadWriteTexture2D } /// - public override void Dispose() + private protected override void OnDispose() { - base.Dispose(); + base.OnDispose(); this.readOnlyWrapper?.Dispose(); } @@ -59,13 +59,8 @@ partial class ReadWriteTexture2D /// /// A wrapper for a resource that has been temporarily transitioned to readonly. /// - private sealed unsafe class ReadOnly : ReferenceTracker.ITrackedObject, IDisposable, IReadOnlyNormalizedTexture2D, GraphicsResourceHelper.IGraphicsResource + private sealed unsafe class ReadOnly : NativeObject, IReadOnlyNormalizedTexture2D, GraphicsResourceHelper.IGraphicsResource { - /// - /// The owning object for the current instance. - /// - private ReferenceTracker referenceTracker; - /// /// The owning instance being wrapped. /// @@ -82,7 +77,6 @@ partial class ReadWriteTexture2D /// The owning instance to wrap. public ReadOnly(ReadWriteTexture2D owner) { - this.referenceTracker = new ReferenceTracker(this); this.owner = owner; owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); @@ -114,7 +108,7 @@ partial class ReadWriteTexture2D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) using (this.owner.GetReferenceTracker().GetLease()) { this.owner.ThrowIfDeviceMismatch(device); @@ -132,7 +126,7 @@ partial class ReadWriteTexture2D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) using (this.owner.GetReferenceTracker().GetLease()) { this.owner.ThrowIfDeviceMismatch(device); @@ -148,21 +142,7 @@ partial class ReadWriteTexture2D } /// - public void Dispose() - { - this.referenceTracker.Dispose(); - - GC.SuppressFinalize(this); - } - - /// - ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - void ReferenceTracker.ITrackedObject.DangerousRelease() + private protected override void OnDispose() { if (this.owner.GraphicsDevice is GraphicsDevice device) { diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs index 056d8ee4..091fae0b 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs @@ -52,9 +52,9 @@ partial class ReadWriteTexture2D } /// - public override void Dispose() + private protected override void OnDispose() { - base.Dispose(); + base.OnDispose(); this.readOnlyWrapper?.Dispose(); } @@ -62,13 +62,8 @@ partial class ReadWriteTexture2D /// /// A wrapper for a resource that has been temporarily transitioned to readonly. /// - private sealed unsafe class ReadOnly : ReferenceTracker.ITrackedObject, IDisposable, IReadOnlyTexture2D, GraphicsResourceHelper.IGraphicsResource + private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture2D, GraphicsResourceHelper.IGraphicsResource { - /// - /// The owning object for the current instance. - /// - private ReferenceTracker referenceTracker; - /// /// The owning instance being wrapped. /// @@ -85,7 +80,6 @@ partial class ReadWriteTexture2D /// The owning instance to wrap. public ReadOnly(ReadWriteTexture2D owner) { - this.referenceTracker = new ReferenceTracker(this); this.owner = owner; owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); @@ -117,7 +111,7 @@ partial class ReadWriteTexture2D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) using (this.owner.GetReferenceTracker().GetLease()) { this.owner.ThrowIfDeviceMismatch(device); @@ -135,7 +129,7 @@ partial class ReadWriteTexture2D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) using (this.owner.GetReferenceTracker().GetLease()) { this.owner.ThrowIfDeviceMismatch(device); @@ -151,21 +145,7 @@ partial class ReadWriteTexture2D } /// - public void Dispose() - { - this.referenceTracker.Dispose(); - - GC.SuppressFinalize(this); - } - - /// - ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - void ReferenceTracker.ITrackedObject.DangerousRelease() + private protected override void OnDispose() { if (this.owner.GraphicsDevice is GraphicsDevice device) { diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs index 8db4d870..7aec0e6f 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs @@ -49,9 +49,9 @@ partial class ReadWriteTexture3D } /// - public override void Dispose() + private protected override void OnDispose() { - base.Dispose(); + base.OnDispose(); this.readOnlyWrapper?.Dispose(); } @@ -59,13 +59,8 @@ partial class ReadWriteTexture3D /// /// A wrapper for a resource that has been temporarily transitioned to readonly. /// - private sealed unsafe class ReadOnly : ReferenceTracker.ITrackedObject, IDisposable, IReadOnlyNormalizedTexture3D, GraphicsResourceHelper.IGraphicsResource + private sealed unsafe class ReadOnly : NativeObject, IReadOnlyNormalizedTexture3D, GraphicsResourceHelper.IGraphicsResource { - /// - /// The owning object for the current instance. - /// - private ReferenceTracker referenceTracker; - /// /// The owning instance being wrapped. /// @@ -82,7 +77,6 @@ partial class ReadWriteTexture3D /// The owning instance to wrap. public ReadOnly(ReadWriteTexture3D owner) { - this.referenceTracker = new ReferenceTracker(this); this.owner = owner; owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); @@ -117,7 +111,7 @@ partial class ReadWriteTexture3D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) using (this.owner.GetReferenceTracker().GetLease()) { this.owner.ThrowIfDeviceMismatch(device); @@ -135,7 +129,7 @@ partial class ReadWriteTexture3D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) using (this.owner.GetReferenceTracker().GetLease()) { this.owner.ThrowIfDeviceMismatch(device); @@ -151,21 +145,7 @@ partial class ReadWriteTexture3D } /// - public void Dispose() - { - this.referenceTracker.Dispose(); - - GC.SuppressFinalize(this); - } - - /// - ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - void ReferenceTracker.ITrackedObject.DangerousRelease() + private protected override void OnDispose() { if (this.owner.GraphicsDevice is GraphicsDevice device) { diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs index f4e7b075..401d91ef 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs @@ -49,9 +49,9 @@ partial class ReadWriteTexture3D } /// - public override void Dispose() + private protected override void OnDispose() { - base.Dispose(); + base.OnDispose(); this.readOnlyWrapper?.Dispose(); } @@ -59,13 +59,8 @@ partial class ReadWriteTexture3D /// /// A wrapper for a resource that has been temporarily transitioned to readonly. /// - private sealed unsafe class ReadOnly : ReferenceTracker.ITrackedObject, IDisposable, IReadOnlyTexture3D, GraphicsResourceHelper.IGraphicsResource + private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture3D, GraphicsResourceHelper.IGraphicsResource { - /// - /// The owning object for the current instance. - /// - private ReferenceTracker referenceTracker; - /// /// The owning instance being wrapped. /// @@ -82,7 +77,6 @@ partial class ReadWriteTexture3D /// The owning instance to wrap. public ReadOnly(ReadWriteTexture3D owner) { - this.referenceTracker = new ReferenceTracker(this); this.owner = owner; owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); @@ -117,7 +111,7 @@ partial class ReadWriteTexture3D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) using (this.owner.GetReferenceTracker().GetLease()) { this.owner.ThrowIfDeviceMismatch(device); @@ -135,7 +129,7 @@ partial class ReadWriteTexture3D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (this.referenceTracker.GetLease()) + using (GetReferenceTracker().GetLease()) using (this.owner.GetReferenceTracker().GetLease()) { this.owner.ThrowIfDeviceMismatch(device); @@ -151,21 +145,7 @@ partial class ReadWriteTexture3D } /// - public void Dispose() - { - this.referenceTracker.Dispose(); - - GC.SuppressFinalize(this); - } - - /// - ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - void ReferenceTracker.ITrackedObject.DangerousRelease() + private protected override void OnDispose() { if (this.owner.GraphicsDevice is GraphicsDevice device) { diff --git a/src/ComputeSharp/Shaders/Models/ICachedShader.cs b/src/ComputeSharp/Shaders/Models/ICachedShader.cs index 7d748577..f05fb96b 100644 --- a/src/ComputeSharp/Shaders/Models/ICachedShader.cs +++ b/src/ComputeSharp/Shaders/Models/ICachedShader.cs @@ -86,7 +86,7 @@ internal interface ICachedShader public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new ((ID3DBlob*)this.dxcBlobBytecode.Get()); /// - protected override void OnDispose() + private protected override void OnDispose() { this.dxcBlobBytecode.Dispose(); } diff --git a/src/ComputeSharp/Shaders/Models/PipelineData.cs b/src/ComputeSharp/Shaders/Models/PipelineData.cs index cddc968f..d7fec9e1 100644 --- a/src/ComputeSharp/Shaders/Models/PipelineData.cs +++ b/src/ComputeSharp/Shaders/Models/PipelineData.cs @@ -41,7 +41,7 @@ internal sealed unsafe class PipelineData : NativeObject public ID3D12PipelineState* D3D12PipelineState => this.d3D12PipelineState; /// - protected override void OnDispose() + private protected override void OnDispose() { this.d3D12RootSignature.Dispose(); this.d3D12PipelineState.Dispose(); From 5100ab471abf6d7558fc46738d92dd9c874adea8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 24 Jul 2022 14:53:29 +0200 Subject: [PATCH 31/64] Move all Guard checks at the start of each method --- .../Helpers/SwapChainManager.Rendering.cs | 28 ++- .../Graphics/Resources/Abstract/Buffer{T}.cs | 20 +-- .../Resources/Abstract/StructuredBuffer{T}.cs | 58 +++--- .../Resources/Abstract/Texture2D{T}.cs | 128 +++++++------- .../Resources/Abstract/Texture3D{T}.cs | 166 +++++++++--------- .../Resources/Abstract/TransferBuffer{T}.cs | 6 +- .../Abstract/TransferTexture2D{T}.cs | 6 +- .../Abstract/TransferTexture3D{T}.cs | 8 +- .../Graphics/Resources/ConstantBuffer{T}.cs | 30 ++-- 9 files changed, 224 insertions(+), 226 deletions(-) diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs index dfb1801a..99c5edf2 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -27,27 +27,25 @@ partial class SwapChainManager /// The instance to use to render frames. public async void StartRenderLoop(IFrameRequestQueue? frameRequestQueue, IShaderRunner shaderRunner) { + Guard.IsNotNull(shaderRunner); + using (GetReferenceTracker().GetLease()) + using (await this.setupSemaphore.LockAsync()) { - Guard.IsNotNull(shaderRunner); + this.renderCancellationTokenSource?.Cancel(); - using (await this.setupSemaphore.LockAsync()) - { - this.renderCancellationTokenSource?.Cancel(); + await this.renderSemaphore.WaitAsync(); - await this.renderSemaphore.WaitAsync(); + Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); - Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); + this.frameRequestQueue = frameRequestQueue; + this.shaderRunner = shaderRunner; + this.renderCancellationTokenSource = new CancellationTokenSource(); + this.renderThread = newRenderThread; + this.renderSemaphore = new SemaphoreSlim(0, 1); + this.isResizePending = true; - this.frameRequestQueue = frameRequestQueue; - this.shaderRunner = shaderRunner; - this.renderCancellationTokenSource = new CancellationTokenSource(); - this.renderThread = newRenderThread; - this.renderSemaphore = new SemaphoreSlim(0, 1); - this.isResizePending = true; - - newRenderThread.Start(this); - } + newRenderThread.Start(this); } } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs index 1054071b..0a1f4745 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs @@ -65,20 +65,20 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource /// The allocation mode to use for the new resource. private protected Buffer(GraphicsDevice device, int length, uint elementSizeInBytes, ResourceType resourceType, AllocationMode allocationMode) { + if (resourceType == ResourceType.Constant) + { + Guard.IsBetweenOrEqualTo(length, 1, D3D12.D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT); + } + else + { + // The maximum length is set such that the aligned buffer size can't exceed uint.MaxValue + Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / elementSizeInBytes) & ~255); + } + using (device.GetReferenceTracker().GetLease()) { device.ThrowIfDeviceLost(); - if (resourceType == ResourceType.Constant) - { - Guard.IsBetweenOrEqualTo(length, 1, D3D12.D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT); - } - else - { - // The maximum length is set such that the aligned buffer size can't exceed uint.MaxValue - Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / elementSizeInBytes) & ~255); - } - if (TypeInfo.IsDoubleOrContainsDoubles && device.D3D12Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS).DoublePrecisionFloatShaderOps == 0) { diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs index be9dcddb..1a49abdb 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs @@ -32,15 +32,15 @@ public abstract class StructuredBuffer : Buffer /// internal override unsafe void CopyTo(ref T destination, int sourceOffset, int count) { + Guard.IsBetweenOrEqualTo(count, 0, Length); + Guard.IsInRange(sourceOffset, 0, Length); + Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); - Guard.IsBetweenOrEqualTo(count, 0, Length); - Guard.IsInRange(sourceOffset, 0, Length); - Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); - if (GraphicsDevice.IsCacheCoherentUMA) { using ID3D12ResourceMap resource = D3D12Resource->Map(); @@ -105,6 +105,13 @@ public abstract class StructuredBuffer : Buffer /// internal override unsafe void CopyTo(Buffer destination, int sourceOffset, int destinationOffset, int count) { + Guard.IsBetweenOrEqualTo(count, 0, Length); + Guard.IsBetweenOrEqualTo(count, 0, destination.Length); + Guard.IsInRange(sourceOffset, 0, Length); + Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); + Guard.IsInRange(destinationOffset, 0, destination.Length); + Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) using (destination.GetReferenceTracker().GetLease()) @@ -113,13 +120,6 @@ public abstract class StructuredBuffer : Buffer destination.ThrowIfDeviceMismatch(GraphicsDevice); - Guard.IsBetweenOrEqualTo(count, 0, Length); - Guard.IsBetweenOrEqualTo(count, 0, destination.Length); - Guard.IsInRange(sourceOffset, 0, Length); - Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); - Guard.IsInRange(destinationOffset, 0, destination.Length); - Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); - if (!destination.IsPaddingPresent) { nint sourceByteOffset = (nint)sourceOffset * sizeof(T); @@ -151,6 +151,13 @@ public abstract class StructuredBuffer : Buffer /// The number of items to read. internal unsafe void CopyTo(ReadBackBuffer destination, int sourceOffset, int destinationOffset, int count) { + Guard.IsBetweenOrEqualTo(count, 0, Length); + Guard.IsBetweenOrEqualTo(count, 0, destination.Length); + Guard.IsInRange(sourceOffset, 0, Length); + Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); + Guard.IsInRange(destinationOffset, 0, destination.Length); + Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) using (destination.GetReferenceTracker().GetLease()) @@ -159,13 +166,6 @@ public abstract class StructuredBuffer : Buffer destination.ThrowIfDeviceMismatch(GraphicsDevice); - Guard.IsBetweenOrEqualTo(count, 0, Length); - Guard.IsBetweenOrEqualTo(count, 0, destination.Length); - Guard.IsInRange(sourceOffset, 0, Length); - Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); - Guard.IsInRange(destinationOffset, 0, destination.Length); - Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); - if (GraphicsDevice.IsCacheCoherentUMA) { using ID3D12ResourceMap resource = D3D12Resource->Map(); @@ -196,15 +196,15 @@ public abstract class StructuredBuffer : Buffer /// internal override unsafe void CopyFrom(ref T source, int offset, int length) { + Guard.IsBetweenOrEqualTo(length, 0, Length); + Guard.IsInRange(offset, 0, Length); + Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); - Guard.IsBetweenOrEqualTo(length, 0, Length); - Guard.IsInRange(offset, 0, Length); - Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); - if (GraphicsDevice.IsCacheCoherentUMA) { using ID3D12ResourceMap resource = D3D12Resource->Map(); @@ -273,6 +273,13 @@ public abstract class StructuredBuffer : Buffer /// The number of items to read. internal unsafe void CopyFrom(UploadBuffer source, int sourceOffset, int destinationOffset, int count) { + Guard.IsBetweenOrEqualTo(count, 0, Length); + Guard.IsBetweenOrEqualTo(count, 0, source.Length); + Guard.IsInRange(sourceOffset, 0, source.Length); + Guard.IsLessThanOrEqualTo(sourceOffset + count, source.Length, nameof(sourceOffset)); + Guard.IsInRange(destinationOffset, 0, Length); + Guard.IsLessThanOrEqualTo(destinationOffset + count, Length, nameof(destinationOffset)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) using (source.GetReferenceTracker().GetLease()) @@ -281,13 +288,6 @@ public abstract class StructuredBuffer : Buffer source.ThrowIfDeviceMismatch(GraphicsDevice); - Guard.IsBetweenOrEqualTo(count, 0, Length); - Guard.IsBetweenOrEqualTo(count, 0, source.Length); - Guard.IsInRange(sourceOffset, 0, source.Length); - Guard.IsLessThanOrEqualTo(sourceOffset + count, source.Length, nameof(sourceOffset)); - Guard.IsInRange(destinationOffset, 0, Length); - Guard.IsLessThanOrEqualTo(destinationOffset + count, Length, nameof(destinationOffset)); - if (GraphicsDevice.IsCacheCoherentUMA) { using ID3D12ResourceMap resource = D3D12Resource->Map(); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs index 48b68a5c..4dfd4596 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs @@ -72,13 +72,13 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// The format support for the current texture type. private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, AllocationMode allocationMode, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { + Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + using (device.GetReferenceTracker().GetLease()) { device.ThrowIfDeviceLost(); - Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) { UnsupportedTextureTypeException.ThrowForTexture2D(); @@ -171,26 +171,26 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// The height of the memory area to copy. internal void CopyTo(ref T destination, int size, int sourceOffsetX, int sourceOffsetY, int width, int height) { + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(sourceOffsetY, 0, Height); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); + Guard.IsGreaterThanOrEqualTo(size, (nint)width * height); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); - Guard.IsInRange(sourceOffsetX, 0, Width); - Guard.IsInRange(sourceOffsetY, 0, Height); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - Guard.IsGreaterThanOrEqualTo(size, (nint)width * height); - GraphicsDevice.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintDestination, - out ulong rowSizeInBytes, - out ulong totalSizeInBytes); + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintDestination, + out ulong rowSizeInBytes, + out ulong totalSizeInBytes); #if NET6_0_OR_GREATER using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( @@ -262,6 +262,19 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// The height of the memory area to copy. internal void CopyTo(Texture2D destination, int sourceOffsetX, int sourceOffsetY, int destinationOffsetX, int destinationOffsetY, int width, int height) { + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(sourceOffsetY, 0, Height); + Guard.IsInRange(destinationOffsetX, 0, destination.Width); + Guard.IsInRange(destinationOffsetY, 0, destination.Height); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(width, 1, destination.Width); + Guard.IsBetweenOrEqualTo(height, 1, destination.Height); + Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); + Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) using (destination.GetReferenceTracker().GetLease()) @@ -270,19 +283,6 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra destination.ThrowIfDeviceMismatch(GraphicsDevice); - Guard.IsInRange(sourceOffsetX, 0, Width); - Guard.IsInRange(sourceOffsetY, 0, Height); - Guard.IsInRange(destinationOffsetX, 0, destination.Width); - Guard.IsInRange(destinationOffsetY, 0, destination.Height); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(width, 1, destination.Width); - Guard.IsBetweenOrEqualTo(height, 1, destination.Height); - Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); - Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - D3D12_COMMAND_LIST_TYPE d3D12CommandListType = this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE @@ -332,6 +332,19 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// The height of the memory area to copy. internal void CopyTo(ReadBackTexture2D destination, int sourceOffsetX, int sourceOffsetY, int destinationOffsetX, int destinationOffsetY, int width, int height) { + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(sourceOffsetY, 0, Height); + Guard.IsInRange(destinationOffsetX, 0, destination.Width); + Guard.IsInRange(destinationOffsetY, 0, destination.Height); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(width, 1, destination.Width); + Guard.IsBetweenOrEqualTo(height, 1, destination.Height); + Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); + Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) using (destination.GetReferenceTracker().GetLease()) @@ -340,19 +353,6 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra destination.ThrowIfDeviceMismatch(GraphicsDevice); - Guard.IsInRange(sourceOffsetX, 0, Width); - Guard.IsInRange(sourceOffsetY, 0, Height); - Guard.IsInRange(destinationOffsetX, 0, destination.Width); - Guard.IsInRange(destinationOffsetY, 0, destination.Height); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(width, 1, destination.Width); - Guard.IsBetweenOrEqualTo(height, 1, destination.Height); - Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); - Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) @@ -397,19 +397,19 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// The height of the memory area to write to. internal void CopyFrom(ref T source, int size, int destinationOffsetX, int destinationOffsetY, int width, int height) { + Guard.IsInRange(destinationOffsetX, 0, Width); + Guard.IsInRange(destinationOffsetY, 0, Height); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); + Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); + Guard.IsGreaterThanOrEqualTo(size, (nint)width * height); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); - Guard.IsInRange(destinationOffsetX, 0, Width); - Guard.IsInRange(destinationOffsetY, 0, Height); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); - Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); - Guard.IsGreaterThanOrEqualTo(size, (nint)width * height); - GraphicsDevice.D3D12Device->GetCopyableFootprint( DXGIFormatHelper.GetForType(), (uint)width, @@ -486,6 +486,19 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// The height of the memory area to write to. internal void CopyFrom(UploadTexture2D source, int sourceOffsetX, int sourceOffsetY, int destinationOffsetX, int destinationOffsetY, int width, int height) { + Guard.IsInRange(sourceOffsetX, 0, source.Width); + Guard.IsInRange(sourceOffsetY, 0, source.Height); + Guard.IsInRange(destinationOffsetX, 0, Width); + Guard.IsInRange(destinationOffsetY, 0, Height); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(width, 1, source.Width); + Guard.IsBetweenOrEqualTo(height, 1, source.Height); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, source.Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, source.Height, nameof(sourceOffsetY)); + Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); + Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) using (source.GetReferenceTracker().GetLease()) @@ -494,19 +507,6 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra source.ThrowIfDeviceMismatch(GraphicsDevice); - Guard.IsInRange(sourceOffsetX, 0, source.Width); - Guard.IsInRange(sourceOffsetY, 0, source.Height); - Guard.IsInRange(destinationOffsetX, 0, Width); - Guard.IsInRange(destinationOffsetY, 0, Height); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(width, 1, source.Width); - Guard.IsBetweenOrEqualTo(height, 1, source.Height); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, source.Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, source.Height, nameof(sourceOffsetY)); - Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); - Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs index 2b85ba0b..7afe5fe3 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs @@ -73,14 +73,14 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// The format support for the current texture type. private protected Texture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType, AllocationMode allocationMode, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { + Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); + Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); + Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); + using (device.GetReferenceTracker().GetLease()) { device.ThrowIfDeviceLost(); - Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) { UnsupportedTextureTypeException.ThrowForTexture3D(); @@ -183,22 +183,22 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// The depth of the memory area to copy. internal void CopyTo(ref T destination, int size, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int width, int height, int depth) { + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(sourceOffsetY, 0, Height); + Guard.IsInRange(sourceOffsetZ, 0, Depth); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(depth, 1, Depth); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); + Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); + Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); - Guard.IsInRange(sourceOffsetX, 0, Width); - Guard.IsInRange(sourceOffsetY, 0, Height); - Guard.IsInRange(sourceOffsetZ, 0, Depth); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(depth, 1, Depth); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); - Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth); - GraphicsDevice.D3D12Device->GetCopyableFootprint( DXGIFormatHelper.GetForType(), (uint)width, @@ -283,6 +283,25 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// The depth of the memory area to copy. internal void CopyTo(Texture3D destination, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(sourceOffsetY, 0, Height); + Guard.IsInRange(sourceOffsetZ, 0, Depth); + Guard.IsInRange(destinationOffsetX, 0, destination.Width); + Guard.IsInRange(destinationOffsetY, 0, destination.Height); + Guard.IsInRange(destinationOffsetZ, 0, destination.Depth); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(depth, 1, Depth); + Guard.IsBetweenOrEqualTo(width, 1, destination.Width); + Guard.IsBetweenOrEqualTo(height, 1, destination.Height); + Guard.IsBetweenOrEqualTo(depth, 1, destination.Depth); + Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); + Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); + Guard.IsBetweenOrEqualTo(destinationOffsetZ + depth, 1, destination.Depth, nameof(destinationOffsetZ)); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); + Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) using (destination.GetReferenceTracker().GetLease()) @@ -291,25 +310,6 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra destination.ThrowIfDeviceMismatch(GraphicsDevice); - Guard.IsInRange(sourceOffsetX, 0, Width); - Guard.IsInRange(sourceOffsetY, 0, Height); - Guard.IsInRange(sourceOffsetZ, 0, Depth); - Guard.IsInRange(destinationOffsetX, 0, destination.Width); - Guard.IsInRange(destinationOffsetY, 0, destination.Height); - Guard.IsInRange(destinationOffsetZ, 0, destination.Depth); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(depth, 1, Depth); - Guard.IsBetweenOrEqualTo(width, 1, destination.Width); - Guard.IsBetweenOrEqualTo(height, 1, destination.Height); - Guard.IsBetweenOrEqualTo(depth, 1, destination.Depth); - Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); - Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); - Guard.IsBetweenOrEqualTo(destinationOffsetZ + depth, 1, destination.Depth, nameof(destinationOffsetZ)); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); - D3D12_COMMAND_LIST_TYPE d3D12CommandListType = this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE @@ -362,6 +362,25 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// The depth of the memory area to copy. internal void CopyTo(ReadBackTexture3D destination, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(sourceOffsetY, 0, Height); + Guard.IsInRange(sourceOffsetZ, 0, Depth); + Guard.IsInRange(destinationOffsetX, 0, destination.Width); + Guard.IsInRange(destinationOffsetY, 0, destination.Height); + Guard.IsInRange(destinationOffsetZ, 0, destination.Depth); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(depth, 1, Depth); + Guard.IsBetweenOrEqualTo(width, 1, destination.Width); + Guard.IsBetweenOrEqualTo(height, 1, destination.Height); + Guard.IsBetweenOrEqualTo(depth, 1, destination.Depth); + Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); + Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); + Guard.IsBetweenOrEqualTo(destinationOffsetZ + depth, 1, destination.Depth, nameof(destinationOffsetZ)); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); + Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) using (destination.GetReferenceTracker().GetLease()) @@ -370,25 +389,6 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra destination.ThrowIfDeviceMismatch(GraphicsDevice); - Guard.IsInRange(sourceOffsetX, 0, Width); - Guard.IsInRange(sourceOffsetY, 0, Height); - Guard.IsInRange(sourceOffsetZ, 0, Depth); - Guard.IsInRange(destinationOffsetX, 0, destination.Width); - Guard.IsInRange(destinationOffsetY, 0, destination.Height); - Guard.IsInRange(destinationOffsetZ, 0, destination.Depth); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(depth, 1, Depth); - Guard.IsBetweenOrEqualTo(width, 1, destination.Width); - Guard.IsBetweenOrEqualTo(height, 1, destination.Height); - Guard.IsBetweenOrEqualTo(depth, 1, destination.Depth); - Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); - Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); - Guard.IsBetweenOrEqualTo(destinationOffsetZ + depth, 1, destination.Depth, nameof(destinationOffsetZ)); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) @@ -435,22 +435,22 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// The depth of the memory area to write to. internal void CopyFrom(ref T source, int size, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { + Guard.IsInRange(destinationOffsetX, 0, Width); + Guard.IsInRange(destinationOffsetY, 0, Height); + Guard.IsInRange(destinationOffsetZ, 0, Depth); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(depth, 1, Depth); + Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); + Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); + Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); + Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); - Guard.IsInRange(destinationOffsetX, 0, Width); - Guard.IsInRange(destinationOffsetY, 0, Height); - Guard.IsInRange(destinationOffsetZ, 0, Depth); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(depth, 1, Depth); - Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); - Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); - Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); - Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth); - GraphicsDevice.D3D12Device->GetCopyableFootprint( DXGIFormatHelper.GetForType(), (uint)width, @@ -533,6 +533,25 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// The depth of the memory area to write to. internal void CopyFrom(UploadTexture3D source, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { + Guard.IsInRange(sourceOffsetX, 0, source.Width); + Guard.IsInRange(sourceOffsetY, 0, source.Height); + Guard.IsInRange(sourceOffsetZ, 0, source.Depth); + Guard.IsInRange(destinationOffsetX, 0, Width); + Guard.IsInRange(destinationOffsetY, 0, Height); + Guard.IsInRange(destinationOffsetZ, 0, Depth); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(height, 1, Height); + Guard.IsBetweenOrEqualTo(depth, 1, Depth); + Guard.IsBetweenOrEqualTo(width, 1, source.Width); + Guard.IsBetweenOrEqualTo(height, 1, source.Height); + Guard.IsBetweenOrEqualTo(depth, 1, source.Depth); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, source.Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetY + height, source.Height, nameof(sourceOffsetY)); + Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, source.Depth, nameof(sourceOffsetZ)); + Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); + Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); + Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) using (source.GetReferenceTracker().GetLease()) @@ -541,25 +560,6 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra source.ThrowIfDeviceMismatch(GraphicsDevice); - Guard.IsInRange(sourceOffsetX, 0, source.Width); - Guard.IsInRange(sourceOffsetY, 0, source.Height); - Guard.IsInRange(sourceOffsetZ, 0, source.Depth); - Guard.IsInRange(destinationOffsetX, 0, Width); - Guard.IsInRange(destinationOffsetY, 0, Height); - Guard.IsInRange(destinationOffsetZ, 0, Depth); - Guard.IsBetweenOrEqualTo(width, 1, Width); - Guard.IsBetweenOrEqualTo(height, 1, Height); - Guard.IsBetweenOrEqualTo(depth, 1, Depth); - Guard.IsBetweenOrEqualTo(width, 1, source.Width); - Guard.IsBetweenOrEqualTo(height, 1, source.Height); - Guard.IsBetweenOrEqualTo(depth, 1, source.Depth); - Guard.IsLessThanOrEqualTo(sourceOffsetX + width, source.Width, nameof(sourceOffsetX)); - Guard.IsLessThanOrEqualTo(sourceOffsetY + height, source.Height, nameof(sourceOffsetY)); - Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, source.Depth, nameof(sourceOffsetZ)); - Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); - Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); - Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs index ca7397b2..53f03fcb 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs @@ -44,13 +44,13 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource /// The allocation mode to use for the new resource. private protected TransferBuffer(GraphicsDevice device, int length, ResourceType resourceType, AllocationMode allocationMode) { + // The maximum length is set such that the aligned buffer size can't exceed uint.MaxValue + Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / (uint)sizeof(T)) & ~255); + using (device.GetReferenceTracker().GetLease()) { device.ThrowIfDeviceLost(); - // The maximum length is set such that the aligned buffer size can't exceed uint.MaxValue - Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / (uint)sizeof(T)) & ~255); - GraphicsDevice = device; Length = length; diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs index 783b6146..4cf69cb3 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs @@ -50,13 +50,13 @@ public unsafe abstract class TransferTexture2D : NativeObject, IGraphicsResou /// The allocation mode to use for the new resource. private protected TransferTexture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, AllocationMode allocationMode) { + Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + using (device.GetReferenceTracker().GetLease()) { device.ThrowIfDeviceLost(); - Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D)) { UnsupportedTextureTypeException.ThrowForTexture2D(); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs index 29243629..149c53f9 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs @@ -51,14 +51,14 @@ public unsafe abstract class TransferTexture3D : NativeObject, IGraphicsResou /// The allocation mode to use for the new resource. private protected TransferTexture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType, AllocationMode allocationMode) { + Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); + Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); + Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); + using (device.GetReferenceTracker().GetLease()) { device.ThrowIfDeviceLost(); - Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D)) { UnsupportedTextureTypeException.ThrowForTexture3D(); diff --git a/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs index 2958f74e..fcd3b810 100644 --- a/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs @@ -57,15 +57,15 @@ public sealed class ConstantBuffer : Buffer /// internal override unsafe void CopyTo(ref T destination, int offset, int length) { + Guard.IsBetweenOrEqualTo(length, 0, Length); + Guard.IsInRange(offset, 0, Length); + Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); - Guard.IsBetweenOrEqualTo(length, 0, Length); - Guard.IsInRange(offset, 0, Length); - Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); - using ID3D12ResourceMap resource = D3D12Resource->Map(); fixed (void* destinationPointer = &destination) @@ -85,6 +85,13 @@ public sealed class ConstantBuffer : Buffer /// internal override unsafe void CopyTo(Buffer destination, int sourceOffset, int destinationOffset, int length) { + Guard.IsBetweenOrEqualTo(length, 0, Length); + Guard.IsBetweenOrEqualTo(length, 0, destination.Length); + Guard.IsInRange(sourceOffset, 0, Length); + Guard.IsLessThanOrEqualTo(sourceOffset + length, Length, nameof(sourceOffset)); + Guard.IsInRange(destinationOffset, 0, destination.Length); + Guard.IsLessThanOrEqualTo(destinationOffset + length, destination.Length, nameof(destinationOffset)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) using (destination.GetReferenceTracker().GetLease()) @@ -93,13 +100,6 @@ public sealed class ConstantBuffer : Buffer destination.ThrowIfDeviceMismatch(GraphicsDevice); - Guard.IsBetweenOrEqualTo(length, 0, Length); - Guard.IsBetweenOrEqualTo(length, 0, destination.Length); - Guard.IsInRange(sourceOffset, 0, Length); - Guard.IsLessThanOrEqualTo(sourceOffset + length, Length, nameof(sourceOffset)); - Guard.IsInRange(destinationOffset, 0, destination.Length); - Guard.IsLessThanOrEqualTo(destinationOffset + length, destination.Length, nameof(destinationOffset)); - if (destination is ConstantBuffer buffer) { using ID3D12ResourceMap sourceMap = D3D12Resource->Map(); @@ -121,15 +121,15 @@ public sealed class ConstantBuffer : Buffer /// internal override unsafe void CopyFrom(ref T source, int offset, int length) { + Guard.IsBetweenOrEqualTo(length, 0, Length); + Guard.IsInRange(offset, 0, Length); + Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); + using (GraphicsDevice.GetReferenceTracker().GetLease()) using (GetReferenceTracker().GetLease()) { GraphicsDevice.ThrowIfDeviceLost(); - Guard.IsBetweenOrEqualTo(length, 0, Length); - Guard.IsInRange(offset, 0, Length); - Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); - using ID3D12ResourceMap resource = D3D12Resource->Map(); fixed (void* sourcePointer = &source) From 65fe7f53c603626afc0cdf69d6bc180f34658eac Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 24 Jul 2022 15:56:50 +0200 Subject: [PATCH 32/64] Switch all GetLease() calls to using declarations --- .../Helpers/SwapChainManager.Rendering.cs | 57 +- .../GraphicsDeviceExtensions.Dispatching.cs | 9 +- .../Graphics/GraphicsDevice.DeviceLost.cs | 43 +- src/ComputeSharp/Graphics/GraphicsDevice.cs | 55 +- .../__Internals/GraphicsResourceHelper.cs | 55 +- .../Graphics/Resources/Abstract/Buffer{T}.cs | 99 ++- .../Resources/Abstract/StructuredBuffer{T}.cs | 367 ++++++----- .../Resources/Abstract/Texture2D{T}.cs | 592 +++++++++-------- .../Resources/Abstract/Texture3D{T}.cs | 610 +++++++++--------- .../Resources/Abstract/TransferBuffer{T}.cs | 48 +- .../Abstract/TransferTexture2D{T}.cs | 50 +- .../Abstract/TransferTexture3D{T}.cs | 52 +- .../Graphics/Resources/ConstantBuffer{T}.cs | 107 ++- .../ReadWriteTexture2D{T,TPixel}.ReadOnly.cs | 61 +- .../ReadWriteTexture2D{T}.ReadOnly.cs | 67 +- .../ReadWriteTexture3D{T,TPixel}.ReadOnly.cs | 61 +- .../ReadWriteTexture3D{T}.ReadOnly.cs | 61 +- 17 files changed, 1165 insertions(+), 1229 deletions(-) diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs index 99c5edf2..261236b1 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -29,7 +29,8 @@ partial class SwapChainManager { Guard.IsNotNull(shaderRunner); - using (GetReferenceTracker().GetLease()) + using var _0 = GetReferenceTracker().GetLease(); + using (await this.setupSemaphore.LockAsync()) { this.renderCancellationTokenSource?.Cancel(); @@ -54,7 +55,8 @@ partial class SwapChainManager /// public async void StopRenderLoop() { - using (GetReferenceTracker().GetLease()) + using var _0 = GetReferenceTracker().GetLease(); + using (await this.setupSemaphore.LockAsync()) { this.renderCancellationTokenSource?.Cancel(); @@ -67,7 +69,8 @@ partial class SwapChainManager /// Whether or not to use dynamic resolution. public async void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled) { - using (GetReferenceTracker().GetLease()) + using var _0 = GetReferenceTracker().GetLease(); + using (await this.setupSemaphore.LockAsync()) { // If there is a render thread currently running, stop it and restart it @@ -100,7 +103,8 @@ partial class SwapChainManager /// Whether or not to use vertical sync. public async void QueueVerticalSyncModeChange(bool isVerticalSyncEnabled) { - using (GetReferenceTracker().GetLease()) + using var _0 = GetReferenceTracker().GetLease(); + using (await this.setupSemaphore.LockAsync()) { // The v-sync option can be toggled on the fly when not using dynamic resolution @@ -134,13 +138,12 @@ partial class SwapChainManager /// The height of the render resolution. public void QueueResize(double width, double height) { - using (GetReferenceTracker().GetLease()) - { - this.width = (float)width; - this.height = (float)height; + using var _0 = GetReferenceTracker().GetLease(); - this.isResizePending = true; - } + this.width = (float)width; + this.height = (float)height; + + this.isResizePending = true; } /// @@ -150,13 +153,12 @@ partial class SwapChainManager /// The composition scale on the Y axis public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY) { - using (GetReferenceTracker().GetLease()) - { - this.compositionScaleX = (float)compositionScaleX; - this.compositionScaleY = (float)compositionScaleY; + using var _0 = GetReferenceTracker().GetLease(); - this.isResizePending = true; - } + this.compositionScaleX = (float)compositionScaleX; + this.compositionScaleY = (float)compositionScaleY; + + this.isResizePending = true; } /// @@ -165,12 +167,11 @@ partial class SwapChainManager /// The resolution scale factor to use. public void QueueResolutionScaleChange(double resolutionScale) { - using (GetReferenceTracker().GetLease()) - { - this.resolutionScale = (float)resolutionScale; + using var _0 = GetReferenceTracker().GetLease(); - this.isResizePending = true; - } + this.resolutionScale = (float)resolutionScale; + + this.isResizePending = true; } /// @@ -187,17 +188,15 @@ partial class SwapChainManager this.dynamicResolutionScale = this.resolutionScale; // These two leases are needed to ensure the manager isn't disposed while rendering is running - using (GetReferenceTracker().GetLease()) - { - RenderLoopWithDynamicResolution(); - } + using var _0 = GetReferenceTracker().GetLease(); + + RenderLoopWithDynamicResolution(); } else { - using (GetReferenceTracker().GetLease()) - { - RenderLoop(); - } + using var _0 = GetReferenceTracker().GetLease(); + + RenderLoop(); } this.renderStopwatch?.Stop(); diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs index afdae583..658d4da4 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs @@ -150,11 +150,10 @@ public static partial class GraphicsDeviceExtensions { Guard.IsNotNull(device); - using (device.GetReferenceTracker().GetLease()) - { - device.ThrowIfDeviceLost(); + using var _0 = device.GetReferenceTracker().GetLease(); - return new(device); - } + device.ThrowIfDeviceLost(); + + return new(device); } } diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index b44272ba..beeb283e 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -48,32 +48,31 @@ unsafe partial class GraphicsDevice /// private void QueueRaiseDeviceLostEventIfNeeded() { - using (GetReferenceTracker().TryGetLease(out bool leaseTaken)) + using var _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); + + if (!leaseTaken) { - if (!leaseTaken) - { - return; - } + return; + } - // If the current device removed reason is not S_OK, it means the event - // has already been raised (but the device will keep reporting that reason). - // In that case, do nothing to avoid raising it again while the device is alive. - if (Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason)) != S.S_OK) - { - return; - } + // If the current device removed reason is not S_OK, it means the event + // has already been raised (but the device will keep reporting that reason). + // In that case, do nothing to avoid raising it again while the device is alive. + if (Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason)) != S.S_OK) + { + return; + } - HRESULT result = this.d3D12Device.Get()->GetDeviceRemovedReason(); + HRESULT result = this.d3D12Device.Get()->GetDeviceRemovedReason(); - // Only raise the event once, and store the device removed reason to track it - if (result != S.S_OK && - Interlocked.CompareExchange( - ref Unsafe.As(ref this.deviceRemovedReason), - (int)result, - S.S_OK) == S.S_OK) - { - QueueRaiseDeviceLostEvent(); - } + // Only raise the event once, and store the device removed reason to track it + if (result != S.S_OK && + Interlocked.CompareExchange( + ref Unsafe.As(ref this.deviceRemovedReason), + (int)result, + S.S_OK) == S.S_OK) + { + QueueRaiseDeviceLostEvent(); } } diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 1e5bf383..a516d4a0 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -238,14 +238,13 @@ public sealed unsafe partial class GraphicsDevice : NativeObject /// Whether the current device supports double precision floating point operations in shaders. public bool IsDoublePrecisionSupportAvailable() { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceLost(); + using var _0 = GetReferenceTracker().GetLease(); - var d3D12OptionsData = this.d3D12Device.Get()->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS); + ThrowIfDeviceLost(); - return d3D12OptionsData.DoublePrecisionFloatShaderOps; - } + var d3D12OptionsData = this.d3D12Device.Get()->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS); + + return d3D12OptionsData.DoublePrecisionFloatShaderOps; } /// @@ -257,12 +256,11 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadOnlyTexture2DSupportedForType() where T : unmanaged { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceLost(); + using var _0 = GetReferenceTracker().GetLease(); - return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D); - } + ThrowIfDeviceLost(); + + return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D); } /// @@ -274,14 +272,13 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadWriteTexture2DSupportedForType() where T : unmanaged { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceLost(); + using var _0 = GetReferenceTracker().GetLease(); - return this.d3D12Device.Get()->IsDxgiFormatSupported( - DXGIFormatHelper.GetForType(), - D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); - } + ThrowIfDeviceLost(); + + return this.d3D12Device.Get()->IsDxgiFormatSupported( + DXGIFormatHelper.GetForType(), + D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); } /// @@ -293,12 +290,11 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadOnlyTexture3DSupportedForType() where T : unmanaged { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceLost(); + using var _0 = GetReferenceTracker().GetLease(); - return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D); - } + ThrowIfDeviceLost(); + + return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D); } /// @@ -310,14 +306,13 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadWriteTexture3DSupportedForType() where T : unmanaged { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceLost(); + using var _0 = GetReferenceTracker().GetLease(); - return this.d3D12Device.Get()->IsDxgiFormatSupported( - DXGIFormatHelper.GetForType(), - D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); - } + ThrowIfDeviceLost(); + + return this.d3D12Device.Get()->IsDxgiFormatSupported( + DXGIFormatHelper.GetForType(), + D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); } /// diff --git a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index 29317385..a326435a 100644 --- a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -64,14 +64,13 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(buffer); - using (buffer.GetReferenceTracker().GetLease()) - { - buffer.ThrowIfDeviceMismatch(device); + using var _0 = buffer.GetReferenceTracker().GetLease(); - D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = buffer.D3D12GpuDescriptorHandle; + buffer.ThrowIfDeviceMismatch(device); - return *(ulong*)&d3D12GpuDescriptorHandle; - } + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = buffer.D3D12GpuDescriptorHandle; + + return *(ulong*)&d3D12GpuDescriptorHandle; } /// @@ -87,14 +86,13 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - using (texture.GetReferenceTracker().GetLease()) - { - texture.ThrowIfDeviceMismatch(device); + using var _0 = texture.GetReferenceTracker().GetLease(); - D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + texture.ThrowIfDeviceMismatch(device); - return *(ulong*)&d3D12GpuDescriptorHandle; - } + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + + return *(ulong*)&d3D12GpuDescriptorHandle; } /// @@ -110,14 +108,13 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - using (texture.GetReferenceTracker().GetLease()) - { - texture.ThrowIfDeviceMismatch(device); + using var _0 = texture.GetReferenceTracker().GetLease(); - D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + texture.ThrowIfDeviceMismatch(device); - return *(ulong*)&d3D12GpuDescriptorHandle; - } + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + + return *(ulong*)&d3D12GpuDescriptorHandle; } /// @@ -202,14 +199,13 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - using (texture.GetReferenceTracker().GetLease()) - { - texture.ThrowIfDeviceMismatch(device); + using var _0 = texture.GetReferenceTracker().GetLease(); - D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + texture.ThrowIfDeviceMismatch(device); - return *(ulong*)&d3D12GpuDescriptorHandle; - } + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + + return *(ulong*)&d3D12GpuDescriptorHandle; } /// @@ -225,14 +221,13 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - using (texture.GetReferenceTracker().GetLease()) - { - texture.ThrowIfDeviceMismatch(device); + using var _0 = texture.GetReferenceTracker().GetLease(); - D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + texture.ThrowIfDeviceMismatch(device); - return *(ulong*)&d3D12GpuDescriptorHandle; - } + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + + return *(ulong*)&d3D12GpuDescriptorHandle; } /// diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs index 0a1f4745..69b53980 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs @@ -75,55 +75,54 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / elementSizeInBytes) & ~255); } - using (device.GetReferenceTracker().GetLease()) + using var _0 = device.GetReferenceTracker().GetLease(); + + device.ThrowIfDeviceLost(); + + if (TypeInfo.IsDoubleOrContainsDoubles && + device.D3D12Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS).DoublePrecisionFloatShaderOps == 0) { - device.ThrowIfDeviceLost(); + UnsupportedDoubleOperationException.Throw(); + } - if (TypeInfo.IsDoubleOrContainsDoubles && - device.D3D12Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS).DoublePrecisionFloatShaderOps == 0) - { - UnsupportedDoubleOperationException.Throw(); - } + nint usableSizeInBytes = checked((nint)(length * elementSizeInBytes)); + nint effectiveSizeInBytes = resourceType == ResourceType.Constant ? AlignmentHelper.Pad(usableSizeInBytes, D3D12.D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT) : usableSizeInBytes; - nint usableSizeInBytes = checked((nint)(length * elementSizeInBytes)); - nint effectiveSizeInBytes = resourceType == ResourceType.Constant ? AlignmentHelper.Pad(usableSizeInBytes, D3D12.D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT) : usableSizeInBytes; - - SizeInBytes = usableSizeInBytes; - GraphicsDevice = device; - Length = length; + SizeInBytes = usableSizeInBytes; + GraphicsDevice = device; + Length = length; #if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, (ulong)effectiveSizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); + this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, (ulong)effectiveSizeInBytes); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); #else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, (ulong)effectiveSizeInBytes, device.IsCacheCoherentUMA); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, (ulong)effectiveSizeInBytes, device.IsCacheCoherentUMA); #endif - device.RegisterAllocatedResource(); - device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); - device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView); + device.RegisterAllocatedResource(); + device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView); - switch (resourceType) - { - case ResourceType.Constant: - device.D3D12Device->CreateConstantBufferView(this.d3D12Resource.Get(), effectiveSizeInBytes, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - break; - case ResourceType.ReadOnly: - device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), (uint)length, elementSizeInBytes, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - break; - case ResourceType.ReadWrite: - device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), (uint)length, elementSizeInBytes, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - device.D3D12Device->CreateUnorderedAccessViewForClear( - this.d3D12Resource.Get(), - DXGI_FORMAT_R32_UINT, - (uint)(usableSizeInBytes / sizeof(uint)), - this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12CpuDescriptorHandle, - this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12CpuDescriptorHandleNonShaderVisible); - break; - } - - this.d3D12Resource.Get()->SetName(this); + switch (resourceType) + { + case ResourceType.Constant: + device.D3D12Device->CreateConstantBufferView(this.d3D12Resource.Get(), effectiveSizeInBytes, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + break; + case ResourceType.ReadOnly: + device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), (uint)length, elementSizeInBytes, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + break; + case ResourceType.ReadWrite: + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), (uint)length, elementSizeInBytes, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + device.D3D12Device->CreateUnorderedAccessViewForClear( + this.d3D12Resource.Get(), + DXGI_FORMAT_R32_UINT, + (uint)(usableSizeInBytes / sizeof(uint)), + this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12CpuDescriptorHandle, + this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12CpuDescriptorHandleNonShaderVisible); + break; } + + this.d3D12Resource.Get()->SetName(this); } /// @@ -234,24 +233,22 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); - return ( - this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12GpuDescriptorHandle, - this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12CpuDescriptorHandleNonShaderVisible); - } + ThrowIfDeviceMismatch(device); + + return ( + this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12GpuDescriptorHandle, + this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView.D3D12CpuDescriptorHandleNonShaderVisible); } /// internal unsafe ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); - return D3D12Resource; - } + ThrowIfDeviceMismatch(device); + + return D3D12Resource; } } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs index 1a49abdb..a5b88ddc 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs @@ -36,68 +36,67 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(sourceOffset, 0, Length); Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + if (GraphicsDevice.IsCacheCoherentUMA) { - GraphicsDevice.ThrowIfDeviceLost(); + using ID3D12ResourceMap resource = D3D12Resource->Map(); - if (GraphicsDevice.IsCacheCoherentUMA) + fixed (void* destinationPointer = &destination) { - using ID3D12ResourceMap resource = D3D12Resource->Map(); - - fixed (void* destinationPointer = &destination) - { - MemoryHelper.Copy( - source: resource.Pointer, - destination: destinationPointer, - sourceElementOffset: (uint)sourceOffset, - destinationElementOffset: 0, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)count); - } + MemoryHelper.Copy( + source: resource.Pointer, + destination: destinationPointer, + sourceElementOffset: (uint)sourceOffset, + destinationElementOffset: 0, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)count); } - else + } + else + { + nint byteOffset = (nint)sourceOffset * sizeof(T); + nint byteLength = count * sizeof(T); + +#if NET6_0_OR_GREATER + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource(null, ResourceType.ReadBack, AllocationMode.Default, (ulong)byteLength); +#else + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.ReadBack, + (ulong)byteLength, + GraphicsDevice.IsCacheCoherentUMA); +#endif + + using (CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY)) { - nint byteOffset = (nint)sourceOffset * sizeof(T); - nint byteLength = count * sizeof(T); +#if NET6_0_OR_GREATER + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(allocation.Get()->GetResource(), 0, D3D12Resource, (ulong)byteOffset, (ulong)byteLength); +#else + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(d3D12Resource.Get(), 0, D3D12Resource, (ulong)byteOffset, (ulong)byteLength); +#endif + copyCommandList.ExecuteAndWaitForCompletion(); + } #if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource(null, ResourceType.ReadBack, AllocationMode.Default, (ulong)byteLength); + using ID3D12ResourceMap resource = allocation.Get()->GetResource()->Map(); #else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.ReadBack, - (ulong)byteLength, - GraphicsDevice.IsCacheCoherentUMA); + using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); #endif - using (CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY)) - { -#if NET6_0_OR_GREATER - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(allocation.Get()->GetResource(), 0, D3D12Resource, (ulong)byteOffset, (ulong)byteLength); -#else - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(d3D12Resource.Get(), 0, D3D12Resource, (ulong)byteOffset, (ulong)byteLength); -#endif - copyCommandList.ExecuteAndWaitForCompletion(); - } - -#if NET6_0_OR_GREATER - using ID3D12ResourceMap resource = allocation.Get()->GetResource()->Map(); -#else - using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); -#endif - - fixed (void* destinationPointer = &destination) - { - MemoryHelper.Copy( - source: resource.Pointer, - destination: destinationPointer, - sourceElementOffset: 0, - destinationElementOffset: 0, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)count); - } + fixed (void* destinationPointer = &destination) + { + MemoryHelper.Copy( + source: resource.Pointer, + destination: destinationPointer, + sourceElementOffset: 0, + destinationElementOffset: 0, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)count); } } } @@ -112,34 +111,33 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(destinationOffset, 0, destination.Length); Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - using (destination.GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + using var _2 = destination.GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + + if (!destination.IsPaddingPresent) { - GraphicsDevice.ThrowIfDeviceLost(); + nint sourceByteOffset = (nint)sourceOffset * sizeof(T); + nint destinationByteOffset = (nint)destinationOffset * sizeof(T); + nint byteLength = count * sizeof(T); - destination.ThrowIfDeviceMismatch(GraphicsDevice); + // Directly copy the input buffer + using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - if (!destination.IsPaddingPresent) - { - nint sourceByteOffset = (nint)sourceOffset * sizeof(T); - nint destinationByteOffset = (nint)destinationOffset * sizeof(T); - nint byteLength = count * sizeof(T); + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion( + destination.D3D12Resource, + (ulong)destinationByteOffset, + D3D12Resource, + (ulong)sourceByteOffset, + (ulong)byteLength); - // Directly copy the input buffer - using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion( - destination.D3D12Resource, - (ulong)destinationByteOffset, - D3D12Resource, - (ulong)sourceByteOffset, - (ulong)byteLength); - - copyCommandList.ExecuteAndWaitForCompletion(); - } - else CopyToWithCpuBuffer(destination, sourceOffset, destinationOffset, count); + copyCommandList.ExecuteAndWaitForCompletion(); } + else CopyToWithCpuBuffer(destination, sourceOffset, destinationOffset, count); } /// @@ -158,38 +156,37 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(destinationOffset, 0, destination.Length); Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - using (destination.GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + using var _2 = destination.GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + + if (GraphicsDevice.IsCacheCoherentUMA) { - GraphicsDevice.ThrowIfDeviceLost(); + using ID3D12ResourceMap resource = D3D12Resource->Map(); - destination.ThrowIfDeviceMismatch(GraphicsDevice); + MemoryHelper.Copy( + source: resource.Pointer, + destination: destination.MappedData, + sourceElementOffset: (uint)sourceOffset, + destinationElementOffset: (uint)destinationOffset, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)count); + } + else + { + ulong byteDestinationOffset = (uint)destinationOffset * (uint)sizeof(T); + ulong byteOffset = (uint)sourceOffset * (uint)sizeof(T); + ulong byteLength = (uint)count * (uint)sizeof(T); - if (GraphicsDevice.IsCacheCoherentUMA) - { - using ID3D12ResourceMap resource = D3D12Resource->Map(); + using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - MemoryHelper.Copy( - source: resource.Pointer, - destination: destination.MappedData, - sourceElementOffset: (uint)sourceOffset, - destinationElementOffset: (uint)destinationOffset, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)count); - } - else - { - ulong byteDestinationOffset = (uint)destinationOffset * (uint)sizeof(T); - ulong byteOffset = (uint)sourceOffset * (uint)sizeof(T); - ulong byteLength = (uint)count * (uint)sizeof(T); - - using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(destination.D3D12Resource, byteDestinationOffset, D3D12Resource, byteOffset, byteLength); - copyCommandList.ExecuteAndWaitForCompletion(); - } + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(destination.D3D12Resource, byteDestinationOffset, D3D12Resource, byteOffset, byteLength); + copyCommandList.ExecuteAndWaitForCompletion(); } } @@ -200,67 +197,66 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(offset, 0, Length); Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + if (GraphicsDevice.IsCacheCoherentUMA) { - GraphicsDevice.ThrowIfDeviceLost(); + using ID3D12ResourceMap resource = D3D12Resource->Map(); - if (GraphicsDevice.IsCacheCoherentUMA) + fixed (void* sourcePointer = &source) { - using ID3D12ResourceMap resource = D3D12Resource->Map(); - - fixed (void* sourcePointer = &source) - { - MemoryHelper.Copy( - source: sourcePointer, - destination: resource.Pointer, - sourceElementOffset: 0, - destinationElementOffset: (uint)offset, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)length); - } + MemoryHelper.Copy( + source: sourcePointer, + destination: resource.Pointer, + sourceElementOffset: 0, + destinationElementOffset: (uint)offset, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)length); } - else + } + else + { + nint byteOffset = (nint)offset * sizeof(T); + nint byteLength = length * sizeof(T); + +#if NET6_0_OR_GREATER + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource(null, ResourceType.Upload, AllocationMode.Default, (ulong)byteLength); +#else + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.Upload, + (ulong)byteLength, + GraphicsDevice.IsCacheCoherentUMA); +#endif + +#if NET6_0_OR_GREATER + using (ID3D12ResourceMap resource = allocation.Get()->GetResource()->Map()) +#else + using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) +#endif + fixed (void* sourcePointer = &source) { - nint byteOffset = (nint)offset * sizeof(T); - nint byteLength = length * sizeof(T); - -#if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource(null, ResourceType.Upload, AllocationMode.Default, (ulong)byteLength); -#else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.Upload, - (ulong)byteLength, - GraphicsDevice.IsCacheCoherentUMA); -#endif - -#if NET6_0_OR_GREATER - using (ID3D12ResourceMap resource = allocation.Get()->GetResource()->Map()) -#else - using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) -#endif - fixed (void* sourcePointer = &source) - { - MemoryHelper.Copy( - source: sourcePointer, - destination: resource.Pointer, - sourceElementOffset: 0, - destinationElementOffset: 0, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)length); - } - - using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - -#if NET6_0_OR_GREATER - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, (ulong)byteOffset, allocation.Get()->GetResource(), 0, (ulong)byteLength); -#else - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, (ulong)byteOffset, d3D12Resource.Get(), 0, (ulong)byteLength); -#endif - copyCommandList.ExecuteAndWaitForCompletion(); + MemoryHelper.Copy( + source: sourcePointer, + destination: resource.Pointer, + sourceElementOffset: 0, + destinationElementOffset: 0, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)length); } + + using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); + +#if NET6_0_OR_GREATER + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, (ulong)byteOffset, allocation.Get()->GetResource(), 0, (ulong)byteLength); +#else + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, (ulong)byteOffset, d3D12Resource.Get(), 0, (ulong)byteLength); +#endif + copyCommandList.ExecuteAndWaitForCompletion(); } } @@ -280,38 +276,37 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(destinationOffset, 0, Length); Guard.IsLessThanOrEqualTo(destinationOffset + count, Length, nameof(destinationOffset)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - using (source.GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + using var _2 = source.GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + source.ThrowIfDeviceMismatch(GraphicsDevice); + + if (GraphicsDevice.IsCacheCoherentUMA) { - GraphicsDevice.ThrowIfDeviceLost(); + using ID3D12ResourceMap resource = D3D12Resource->Map(); - source.ThrowIfDeviceMismatch(GraphicsDevice); + MemoryHelper.Copy( + source: source.MappedData, + destination: resource.Pointer, + sourceElementOffset: (uint)sourceOffset, + destinationElementOffset: (uint)destinationOffset, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)count); + } + else + { + ulong byteSourceOffset = (uint)sourceOffset * (uint)sizeof(T); + ulong byteOffset = (uint)destinationOffset * (uint)sizeof(T); + ulong byteLength = (uint)count * (uint)sizeof(T); - if (GraphicsDevice.IsCacheCoherentUMA) - { - using ID3D12ResourceMap resource = D3D12Resource->Map(); + using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - MemoryHelper.Copy( - source: source.MappedData, - destination: resource.Pointer, - sourceElementOffset: (uint)sourceOffset, - destinationElementOffset: (uint)destinationOffset, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)count); - } - else - { - ulong byteSourceOffset = (uint)sourceOffset * (uint)sizeof(T); - ulong byteOffset = (uint)destinationOffset * (uint)sizeof(T); - ulong byteLength = (uint)count * (uint)sizeof(T); - - using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, byteOffset, source.D3D12Resource, byteSourceOffset, byteLength); - copyCommandList.ExecuteAndWaitForCompletion(); - } + copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, byteOffset, source.D3D12Resource, byteSourceOffset, byteLength); + copyCommandList.ExecuteAndWaitForCompletion(); } } } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs index 4dfd4596..78876122 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs @@ -75,66 +75,65 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - using (device.GetReferenceTracker().GetLease()) + using var _0 = device.GetReferenceTracker().GetLease(); + + device.ThrowIfDeviceLost(); + + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) { - device.ThrowIfDeviceLost(); + UnsupportedTextureTypeException.ThrowForTexture2D(); + } - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) - { - UnsupportedTextureTypeException.ThrowForTexture2D(); - } - - GraphicsDevice = device; + GraphicsDevice = device; #if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource( - device.Pool, - resourceType, - allocationMode, - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - out this.d3D12ResourceState); + this.allocation = device.Allocator->CreateResource( + device.Pool, + resourceType, + allocationMode, + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out this.d3D12ResourceState); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); #else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource( - resourceType, - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - device.IsCacheCoherentUMA, - out this.d3D12ResourceState); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource( + resourceType, + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + device.IsCacheCoherentUMA, + out this.d3D12ResourceState); #endif - this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON - ? D3D12_COMMAND_LIST_TYPE_COPY - : D3D12_COMMAND_LIST_TYPE_COMPUTE; + this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON + ? D3D12_COMMAND_LIST_TYPE_COPY + : D3D12_COMMAND_LIST_TYPE_COMPUTE; - device.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - out this.d3D12PlacedSubresourceFootprint, - out _, - out _); + device.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out this.d3D12PlacedSubresourceFootprint, + out _, + out _); - device.RegisterAllocatedResource(); - device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + device.RegisterAllocatedResource(); + device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); - switch (resourceType) - { - case ResourceType.ReadOnly: - device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - break; - case ResourceType.ReadWrite: - device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); - break; - } - - this.d3D12Resource.Get()->SetName(this); + switch (resourceType) + { + case ResourceType.ReadOnly: + device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + break; + case ResourceType.ReadWrite: + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); + break; } + + this.d3D12Resource.Get()->SetName(this); } /// @@ -179,74 +178,73 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); Guard.IsGreaterThanOrEqualTo(size, (nint)width * height); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - { - GraphicsDevice.ThrowIfDeviceLost(); + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); - GraphicsDevice.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintDestination, - out ulong rowSizeInBytes, - out ulong totalSizeInBytes); + GraphicsDevice.ThrowIfDeviceLost(); + + GraphicsDevice.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintDestination, + out ulong rowSizeInBytes, + out ulong totalSizeInBytes); #if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, - ResourceType.ReadBack, - AllocationMode.Default, - totalSizeInBytes); + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( + GraphicsDevice.Pool, + ResourceType.ReadBack, + AllocationMode.Default, + totalSizeInBytes); - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); + using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); #else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.ReadBack, - totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.ReadBack, + totalSizeInBytes, + GraphicsDevice.IsCacheCoherentUMA); #endif - using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) + using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) + { + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - } - - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: d3D12Resource.Get(), - &d3D12PlacedSubresourceFootprintDestination, - destinationX: 0, - destinationY: 0, - destinationZ: 0, - d3D12ResourceSource: D3D12Resource, - sourceX: (uint)sourceOffsetX, - sourceY: (uint)sourceOffsetY, - sourceZ: 0, - (uint)width, - (uint)height, - depth: 1); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); } - using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: d3D12Resource.Get(), + &d3D12PlacedSubresourceFootprintDestination, + destinationX: 0, + destinationY: 0, + destinationZ: 0, + d3D12ResourceSource: D3D12Resource, + sourceX: (uint)sourceOffsetX, + sourceY: (uint)sourceOffsetY, + sourceZ: 0, + (uint)width, + (uint)height, + depth: 1); - fixed (void* destinationPointer = &destination) + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - MemoryHelper.Copy( - resource.Pointer, - (uint)height, - rowSizeInBytes, - d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch, - destinationPointer); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); } + + copyCommandList.ExecuteAndWaitForCompletion(); + } + + using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); + + fixed (void* destinationPointer = &destination) + { + MemoryHelper.Copy( + resource.Pointer, + (uint)height, + rowSizeInBytes, + d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch, + destinationPointer); } } @@ -275,49 +273,48 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - using (destination.GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + using var _2 = destination.GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + + D3D12_COMMAND_LIST_TYPE d3D12CommandListType = + this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || + destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE + ? D3D12_COMMAND_LIST_TYPE_COMPUTE + : D3D12_COMMAND_LIST_TYPE_COPY; + + using CommandList copyCommandList = new(GraphicsDevice, d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - GraphicsDevice.ThrowIfDeviceLost(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - - D3D12_COMMAND_LIST_TYPE d3D12CommandListType = - this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || - destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE - ? D3D12_COMMAND_LIST_TYPE_COMPUTE - : D3D12_COMMAND_LIST_TYPE_COPY; - - using CommandList copyCommandList = new(GraphicsDevice, d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); - } - - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: destination.D3D12Resource, - (uint)destinationOffsetX, - (uint)destinationOffsetY, - destinationZ: 0, - d3D12ResourceSource: D3D12Resource, - (uint)sourceOffsetX, - (uint)sourceOffsetY, - sourceZ: 0, - (uint)width, - (uint)height, - 1); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: destination.D3D12Resource, + (uint)destinationOffsetX, + (uint)destinationOffsetY, + destinationZ: 0, + d3D12ResourceSource: D3D12Resource, + (uint)sourceOffsetX, + (uint)sourceOffsetY, + sourceZ: 0, + (uint)width, + (uint)height, + 1); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } /// @@ -345,45 +342,44 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - using (destination.GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + using var _2 = destination.GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - GraphicsDevice.ThrowIfDeviceLost(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - } - - fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintDestination = &destination.D3D12PlacedSubresourceFootprint) - { - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: destination.D3D12Resource, - d3D12PlacedSubresourceFootprintDestination, - (uint)destinationOffsetX, - (uint)destinationOffsetY, - destinationZ: 0, - d3D12ResourceSource: D3D12Resource, - (uint)sourceOffsetX, - (uint)sourceOffsetY, - sourceZ: 0, - (uint)width, - (uint)height, - 1); - } - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); } + + fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintDestination = &destination.D3D12PlacedSubresourceFootprint) + { + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: destination.D3D12Resource, + d3D12PlacedSubresourceFootprintDestination, + (uint)destinationOffsetX, + (uint)destinationOffsetY, + destinationZ: 0, + d3D12ResourceSource: D3D12Resource, + (uint)sourceOffsetX, + (uint)sourceOffsetY, + sourceZ: 0, + (uint)width, + (uint)height, + 1); + } + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } /// @@ -405,73 +401,72 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); Guard.IsGreaterThanOrEqualTo(size, (nint)width * height); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - { - GraphicsDevice.ThrowIfDeviceLost(); + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); - GraphicsDevice.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintSource, - out ulong rowSizeInBytes, - out ulong totalSizeInBytes); + GraphicsDevice.ThrowIfDeviceLost(); + + GraphicsDevice.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintSource, + out ulong rowSizeInBytes, + out ulong totalSizeInBytes); #if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, - ResourceType.Upload, - AllocationMode.Default, - totalSizeInBytes); + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( + GraphicsDevice.Pool, + ResourceType.Upload, + AllocationMode.Default, + totalSizeInBytes); - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); + using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); #else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.Upload, - totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.Upload, + totalSizeInBytes, + GraphicsDevice.IsCacheCoherentUMA); #endif - using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) - fixed (void* sourcePointer = &source) - { - MemoryHelper.Copy( - sourcePointer, - resource.Pointer, - (uint)height, - rowSizeInBytes, - d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch); - } - - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); - } - - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: D3D12Resource, - destinationX: (uint)destinationOffsetX, - destinationY: (uint)destinationOffsetY, - destinationZ: 0, - d3D12ResourceSource: d3D12Resource.Get(), - &d3D12PlacedSubresourceFootprintSource, - sourceX: 0, - sourceY: 0, - sourceZ: 0, - (uint)width, + using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) + fixed (void* sourcePointer = &source) + { + MemoryHelper.Copy( + sourcePointer, + resource.Pointer, (uint)height, - depth: 1); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); + rowSizeInBytes, + d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch); } + + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: D3D12Resource, + destinationX: (uint)destinationOffsetX, + destinationY: (uint)destinationOffsetY, + destinationZ: 0, + d3D12ResourceSource: d3D12Resource.Get(), + &d3D12PlacedSubresourceFootprintSource, + sourceX: 0, + sourceY: 0, + sourceZ: 0, + (uint)width, + (uint)height, + depth: 1); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } /// @@ -499,45 +494,44 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - using (source.GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + using var _2 = source.GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + source.ThrowIfDeviceMismatch(GraphicsDevice); + + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - GraphicsDevice.ThrowIfDeviceLost(); - - source.ThrowIfDeviceMismatch(GraphicsDevice); - - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); - } - - fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintSource = &source.D3D12PlacedSubresourceFootprint) - { - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: D3D12Resource, - (uint)destinationOffsetX, - (uint)destinationOffsetY, - destinationZ: 0, - d3D12ResourceSource: source.D3D12Resource, - d3D12PlacedSubresourceFootprintSource, - (uint)sourceOffsetX, - (uint)sourceOffsetY, - sourceZ: 0, - (uint)width, - (uint)height, - depth: 1); - } - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } + + fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintSource = &source.D3D12PlacedSubresourceFootprint) + { + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: D3D12Resource, + (uint)destinationOffsetX, + (uint)destinationOffsetY, + destinationZ: 0, + d3D12ResourceSource: source.D3D12Resource, + d3D12PlacedSubresourceFootprintSource, + (uint)sourceOffsetX, + (uint)sourceOffsetY, + sourceZ: 0, + (uint)width, + (uint)height, + depth: 1); + } + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } /// @@ -589,54 +583,50 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); - isNormalized = DXGIFormatHelper.IsNormalizedType(); + ThrowIfDeviceMismatch(device); - return (this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); - } + isNormalized = DXGIFormatHelper.IsNormalizedType(); + + return (this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); } /// internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); - return D3D12Resource; - } + ThrowIfDeviceMismatch(device); + + return D3D12Resource; } /// internal (D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource) { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); - D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState; - D3D12_RESOURCE_STATES d3D12ResourceStatesAfter = ResourceStateHelper.GetD3D12ResourceStates(resourceState); + ThrowIfDeviceMismatch(device); - this.d3D12ResourceState = d3D12ResourceStatesAfter; + D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState; + D3D12_RESOURCE_STATES d3D12ResourceStatesAfter = ResourceStateHelper.GetD3D12ResourceStates(resourceState); - d3D12Resource = D3D12Resource; + this.d3D12ResourceState = d3D12ResourceStatesAfter; - return (d3D12ResourceStatesBefore, d3D12ResourceStatesAfter); - } + d3D12Resource = D3D12Resource; + + return (d3D12ResourceStatesBefore, d3D12ResourceStatesAfter); } /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); - return D3D12GpuDescriptorHandle; - } + ThrowIfDeviceMismatch(device); + + return D3D12GpuDescriptorHandle; } /// diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs index 7afe5fe3..090b3212 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs @@ -77,69 +77,68 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - using (device.GetReferenceTracker().GetLease()) + using var _0 = device.GetReferenceTracker().GetLease(); + + device.ThrowIfDeviceLost(); + + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) { - device.ThrowIfDeviceLost(); + UnsupportedTextureTypeException.ThrowForTexture3D(); + } - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) - { - UnsupportedTextureTypeException.ThrowForTexture3D(); - } - - GraphicsDevice = device; + GraphicsDevice = device; #if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource( - device.Pool, - resourceType, - allocationMode, - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - out this.d3D12ResourceState); + this.allocation = device.Allocator->CreateResource( + device.Pool, + resourceType, + allocationMode, + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + (ushort)depth, + out this.d3D12ResourceState); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); #else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource( - resourceType, - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - device.IsCacheCoherentUMA, - out this.d3D12ResourceState); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource( + resourceType, + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + (ushort)depth, + device.IsCacheCoherentUMA, + out this.d3D12ResourceState); #endif - this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON - ? D3D12_COMMAND_LIST_TYPE_COPY - : D3D12_COMMAND_LIST_TYPE_COMPUTE; + this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON + ? D3D12_COMMAND_LIST_TYPE_COPY + : D3D12_COMMAND_LIST_TYPE_COMPUTE; - device.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - out this.d3D12PlacedSubresourceFootprint, - out _, - out _); + device.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + (ushort)depth, + out this.d3D12PlacedSubresourceFootprint, + out _, + out _); - device.RegisterAllocatedResource(); - device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + device.RegisterAllocatedResource(); + device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); - switch (resourceType) - { - case ResourceType.ReadOnly: - device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - break; - case ResourceType.ReadWrite: - device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); - device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); - break; - } - - this.d3D12Resource.Get()->SetName(this); + switch (resourceType) + { + case ResourceType.ReadOnly: + device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + break; + case ResourceType.ReadWrite: + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); + break; } + + this.d3D12Resource.Get()->SetName(this); } /// @@ -194,77 +193,76 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - { - GraphicsDevice.ThrowIfDeviceLost(); + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); - GraphicsDevice.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintDestination, - out ulong rowSizeInBytes, - out ulong totalSizeInBytes); + GraphicsDevice.ThrowIfDeviceLost(); + + GraphicsDevice.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + (ushort)depth, + out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintDestination, + out ulong rowSizeInBytes, + out ulong totalSizeInBytes); #if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, - ResourceType.ReadBack, - AllocationMode.Default, - totalSizeInBytes); + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( + GraphicsDevice.Pool, + ResourceType.ReadBack, + AllocationMode.Default, + totalSizeInBytes); - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); + using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); #else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.ReadBack, - totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.ReadBack, + totalSizeInBytes, + GraphicsDevice.IsCacheCoherentUMA); #endif - using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) + using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) + { + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - } - - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: d3D12Resource.Get(), - &d3D12PlacedSubresourceFootprintDestination, - destinationX: 0, - destinationY: 0, - destinationZ: 0, - d3D12ResourceSource: D3D12Resource, - sourceX: (uint)sourceOffsetX, - sourceY: (uint)sourceOffsetY, - sourceZ: (ushort)sourceOffsetZ, - (uint)width, - (uint)height, - (ushort)depth); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); } - using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: d3D12Resource.Get(), + &d3D12PlacedSubresourceFootprintDestination, + destinationX: 0, + destinationY: 0, + destinationZ: 0, + d3D12ResourceSource: D3D12Resource, + sourceX: (uint)sourceOffsetX, + sourceY: (uint)sourceOffsetY, + sourceZ: (ushort)sourceOffsetZ, + (uint)width, + (uint)height, + (ushort)depth); - fixed (void* destinationPointer = &destination) + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - MemoryHelper.Copy( - resource.Pointer, - (uint)height, - (uint)depth, - rowSizeInBytes, - d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch, - d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch * (uint)height, - destinationPointer); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); } + + copyCommandList.ExecuteAndWaitForCompletion(); + } + + using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); + + fixed (void* destinationPointer = &destination) + { + MemoryHelper.Copy( + resource.Pointer, + (uint)height, + (uint)depth, + rowSizeInBytes, + d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch, + d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch * (uint)height, + destinationPointer); } } @@ -302,49 +300,48 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - using (destination.GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + using var _2 = destination.GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + + D3D12_COMMAND_LIST_TYPE d3D12CommandListType = + this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || + destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE + ? D3D12_COMMAND_LIST_TYPE_COMPUTE + : D3D12_COMMAND_LIST_TYPE_COPY; + + using CommandList copyCommandList = new(GraphicsDevice, d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - GraphicsDevice.ThrowIfDeviceLost(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - - D3D12_COMMAND_LIST_TYPE d3D12CommandListType = - this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || - destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE - ? D3D12_COMMAND_LIST_TYPE_COMPUTE - : D3D12_COMMAND_LIST_TYPE_COPY; - - using CommandList copyCommandList = new(GraphicsDevice, d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); - } - - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: destination.D3D12Resource, - (uint)destinationOffsetX, - (uint)destinationOffsetY, - (ushort)destinationOffsetZ, - d3D12ResourceSource: D3D12Resource, - (uint)sourceOffsetX, - (uint)sourceOffsetY, - (ushort)sourceOffsetZ, - (uint)width, - (uint)height, - (ushort)depth); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: destination.D3D12Resource, + (uint)destinationOffsetX, + (uint)destinationOffsetY, + (ushort)destinationOffsetZ, + d3D12ResourceSource: D3D12Resource, + (uint)sourceOffsetX, + (uint)sourceOffsetY, + (ushort)sourceOffsetZ, + (uint)width, + (uint)height, + (ushort)depth); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } /// @@ -381,45 +378,44 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - using (destination.GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + using var _2 = destination.GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - GraphicsDevice.ThrowIfDeviceLost(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - } - - fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintDestination = &destination.D3D12PlacedSubresourceFootprint) - { - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: destination.D3D12Resource, - d3D12PlacedSubresourceFootprintDestination, - (uint)destinationOffsetX, - (uint)destinationOffsetY, - (ushort)destinationOffsetZ, - d3D12ResourceSource: D3D12Resource, - (uint)sourceOffsetX, - (uint)sourceOffsetY, - (ushort)sourceOffsetZ, - (uint)width, - (uint)height, - (ushort)depth); - } - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); } + + fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintDestination = &destination.D3D12PlacedSubresourceFootprint) + { + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: destination.D3D12Resource, + d3D12PlacedSubresourceFootprintDestination, + (uint)destinationOffsetX, + (uint)destinationOffsetY, + (ushort)destinationOffsetZ, + d3D12ResourceSource: D3D12Resource, + (uint)sourceOffsetX, + (uint)sourceOffsetY, + (ushort)sourceOffsetZ, + (uint)width, + (uint)height, + (ushort)depth); + } + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } /// @@ -446,76 +442,75 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - { - GraphicsDevice.ThrowIfDeviceLost(); + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); - GraphicsDevice.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintSource, - out ulong rowSizeInBytes, - out ulong totalSizeInBytes); + GraphicsDevice.ThrowIfDeviceLost(); + + GraphicsDevice.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + (ushort)depth, + out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintSource, + out ulong rowSizeInBytes, + out ulong totalSizeInBytes); #if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, - ResourceType.Upload, - AllocationMode.Default, - totalSizeInBytes); + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( + GraphicsDevice.Pool, + ResourceType.Upload, + AllocationMode.Default, + totalSizeInBytes); - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); + using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); #else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.Upload, - totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.Upload, + totalSizeInBytes, + GraphicsDevice.IsCacheCoherentUMA); #endif - using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) - fixed (void* sourcePointer = &source) - { - MemoryHelper.Copy( - sourcePointer, - resource.Pointer, - (uint)height, - (uint)depth, - rowSizeInBytes, - d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch, - d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch * (uint)height); - } - - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); - } - - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: D3D12Resource, - destinationX: (uint)destinationOffsetX, - destinationY: (uint)destinationOffsetY, - destinationZ: (ushort)destinationOffsetZ, - d3D12ResourceSource: d3D12Resource.Get(), - &d3D12PlacedSubresourceFootprintSource, - sourceX: 0, - sourceY: 0, - sourceZ: 0, - (uint)width, + using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) + fixed (void* sourcePointer = &source) + { + MemoryHelper.Copy( + sourcePointer, + resource.Pointer, (uint)height, - (ushort)depth); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); + (uint)depth, + rowSizeInBytes, + d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch, + d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch * (uint)height); } + + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: D3D12Resource, + destinationX: (uint)destinationOffsetX, + destinationY: (uint)destinationOffsetY, + destinationZ: (ushort)destinationOffsetZ, + d3D12ResourceSource: d3D12Resource.Get(), + &d3D12PlacedSubresourceFootprintSource, + sourceX: 0, + sourceY: 0, + sourceZ: 0, + (uint)width, + (uint)height, + (ushort)depth); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } /// @@ -552,45 +547,44 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - using (source.GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + using var _2 = source.GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + source.ThrowIfDeviceMismatch(GraphicsDevice); + + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - GraphicsDevice.ThrowIfDeviceLost(); - - source.ThrowIfDeviceMismatch(GraphicsDevice); - - using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); - } - - fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintSource = &source.D3D12PlacedSubresourceFootprint) - { - copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( - d3D12ResourceDestination: D3D12Resource, - (uint)destinationOffsetX, - (uint)destinationOffsetY, - (ushort)destinationOffsetZ, - d3D12ResourceSource: source.D3D12Resource, - d3D12PlacedSubresourceFootprintSource, - (uint)sourceOffsetX, - (uint)sourceOffsetY, - (ushort)sourceOffsetZ, - (uint)width, - (uint)height, - (ushort)depth); - } - - if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - { - copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); - } - - copyCommandList.ExecuteAndWaitForCompletion(); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } + + fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintSource = &source.D3D12PlacedSubresourceFootprint) + { + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: D3D12Resource, + (uint)destinationOffsetX, + (uint)destinationOffsetY, + (ushort)destinationOffsetZ, + d3D12ResourceSource: source.D3D12Resource, + d3D12PlacedSubresourceFootprintSource, + (uint)sourceOffsetX, + (uint)sourceOffsetY, + (ushort)sourceOffsetZ, + (uint)width, + (uint)height, + (ushort)depth); + } + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); } /// @@ -642,54 +636,50 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); - isNormalized = DXGIFormatHelper.IsNormalizedType(); + ThrowIfDeviceMismatch(device); - return (this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); - } + isNormalized = DXGIFormatHelper.IsNormalizedType(); + + return (this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); } /// internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); - return D3D12Resource; - } + ThrowIfDeviceMismatch(device); + + return D3D12Resource; } /// internal (D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource) { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); - D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState; - D3D12_RESOURCE_STATES d3D12ResourceStatesAfter = ResourceStateHelper.GetD3D12ResourceStates(resourceState); + ThrowIfDeviceMismatch(device); - this.d3D12ResourceState = d3D12ResourceStatesAfter; + D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState; + D3D12_RESOURCE_STATES d3D12ResourceStatesAfter = ResourceStateHelper.GetD3D12ResourceStates(resourceState); - d3D12Resource = D3D12Resource; + this.d3D12ResourceState = d3D12ResourceStatesAfter; - return (d3D12ResourceStatesBefore, d3D12ResourceStatesAfter); - } + d3D12Resource = D3D12Resource; + + return (d3D12ResourceStatesBefore, d3D12ResourceStatesAfter); } /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - { - ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); - return D3D12GpuDescriptorHandle; - } + ThrowIfDeviceMismatch(device); + + return D3D12GpuDescriptorHandle; } /// diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs index 53f03fcb..93c68d5e 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs @@ -47,28 +47,27 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource // The maximum length is set such that the aligned buffer size can't exceed uint.MaxValue Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / (uint)sizeof(T)) & ~255); - using (device.GetReferenceTracker().GetLease()) - { - device.ThrowIfDeviceLost(); + using var _0 = device.GetReferenceTracker().GetLease(); - GraphicsDevice = device; - Length = length; + device.ThrowIfDeviceLost(); - ulong sizeInBytes = (uint)length * (uint)sizeof(T); + GraphicsDevice = device; + Length = length; + + ulong sizeInBytes = (uint)length * (uint)sizeof(T); #if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, sizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); + this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, sizeInBytes); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); #else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, sizeInBytes, device.IsCacheCoherentUMA); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, sizeInBytes, device.IsCacheCoherentUMA); #endif - device.RegisterAllocatedResource(); + device.RegisterAllocatedResource(); - this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; + this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; - this.d3D12Resource.Get()->SetName(this); - } + this.d3D12Resource.Get()->SetName(this); } /// @@ -95,10 +94,9 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - using (GetReferenceTracker().GetLease()) - { - return new MemoryManager(this).Memory; - } + using var _0 = GetReferenceTracker().GetLease(); + + return new MemoryManager(this).Memory; } } @@ -108,10 +106,9 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - using (GetReferenceTracker().GetLease()) - { - return new(this.mappedData, Length); - } + using var _0 = GetReferenceTracker().GetLease(); + + return new(this.mappedData, Length); } } @@ -175,12 +172,11 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource /// public override MemoryHandle Pin(int elementIndex = 0) { - using (this.buffer.GetReferenceTracker().GetLease()) - { - Guard.IsEqualTo(elementIndex, 0); + Guard.IsEqualTo(elementIndex, 0); - return new(this.buffer.mappedData); - } + using var _0 = this.buffer.GetReferenceTracker().GetLease(); + + return new(this.buffer.mappedData); } /// diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs index 4cf69cb3..232e59ed 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs @@ -53,38 +53,37 @@ public unsafe abstract class TransferTexture2D : NativeObject, IGraphicsResou Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - using (device.GetReferenceTracker().GetLease()) + using var _0 = device.GetReferenceTracker().GetLease(); + + device.ThrowIfDeviceLost(); + + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D)) { - device.ThrowIfDeviceLost(); + UnsupportedTextureTypeException.ThrowForTexture2D(); + } - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D)) - { - UnsupportedTextureTypeException.ThrowForTexture2D(); - } + GraphicsDevice = device; - GraphicsDevice = device; - - device.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - out this.d3D12PlacedSubresourceFootprint, - out _, - out ulong totalSizeInBytes); + device.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out this.d3D12PlacedSubresourceFootprint, + out _, + out ulong totalSizeInBytes); #if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, totalSizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); + this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, totalSizeInBytes); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); #else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, totalSizeInBytes, device.IsCacheCoherentUMA); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, totalSizeInBytes, device.IsCacheCoherentUMA); #endif - device.RegisterAllocatedResource(); + device.RegisterAllocatedResource(); - this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; + this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; - this.d3D12Resource.Get()->SetName(this); - } + this.d3D12Resource.Get()->SetName(this); } /// @@ -116,10 +115,9 @@ public unsafe abstract class TransferTexture2D : NativeObject, IGraphicsResou [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - using (this.GetReferenceTracker().GetLease()) - { - return new(this.mappedData, Width, Height, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); - } + using var _0 = this.GetReferenceTracker().GetLease(); + + return new(this.mappedData, Width, Height, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); } } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs index 149c53f9..04bf0bb6 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs @@ -55,39 +55,38 @@ public unsafe abstract class TransferTexture3D : NativeObject, IGraphicsResou Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - using (device.GetReferenceTracker().GetLease()) + using var _0 = device.GetReferenceTracker().GetLease(); + + device.ThrowIfDeviceLost(); + + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D)) { - device.ThrowIfDeviceLost(); + UnsupportedTextureTypeException.ThrowForTexture3D(); + } - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D)) - { - UnsupportedTextureTypeException.ThrowForTexture3D(); - } + GraphicsDevice = device; - GraphicsDevice = device; - - device.D3D12Device->GetCopyableFootprint( - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - out this.d3D12PlacedSubresourceFootprint, - out _, - out ulong totalSizeInBytes); + device.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + (ushort)depth, + out this.d3D12PlacedSubresourceFootprint, + out _, + out ulong totalSizeInBytes); #if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, totalSizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); + this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, totalSizeInBytes); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); #else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, totalSizeInBytes, device.IsCacheCoherentUMA); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, totalSizeInBytes, device.IsCacheCoherentUMA); #endif - device.RegisterAllocatedResource(); + device.RegisterAllocatedResource(); - this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; + this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; - this.d3D12Resource.Get()->SetName(this); - } + this.d3D12Resource.Get()->SetName(this); } /// @@ -124,10 +123,9 @@ public unsafe abstract class TransferTexture3D : NativeObject, IGraphicsResou [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - using (this.GetReferenceTracker().GetLease()) - { - return new(this.mappedData, Width, Height, Depth, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); - } + using var _0 = this.GetReferenceTracker().GetLease(); + + return new(this.mappedData, Width, Height, Depth, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); } } diff --git a/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs index fcd3b810..490f9b6f 100644 --- a/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs @@ -61,24 +61,23 @@ public sealed class ConstantBuffer : Buffer Guard.IsInRange(offset, 0, Length); Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + using ID3D12ResourceMap resource = D3D12Resource->Map(); + + fixed (void* destinationPointer = &destination) { - GraphicsDevice.ThrowIfDeviceLost(); - - using ID3D12ResourceMap resource = D3D12Resource->Map(); - - fixed (void* destinationPointer = &destination) - { - MemoryHelper.Copy( - source: resource.Pointer, - destination: destinationPointer, - sourceElementOffset: (uint)offset, - destinationElementOffset: 0, - sourceElementPitchInBytes: (uint)GetPaddedSize(), - destinationElementPitchInBytes: (uint)sizeof(T), - count: (uint)length); - } + MemoryHelper.Copy( + source: resource.Pointer, + destination: destinationPointer, + sourceElementOffset: (uint)offset, + destinationElementOffset: 0, + sourceElementPitchInBytes: (uint)GetPaddedSize(), + destinationElementPitchInBytes: (uint)sizeof(T), + count: (uint)length); } } @@ -92,30 +91,29 @@ public sealed class ConstantBuffer : Buffer Guard.IsInRange(destinationOffset, 0, destination.Length); Guard.IsLessThanOrEqualTo(destinationOffset + length, destination.Length, nameof(destinationOffset)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) - using (destination.GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + using var _2 = destination.GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + + if (destination is ConstantBuffer buffer) { - GraphicsDevice.ThrowIfDeviceLost(); + using ID3D12ResourceMap sourceMap = D3D12Resource->Map(); + using ID3D12ResourceMap destinationMap = buffer.D3D12Resource->Map(); - destination.ThrowIfDeviceMismatch(GraphicsDevice); - - if (destination is ConstantBuffer buffer) - { - using ID3D12ResourceMap sourceMap = D3D12Resource->Map(); - using ID3D12ResourceMap destinationMap = buffer.D3D12Resource->Map(); - - MemoryHelper.Copy( - source: sourceMap.Pointer, - destination: destinationMap.Pointer, - sourceElementOffset: (uint)sourceOffset, - destinationElementOffset: (uint)destinationOffset, - sourceElementPitchInBytes: (uint)GetPaddedSize(), - destinationElementPitchInBytes: (uint)GetPaddedSize(), - count: (uint)length); - } - else CopyToWithCpuBuffer(destination, sourceOffset, destinationOffset, length); + MemoryHelper.Copy( + source: sourceMap.Pointer, + destination: destinationMap.Pointer, + sourceElementOffset: (uint)sourceOffset, + destinationElementOffset: (uint)destinationOffset, + sourceElementPitchInBytes: (uint)GetPaddedSize(), + destinationElementPitchInBytes: (uint)GetPaddedSize(), + count: (uint)length); } + else CopyToWithCpuBuffer(destination, sourceOffset, destinationOffset, length); } /// @@ -125,24 +123,23 @@ public sealed class ConstantBuffer : Buffer Guard.IsInRange(offset, 0, Length); Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + using ID3D12ResourceMap resource = D3D12Resource->Map(); + + fixed (void* sourcePointer = &source) { - GraphicsDevice.ThrowIfDeviceLost(); - - using ID3D12ResourceMap resource = D3D12Resource->Map(); - - fixed (void* sourcePointer = &source) - { - MemoryHelper.Copy( - source: sourcePointer, - destination: resource.Pointer, - sourceElementOffset: 0, - destinationElementOffset: (uint)offset, - sourceElementPitchInBytes: (uint)sizeof(T), - destinationElementPitchInBytes: (uint)GetPaddedSize(), - count: (uint)length); - } + MemoryHelper.Copy( + source: sourcePointer, + destination: resource.Pointer, + sourceElementOffset: 0, + destinationElementOffset: (uint)offset, + sourceElementPitchInBytes: (uint)sizeof(T), + destinationElementPitchInBytes: (uint)GetPaddedSize(), + count: (uint)length); } } diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs index 014ba208..925c63e8 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs @@ -24,28 +24,27 @@ partial class ReadWriteTexture2D /// internal IReadOnlyNormalizedTexture2D AsReadOnly() { - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + ThrowIfIsNotInReadOnlyState(); + + ReadOnly? readOnlyWrapper = this.readOnlyWrapper; + + if (readOnlyWrapper is not null) { - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfIsNotInReadOnlyState(); - - ReadOnly? readOnlyWrapper = this.readOnlyWrapper; - - if (readOnlyWrapper is not null) - { - return readOnlyWrapper; - } - - [MethodImpl(MethodImplOptions.NoInlining)] - static ReadOnly InitializeWrapper(ReadWriteTexture2D texture) - { - return texture.readOnlyWrapper = new(texture); - } - - return InitializeWrapper(this); + return readOnlyWrapper; } + + [MethodImpl(MethodImplOptions.NoInlining)] + static ReadOnly InitializeWrapper(ReadWriteTexture2D texture) + { + return texture.readOnlyWrapper = new(texture); + } + + return InitializeWrapper(this); } /// @@ -108,13 +107,12 @@ partial class ReadWriteTexture2D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - using (this.owner.GetReferenceTracker().GetLease()) - { - this.owner.ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); + using var _1 = this.owner.GetReferenceTracker().GetLease(); - return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; - } + this.owner.ThrowIfDeviceMismatch(device); + + return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; } /// @@ -126,13 +124,12 @@ partial class ReadWriteTexture2D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - using (this.owner.GetReferenceTracker().GetLease()) - { - this.owner.ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); + using var _1 = this.owner.GetReferenceTracker().GetLease(); - return this.owner.D3D12Resource; - } + this.owner.ThrowIfDeviceMismatch(device); + + return this.owner.D3D12Resource; } /// diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs index 091fae0b..b1ea02fc 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs @@ -24,31 +24,30 @@ partial class ReadWriteTexture2D /// public IReadOnlyTexture2D AsReadOnly() { - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + ThrowIfIsNotInReadOnlyState(); + + ReadOnly? readOnlyWrapper = this.readOnlyWrapper; + + if (readOnlyWrapper is not null) { - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfIsNotInReadOnlyState(); - - ReadOnly? readOnlyWrapper = this.readOnlyWrapper; - - if (readOnlyWrapper is not null) - { - return readOnlyWrapper; - } - - // The wrapper initialization is moved to a non inlined helper to keep the codegen of this method - // as compact as possible. If the current wrapper is not initialized, control goes directly to the - // helper that will initialize and return it, which translates to a single jump. - [MethodImpl(MethodImplOptions.NoInlining)] - static ReadOnly InitializeWrapper(ReadWriteTexture2D texture) - { - return texture.readOnlyWrapper = new(texture); - } - - return InitializeWrapper(this); + return readOnlyWrapper; } + + // The wrapper initialization is moved to a non inlined helper to keep the codegen of this method + // as compact as possible. If the current wrapper is not initialized, control goes directly to the + // helper that will initialize and return it, which translates to a single jump. + [MethodImpl(MethodImplOptions.NoInlining)] + static ReadOnly InitializeWrapper(ReadWriteTexture2D texture) + { + return texture.readOnlyWrapper = new(texture); + } + + return InitializeWrapper(this); } /// @@ -111,13 +110,12 @@ partial class ReadWriteTexture2D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - using (this.owner.GetReferenceTracker().GetLease()) - { - this.owner.ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); + using var _1 = this.owner.GetReferenceTracker().GetLease(); - return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; - } + this.owner.ThrowIfDeviceMismatch(device); + + return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; } /// @@ -129,13 +127,12 @@ partial class ReadWriteTexture2D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - using (this.owner.GetReferenceTracker().GetLease()) - { - this.owner.ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); + using var _1 = this.owner.GetReferenceTracker().GetLease(); - return this.owner.D3D12Resource; - } + this.owner.ThrowIfDeviceMismatch(device); + + return this.owner.D3D12Resource; } /// diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs index 7aec0e6f..96e35601 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs @@ -24,28 +24,27 @@ partial class ReadWriteTexture3D /// public IReadOnlyNormalizedTexture3D AsReadOnly() { - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + ThrowIfIsNotInReadOnlyState(); + + ReadOnly? readOnlyWrapper = this.readOnlyWrapper; + + if (readOnlyWrapper is not null) { - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfIsNotInReadOnlyState(); - - ReadOnly? readOnlyWrapper = this.readOnlyWrapper; - - if (readOnlyWrapper is not null) - { - return readOnlyWrapper; - } - - [MethodImpl(MethodImplOptions.NoInlining)] - static ReadOnly InitializeWrapper(ReadWriteTexture3D texture) - { - return texture.readOnlyWrapper = new(texture); - } - - return InitializeWrapper(this); + return readOnlyWrapper; } + + [MethodImpl(MethodImplOptions.NoInlining)] + static ReadOnly InitializeWrapper(ReadWriteTexture3D texture) + { + return texture.readOnlyWrapper = new(texture); + } + + return InitializeWrapper(this); } /// @@ -111,13 +110,12 @@ partial class ReadWriteTexture3D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - using (this.owner.GetReferenceTracker().GetLease()) - { - this.owner.ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); + using var _1 = this.owner.GetReferenceTracker().GetLease(); - return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; - } + this.owner.ThrowIfDeviceMismatch(device); + + return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; } /// @@ -129,13 +127,12 @@ partial class ReadWriteTexture3D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - using (this.owner.GetReferenceTracker().GetLease()) - { - this.owner.ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); + using var _1 = this.owner.GetReferenceTracker().GetLease(); - return this.owner.D3D12Resource; - } + this.owner.ThrowIfDeviceMismatch(device); + + return this.owner.D3D12Resource; } /// diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs index 401d91ef..db0e67d1 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs @@ -24,28 +24,27 @@ partial class ReadWriteTexture3D /// public IReadOnlyTexture3D AsReadOnly() { - using (GraphicsDevice.GetReferenceTracker().GetLease()) - using (GetReferenceTracker().GetLease()) + using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); + using var _1 = GetReferenceTracker().GetLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + ThrowIfIsNotInReadOnlyState(); + + ReadOnly? readOnlyWrapper = this.readOnlyWrapper; + + if (readOnlyWrapper is not null) { - GraphicsDevice.ThrowIfDeviceLost(); - - ThrowIfIsNotInReadOnlyState(); - - ReadOnly? readOnlyWrapper = this.readOnlyWrapper; - - if (readOnlyWrapper is not null) - { - return readOnlyWrapper; - } - - [MethodImpl(MethodImplOptions.NoInlining)] - static ReadOnly InitializeWrapper(ReadWriteTexture3D texture) - { - return texture.readOnlyWrapper = new(texture); - } - - return InitializeWrapper(this); + return readOnlyWrapper; } + + [MethodImpl(MethodImplOptions.NoInlining)] + static ReadOnly InitializeWrapper(ReadWriteTexture3D texture) + { + return texture.readOnlyWrapper = new(texture); + } + + return InitializeWrapper(this); } /// @@ -111,13 +110,12 @@ partial class ReadWriteTexture3D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - using (this.owner.GetReferenceTracker().GetLease()) - { - this.owner.ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); + using var _1 = this.owner.GetReferenceTracker().GetLease(); - return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; - } + this.owner.ThrowIfDeviceMismatch(device); + + return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; } /// @@ -129,13 +127,12 @@ partial class ReadWriteTexture3D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - using (GetReferenceTracker().GetLease()) - using (this.owner.GetReferenceTracker().GetLease()) - { - this.owner.ThrowIfDeviceMismatch(device); + using var _0 = GetReferenceTracker().GetLease(); + using var _1 = this.owner.GetReferenceTracker().GetLease(); - return this.owner.D3D12Resource; - } + this.owner.ThrowIfDeviceMismatch(device); + + return this.owner.D3D12Resource; } /// From 84ebe369755c2c1d06018a0e56a726137a5c7a28 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 24 Jul 2022 22:39:08 +0200 Subject: [PATCH 33/64] Make InteropServices APIs thread safe --- .../Graphics/Interop/InteropServices.cs | 42 +++++++++++++++++++ .../Graphics/Interop/NativeObject.cs | 2 +- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp/Graphics/Interop/InteropServices.cs b/src/ComputeSharp/Graphics/Interop/InteropServices.cs index 288679f7..4fa165e2 100644 --- a/src/ComputeSharp/Graphics/Interop/InteropServices.cs +++ b/src/ComputeSharp/Graphics/Interop/InteropServices.cs @@ -30,9 +30,12 @@ public static unsafe class InteropServices /// The input instance in use. /// A reference to the interface identifier (IID) of the device interface being queried for. /// The address of a pointer to an interface with the IID specified in . + /// The instance has been disposed. /// Thrown if the IUnknown::QueryInterface call doesn't return S_OK. public static void GetID3D12Device(GraphicsDevice device, Guid* riid, void** ppvObject) { + using var _0 = device.GetReferenceTracker().GetLease(); + device.D3D12Device->QueryInterface(riid, ppvObject).Assert(); } @@ -44,10 +47,13 @@ public static unsafe class InteropServices /// The input instance in use. /// A reference to the interface identifier (IID) of the resource interface being queried for. /// The address of a pointer to an interface with the IID specified in . + /// The instance has been disposed. /// Thrown if the IUnknown::QueryInterface call doesn't return S_OK. public static void GetID3D12Resource(Buffer buffer, Guid* riid, void** ppvObject) where T : unmanaged { + using var _0 = buffer.GetReferenceTracker().GetLease(); + buffer.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } @@ -59,10 +65,13 @@ public static unsafe class InteropServices /// The input instance in use. /// A reference to the interface identifier (IID) of the resource interface being queried for. /// The address of a pointer to an interface with the IID specified in . + /// The instance has been disposed. /// Thrown if the IUnknown::QueryInterface call doesn't return S_OK. public static void GetID3D12Resource(Texture2D texture, Guid* riid, void** ppvObject) where T : unmanaged { + using var _0 = texture.GetReferenceTracker().GetLease(); + texture.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } @@ -74,10 +83,13 @@ public static unsafe class InteropServices /// The input instance in use. /// A reference to the interface identifier (IID) of the resource interface being queried for. /// The address of a pointer to an interface with the IID specified in . + /// The instance has been disposed. /// Thrown if the IUnknown::QueryInterface call doesn't return S_OK. public static void GetID3D12Resource(Texture3D texture, Guid* riid, void** ppvObject) where T : unmanaged { + using var _0 = texture.GetReferenceTracker().GetLease(); + texture.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } @@ -89,10 +101,13 @@ public static unsafe class InteropServices /// The input instance in use. /// A reference to the interface identifier (IID) of the resource interface being queried for. /// The address of a pointer to an interface with the IID specified in . + /// The instance has been disposed. /// Thrown if the IUnknown::QueryInterface call doesn't return S_OK. public static void GetID3D12Resource(TransferBuffer buffer, Guid* riid, void** ppvObject) where T : unmanaged { + using var _0 = buffer.GetReferenceTracker().GetLease(); + buffer.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } @@ -104,10 +119,13 @@ public static unsafe class InteropServices /// The input instance in use. /// A reference to the interface identifier (IID) of the resource interface being queried for. /// The address of a pointer to an interface with the IID specified in . + /// The instance has been disposed. /// Thrown if the IUnknown::QueryInterface call doesn't return S_OK. public static void GetID3D12Resource(TransferTexture2D texture, Guid* riid, void** ppvObject) where T : unmanaged { + using var _0 = texture.GetReferenceTracker().GetLease(); + texture.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } @@ -119,10 +137,13 @@ public static unsafe class InteropServices /// The input instance in use. /// A reference to the interface identifier (IID) of the resource interface being queried for. /// The address of a pointer to an interface with the IID specified in . + /// The instance has been disposed. /// Thrown if the IUnknown::QueryInterface call doesn't return S_OK. public static void GetID3D12Resource(TransferTexture3D texture, Guid* riid, void** ppvObject) where T : unmanaged { + using var _0 = texture.GetReferenceTracker().GetLease(); + texture.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } @@ -137,8 +158,11 @@ public static unsafe class InteropServices /// S_OK if the interface is supported, and E_NOINTERFACE otherwise. /// If ppvObject (the address) is nullptr, then this method returns E_POINTER. /// + /// The instance has been disposed. public static int TryGetID3D12Device(GraphicsDevice device, Guid* riid, void** ppvObject) { + using var _0 = device.GetReferenceTracker().GetLease(); + return device.D3D12Device->QueryInterface(riid, ppvObject); } @@ -154,9 +178,12 @@ public static unsafe class InteropServices /// S_OK if the interface is supported, and E_NOINTERFACE otherwise. /// If ppvObject (the address) is nullptr, then this method returns E_POINTER. /// + /// The instance has been disposed. public static int TryGetID3D12Resource(Buffer buffer, Guid* riid, void** ppvObject) where T : unmanaged { + using var _0 = buffer.GetReferenceTracker().GetLease(); + return buffer.D3D12Resource->QueryInterface(riid, ppvObject); } @@ -172,9 +199,12 @@ public static unsafe class InteropServices /// S_OK if the interface is supported, and E_NOINTERFACE otherwise. /// If ppvObject (the address) is nullptr, then this method returns E_POINTER. /// + /// The instance has been disposed. public static int TryGetID3D12Resource(Texture2D texture, Guid* riid, void** ppvObject) where T : unmanaged { + using var _0 = texture.GetReferenceTracker().GetLease(); + return texture.D3D12Resource->QueryInterface(riid, ppvObject); } @@ -190,9 +220,12 @@ public static unsafe class InteropServices /// S_OK if the interface is supported, and E_NOINTERFACE otherwise. /// If ppvObject (the address) is nullptr, then this method returns E_POINTER. /// + /// The instance has been disposed. public static int TryGetID3D12Resource(Texture3D texture, Guid* riid, void** ppvObject) where T : unmanaged { + using var _0 = texture.GetReferenceTracker().GetLease(); + return texture.D3D12Resource->QueryInterface(riid, ppvObject); } @@ -208,9 +241,12 @@ public static unsafe class InteropServices /// S_OK if the interface is supported, and E_NOINTERFACE otherwise. /// If ppvObject (the address) is nullptr, then this method returns E_POINTER. /// + /// The instance has been disposed. public static int TryGetID3D12Resource(TransferBuffer buffer, Guid* riid, void** ppvObject) where T : unmanaged { + using var _0 = buffer.GetReferenceTracker().GetLease(); + return buffer.D3D12Resource->QueryInterface(riid, ppvObject); } @@ -226,9 +262,12 @@ public static unsafe class InteropServices /// S_OK if the interface is supported, and E_NOINTERFACE otherwise. /// If ppvObject (the address) is nullptr, then this method returns E_POINTER. /// + /// The instance has been disposed. public static int TryGetID3D12Resource(TransferTexture2D texture, Guid* riid, void** ppvObject) where T : unmanaged { + using var _0 = texture.GetReferenceTracker().GetLease(); + return texture.D3D12Resource->QueryInterface(riid, ppvObject); } @@ -244,9 +283,12 @@ public static unsafe class InteropServices /// S_OK if the interface is supported, and E_NOINTERFACE otherwise. /// If ppvObject (the address) is nullptr, then this method returns E_POINTER. /// + /// The instance has been disposed. public static int TryGetID3D12Resource(TransferTexture3D texture, Guid* riid, void** ppvObject) where T : unmanaged { + using var _0 = texture.GetReferenceTracker().GetLease(); + return texture.D3D12Resource->QueryInterface(riid, ppvObject); } } diff --git a/src/ComputeSharp/Graphics/Interop/NativeObject.cs b/src/ComputeSharp/Graphics/Interop/NativeObject.cs index 53383848..bfbc2c04 100644 --- a/src/ComputeSharp/Graphics/Interop/NativeObject.cs +++ b/src/ComputeSharp/Graphics/Interop/NativeObject.cs @@ -16,7 +16,7 @@ public abstract class NativeObject : IDisposable, ReferenceTracker.ITrackedObjec /// /// Creates a new instance. /// - internal NativeObject() + private protected NativeObject() { this.referenceTracker = new ReferenceTracker(this); } From 1ab393139191471f6b57dfa773bfe6eb185f41dd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 24 Jul 2022 23:13:27 +0200 Subject: [PATCH 34/64] Fix reference tracking with ComputeContext and async execution --- .../Graphics/GraphicsDevice.Execute.cs | 18 ++++++++- .../Graphics/Interop/ReferenceTracker.cs | 17 +++++++++ src/ComputeSharp/Shaders/ComputeContext.cs | 38 ++++++++++++++++++- 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs index 8f17e00f..e8f55f5c 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs @@ -9,6 +9,7 @@ using CommunityToolkit.Diagnostics; using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Commands.Interop; +using ComputeSharp.Interop; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; @@ -191,7 +192,9 @@ unsafe partial class GraphicsDevice HANDLE waitHandle; - _ = Windows.RegisterWaitForSingleObject( + device.GetReferenceTracker().DangerousAddRef(); + + int result = Windows.RegisterWaitForSingleObject( phNewWaitObject: &waitHandle, hObject: eventHandle, #if NET6_0_OR_GREATER @@ -203,6 +206,16 @@ unsafe partial class GraphicsDevice dwMilliseconds: Windows.INFINITE, dwFlags: 0); + // The register is successful if the return value is nonzero + if (result == 0) + { + device.GetReferenceTracker().DangerousRelease(); + + NativeMemory.Free(callbackContext); + + ThrowHelper.ThrowWin32Exception("Failed to register the compute context completion callback."); + } + return waitForFenceValueTaskSource; } @@ -227,6 +240,9 @@ unsafe partial class GraphicsDevice device.computeCommandListPool.Return(d3D12GraphicsCommandList, d3D12CommandAllocator); + // Decrement the reference count that was incremented when scheduling the completion callback + device.GetReferenceTracker().DangerousRelease(); + _ = Windows.CloseHandle(eventHandle); NativeMemory.Free(callbackContext); diff --git a/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs b/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs index 3f26d23b..6d325165 100644 --- a/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs +++ b/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs @@ -40,6 +40,23 @@ internal struct ReferenceTracker : IDisposable this.isDisposeRequested = false; } + /// + /// Adds an untracked reference to the underlying object. This needs to be released with . + /// + /// Thrown if the tracked object has been disposed. + public void DangerousAddRef() + { + _ = GetLease(); + } + + /// + /// Decrements the reference count for the underlying object. A call to this API has to match a previous call. + /// + public void DangerousRelease() + { + ReturnLease(); + } + /// /// Gets a value to extend the lifetime of the tracked object. /// diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs index 46c03c31..321a43af 100644 --- a/src/ComputeSharp/Shaders/ComputeContext.cs +++ b/src/ComputeSharp/Shaders/ComputeContext.cs @@ -6,6 +6,7 @@ using CommunityToolkit.Diagnostics; using ComputeSharp.__Internals; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Interop; using ComputeSharp.Shaders.Dispatching; using ComputeSharp.Shaders.Loading; using ComputeSharp.Shaders.Models; @@ -18,6 +19,15 @@ namespace ComputeSharp; /// /// A context to batch compute operations in a single invocation, minimizing GPU overhead. /// +/// +/// +/// This type must always be used in a statement and disposed properly. +/// Not doing so is undefined behavior and may result in the target device not being disposed correctly. +/// +/// +/// For more documentation on this, see the remarks in . +/// +/// public struct ComputeContext : IDisposable, IAsyncDisposable { /// @@ -30,6 +40,11 @@ public struct ComputeContext : IDisposable, IAsyncDisposable /// private CommandList commandList; + /// + /// The lease to ensure is not disposed until the context is no longer in use. + /// + private ReferenceTracker.Lease lease; + /// /// Creates a new instance with the specified parameters. /// @@ -38,6 +53,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable { this.device = device; this.commandList = default; + this.lease = device.GetReferenceTracker().GetLease(); } /// @@ -290,10 +306,19 @@ public struct ComputeContext : IDisposable, IAsyncDisposable if (!this.commandList.IsAllocated) { + this.lease.Dispose(); + return; } - this.commandList.ExecuteAndWaitForCompletion(); + try + { + this.commandList.ExecuteAndWaitForCompletion(); + } + finally + { + this.lease.Dispose(); + } } /// @@ -306,6 +331,8 @@ public struct ComputeContext : IDisposable, IAsyncDisposable if (!this.commandList.IsAllocated) { + this.lease.Dispose(); + #if NET6_0_OR_GREATER return ValueTask.CompletedTask; #else @@ -313,7 +340,14 @@ public struct ComputeContext : IDisposable, IAsyncDisposable #endif } - return this.commandList.ExecuteAndWaitForCompletionAsync(); + try + { + return this.commandList.ExecuteAndWaitForCompletionAsync(); + } + finally + { + this.lease.Dispose(); + } } /// From e045fc2dce38d18059a67fa389148417f792134f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 24 Jul 2022 23:13:41 +0200 Subject: [PATCH 35/64] Add unit test for InteropServices APIs with disposed device --- .../DeviceDisposalTests.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs index c2ec6e2c..113429b1 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs @@ -1,4 +1,5 @@ -using ComputeSharp.Interop; +using System; +using ComputeSharp.Interop; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -58,6 +59,20 @@ public class DeviceDisposalTests Assert.AreEqual(refCount, 1u); } + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(ObjectDisposedException))] + public unsafe void DeviceDisposal_InteropServicesThrowsObjectDisposedException(Device device) + { + using ComPtr d3D12Device = default; + + GraphicsDevice graphicsDevice = device.Get(); + + graphicsDevice.Dispose(); + + InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + } + [CombinatorialTestMethod] [AllDevices] public unsafe void DeviceDisposal_DisposedResources_ReferenceCounting(Device device) From b1f596402e1c6b8100fa6de3de5c9a6f09f33d5d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 24 Jul 2022 23:52:23 +0200 Subject: [PATCH 36/64] Simplify reference tracking logic in ComputeContext type --- src/ComputeSharp/Shaders/ComputeContext.cs | 23 +++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs index 321a43af..6210664c 100644 --- a/src/ComputeSharp/Shaders/ComputeContext.cs +++ b/src/ComputeSharp/Shaders/ComputeContext.cs @@ -6,7 +6,6 @@ using CommunityToolkit.Diagnostics; using ComputeSharp.__Internals; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; -using ComputeSharp.Interop; using ComputeSharp.Shaders.Dispatching; using ComputeSharp.Shaders.Loading; using ComputeSharp.Shaders.Models; @@ -40,11 +39,6 @@ public struct ComputeContext : IDisposable, IAsyncDisposable /// private CommandList commandList; - /// - /// The lease to ensure is not disposed until the context is no longer in use. - /// - private ReferenceTracker.Lease lease; - /// /// Creates a new instance with the specified parameters. /// @@ -53,7 +47,10 @@ public struct ComputeContext : IDisposable, IAsyncDisposable { this.device = device; this.commandList = default; - this.lease = device.GetReferenceTracker().GetLease(); + + // Increment the reference count for the device. This has to be released when disposing the context. + // Not disposing the context is undefined behavior, so we can rely on that to release the reference. + device.GetReferenceTracker().DangerousAddRef(); } /// @@ -302,11 +299,13 @@ public struct ComputeContext : IDisposable, IAsyncDisposable { ThrowInvalidOperationExceptionIfDeviceIsNull(); + GraphicsDevice device = this.device; + this.device = null; if (!this.commandList.IsAllocated) { - this.lease.Dispose(); + device.GetReferenceTracker().DangerousRelease(); return; } @@ -317,7 +316,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable } finally { - this.lease.Dispose(); + device.GetReferenceTracker().DangerousRelease(); } } @@ -327,11 +326,13 @@ public struct ComputeContext : IDisposable, IAsyncDisposable { ThrowInvalidOperationExceptionIfDeviceIsNull(); + GraphicsDevice device = this.device; + this.device = null; if (!this.commandList.IsAllocated) { - this.lease.Dispose(); + device.GetReferenceTracker().DangerousRelease(); #if NET6_0_OR_GREATER return ValueTask.CompletedTask; @@ -346,7 +347,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable } finally { - this.lease.Dispose(); + device.GetReferenceTracker().DangerousRelease(); } } From 27a5410a729636fec19550fe58200704e0ee9d75 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 25 Jul 2022 00:14:54 +0200 Subject: [PATCH 37/64] Ensure same graphics device is used --- src/ComputeSharp.UI/Helpers/SwapChainManager.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index c0a9e85b..54ef9d84 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -49,6 +49,11 @@ internal sealed unsafe partial class SwapChainManager : NativeObject /// private readonly TOwner owner; + /// + /// The instance in use. + /// + private readonly GraphicsDevice device; + /// /// The captured for the current instance. /// @@ -216,6 +221,7 @@ internal sealed unsafe partial class SwapChainManager : NativeObject public SwapChainManager(TOwner owner) { this.owner = owner; + this.device = GraphicsDevice.GetDefault(); // Extract the ISwapChainPanelNative reference from the current panel, then query the // IDXGISwapChain reference just created and set that as the swap chain panel to use. @@ -239,7 +245,7 @@ internal sealed unsafe partial class SwapChainManager : NativeObject // Get the underlying ID3D12Device in use fixed (ID3D12Device** d3D12Device = this.d3D12Device) { - GraphicsDevice.GetDefault().D3D12Device->QueryInterface(Win32.__uuidof(), (void**)d3D12Device).Assert(); + this.device.D3D12Device->QueryInterface(Win32.__uuidof(), (void**)d3D12Device).Assert(); } // Create the direct command queue to use @@ -394,7 +400,7 @@ internal sealed unsafe partial class SwapChainManager : NativeObject // Dispose the previous texture, if present, and create the new 2D texture to use to generate frames to display this.texture?.Dispose(); - this.texture = GraphicsDevice.GetDefault().AllocateReadWriteTexture2D((int)resizedWidth, (int)resizeHeight); + this.texture = this.device.AllocateReadWriteTexture2D((int)resizedWidth, (int)resizeHeight); } } From 4b3dd0ecf9008cfa184c3f51931f4ee6eb13d5c8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 25 Jul 2022 00:32:10 +0200 Subject: [PATCH 38/64] Add unit tests for GraphicsDevice.GetDefault() contract --- .../DeviceLostTests.cs | 2 +- .../GetDefaultDeviceTests.cs | 76 +++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs index 7c0cf7d1..0bb4e179 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs @@ -186,7 +186,7 @@ public class DeviceLostTests /// Removes the underlying device for a given instance and waits for it to be reported. /// /// The target instance. - private static async Task RemoveDeviceAsync(GraphicsDevice graphicsDevice) + internal static async Task RemoveDeviceAsync(GraphicsDevice graphicsDevice) { TaskCompletionSource tcs = new(); diff --git a/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs b/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs new file mode 100644 index 00000000..b5ae5c3f --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs @@ -0,0 +1,76 @@ +using System; +using System.Threading.Tasks; +using ComputeSharp.Interop; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.Tests.DeviceLost; + +[TestClass] +[TestCategory("GetDefaultDevice")] +public class GetDefaultDeviceTests +{ + [TestMethod] + public async Task GetDefault_VerifyContract() + { + GraphicsDevice device1 = GraphicsDevice.GetDefault(); + + // The default device is never null (or the previous call would've thrown an exception) + Assert.IsNotNull(device1); + + GraphicsDevice device2 = GraphicsDevice.GetDefault(); + + // Assuming the device hasn't been disposed (tests don't run concurrently), calling + // GraphicsDevice.GetDefault() again will always return the same cached instance. + Assert.AreSame(device1, device2); + + await DeviceLostTests.RemoveDeviceAsync(device1); + + // The device is lost but not disposed, so the same instance should be returned yet again + GraphicsDevice device3 = GraphicsDevice.GetDefault(); + + Assert.AreSame(device1, device3); + + device1.Dispose(); + + // Calling GraphicsDevice.GetDefault() after disposing it should always succeed... + GraphicsDevice device4 = GraphicsDevice.GetDefault(); + + // But it will return a new instance (assuming the device has been disposed properly). + // That is, the caller has to ensure that no other object is keeping the device alive. + Assert.AreNotSame(device1, device4); + + // The LUID should match though, as the same adapter should be returned + Assert.AreEqual(device1.Luid, device4.Luid); + + unsafe void GetDefault_VerifyContract_Part2() + { + using ComPtr d3D12Device = default; + + // Increment the reference count on the internal device, causing it to remain alive + InteropServices.GetID3D12Device(device4, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + + device4.Dispose(); + + _ = d3D12Device.Get()->AddRef(); + + uint refCount = d3D12Device.Get()->Release(); + + // Sanity check that this is in fact the only reference keeping the device alive + Assert.AreEqual(refCount, 1u); + + HRESULT removalReason = d3D12Device.Get()->GetDeviceRemovedReason(); + + // Sanity check that the device is in fact removed + Assert.AreEqual((int)removalReason, DXGI.DXGI_ERROR_DEVICE_REMOVED); + + // Calling GraphicsDevice.GetDefault() will now throw, because the native device has not been disposed properly + Assert.ThrowsException(() => GraphicsDevice.GetDefault()); + } + + await DeviceLostTests.RemoveDeviceAsync(device4); + + GetDefault_VerifyContract_Part2(); + } +} From 12f451977ab7c2ea6bb08b8e7cfc74f905ffbf80 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 25 Jul 2022 17:21:27 +0200 Subject: [PATCH 39/64] Fix typo, enable nightly builds regardless of test results --- .github/workflows/dotnet.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 3bf304b2..91ee8fb0 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -146,7 +146,7 @@ jobs: shell: cmd # Run all the DX12 device lost unit tests (run the separately to minimize issues) - run-dx12-device-list-tests: + run-dx12-device-lost-tests: if: success() needs: [build-solution-debug, build-solution-release] runs-on: windows-2022 @@ -394,7 +394,7 @@ jobs: # Publish the packages to GitHub packages publish-nightlies-github: - needs: [run-dx12-tests, run-dx12-device-list-tests, run-d2d1-tests, run-dx12-samples, verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs] + needs: [verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs] runs-on: windows-2022 if: ${{github.event_name == 'push'}} steps: @@ -410,7 +410,7 @@ jobs: # Publish the packages to Azure DevOps publish-nightlies-azure-devops: - needs: [run-dx12-tests, run-dx12-device-list-tests, run-d2d1-tests, run-dx12-samples, verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs] + needs: [verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs] runs-on: windows-2022 if: ${{github.event_name == 'push'}} steps: From 77503542aa6982961a36f55906913f24e64825b3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 25 Jul 2022 17:27:54 +0200 Subject: [PATCH 40/64] Add IDisposable interface to compute shader panels --- .../Controls/AnimatedComputeShaderPanel.cs | 11 +++++++++-- src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs | 11 +++++++++-- .../Helpers/SwapChainManager.Rendering.cs | 6 ++++-- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs index 7fb592ae..8265c55b 100644 --- a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs @@ -1,4 +1,5 @@ -#if WINDOWS_UWP +using System; +#if WINDOWS_UWP using ComputeSharp.Uwp.Helpers; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; @@ -23,7 +24,7 @@ namespace ComputeSharp.WinUI; /// This panel will always render new frames at the current display refresh rate, automatically. /// /// -public sealed partial class AnimatedComputeShaderPanel : SwapChainPanel +public sealed partial class AnimatedComputeShaderPanel : SwapChainPanel, IDisposable { /// /// The instance handling rendering. @@ -76,4 +77,10 @@ public sealed partial class AnimatedComputeShaderPanel : SwapChainPanel { this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY); } + + /// + public void Dispose() + { + this.swapChainManager.Dispose(); + } } diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs index 560f1950..af51a4bd 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs @@ -1,4 +1,5 @@ -#if WINDOWS_UWP +using System; +#if WINDOWS_UWP using ComputeSharp.Uwp.Helpers; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; @@ -23,7 +24,7 @@ namespace ComputeSharp.WinUI; /// This panel accepts a custom instance to customize frame requests. /// /// -public sealed partial class ComputeShaderPanel : SwapChainPanel +public sealed partial class ComputeShaderPanel : SwapChainPanel, IDisposable { /// /// The instance handling rendering. @@ -76,4 +77,10 @@ public sealed partial class ComputeShaderPanel : SwapChainPanel { this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY); } + + /// + public void Dispose() + { + this.swapChainManager.Dispose(); + } } diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs index 261236b1..38fde6a6 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -55,8 +55,10 @@ partial class SwapChainManager /// public async void StopRenderLoop() { - using var _0 = GetReferenceTracker().GetLease(); - + // Stopping the render loop doesn't use a reference tracking lease on purpose. + // This is to allow callers to stop the render loop even after disposing without + // the method throwing an exception. Stopping a loop doesn't actually access any + // native objects anyway, as it's just cancelling the cancellation token source. using (await this.setupSemaphore.LockAsync()) { this.renderCancellationTokenSource?.Cancel(); From 6921602b8a14bde6becbddbab05e8716e8e7a5d9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 25 Jul 2022 18:17:31 +0200 Subject: [PATCH 41/64] Add missing CloseHandle call in SwapChainManager --- src/ComputeSharp.UI/Helpers/SwapChainManager.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 54ef9d84..982da116 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -511,6 +511,8 @@ internal sealed unsafe partial class SwapChainManager : NativeObject @this.UnsafeStopRenderLoopAndWait(); + _ = Win32.CloseHandle(@this.frameLatencyWaitableObject); + @this.d3D12Device.Dispose(); @this.d3D12CommandQueue.Dispose(); @this.d3D12Fence.Dispose(); From d5b746402ea5b8b9aee6e74c99e44c1d9528af7e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 25 Jul 2022 22:45:53 +0200 Subject: [PATCH 42/64] Add missing logic to reset the swap chain in ISwapChainPanelNative --- .../Helpers/SwapChainManager.cs | 29 +++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 982da116..c4e53de2 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -94,6 +94,15 @@ internal sealed unsafe partial class SwapChainManager : NativeObject /// private ComPtr d3D12GraphicsCommandList; + /// + /// The instance for the underlying object wrapped by the target control. + /// + /// + /// This is needed to call with + /// when the panel is destroyed, so the additional implicit references to the swap chain an native device can be released. + /// + private ComPtr swapChainPanelNative; + /// /// The instance used to display content onto the target window. /// @@ -225,20 +234,19 @@ internal sealed unsafe partial class SwapChainManager : NativeObject // Extract the ISwapChainPanelNative reference from the current panel, then query the // IDXGISwapChain reference just created and set that as the swap chain panel to use. - using ComPtr swapChainPanelNative = default; - + fixed (ISwapChainPanelNative** swapChainPanelNative = this.swapChainPanelNative) using (ComPtr swapChainPanel = default) { #if WINDOWS_UWP swapChainPanel.Attach((IUnknown*)Marshal.GetIUnknownForObject(owner)); - swapChainPanel.CopyTo(swapChainPanelNative.GetAddressOf()).Assert(); + swapChainPanel.CopyTo(swapChainPanelNative).Assert(); #else swapChainPanel.Attach((IUnknown*)((IWinRTObject)owner).NativeObject.GetRef()); swapChainPanel.CopyTo( (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(new Guid(0x63AAD0B8, 0x7C24, 0x40FF, 0x85, 0xA8, 0x64, 0x0D, 0x94, 0x4C, 0xC3, 0x25))), - (void**)swapChainPanelNative.GetAddressOf()).Assert(); + (void**)swapChainPanelNative).Assert(); #endif } @@ -336,7 +344,7 @@ internal sealed unsafe partial class SwapChainManager : NativeObject { this.dxgiSwapChain3.CopyTo(&idxgiSwapChain).Assert(); - swapChainPanelNative.Get()->SetSwapChain(idxgiSwapChain.Get()).Assert(); + this.swapChainPanelNative.Get()->SetSwapChain(idxgiSwapChain.Get()).Assert(); } GC.KeepAlive(this); @@ -505,6 +513,17 @@ internal sealed unsafe partial class SwapChainManager : NativeObject /// private protected override void OnDispose() { + // Even while rendering is still running, we need to properly release all implicit references + // that have been added when connecting the swap chain panel that was used. To do that, the + // same ISwapChainPanelNative::SetSwapChain API has to be called, but passing null as the + // target swap chain. This is handled correctly in the implementation, and all the additional + // references to the swap chain we passed during initialization will be dropped. Once that + // is done, we can then dispose our reference to the underlying swap chain panel for the control. + // This API has to be called on the UI thread, and it can be called just fine even if rendering + // is still running, so we can just call it immediately before moving to a thread to stop rendering. + this.swapChainPanelNative.Get()->SetSwapChain(null).Assert(); + this.swapChainPanelNative.Dispose(); + ThreadPool.UnsafeQueueUserWorkItem(static state => { SwapChainManager @this = (SwapChainManager)state!; From 9dd707a8352c67f95155e7bff593e48dc0fe857c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 25 Jul 2022 23:17:51 +0200 Subject: [PATCH 43/64] Add safety Signal/Wait when disposing SwapChainManager --- src/ComputeSharp.UI/Helpers/SwapChainManager.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index c4e53de2..d26f6a25 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -530,6 +530,14 @@ internal sealed unsafe partial class SwapChainManager : NativeObject @this.UnsafeStopRenderLoopAndWait(); + ulong updatedFenceValue = @this.nextD3D12FenceValue + 1; + + @this.d3D12CommandQueue.Get()->Signal(@this.d3D12Fence.Get(), updatedFenceValue).Assert(); + + // Just like in the resize logic, signal and wait to make sure no operations are pending. This + // is needed to avoid a crash when disposing resources when disposing after stopping rendering. + @this.d3D12Fence.Get()->SetEventOnCompletion(updatedFenceValue, default).Assert(); + _ = Win32.CloseHandle(@this.frameLatencyWaitableObject); @this.d3D12Device.Dispose(); From edddb72ddddabe4d62d4bf288444f17bf7dc258d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 26 Jul 2022 02:13:22 +0200 Subject: [PATCH 44/64] Add eager disposal of cached pipeline states when disposing devices --- src/ComputeSharp/Graphics/GraphicsDevice.cs | 39 ++++++++++ .../Shaders/Loading/PipelineDataLoader{T}.cs | 3 + .../DeviceDisposalTests.cs | 76 ++++++++++++++++++- 3 files changed, 117 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index a516d4a0..c988f565 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -10,6 +11,7 @@ using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; +using ComputeSharp.Shaders.Models; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; @@ -107,6 +109,17 @@ public sealed unsafe partial class GraphicsDevice : NativeObject /// private HRESULT deviceRemovedReason; + /// + /// The list of cached objects for the current device. + /// + /// + /// A new entry is added to this list every time a shader is dispatched using this device. These cached items + /// are stored via a , meaning they will be collected automatically + /// when the device is collected. But, due to the fact that could happen at any time, a list is required to guarantee + /// the additional references added by the native objects in the pipeline model can be released immediately. + /// + private List cachedPipelineData; + /// /// Raised whenever the device is lost. /// @@ -170,6 +183,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject #endif this.deviceRemovedReason = S.S_OK; + this.cachedPipelineData = new List(); RegisterDeviceLostCallback(this, out this.deviceHandle, out this.deviceRemovedEvent, out this.deviceRemovedWaitHandle); } @@ -337,6 +351,21 @@ public sealed unsafe partial class GraphicsDevice : NativeObject #endif } + /// + /// Registers a object for the current device to enable early disposal. + /// + /// The instance just loaded to run a shader. + internal void RegisterPipelineData(PipelineData pipelineData) + { + // This is only used when first initializing a pipeline data for a given shader. + // Adding an item is very quick, so we can just use a lock and not a concurrent + // list. That would've added more overhead given the low contention in this case. + lock (this.cachedPipelineData) + { + this.cachedPipelineData.Add(pipelineData); + } + } + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void RentShaderResourceViewDescriptorHandles(out ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles) @@ -421,6 +450,16 @@ public sealed unsafe partial class GraphicsDevice : NativeObject #endif UnregisterDeviceLostCallback(this); + + // Explicitly release the cached pipeline objects as well. + // Locking is not needed here, as this method is only invoked + // when the device has been disposed and no other usage is active + // for the device (ie. no lease exists), meaning that no other + // thread could potentially add a new pipeline data concurrently. + foreach (PipelineData pipelineData in this.cachedPipelineData) + { + pipelineData.Dispose(); + } } /// diff --git a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs index 4af52e05..415e9b89 100644 --- a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs @@ -98,5 +98,8 @@ internal static class PipelineDataLoader pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get()); shaderData.CachedPipelines.Add(device, pipelineData); + + // Register the newly created pipeline data to enable early disposal + device.RegisterPipelineData(pipelineData); } } diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs index 113429b1..174b7b0d 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs @@ -12,7 +12,7 @@ namespace ComputeSharp.Tests.DeviceLost; [TestClass] [TestCategory("DeviceDisposal")] -public class DeviceDisposalTests +public partial class DeviceDisposalTests { [TestMethod] public unsafe void DeviceDisposal_GetDefault_ReferenceCounting() @@ -137,4 +137,78 @@ public class DeviceDisposalTests Assert.AreEqual(refCount, 1u); } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void DeviceDisposal_WithComputeShader_ReferenceCounting(Device device) + { + using ComPtr d3D12Device = default; + + using (GraphicsDevice graphicsDevice = device.Get()) + { + using var buffer = graphicsDevice.AllocateReadWriteBuffer(128); + + using (ComputeContext context = graphicsDevice.CreateComputeContext()) + { + context.For(buffer.Length, new InitializeShader(buffer)); + } + + InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + } + + _ = d3D12Device.Get()->AddRef(); + + uint refCount = d3D12Device.Get()->Release(); + + Assert.AreEqual(refCount, 1u); + } + + [EmbeddedBytecode(DispatchAxis.X)] + [AutoConstructor] + private partial struct InitializeShader : IComputeShader + { + private readonly ReadWriteBuffer buffer; + + public void Execute() + { + buffer[ThreadIds.X] = ThreadIds.X; + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void DeviceDisposal_WithPixelShader_ReferenceCounting(Device device) + { + using ComPtr d3D12Device = default; + + using (GraphicsDevice graphicsDevice = device.Get()) + { + using var texture = graphicsDevice.AllocateReadWriteTexture2D(128, 128); + + using (ComputeContext context = graphicsDevice.CreateComputeContext()) + { + context.ForEach(texture, default(HelloWorldShader)); + } + + InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + } + + _ = d3D12Device.Get()->AddRef(); + + uint refCount = d3D12Device.Get()->Release(); + + Assert.AreEqual(refCount, 1u); + } + + [EmbeddedBytecode(DispatchAxis.XY)] + private partial struct HelloWorldShader : IPixelShader + { + public float4 Execute() + { + float2 uv = ThreadIds.Normalized.XY; + float3 col = 0.5f + 0.5f * Hlsl.Cos(new float3(uv, uv.X) + new float3(0, 2, 4)); + + return new(col, 1f); + } + } } From 93a98a60ac751ce095855cc8d9c8c584dfc4e164 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 26 Jul 2022 13:03:50 +0200 Subject: [PATCH 45/64] Minor code refactoring --- .../Extensions/Interop/HResultExtensions.cs | 28 +++++++++++++++++++ .../Graphics/Helpers/DeviceHelper.cs | 16 ++--------- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs index 403dc0ba..85b7f135 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Runtime.CompilerServices; using CommunityToolkit.Diagnostics; using ComputeSharp.Graphics.Helpers; +using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; namespace ComputeSharp.Core.Extensions; @@ -64,4 +65,31 @@ internal static class HResultExtensions AssertWithDebugInfo(result); } } + + /// + /// Checks whether or not a given represents a device lost reason. + /// + /// The input to check. + /// Whether or not a given represents a device lost reason. + /// + /// An is a device lost reason when it has one of the following values: + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool IsDeviceLostReason(this HRESULT result) + { + return (int)result is + DXGI.DXGI_ERROR_DEVICE_HUNG or + DXGI.DXGI_ERROR_DEVICE_REMOVED or + DXGI.DXGI_ERROR_DEVICE_RESET or + DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR or + DXGI.DXGI_ERROR_INVALID_CALL or + DXGI.DXGI_ERROR_ACCESS_DENIED; + } } diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs index 256e4eab..54ae9364 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs @@ -105,13 +105,7 @@ internal static partial class DeviceHelper d3D12DeviceCandidate.GetVoidAddressOf()); // Check and throw if the device is a device lost state and not disposed properly - if ((int)createDeviceResult is - DXGI.DXGI_ERROR_DEVICE_HUNG or - DXGI.DXGI_ERROR_DEVICE_REMOVED or - DXGI.DXGI_ERROR_DEVICE_RESET or - DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR or - DXGI.DXGI_ERROR_INVALID_CALL or - DXGI.DXGI_ERROR_ACCESS_DENIED) + if (createDeviceResult.IsDeviceLostReason()) { ThrowHelper.ThrowInvalidOperationException("The default device is in device lost state and has not been disposed properly."); } @@ -157,13 +151,7 @@ internal static partial class DeviceHelper Windows.__uuidof(), d3D12DeviceCandidate.GetVoidAddressOf()); - if ((int)createDeviceResult is - DXGI.DXGI_ERROR_DEVICE_HUNG or - DXGI.DXGI_ERROR_DEVICE_REMOVED or - DXGI.DXGI_ERROR_DEVICE_RESET or - DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR or - DXGI.DXGI_ERROR_INVALID_CALL or - DXGI.DXGI_ERROR_ACCESS_DENIED) + if (createDeviceResult.IsDeviceLostReason()) { ThrowHelper.ThrowInvalidOperationException("The default device is in device lost state and has not been disposed properly."); } From 05eff37ff00002e227e720900cf03dc4e1588a97 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 26 Jul 2022 16:42:18 +0200 Subject: [PATCH 46/64] Optimize reference tracking logic Remove one object field and virtual stub dispatch calls --- .../Helpers/SwapChainManager.Rendering.cs | 16 +-- .../GraphicsDeviceMismatchException.cs | 6 +- .../GraphicsDeviceExtensions.Dispatching.cs | 2 +- .../Graphics/GraphicsDevice.DeviceLost.cs | 2 +- .../Graphics/GraphicsDevice.Execute.cs | 6 +- src/ComputeSharp/Graphics/GraphicsDevice.cs | 10 +- .../__Internals/GraphicsResourceHelper.cs | 10 +- .../Graphics/Interop/InteropServices.cs | 28 ++--- ...r.cs => NativeObject.ReferenceTracking.cs} | 115 ++++++------------ .../Graphics/Interop/NativeObject.cs | 49 ++++---- .../Graphics/Resources/Abstract/Buffer{T}.cs | 6 +- .../Resources/Abstract/StructuredBuffer{T}.cs | 26 ++-- .../Resources/Abstract/Texture2D{T}.cs | 36 +++--- .../Resources/Abstract/Texture3D{T}.cs | 36 +++--- .../Resources/Abstract/TransferBuffer{T}.cs | 8 +- .../Abstract/TransferTexture2D{T}.cs | 4 +- .../Abstract/TransferTexture3D{T}.cs | 4 +- .../Graphics/Resources/ConstantBuffer{T}.cs | 14 +-- .../ReadWriteTexture2D{T,TPixel}.ReadOnly.cs | 12 +- .../ReadWriteTexture2D{T}.ReadOnly.cs | 12 +- .../ReadWriteTexture3D{T,TPixel}.ReadOnly.cs | 12 +- .../ReadWriteTexture3D{T}.ReadOnly.cs | 12 +- src/ComputeSharp/Shaders/ComputeContext.cs | 10 +- 23 files changed, 192 insertions(+), 244 deletions(-) rename src/ComputeSharp/Graphics/Interop/{ReferenceTracker.cs => NativeObject.ReferenceTracking.cs} (55%) diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs index 38fde6a6..bf8e10f9 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -29,7 +29,7 @@ partial class SwapChainManager { Guard.IsNotNull(shaderRunner); - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); using (await this.setupSemaphore.LockAsync()) { @@ -71,7 +71,7 @@ partial class SwapChainManager /// Whether or not to use dynamic resolution. public async void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); using (await this.setupSemaphore.LockAsync()) { @@ -105,7 +105,7 @@ partial class SwapChainManager /// Whether or not to use vertical sync. public async void QueueVerticalSyncModeChange(bool isVerticalSyncEnabled) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); using (await this.setupSemaphore.LockAsync()) { @@ -140,7 +140,7 @@ partial class SwapChainManager /// The height of the render resolution. public void QueueResize(double width, double height) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); this.width = (float)width; this.height = (float)height; @@ -155,7 +155,7 @@ partial class SwapChainManager /// The composition scale on the Y axis public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); this.compositionScaleX = (float)compositionScaleX; this.compositionScaleY = (float)compositionScaleY; @@ -169,7 +169,7 @@ partial class SwapChainManager /// The resolution scale factor to use. public void QueueResolutionScaleChange(double resolutionScale) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); this.resolutionScale = (float)resolutionScale; @@ -190,13 +190,13 @@ partial class SwapChainManager this.dynamicResolutionScale = this.resolutionScale; // These two leases are needed to ensure the manager isn't disposed while rendering is running - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); RenderLoopWithDynamicResolution(); } else { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); RenderLoop(); } diff --git a/src/ComputeSharp/Graphics/Exceptions/GraphicsDeviceMismatchException.cs b/src/ComputeSharp/Graphics/Exceptions/GraphicsDeviceMismatchException.cs index 814a9d05..6283a35b 100644 --- a/src/ComputeSharp/Graphics/Exceptions/GraphicsDeviceMismatchException.cs +++ b/src/ComputeSharp/Graphics/Exceptions/GraphicsDeviceMismatchException.cs @@ -22,15 +22,15 @@ public sealed class GraphicsDeviceMismatchException : InvalidOperationException /// /// Creates a new instance from the specified parameters. /// - /// The input that was used. + /// The input that was used. /// The source instance tied to . /// The target instance that was used. /// A new instance with a formatted error message. /// - /// This method only takes a instance and the associated instance as + /// This method only takes a instance and the associated instance as /// will still be available, but without the unnecessary generic type specializations for the method. /// - private static GraphicsDeviceMismatchException Create(ReferenceTracker.ITrackedObject resource, GraphicsDevice sourceDevice, GraphicsDevice destinationDevice) + private static GraphicsDeviceMismatchException Create(NativeObject resource, GraphicsDevice sourceDevice, GraphicsDevice destinationDevice) { StringBuilder builder = new(512); diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs index 658d4da4..bf7c5ee9 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs @@ -150,7 +150,7 @@ public static partial class GraphicsDeviceExtensions { Guard.IsNotNull(device); - using var _0 = device.GetReferenceTracker().GetLease(); + using var _0 = device.GetReferenceTrackingLease(); device.ThrowIfDeviceLost(); diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index beeb283e..2950963f 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -48,7 +48,7 @@ unsafe partial class GraphicsDevice /// private void QueueRaiseDeviceLostEventIfNeeded() { - using var _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); + using var _0 = TryGetReferenceTrackingLease(out bool leaseTaken); if (!leaseTaken) { diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs index e8f55f5c..02f7f4a7 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs @@ -192,7 +192,7 @@ unsafe partial class GraphicsDevice HANDLE waitHandle; - device.GetReferenceTracker().DangerousAddRef(); + device.DangerousAddRef(); int result = Windows.RegisterWaitForSingleObject( phNewWaitObject: &waitHandle, @@ -209,7 +209,7 @@ unsafe partial class GraphicsDevice // The register is successful if the return value is nonzero if (result == 0) { - device.GetReferenceTracker().DangerousRelease(); + device.DangerousRelease(); NativeMemory.Free(callbackContext); @@ -241,7 +241,7 @@ unsafe partial class GraphicsDevice device.computeCommandListPool.Return(d3D12GraphicsCommandList, d3D12CommandAllocator); // Decrement the reference count that was incremented when scheduling the completion callback - device.GetReferenceTracker().DangerousRelease(); + device.DangerousRelease(); _ = Windows.CloseHandle(eventHandle); diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index c988f565..9f243bff 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -252,7 +252,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject /// Whether the current device supports double precision floating point operations in shaders. public bool IsDoublePrecisionSupportAvailable() { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceLost(); @@ -270,7 +270,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadOnlyTexture2DSupportedForType() where T : unmanaged { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceLost(); @@ -286,7 +286,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadWriteTexture2DSupportedForType() where T : unmanaged { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceLost(); @@ -304,7 +304,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadOnlyTexture3DSupportedForType() where T : unmanaged { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceLost(); @@ -320,7 +320,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadWriteTexture3DSupportedForType() where T : unmanaged { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceLost(); diff --git a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index a326435a..6b1c589a 100644 --- a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -64,7 +64,7 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(buffer); - using var _0 = buffer.GetReferenceTracker().GetLease(); + using var _0 = buffer.GetReferenceTrackingLease(); buffer.ThrowIfDeviceMismatch(device); @@ -86,7 +86,7 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - using var _0 = texture.GetReferenceTracker().GetLease(); + using var _0 = texture.GetReferenceTrackingLease(); texture.ThrowIfDeviceMismatch(device); @@ -108,7 +108,7 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - using var _0 = texture.GetReferenceTracker().GetLease(); + using var _0 = texture.GetReferenceTrackingLease(); texture.ThrowIfDeviceMismatch(device); @@ -199,7 +199,7 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - using var _0 = texture.GetReferenceTracker().GetLease(); + using var _0 = texture.GetReferenceTrackingLease(); texture.ThrowIfDeviceMismatch(device); @@ -221,7 +221,7 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - using var _0 = texture.GetReferenceTracker().GetLease(); + using var _0 = texture.GetReferenceTrackingLease(); texture.ThrowIfDeviceMismatch(device); diff --git a/src/ComputeSharp/Graphics/Interop/InteropServices.cs b/src/ComputeSharp/Graphics/Interop/InteropServices.cs index 4fa165e2..5427cb64 100644 --- a/src/ComputeSharp/Graphics/Interop/InteropServices.cs +++ b/src/ComputeSharp/Graphics/Interop/InteropServices.cs @@ -34,7 +34,7 @@ public static unsafe class InteropServices /// Thrown if the IUnknown::QueryInterface call doesn't return S_OK. public static void GetID3D12Device(GraphicsDevice device, Guid* riid, void** ppvObject) { - using var _0 = device.GetReferenceTracker().GetLease(); + using var _0 = device.GetReferenceTrackingLease(); device.D3D12Device->QueryInterface(riid, ppvObject).Assert(); } @@ -52,7 +52,7 @@ public static unsafe class InteropServices public static void GetID3D12Resource(Buffer buffer, Guid* riid, void** ppvObject) where T : unmanaged { - using var _0 = buffer.GetReferenceTracker().GetLease(); + using var _0 = buffer.GetReferenceTrackingLease(); buffer.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } @@ -70,7 +70,7 @@ public static unsafe class InteropServices public static void GetID3D12Resource(Texture2D texture, Guid* riid, void** ppvObject) where T : unmanaged { - using var _0 = texture.GetReferenceTracker().GetLease(); + using var _0 = texture.GetReferenceTrackingLease(); texture.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } @@ -88,7 +88,7 @@ public static unsafe class InteropServices public static void GetID3D12Resource(Texture3D texture, Guid* riid, void** ppvObject) where T : unmanaged { - using var _0 = texture.GetReferenceTracker().GetLease(); + using var _0 = texture.GetReferenceTrackingLease(); texture.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } @@ -106,7 +106,7 @@ public static unsafe class InteropServices public static void GetID3D12Resource(TransferBuffer buffer, Guid* riid, void** ppvObject) where T : unmanaged { - using var _0 = buffer.GetReferenceTracker().GetLease(); + using var _0 = buffer.GetReferenceTrackingLease(); buffer.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } @@ -124,7 +124,7 @@ public static unsafe class InteropServices public static void GetID3D12Resource(TransferTexture2D texture, Guid* riid, void** ppvObject) where T : unmanaged { - using var _0 = texture.GetReferenceTracker().GetLease(); + using var _0 = texture.GetReferenceTrackingLease(); texture.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } @@ -142,7 +142,7 @@ public static unsafe class InteropServices public static void GetID3D12Resource(TransferTexture3D texture, Guid* riid, void** ppvObject) where T : unmanaged { - using var _0 = texture.GetReferenceTracker().GetLease(); + using var _0 = texture.GetReferenceTrackingLease(); texture.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } @@ -161,7 +161,7 @@ public static unsafe class InteropServices /// The instance has been disposed. public static int TryGetID3D12Device(GraphicsDevice device, Guid* riid, void** ppvObject) { - using var _0 = device.GetReferenceTracker().GetLease(); + using var _0 = device.GetReferenceTrackingLease(); return device.D3D12Device->QueryInterface(riid, ppvObject); } @@ -182,7 +182,7 @@ public static unsafe class InteropServices public static int TryGetID3D12Resource(Buffer buffer, Guid* riid, void** ppvObject) where T : unmanaged { - using var _0 = buffer.GetReferenceTracker().GetLease(); + using var _0 = buffer.GetReferenceTrackingLease(); return buffer.D3D12Resource->QueryInterface(riid, ppvObject); } @@ -203,7 +203,7 @@ public static unsafe class InteropServices public static int TryGetID3D12Resource(Texture2D texture, Guid* riid, void** ppvObject) where T : unmanaged { - using var _0 = texture.GetReferenceTracker().GetLease(); + using var _0 = texture.GetReferenceTrackingLease(); return texture.D3D12Resource->QueryInterface(riid, ppvObject); } @@ -224,7 +224,7 @@ public static unsafe class InteropServices public static int TryGetID3D12Resource(Texture3D texture, Guid* riid, void** ppvObject) where T : unmanaged { - using var _0 = texture.GetReferenceTracker().GetLease(); + using var _0 = texture.GetReferenceTrackingLease(); return texture.D3D12Resource->QueryInterface(riid, ppvObject); } @@ -245,7 +245,7 @@ public static unsafe class InteropServices public static int TryGetID3D12Resource(TransferBuffer buffer, Guid* riid, void** ppvObject) where T : unmanaged { - using var _0 = buffer.GetReferenceTracker().GetLease(); + using var _0 = buffer.GetReferenceTrackingLease(); return buffer.D3D12Resource->QueryInterface(riid, ppvObject); } @@ -266,7 +266,7 @@ public static unsafe class InteropServices public static int TryGetID3D12Resource(TransferTexture2D texture, Guid* riid, void** ppvObject) where T : unmanaged { - using var _0 = texture.GetReferenceTracker().GetLease(); + using var _0 = texture.GetReferenceTrackingLease(); return texture.D3D12Resource->QueryInterface(riid, ppvObject); } @@ -287,7 +287,7 @@ public static unsafe class InteropServices public static int TryGetID3D12Resource(TransferTexture3D texture, Guid* riid, void** ppvObject) where T : unmanaged { - using var _0 = texture.GetReferenceTracker().GetLease(); + using var _0 = texture.GetReferenceTrackingLease(); return texture.D3D12Resource->QueryInterface(riid, ppvObject); } diff --git a/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs b/src/ComputeSharp/Graphics/Interop/NativeObject.ReferenceTracking.cs similarity index 55% rename from src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs rename to src/ComputeSharp/Graphics/Interop/NativeObject.ReferenceTracking.cs index 6d325165..a5c914d3 100644 --- a/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs +++ b/src/ComputeSharp/Graphics/Interop/NativeObject.ReferenceTracking.cs @@ -3,58 +3,28 @@ using System.Runtime.CompilerServices; namespace ComputeSharp.Interop; -/// -/// An object acting as reference tracked for a given managed object. -/// -internal struct ReferenceTracker : IDisposable +#pragma warning disable CS0618 + +/// +partial class NativeObject { - /// - /// The target object to track. - /// - private readonly ITrackedObject trackedObject; - - /// - /// An object to use to synchronize the reference tracking operations. - /// - private readonly object lockObject; - - /// - /// The number of existing reference tracking leases for . - /// - private int leasesCount; - - /// - /// Whether or not has been called on . - /// - private bool isDisposeRequested; - - /// - /// Creates a new instance with the specified paramters. - /// - /// The input tracked object to wrap. - public ReferenceTracker(ITrackedObject trackedObject) - { - this.trackedObject = trackedObject; - this.lockObject = new object(); - this.leasesCount = 0; - this.isDisposeRequested = false; - } - /// /// Adds an untracked reference to the underlying object. This needs to be released with . /// /// Thrown if the tracked object has been disposed. - public void DangerousAddRef() + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void DangerousAddRef() { - _ = GetLease(); + _ = GetReferenceTrackingLease(); } /// /// Decrements the reference count for the underlying object. A call to this API has to match a previous call. /// - public void DangerousRelease() + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void DangerousRelease() { - ReturnLease(); + ReturnReferenceTrackingLease(); } /// @@ -63,9 +33,9 @@ internal struct ReferenceTracker : IDisposable /// A object that can extend the lifetime of the tracked object. /// Thrown if the tracked object has been disposed. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Lease GetLease() + internal Lease GetReferenceTrackingLease() { - Lease lease = TryGetLease(out bool leaseTaken); + Lease lease = TryGetReferenceTrackingLease(out bool leaseTaken); if (!leaseTaken) { @@ -74,7 +44,7 @@ internal struct ReferenceTracker : IDisposable // as this method has a single basic block that always throws an exception. static void Throw(object trackedObject) => throw new ObjectDisposedException(trackedObject.ToString()); - Throw(this.trackedObject); + Throw(this); } return lease; @@ -85,7 +55,7 @@ internal struct ReferenceTracker : IDisposable /// /// Whether or not the returned value is enabled. /// A object that can extend the lifetime of the tracked object. - public Lease TryGetLease(out bool leaseTaken) + internal Lease TryGetReferenceTrackingLease(out bool leaseTaken) { bool success = true; @@ -101,24 +71,24 @@ internal struct ReferenceTracker : IDisposable } } - ITrackedObject? trackedObject; + NativeObject? nativeObject; if (success) { leaseTaken = true; - trackedObject = this.trackedObject; + nativeObject = this; } else { leaseTaken = false; - trackedObject = null; + nativeObject = null; } - return new(trackedObject); + return new(nativeObject); } /// - public void Dispose() + private void RequestDispose() { bool shouldRelease = false; @@ -140,14 +110,14 @@ internal struct ReferenceTracker : IDisposable if (shouldRelease) { - this.trackedObject.DangerousRelease(); + OnDispose(); } } /// /// Returns a given lease (ie. decrements the ref count for the tracked object). /// - private void ReturnLease() + private void ReturnReferenceTrackingLease() { bool shouldRelease = false; @@ -164,58 +134,41 @@ internal struct ReferenceTracker : IDisposable if (shouldRelease) { - this.trackedObject.DangerousRelease(); + OnDispose(); } } /// - /// A reference tracking lease to extend the lifetime of a given tracked object while in a given scope. + /// A reference tracking lease to extend the lifetime of a given instance while in a given scope. /// - public struct Lease : IDisposable + internal struct Lease : IDisposable { /// - /// The tracked object being wrapped, if any. + /// The instance being wrapped, if any. /// - private ITrackedObject? trackedObject; + private NativeObject? nativeObject; /// /// Creates a new instance with the specified parameters. /// - /// The input tracked object to wrap, if any. - public Lease(ITrackedObject? trackedObject) + /// The instance being wrapped, if any. + [Obsolete("This constructor is only meant to be called from within NativeObject.")] + public Lease(NativeObject? nativeObject) { - this.trackedObject = trackedObject; + this.nativeObject = nativeObject; } /// public void Dispose() { - ITrackedObject? trackedObject = this.trackedObject; + NativeObject? nativeObject = this.nativeObject; - this.trackedObject = null; + this.nativeObject = null; - if (trackedObject is not null) + if (nativeObject is not null) { - trackedObject.GetReferenceTracker().ReturnLease(); + nativeObject.ReturnReferenceTrackingLease(); } } } - - /// - /// An interface for an object being tracked by an owning object. - /// - public interface ITrackedObject - { - /// - /// Gets a reference to the owning for the object. - /// - /// A reference to the owning for the object. - ref ReferenceTracker GetReferenceTracker(); - - /// - /// Releases all resources (including unmanaged ones) for the tracked object. - /// - /// This method is guaranteed to only ever be called once for a given tracked object. - void DangerousRelease(); - } } diff --git a/src/ComputeSharp/Graphics/Interop/NativeObject.cs b/src/ComputeSharp/Graphics/Interop/NativeObject.cs index bfbc2c04..1057f476 100644 --- a/src/ComputeSharp/Graphics/Interop/NativeObject.cs +++ b/src/ComputeSharp/Graphics/Interop/NativeObject.cs @@ -1,24 +1,35 @@ using System; -using System.Runtime.CompilerServices; namespace ComputeSharp.Interop; /// /// Base class for a class. /// -public abstract class NativeObject : IDisposable, ReferenceTracker.ITrackedObject +public abstract partial class NativeObject : IDisposable { /// - /// The owning object for the current instance. + /// An object to use to synchronize the reference tracking operations. /// - private ReferenceTracker referenceTracker; + private readonly object lockObject; + + /// + /// The number of existing reference tracking leases for the current instance. + /// + private int leasesCount; + + /// + /// Whether or not has been called on the current instance. + /// + private bool isDisposeRequested; /// /// Creates a new instance. /// private protected NativeObject() { - this.referenceTracker = new ReferenceTracker(this); + this.lockObject = new object(); + this.leasesCount = 0; + this.isDisposeRequested = false; } /// @@ -26,36 +37,20 @@ public abstract class NativeObject : IDisposable, ReferenceTracker.ITrackedObjec /// ~NativeObject() { - this.referenceTracker.Dispose(); + RequestDispose(); } /// public void Dispose() { - this.referenceTracker.Dispose(); + RequestDispose(); GC.SuppressFinalize(this); } - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ref ReferenceTracker GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - ref ReferenceTracker ReferenceTracker.ITrackedObject.GetReferenceTracker() - { - return ref this.referenceTracker; - } - - /// - void ReferenceTracker.ITrackedObject.DangerousRelease() - { - OnDispose(); - } - - /// + /// + /// Releases all resources (including unmanaged ones) for the tracked object. + /// + /// This method is guaranteed to only ever be called once for a given tracked object. private protected abstract void OnDispose(); } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs index 69b53980..bb15e4c7 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs @@ -75,7 +75,7 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / elementSizeInBytes) & ~255); } - using var _0 = device.GetReferenceTracker().GetLease(); + using var _0 = device.GetReferenceTrackingLease(); device.ThrowIfDeviceLost(); @@ -233,7 +233,7 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceMismatch(device); @@ -245,7 +245,7 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource /// internal unsafe ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceMismatch(device); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs index a5b88ddc..81a977de 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs @@ -36,8 +36,8 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(sourceOffset, 0, Length); Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -111,9 +111,9 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(destinationOffset, 0, destination.Length); Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); - using var _2 = destination.GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -156,9 +156,9 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(destinationOffset, 0, destination.Length); Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); - using var _2 = destination.GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -197,8 +197,8 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(offset, 0, Length); Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -276,9 +276,9 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(destinationOffset, 0, Length); Guard.IsLessThanOrEqualTo(destinationOffset + count, Length, nameof(destinationOffset)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); - using var _2 = source.GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = source.GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs index 78876122..a2d2688d 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs @@ -75,7 +75,7 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - using var _0 = device.GetReferenceTracker().GetLease(); + using var _0 = device.GetReferenceTrackingLease(); device.ThrowIfDeviceLost(); @@ -178,8 +178,8 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); Guard.IsGreaterThanOrEqualTo(size, (nint)width * height); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -273,9 +273,9 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); - using var _2 = destination.GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -342,9 +342,9 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); - using var _2 = destination.GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -401,8 +401,8 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); Guard.IsGreaterThanOrEqualTo(size, (nint)width * height); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -494,9 +494,9 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); - using var _2 = source.GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = source.GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -583,7 +583,7 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceMismatch(device); @@ -595,7 +595,7 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceMismatch(device); @@ -605,7 +605,7 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// internal (D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceMismatch(device); @@ -622,7 +622,7 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceMismatch(device); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs index 090b3212..9da307fd 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs @@ -77,7 +77,7 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - using var _0 = device.GetReferenceTracker().GetLease(); + using var _0 = device.GetReferenceTrackingLease(); device.ThrowIfDeviceLost(); @@ -193,8 +193,8 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -300,9 +300,9 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); - using var _2 = destination.GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -378,9 +378,9 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); - using var _2 = destination.GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -442,8 +442,8 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -547,9 +547,9 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); - using var _2 = source.GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = source.GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -636,7 +636,7 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceMismatch(device); @@ -648,7 +648,7 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceMismatch(device); @@ -658,7 +658,7 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// internal (D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceMismatch(device); @@ -675,7 +675,7 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); ThrowIfDeviceMismatch(device); diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs index 93c68d5e..b227b2f8 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs @@ -47,7 +47,7 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource // The maximum length is set such that the aligned buffer size can't exceed uint.MaxValue Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / (uint)sizeof(T)) & ~255); - using var _0 = device.GetReferenceTracker().GetLease(); + using var _0 = device.GetReferenceTrackingLease(); device.ThrowIfDeviceLost(); @@ -94,7 +94,7 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); return new MemoryManager(this).Memory; } @@ -106,7 +106,7 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - using var _0 = GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); return new(this.mappedData, Length); } @@ -174,7 +174,7 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource { Guard.IsEqualTo(elementIndex, 0); - using var _0 = this.buffer.GetReferenceTracker().GetLease(); + using var _0 = this.buffer.GetReferenceTrackingLease(); return new(this.buffer.mappedData); } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs index 232e59ed..61c0c892 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs @@ -53,7 +53,7 @@ public unsafe abstract class TransferTexture2D : NativeObject, IGraphicsResou Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - using var _0 = device.GetReferenceTracker().GetLease(); + using var _0 = device.GetReferenceTrackingLease(); device.ThrowIfDeviceLost(); @@ -115,7 +115,7 @@ public unsafe abstract class TransferTexture2D : NativeObject, IGraphicsResou [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - using var _0 = this.GetReferenceTracker().GetLease(); + using var _0 = this.GetReferenceTrackingLease(); return new(this.mappedData, Width, Height, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs index 04bf0bb6..5f310119 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs @@ -55,7 +55,7 @@ public unsafe abstract class TransferTexture3D : NativeObject, IGraphicsResou Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); - using var _0 = device.GetReferenceTracker().GetLease(); + using var _0 = device.GetReferenceTrackingLease(); device.ThrowIfDeviceLost(); @@ -123,7 +123,7 @@ public unsafe abstract class TransferTexture3D : NativeObject, IGraphicsResou [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - using var _0 = this.GetReferenceTracker().GetLease(); + using var _0 = this.GetReferenceTrackingLease(); return new(this.mappedData, Width, Height, Depth, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); } diff --git a/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs index 490f9b6f..f7002cdc 100644 --- a/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs @@ -61,8 +61,8 @@ public sealed class ConstantBuffer : Buffer Guard.IsInRange(offset, 0, Length); Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -91,9 +91,9 @@ public sealed class ConstantBuffer : Buffer Guard.IsInRange(destinationOffset, 0, destination.Length); Guard.IsLessThanOrEqualTo(destinationOffset + length, destination.Length, nameof(destinationOffset)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); - using var _2 = destination.GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -123,8 +123,8 @@ public sealed class ConstantBuffer : Buffer Guard.IsInRange(offset, 0, Length); Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs index 925c63e8..0e0373ee 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs @@ -24,8 +24,8 @@ partial class ReadWriteTexture2D /// internal IReadOnlyNormalizedTexture2D AsReadOnly() { - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -107,8 +107,8 @@ partial class ReadWriteTexture2D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); - using var _1 = this.owner.GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); this.owner.ThrowIfDeviceMismatch(device); @@ -124,8 +124,8 @@ partial class ReadWriteTexture2D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); - using var _1 = this.owner.GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); this.owner.ThrowIfDeviceMismatch(device); diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs index b1ea02fc..4b89fcf0 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs @@ -24,8 +24,8 @@ partial class ReadWriteTexture2D /// public IReadOnlyTexture2D AsReadOnly() { - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -110,8 +110,8 @@ partial class ReadWriteTexture2D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); - using var _1 = this.owner.GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); this.owner.ThrowIfDeviceMismatch(device); @@ -127,8 +127,8 @@ partial class ReadWriteTexture2D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); - using var _1 = this.owner.GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); this.owner.ThrowIfDeviceMismatch(device); diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs index 96e35601..5c756a31 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs @@ -24,8 +24,8 @@ partial class ReadWriteTexture3D /// public IReadOnlyNormalizedTexture3D AsReadOnly() { - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -110,8 +110,8 @@ partial class ReadWriteTexture3D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); - using var _1 = this.owner.GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); this.owner.ThrowIfDeviceMismatch(device); @@ -127,8 +127,8 @@ partial class ReadWriteTexture3D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); - using var _1 = this.owner.GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); this.owner.ThrowIfDeviceMismatch(device); diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs index db0e67d1..2fd55a24 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs @@ -24,8 +24,8 @@ partial class ReadWriteTexture3D /// public IReadOnlyTexture3D AsReadOnly() { - using var _0 = GraphicsDevice.GetReferenceTracker().GetLease(); - using var _1 = GetReferenceTracker().GetLease(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); GraphicsDevice.ThrowIfDeviceLost(); @@ -110,8 +110,8 @@ partial class ReadWriteTexture3D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); - using var _1 = this.owner.GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); this.owner.ThrowIfDeviceMismatch(device); @@ -127,8 +127,8 @@ partial class ReadWriteTexture3D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - using var _0 = GetReferenceTracker().GetLease(); - using var _1 = this.owner.GetReferenceTracker().GetLease(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); this.owner.ThrowIfDeviceMismatch(device); diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs index 6210664c..d7021e83 100644 --- a/src/ComputeSharp/Shaders/ComputeContext.cs +++ b/src/ComputeSharp/Shaders/ComputeContext.cs @@ -50,7 +50,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable // Increment the reference count for the device. This has to be released when disposing the context. // Not disposing the context is undefined behavior, so we can rely on that to release the reference. - device.GetReferenceTracker().DangerousAddRef(); + device.DangerousAddRef(); } /// @@ -305,7 +305,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable if (!this.commandList.IsAllocated) { - device.GetReferenceTracker().DangerousRelease(); + device.DangerousRelease(); return; } @@ -316,7 +316,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable } finally { - device.GetReferenceTracker().DangerousRelease(); + device.DangerousRelease(); } } @@ -332,7 +332,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable if (!this.commandList.IsAllocated) { - device.GetReferenceTracker().DangerousRelease(); + device.DangerousRelease(); #if NET6_0_OR_GREATER return ValueTask.CompletedTask; @@ -347,7 +347,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable } finally { - device.GetReferenceTracker().DangerousRelease(); + device.DangerousRelease(); } } From 33983506a93314a4ff495d985be3f8c8dba5b541 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 26 Jul 2022 19:10:04 +0200 Subject: [PATCH 47/64] Add Disposed event to compute shader panels --- .../Controls/AnimatedComputeShaderPanel.Properties.cs | 9 +++++++++ .../Controls/ComputeShaderPanel.Properties.cs | 9 +++++++++ .../Helpers/SwapChainManager.Rendering.cs | 8 ++++++++ src/ComputeSharp.UI/Helpers/SwapChainManager.cs | 7 +++++++ 4 files changed, 33 insertions(+) diff --git a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs index 912de608..2a08c9d5 100644 --- a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs @@ -42,6 +42,15 @@ partial class AnimatedComputeShaderPanel remove => this.swapChainManager.RenderingFailed -= value; } + /// + /// Raised whenever the control is disposed and all underlying resources are released. + /// + public event TypedEventHandler? Disposed + { + add => this.swapChainManager.Disposed += value; + remove => this.swapChainManager.Disposed -= value; + } + /// /// Gets or sets the instance to use to render content. /// diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs index 7c76dc3c..aed165f1 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs @@ -42,6 +42,15 @@ partial class ComputeShaderPanel remove => this.swapChainManager.RenderingFailed -= value; } + /// + /// Raised whenever the control is disposed and all underlying resources are released. + /// + public event TypedEventHandler? Disposed + { + add => this.swapChainManager.Disposed += value; + remove => this.swapChainManager.Disposed -= value; + } + /// /// Gets or sets the instance to use to request new frames. /// diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs index bf8e10f9..7cd9f29b 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -425,6 +425,14 @@ partial class SwapChainManager _ = this.dispatcherQueue.TryEnqueue(() => RenderingFailed?.Invoke(this.owner, e)); } + /// + /// Raises . + /// + private void OnDisposed() + { + _ = this.dispatcherQueue.TryEnqueue(() => Disposed?.Invoke(this.owner, EventArgs.Empty)); + } + /// /// Stops the current render loop, if one is running, and waits for it. /// diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index d26f6a25..5166414c 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -223,6 +223,11 @@ internal sealed unsafe partial class SwapChainManager : NativeObject /// public event TypedEventHandler? RenderingFailed; + /// + /// Raised whenever the parent control is disposed and all underlying resources are released. + /// + public event TypedEventHandler? Disposed; + /// /// Initializes a new instance of the type. /// @@ -549,6 +554,8 @@ internal sealed unsafe partial class SwapChainManager : NativeObject @this.d3D12Resource0.Dispose(); @this.d3D12Resource1.Dispose(); @this.texture?.Dispose(); + + @this.OnDisposed(); }, this); } } From 1226da5b4b97012a68c4e7d50193640ace0e6674 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 27 Jul 2022 17:43:04 +0200 Subject: [PATCH 48/64] Add unit tests for NativeObject dispose logic --- .../NativeObjectTests.cs | 180 ++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 tests/ComputeSharp.Tests.Internals/NativeObjectTests.cs diff --git a/tests/ComputeSharp.Tests.Internals/NativeObjectTests.cs b/tests/ComputeSharp.Tests.Internals/NativeObjectTests.cs new file mode 100644 index 00000000..f5a387a0 --- /dev/null +++ b/tests/ComputeSharp.Tests.Internals/NativeObjectTests.cs @@ -0,0 +1,180 @@ +using System; +using System.Threading.Tasks; +using ComputeSharp.Interop; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests.Internals; + +[TestClass] +[TestCategory("NativeObject")] +public class NativeObjectTests +{ + [TestMethod] + public void NormalDispose_GettingLeasesFails() + { + DisposableObject obj = new(); + + obj.Dispose(); + + Assert.IsTrue(obj.IsDisposed); + + using var _ = obj.TryGetReferenceTrackingLease(out bool leaseTaken); + + Assert.IsFalse(leaseTaken); + + Assert.ThrowsException(() => obj.GetReferenceTrackingLease()); + } + + [TestMethod] + public void DisposeWithLease() + { + DisposableObject obj = new(); + + var lease0 = obj.GetReferenceTrackingLease(); + + obj.Dispose(); + + Assert.IsFalse(obj.IsDisposed); + + lease0.Dispose(); + + Assert.IsTrue(obj.IsDisposed); + + // This doesn't do anything + lease0.Dispose(); + } + + [TestMethod] + public void DisposeWithTryGetLease() + { + DisposableObject obj = new(); + + var lease0 = obj.TryGetReferenceTrackingLease(out bool leaseTaken); + + Assert.IsTrue(leaseTaken); + + obj.Dispose(); + + Assert.IsFalse(obj.IsDisposed); + + lease0.Dispose(); + + Assert.IsTrue(obj.IsDisposed); + + lease0.Dispose(); + } + + [TestMethod] + public void DisposeWithDangerousAddRefsAndRelease() + { + DisposableObject obj = new(); + + obj.DangerousAddRef(); + + obj.Dispose(); + + Assert.IsFalse(obj.IsDisposed); + + obj.DangerousRelease(); + + Assert.IsTrue(obj.IsDisposed); + } + + [TestMethod] + public void Dispose_Multithreaded() + { + DisposableObject obj = new(); + + Parallel.For(0, 2048, i => + { + for (int j = 0; j < 4; j++) + { + using var lease = obj.GetReferenceTrackingLease(); + } + }); + + Assert.IsFalse(obj.IsDisposed); + + obj.Dispose(); + + Assert.IsTrue(obj.IsDisposed); + } + + [TestMethod] + public void Dispose_MultithreadedWithConcurrentDispose() + { + DisposableObject obj = new(); + + Parallel.For(0, 2048, i => + { + bool isDisposed = false; + + if (i == 1024) + { + isDisposed = true; + + obj.Dispose(); + } + + for (int j = 0; j < 4; j++) + { + using var lease = obj.TryGetReferenceTrackingLease(out bool leaseTaken); + + if (isDisposed) + { + Assert.IsFalse(leaseTaken); + } + } + }); + + Assert.IsTrue(obj.IsDisposed); + } + + [TestMethod] + public void Dispose_MultithreadedWithConcurrentDisposeAndOutstandingLease() + { + DisposableObject obj = new(); + + var outstandingLease = obj.GetReferenceTrackingLease(); + + Parallel.For(0, 2048, i => + { + bool isDisposed = false; + + if (i == 1024) + { + isDisposed = true; + + obj.Dispose(); + } + + for (int j = 0; j < 4; j++) + { + using var lease = obj.TryGetReferenceTrackingLease(out bool leaseTaken); + + if (isDisposed) + { + Assert.IsFalse(leaseTaken); + } + } + }); + + Assert.IsFalse(obj.IsDisposed); + + outstandingLease.Dispose(); + + Assert.IsTrue(obj.IsDisposed); + } + + private sealed class DisposableObject : NativeObject + { + public bool IsDisposed { get; private set; } + + private protected override void OnDispose() + { + Assert.IsFalse(IsDisposed); + + IsDisposed = true; + } + } +} From 2623754991bcd57f850bb21653040b7602f430d8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 27 Jul 2022 23:20:54 +0200 Subject: [PATCH 49/64] Fix shader panels Dispose() logic when called off the UI thread --- .../Helpers/SwapChainManager.cs | 87 ++++++++++++------- 1 file changed, 54 insertions(+), 33 deletions(-) diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 5166414c..aa1fc4ef 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -1,9 +1,8 @@ using System; using System.Diagnostics; +using System.Runtime.CompilerServices; #if WINDOWS_UWP using System.Runtime.InteropServices; -#else -using System.Runtime.CompilerServices; #endif using System.Threading; using ComputeSharp.Core.Extensions; @@ -518,44 +517,66 @@ internal sealed unsafe partial class SwapChainManager : NativeObject /// private protected override void OnDispose() { - // Even while rendering is still running, we need to properly release all implicit references - // that have been added when connecting the swap chain panel that was used. To do that, the - // same ISwapChainPanelNative::SetSwapChain API has to be called, but passing null as the - // target swap chain. This is handled correctly in the implementation, and all the additional - // references to the swap chain we passed during initialization will be dropped. Once that - // is done, we can then dispose our reference to the underlying swap chain panel for the control. - // This API has to be called on the UI thread, and it can be called just fine even if rendering - // is still running, so we can just call it immediately before moving to a thread to stop rendering. - this.swapChainPanelNative.Get()->SetSwapChain(null).Assert(); - this.swapChainPanelNative.Dispose(); - - ThreadPool.UnsafeQueueUserWorkItem(static state => + static void OnDisposeOnDispatcherQueueThread(SwapChainManager @this) { - SwapChainManager @this = (SwapChainManager)state!; + // Even while rendering is still running, we need to properly release all implicit references + // that have been added when connecting the swap chain panel that was used. To do that, the + // same ISwapChainPanelNative::SetSwapChain API has to be called, but passing null as the + // target swap chain. This is handled correctly in the implementation, and all the additional + // references to the swap chain we passed during initialization will be dropped. Once that + // is done, we can then dispose our reference to the underlying swap chain panel for the control. + // This API has to be called on the UI thread, and it can be called just fine even if rendering + // is still running, so we can just call it immediately before moving to a thread to stop rendering. + @this.swapChainPanelNative.Get()->SetSwapChain(null).Assert(); + @this.swapChainPanelNative.Dispose(); - @this.UnsafeStopRenderLoopAndWait(); + ThreadPool.UnsafeQueueUserWorkItem(static state => + { + SwapChainManager @this = (SwapChainManager)state!; - ulong updatedFenceValue = @this.nextD3D12FenceValue + 1; + @this.UnsafeStopRenderLoopAndWait(); - @this.d3D12CommandQueue.Get()->Signal(@this.d3D12Fence.Get(), updatedFenceValue).Assert(); + ulong updatedFenceValue = @this.nextD3D12FenceValue + 1; - // Just like in the resize logic, signal and wait to make sure no operations are pending. This - // is needed to avoid a crash when disposing resources when disposing after stopping rendering. - @this.d3D12Fence.Get()->SetEventOnCompletion(updatedFenceValue, default).Assert(); + @this.d3D12CommandQueue.Get()->Signal(@this.d3D12Fence.Get(), updatedFenceValue).Assert(); - _ = Win32.CloseHandle(@this.frameLatencyWaitableObject); + // Just like in the resize logic, signal and wait to make sure no operations are pending. This + // is needed to avoid a crash when disposing resources when disposing after stopping rendering. + @this.d3D12Fence.Get()->SetEventOnCompletion(updatedFenceValue, default).Assert(); - @this.d3D12Device.Dispose(); - @this.d3D12CommandQueue.Dispose(); - @this.d3D12Fence.Dispose(); - @this.d3D12CommandAllocator.Dispose(); - @this.d3D12GraphicsCommandList.Dispose(); - @this.dxgiSwapChain3.Dispose(); - @this.d3D12Resource0.Dispose(); - @this.d3D12Resource1.Dispose(); - @this.texture?.Dispose(); + _ = Win32.CloseHandle(@this.frameLatencyWaitableObject); - @this.OnDisposed(); - }, this); + @this.d3D12Device.Dispose(); + @this.d3D12CommandQueue.Dispose(); + @this.d3D12Fence.Dispose(); + @this.d3D12CommandAllocator.Dispose(); + @this.d3D12GraphicsCommandList.Dispose(); + @this.dxgiSwapChain3.Dispose(); + @this.d3D12Resource0.Dispose(); + @this.d3D12Resource1.Dispose(); + @this.texture?.Dispose(); + + @this.OnDisposed(); + }, @this); + } + + // Check whether the current thread is the one associated with the dispatcher queue. If so, the dispose + // logic can be called directly, otherwise an extra dispatch is needed. This is because the start of + // the dispose logic requires UI thread access to interact with the swap chain panel. + if (this.dispatcherQueue.HasThreadAccess) + { + OnDisposeOnDispatcherQueueThread(this); + } + else + { + [MethodImpl(MethodImplOptions.NoInlining)] + static void OnDisposeOnThreadPoolThread(SwapChainManager @this) + { + _ = @this.dispatcherQueue.TryEnqueue(() => OnDisposeOnDispatcherQueueThread(@this)); + } + + // Move to a separate queue to skip the closure when lowering this method, if not needed + OnDisposeOnThreadPoolThread(this); + } } } From 37823f366c836614c6e5d69826d8a619817f06de Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 29 Jul 2022 01:35:17 +0200 Subject: [PATCH 50/64] Move GPU disposal tests to DeviceLost test project --- .../DeviceDisposalTests.cs | 4 ++ .../GetDefaultDeviceTests.cs | 43 +++++++++++++++++++ tests/ComputeSharp.Tests/BufferTests.cs | 27 ------------ .../ComputeSharp.Tests/InitializationTests.cs | 10 ----- tests/ComputeSharp.Tests/Texture2DTests.cs | 26 ----------- tests/ComputeSharp.Tests/Texture3DTests.cs | 26 ----------- .../ComputeSharp.Tests/TransferBufferTests.cs | 26 ----------- .../TransferTexture2DTests.cs | 26 ----------- .../TransferTexture3DTests.cs | 26 ----------- 9 files changed, 47 insertions(+), 167 deletions(-) diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs index 174b7b0d..6c6b9070 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs @@ -86,6 +86,10 @@ public partial class DeviceDisposalTests using var r3 = graphicsDevice.AllocateReadWriteBuffer(128); using var r4 = graphicsDevice.AllocateReadOnlyTexture2D(128, 128); using var r5 = graphicsDevice.AllocateReadWriteTexture2D(128, 128); + using var r6 = graphicsDevice.AllocateUploadBuffer(128); + using var r7 = graphicsDevice.AllocateReadBackBuffer(128); + using var r8 = graphicsDevice.AllocateUploadTexture2D(128, 128); + using var r9 = graphicsDevice.AllocateReadBackTexture2D(128, 128); InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); } diff --git a/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs b/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs index b5ae5c3f..be8c93b5 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs @@ -73,4 +73,47 @@ public class GetDefaultDeviceTests GetDefault_VerifyContract_Part2(); } + + [TestMethod] + public unsafe void GetDefault_DisposeAndUseNewInstance() + { + using (ComPtr d3D12Device = default) + { + GraphicsDevice device = GraphicsDevice.GetDefault(); + + using (device.AllocateReadOnlyBuffer(128)) + { + } + + InteropServices.GetID3D12Device(device, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + + device.Dispose(); + + _ = d3D12Device.Get()->AddRef(); + + uint refCount = d3D12Device.Get()->Release(); + + Assert.AreEqual(refCount, 1u); + } + + // Just same test but twice, just for good measure + using (ComPtr d3D12Device = default) + { + GraphicsDevice device = GraphicsDevice.GetDefault(); + + using (device.AllocateReadOnlyBuffer(128)) + { + } + + InteropServices.GetID3D12Device(device, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + + device.Dispose(); + + _ = d3D12Device.Get()->AddRef(); + + uint refCount = d3D12Device.Get()->Release(); + + Assert.AreEqual(refCount, 1u); + } + } } diff --git a/tests/ComputeSharp.Tests/BufferTests.cs b/tests/ComputeSharp.Tests/BufferTests.cs index 39370cfc..4e468e16 100644 --- a/tests/ComputeSharp.Tests/BufferTests.cs +++ b/tests/ComputeSharp.Tests/BufferTests.cs @@ -124,33 +124,6 @@ public partial class BufferTests _ = buffer.ToArray(); } - [CombinatorialTestMethod] - [AllDevices] - [Resource(typeof(ConstantBuffer<>))] - [Resource(typeof(ReadOnlyBuffer<>))] - [Resource(typeof(ReadWriteBuffer<>))] - public void DisposeAfterDevice(Device device, Type bufferType) - { - GraphicsDevice? gpu = device switch - { - Device.Discrete => GraphicsDevice.QueryDevices(info => info.IsHardwareAccelerated).FirstOrDefault(), - Device.Warp => GraphicsDevice.QueryDevices(info => !info.IsHardwareAccelerated).First(), - _ => throw new ArgumentException(nameof(device)) - }; - - if (gpu is null) - { - Assert.Inconclusive(); - - return; - } - - Buffer buffer = gpu.AllocateBuffer(bufferType, 128); - - gpu.Dispose(); - buffer.Dispose(); - } - [CombinatorialTestMethod] [AllDevices] [Resource(typeof(ConstantBuffer<>))] diff --git a/tests/ComputeSharp.Tests/InitializationTests.cs b/tests/ComputeSharp.Tests/InitializationTests.cs index 0b5f1496..3609519c 100644 --- a/tests/ComputeSharp.Tests/InitializationTests.cs +++ b/tests/ComputeSharp.Tests/InitializationTests.cs @@ -28,16 +28,6 @@ public partial class InitializationTests Assert.IsTrue(gpu.WavefrontSize != 0); } - [TestMethod] - public void DisposeDefault() - { - using var before = GraphicsDevice.GetDefault().AllocateReadOnlyBuffer(128); - - GraphicsDevice.GetDefault().Dispose(); - - using var after = GraphicsDevice.GetDefault().AllocateReadOnlyBuffer(128); - } - [TestMethod] public void EnumerateDevices() { diff --git a/tests/ComputeSharp.Tests/Texture2DTests.cs b/tests/ComputeSharp.Tests/Texture2DTests.cs index 32d782f7..a72642a4 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.cs @@ -86,32 +86,6 @@ public partial class Texture2DTests _ = texture.ToArray(); } - [CombinatorialTestMethod] - [AllDevices] - [Resource(typeof(ReadOnlyTexture2D<>))] - [Resource(typeof(ReadWriteTexture2D<>))] - public void DisposeAfterDevice(Device device, Type textureType) - { - GraphicsDevice? gpu = device switch - { - Device.Discrete => GraphicsDevice.QueryDevices(info => info.IsHardwareAccelerated).FirstOrDefault(), - Device.Warp => GraphicsDevice.QueryDevices(info => !info.IsHardwareAccelerated).First(), - _ => throw new ArgumentException(nameof(device)) - }; - - if (gpu is null) - { - Assert.Inconclusive(); - - return; - } - - Texture2D texture = gpu.AllocateTexture2D(textureType, 10, 10); - - gpu.Dispose(); - texture.Dispose(); - } - [CombinatorialTestMethod] [AllDevices] [Resource(typeof(ReadOnlyTexture2D<>))] diff --git a/tests/ComputeSharp.Tests/Texture3DTests.cs b/tests/ComputeSharp.Tests/Texture3DTests.cs index c05252bc..80dbcdbe 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.cs +++ b/tests/ComputeSharp.Tests/Texture3DTests.cs @@ -105,32 +105,6 @@ public partial class Texture3DTests _ = texture.ToArray(); } - [CombinatorialTestMethod] - [AllDevices] - [Resource(typeof(ReadOnlyTexture3D<>))] - [Resource(typeof(ReadWriteTexture3D<>))] - public void DisposeAfterDevice(Device device, Type textureType) - { - GraphicsDevice? gpu = device switch - { - Device.Discrete => GraphicsDevice.QueryDevices(info => info.IsHardwareAccelerated).FirstOrDefault(), - Device.Warp => GraphicsDevice.QueryDevices(info => !info.IsHardwareAccelerated).First(), - _ => throw new ArgumentException(nameof(device)) - }; - - if (gpu is null) - { - Assert.Inconclusive(); - - return; - } - - Texture3D texture = gpu.AllocateTexture3D(textureType, 10, 10, 4); - - gpu.Dispose(); - texture.Dispose(); - } - [CombinatorialTestMethod] [AllDevices] [Resource(typeof(ReadOnlyTexture3D<>))] diff --git a/tests/ComputeSharp.Tests/TransferBufferTests.cs b/tests/ComputeSharp.Tests/TransferBufferTests.cs index 9d454bb4..62900553 100644 --- a/tests/ComputeSharp.Tests/TransferBufferTests.cs +++ b/tests/ComputeSharp.Tests/TransferBufferTests.cs @@ -66,32 +66,6 @@ public partial class TransferBufferTests _ = buffer.Span; } - [CombinatorialTestMethod] - [AllDevices] - [Resource(typeof(UploadBuffer<>))] - [Resource(typeof(ReadBackBuffer<>))] - public void DisposeAfterDevice(Device device, Type bufferType) - { - GraphicsDevice? gpu = device switch - { - Device.Discrete => GraphicsDevice.QueryDevices(info => info.IsHardwareAccelerated).FirstOrDefault(), - Device.Warp => GraphicsDevice.QueryDevices(info => !info.IsHardwareAccelerated).First(), - _ => throw new ArgumentException(nameof(device)) - }; - - if (gpu is null) - { - Assert.Inconclusive(); - - return; - } - - TransferBuffer buffer = gpu.AllocateTransferBuffer(bufferType, 128); - - gpu.Dispose(); - buffer.Dispose(); - } - [CombinatorialTestMethod] [AllDevices] public void Allocate_UploadBuffer_CopyTo_Full(Device device) diff --git a/tests/ComputeSharp.Tests/TransferTexture2DTests.cs b/tests/ComputeSharp.Tests/TransferTexture2DTests.cs index 9b4de975..82fe3d4d 100644 --- a/tests/ComputeSharp.Tests/TransferTexture2DTests.cs +++ b/tests/ComputeSharp.Tests/TransferTexture2DTests.cs @@ -70,32 +70,6 @@ public partial class TransferTexture2DTests _ = texture.View; } - [CombinatorialTestMethod] - [AllDevices] - [Resource(typeof(UploadTexture2D<>))] - [Resource(typeof(ReadBackTexture2D<>))] - public void DisposeAfterDevice(Device device, Type textureType) - { - GraphicsDevice? gpu = device switch - { - Device.Discrete => GraphicsDevice.QueryDevices(info => info.IsHardwareAccelerated).FirstOrDefault(), - Device.Warp => GraphicsDevice.QueryDevices(info => !info.IsHardwareAccelerated).First(), - _ => throw new ArgumentException(nameof(device)) - }; - - if (gpu is null) - { - Assert.Inconclusive(); - - return; - } - - TransferTexture2D texture = gpu.AllocateTransferTexture2D(textureType, 32, 32); - - gpu.Dispose(); - texture.Dispose(); - } - [CombinatorialTestMethod] [AllDevices] public unsafe void Allocate_UploadTexture2D_Copy_Full(Device device) diff --git a/tests/ComputeSharp.Tests/TransferTexture3DTests.cs b/tests/ComputeSharp.Tests/TransferTexture3DTests.cs index ca13f03b..54c0fa53 100644 --- a/tests/ComputeSharp.Tests/TransferTexture3DTests.cs +++ b/tests/ComputeSharp.Tests/TransferTexture3DTests.cs @@ -77,32 +77,6 @@ public partial class TransferTexture3DTests _ = texture.View; } - [CombinatorialTestMethod] - [AllDevices] - [Resource(typeof(UploadTexture3D<>))] - [Resource(typeof(ReadBackTexture3D<>))] - public void DisposeAfterDevice(Device device, Type textureType) - { - GraphicsDevice? gpu = device switch - { - Device.Discrete => GraphicsDevice.QueryDevices(info => info.IsHardwareAccelerated).FirstOrDefault(), - Device.Warp => GraphicsDevice.QueryDevices(info => !info.IsHardwareAccelerated).First(), - _ => throw new ArgumentException(nameof(device)) - }; - - if (gpu is null) - { - Assert.Inconclusive(); - - return; - } - - TransferTexture3D texture = gpu.AllocateTransferTexture3D(textureType, 32, 32, 16); - - gpu.Dispose(); - texture.Dispose(); - } - [CombinatorialTestMethod] [AllDevices] public unsafe void Allocate_UploadTexture3D_Copy_Full(Device device) From 748f14d7fdabb1c9f780812ee777de3e6dd021bb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 29 Jul 2022 01:51:06 +0200 Subject: [PATCH 51/64] Switch to cached devices in ComputeSharp tests --- .../ComputeSharp.Tests.DeviceLost.csproj | 1 - .../Extensions/DeviceExtensions.cs | 57 +++++++++++++++++++ .../Extensions/DeviceExtensions.cs | 23 +++++++- 3 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 tests/ComputeSharp.Tests.DeviceLost/Extensions/DeviceExtensions.cs diff --git a/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj b/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj index ebc7641b..24bb2044 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj +++ b/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj @@ -37,7 +37,6 @@ - diff --git a/tests/ComputeSharp.Tests.DeviceLost/Extensions/DeviceExtensions.cs b/tests/ComputeSharp.Tests.DeviceLost/Extensions/DeviceExtensions.cs new file mode 100644 index 00000000..983083bb --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/Extensions/DeviceExtensions.cs @@ -0,0 +1,57 @@ +using System.Linq; +using CommunityToolkit.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests.Extensions; + +/// +/// A helper class for testing APIs. +/// +public static class DeviceExtensions +{ + /// + /// Gets a instance matching a specified type. + /// + /// The device to retrieve. + /// The device of the requested type. + /// Thrown when the requested device is not present. + public static GraphicsDevice Get(this Device type) + { + GraphicsDevice? device = type switch + { + Device.Discrete => GraphicsDevice.QueryDevices(info => info.IsHardwareAccelerated).FirstOrDefault(), + Device.Warp => GraphicsDevice.QueryDevices(info => !info.IsHardwareAccelerated).FirstOrDefault(), + _ => ThrowHelper.ThrowArgumentException("Invalid device.") + }; + + if (device is null) + { + // If the device is null, fail only if the device was WARP (as it should always be available). + // If a dedicated device was requested instead, just report the test as inconclusive (no GPU). + switch (type) + { + case Device.Discrete: Assert.Inconclusive(); break; + case Device.Warp: Assert.Fail(); break; + } + + } + + return device!; + } +} + +/// +/// Indicates a specific compute device. +/// +public enum Device +{ + /// + /// A discrete device. + /// + Discrete, + + /// + /// A WARP device (software fallback). + /// + Warp +} diff --git a/tests/ComputeSharp.Tests/Extensions/DeviceExtensions.cs b/tests/ComputeSharp.Tests/Extensions/DeviceExtensions.cs index 983083bb..07a3b3ac 100644 --- a/tests/ComputeSharp.Tests/Extensions/DeviceExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/DeviceExtensions.cs @@ -9,6 +9,25 @@ namespace ComputeSharp.Tests.Extensions; /// public static class DeviceExtensions { + /// + /// The instance for the discrete device. + /// + private static readonly GraphicsDevice? DiscreteDevice; + + /// + /// The instance for the WARP device. + /// + private static readonly GraphicsDevice? WarpDevice; + + /// + /// Initializes and . + /// + static DeviceExtensions() + { + DiscreteDevice = GraphicsDevice.QueryDevices(info => info.IsHardwareAccelerated).FirstOrDefault(); + WarpDevice = GraphicsDevice.QueryDevices(info => !info.IsHardwareAccelerated).FirstOrDefault(); + } + /// /// Gets a instance matching a specified type. /// @@ -19,8 +38,8 @@ public static class DeviceExtensions { GraphicsDevice? device = type switch { - Device.Discrete => GraphicsDevice.QueryDevices(info => info.IsHardwareAccelerated).FirstOrDefault(), - Device.Warp => GraphicsDevice.QueryDevices(info => !info.IsHardwareAccelerated).FirstOrDefault(), + Device.Discrete => DiscreteDevice, + Device.Warp => WarpDevice, _ => ThrowHelper.ThrowArgumentException("Invalid device.") }; From 02ec241dde3248b0d2106ff6a0e73dcd96f9de50 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 29 Jul 2022 18:41:36 +0200 Subject: [PATCH 52/64] Restore unit test checks before publishing nightlies --- .github/workflows/dotnet.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 91ee8fb0..a91dfdb1 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -394,7 +394,7 @@ jobs: # Publish the packages to GitHub packages publish-nightlies-github: - needs: [verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs] + needs: [run-dx12-tests, run-dx12-device-lost-tests, run-d2d1-tests, run-dx12-samples, verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs] runs-on: windows-2022 if: ${{github.event_name == 'push'}} steps: @@ -410,7 +410,7 @@ jobs: # Publish the packages to Azure DevOps publish-nightlies-azure-devops: - needs: [verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs] + needs: [run-dx12-tests, run-dx12-device-lost-tests, run-d2d1-tests, run-dx12-samples, verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs] runs-on: windows-2022 if: ${{github.event_name == 'push'}} steps: From 358f89adb1cda02453ca695d4e9e935422228634 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 30 Jul 2022 05:09:05 +0200 Subject: [PATCH 53/64] Improve GetDefault_VerifyContract unit test --- .../GetDefaultDeviceTests.cs | 45 +++++++++++++++---- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs b/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs index be8c93b5..bc053f14 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.CompilerServices; using System.Threading.Tasks; using ComputeSharp.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -19,20 +20,46 @@ public class GetDefaultDeviceTests // The default device is never null (or the previous call would've thrown an exception) Assert.IsNotNull(device1); - GraphicsDevice device2 = GraphicsDevice.GetDefault(); + using (ComPtr d3D12Device = default) + { + unsafe void GetNativeDevice(in ComPtr d3D12Device) + { + InteropServices.GetID3D12Device(device1, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + } - // Assuming the device hasn't been disposed (tests don't run concurrently), calling - // GraphicsDevice.GetDefault() again will always return the same cached instance. - Assert.AreSame(device1, device2); + GetNativeDevice(in d3D12Device); - await DeviceLostTests.RemoveDeviceAsync(device1); + GraphicsDevice device2 = GraphicsDevice.GetDefault(); - // The device is lost but not disposed, so the same instance should be returned yet again - GraphicsDevice device3 = GraphicsDevice.GetDefault(); + // Assuming the device hasn't been disposed (tests don't run concurrently), calling + // GraphicsDevice.GetDefault() again will always return the same cached instance. + Assert.AreSame(device1, device2); - Assert.AreSame(device1, device3); + await DeviceLostTests.RemoveDeviceAsync(device1); - device1.Dispose(); + // The device is lost but not disposed, so the same instance should be returned yet again + GraphicsDevice device3 = GraphicsDevice.GetDefault(); + + Assert.AreSame(device1, device3); + + // Dispose the device, which should make its actual release logic execute + device1.Dispose(); + + // The device is correctly marked as disposed + Assert.ThrowsException(() => device1.IsDoublePrecisionSupportAvailable()); + + unsafe void VerifyDisposeForDevice1(ComPtr d3D12Device) + { + _ = d3D12Device.Get()->AddRef(); + + uint refCount = d3D12Device.Get()->Release(); + + // Now there should just be this one last reference left to the native device + Assert.AreEqual(refCount, 1u); + } + + VerifyDisposeForDevice1(d3D12Device); + } // Calling GraphicsDevice.GetDefault() after disposing it should always succeed... GraphicsDevice device4 = GraphicsDevice.GetDefault(); From f9c9b5a24b3450db7b819d4da51231a2092ec5f2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 30 Jul 2022 15:57:54 +0200 Subject: [PATCH 54/64] Code refactoring to unit tests --- .../DeviceDisposalTests.cs | 73 ++++---------- .../DeviceLostTests.cs | 72 +++----------- .../GetDefaultDeviceTests.cs | 84 ++++++----------- .../Helpers/GraphicsDeviceHelper.cs | 94 +++++++++++++++++++ 4 files changed, 152 insertions(+), 171 deletions(-) create mode 100644 tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs index 6c6b9070..83ce5707 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs @@ -1,13 +1,12 @@ using System; using ComputeSharp.Interop; using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.DeviceLost.Helpers; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; -#pragma warning disable CA1416 - namespace ComputeSharp.Tests.DeviceLost; [TestClass] @@ -15,48 +14,30 @@ namespace ComputeSharp.Tests.DeviceLost; public partial class DeviceDisposalTests { [TestMethod] - public unsafe void DeviceDisposal_GetDefault_ReferenceCounting() + public void DeviceDisposal_GetDefault_ReferenceCounting() { using ComPtr d3D12Device = default; using (GraphicsDevice graphicsDevice = GraphicsDevice.GetDefault()) { - InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device); } - // This test has to ensure a GraphicsDevice instance correctly destroys the underlying device - // when disposed. To verify this, we first get the underlying ID3D12Device* object, which causes - // its reference count to be incremented by 1. Assuming GraphicsDevice is working correctly, once - // it is disposed, the underlying ID3D12Device* object should have its ref count set to just 1, - // which is the one we added when doing QueryInterface on it. To verify this, we first increment - // that, and then release it to get the updated count. If everything is correct, the ref count - // we got back should be 1, with the last one just being from our own ID3D12Device* local. We - // can't just do Release() and check that, as that'd cause the ref count to just go to 0 but - // without clearing the pointer stored in the ComPtr local, which would then crash when - // going out of scope and trying to dereference that object to call Release() on it. - _ = d3D12Device.Get()->AddRef(); - - uint refCount = d3D12Device.Get()->Release(); - - Assert.AreEqual(refCount, 1u); + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device)); } [CombinatorialTestMethod] [AllDevices] - public unsafe void DeviceDisposal_ReferenceCounting(Device device) + public void DeviceDisposal_ReferenceCounting(Device device) { using ComPtr d3D12Device = default; using (GraphicsDevice graphicsDevice = device.Get()) { - InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device); } - _ = d3D12Device.Get()->AddRef(); - - uint refCount = d3D12Device.Get()->Release(); - - Assert.AreEqual(refCount, 1u); + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device)); } [CombinatorialTestMethod] @@ -75,7 +56,7 @@ public partial class DeviceDisposalTests [CombinatorialTestMethod] [AllDevices] - public unsafe void DeviceDisposal_DisposedResources_ReferenceCounting(Device device) + public void DeviceDisposal_DisposedResources_ReferenceCounting(Device device) { using ComPtr d3D12Device = default; @@ -91,19 +72,15 @@ public partial class DeviceDisposalTests using var r8 = graphicsDevice.AllocateUploadTexture2D(128, 128); using var r9 = graphicsDevice.AllocateReadBackTexture2D(128, 128); - InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device); } - _ = d3D12Device.Get()->AddRef(); - - uint refCount = d3D12Device.Get()->Release(); - - Assert.AreEqual(refCount, 1u); + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device)); } [CombinatorialTestMethod] [AllDevices] - public unsafe void DeviceDisposal_DisposedResourcesAfterDevice_ReferenceCounting(Device device) + public void DeviceDisposal_DisposedResourcesAfterDevice_ReferenceCounting(Device device) { #if NET6_0_OR_GREATER // TODO: investigate ref count with resources disposed after device when using D3D12MA @@ -126,7 +103,7 @@ public partial class DeviceDisposalTests r4 = graphicsDevice.AllocateReadOnlyTexture2D(128, 128); r5 = graphicsDevice.AllocateReadWriteTexture2D(128, 128); - InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device); } r1.Dispose(); @@ -135,16 +112,12 @@ public partial class DeviceDisposalTests r4.Dispose(); r5.Dispose(); - _ = d3D12Device.Get()->AddRef(); - - uint refCount = d3D12Device.Get()->Release(); - - Assert.AreEqual(refCount, 1u); + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device)); } [CombinatorialTestMethod] [AllDevices] - public unsafe void DeviceDisposal_WithComputeShader_ReferenceCounting(Device device) + public void DeviceDisposal_WithComputeShader_ReferenceCounting(Device device) { using ComPtr d3D12Device = default; @@ -157,14 +130,10 @@ public partial class DeviceDisposalTests context.For(buffer.Length, new InitializeShader(buffer)); } - InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device); } - _ = d3D12Device.Get()->AddRef(); - - uint refCount = d3D12Device.Get()->Release(); - - Assert.AreEqual(refCount, 1u); + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device)); } [EmbeddedBytecode(DispatchAxis.X)] @@ -181,7 +150,7 @@ public partial class DeviceDisposalTests [CombinatorialTestMethod] [AllDevices] - public unsafe void DeviceDisposal_WithPixelShader_ReferenceCounting(Device device) + public void DeviceDisposal_WithPixelShader_ReferenceCounting(Device device) { using ComPtr d3D12Device = default; @@ -194,14 +163,10 @@ public partial class DeviceDisposalTests context.ForEach(texture, default(HelloWorldShader)); } - InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device); } - _ = d3D12Device.Get()->AddRef(); - - uint refCount = d3D12Device.Get()->Release(); - - Assert.AreEqual(refCount, 1u); + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device)); } [EmbeddedBytecode(DispatchAxis.XY)] diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs index 0bb4e179..e3077d35 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs @@ -1,12 +1,9 @@ using System; using System.Threading.Tasks; -using ComputeSharp.Interop; using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.DeviceLost.Helpers; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; -using TerraFX.Interop.DirectX; - -#pragma warning disable CA1416 namespace ComputeSharp.Tests.DeviceLost; @@ -25,7 +22,7 @@ public class DeviceLostTests // Register the device lost callback graphicsDevice.DeviceLost += (s, e) => tcs.SetResult((s, e)); - RemoveDevice(graphicsDevice); + GraphicsDeviceHelper.RemoveDevice(graphicsDevice); // Wait up to a second for the event to be raised (it's raised asynchronously on a thread pool thread) await Task.WhenAny(tcs.Task, Task.Delay(1000)); @@ -50,7 +47,7 @@ public class DeviceLostTests { using GraphicsDevice graphicsDevice = device.Get(); - await RemoveDeviceAsync(graphicsDevice); + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); using var _ = graphicsDevice.AllocateBuffer(bufferType, 128); } @@ -64,7 +61,7 @@ public class DeviceLostTests { using GraphicsDevice graphicsDevice = device.Get(); - await RemoveDeviceAsync(graphicsDevice); + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); using var _ = graphicsDevice.AllocateTexture2D(textureType, 128, 128); } @@ -78,7 +75,7 @@ public class DeviceLostTests { using GraphicsDevice graphicsDevice = device.Get(); - await RemoveDeviceAsync(graphicsDevice); + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); using var _ = graphicsDevice.AllocateTexture3D(textureType, 128, 128, 3); } @@ -90,7 +87,7 @@ public class DeviceLostTests { using GraphicsDevice graphicsDevice = device.Get(); - await RemoveDeviceAsync(graphicsDevice); + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); _ = graphicsDevice.IsDoublePrecisionSupportAvailable(); } @@ -102,7 +99,7 @@ public class DeviceLostTests { using GraphicsDevice graphicsDevice = device.Get(); - await RemoveDeviceAsync(graphicsDevice); + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); _ = graphicsDevice.IsReadOnlyTexture2DSupportedForType(); } @@ -114,7 +111,7 @@ public class DeviceLostTests { using GraphicsDevice graphicsDevice = device.Get(); - await RemoveDeviceAsync(graphicsDevice); + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); _ = graphicsDevice.IsReadWriteTexture2DSupportedForType(); } @@ -126,7 +123,7 @@ public class DeviceLostTests { using GraphicsDevice graphicsDevice = device.Get(); - await RemoveDeviceAsync(graphicsDevice); + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); _ = graphicsDevice.IsReadOnlyTexture3DSupportedForType(); } @@ -138,7 +135,7 @@ public class DeviceLostTests { using GraphicsDevice graphicsDevice = device.Get(); - await RemoveDeviceAsync(graphicsDevice); + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); _ = graphicsDevice.IsReadWriteTexture3DSupportedForType(); } @@ -150,55 +147,8 @@ public class DeviceLostTests { using GraphicsDevice graphicsDevice = device.Get(); - await RemoveDeviceAsync(graphicsDevice); + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); using var _ = graphicsDevice.CreateComputeContext(); } - - /// - /// Removes the underlying device for a given instance. - /// - /// The target instance. - private static unsafe void RemoveDevice(GraphicsDevice graphicsDevice) - { - ID3D12Device5* d3D12Device = default; - Guid d3D12Device5Guid = typeof(ID3D12Device5).GUID; - - if (InteropServices.TryGetID3D12Device(graphicsDevice, &d3D12Device5Guid, (void**)&d3D12Device) != 0) - { - Assert.Inconclusive(); - } - - try - { - d3D12Device->RemoveDevice(); - } - finally - { - if (d3D12Device is not null) - { - d3D12Device->Release(); - } - } - } - - /// - /// Removes the underlying device for a given instance and waits for it to be reported. - /// - /// The target instance. - internal static async Task RemoveDeviceAsync(GraphicsDevice graphicsDevice) - { - TaskCompletionSource tcs = new(); - - graphicsDevice.DeviceLost += (s, e) => tcs.SetResult(null); - - RemoveDevice(graphicsDevice); - - await Task.WhenAny(tcs.Task, Task.Delay(1000)); - - if (!tcs.Task.IsCompleted) - { - Assert.Fail(); - } - } } diff --git a/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs b/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs index bc053f14..c1071b4c 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs @@ -1,7 +1,5 @@ using System; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; -using ComputeSharp.Interop; +using ComputeSharp.Tests.DeviceLost.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -13,7 +11,7 @@ namespace ComputeSharp.Tests.DeviceLost; public class GetDefaultDeviceTests { [TestMethod] - public async Task GetDefault_VerifyContract() + public unsafe void GetDefault_VerifyContract() { GraphicsDevice device1 = GraphicsDevice.GetDefault(); @@ -22,12 +20,7 @@ public class GetDefaultDeviceTests using (ComPtr d3D12Device = default) { - unsafe void GetNativeDevice(in ComPtr d3D12Device) - { - InteropServices.GetID3D12Device(device1, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); - } - - GetNativeDevice(in d3D12Device); + GraphicsDeviceHelper.GetD3D12Device(device1, in d3D12Device); GraphicsDevice device2 = GraphicsDevice.GetDefault(); @@ -35,7 +28,7 @@ public class GetDefaultDeviceTests // GraphicsDevice.GetDefault() again will always return the same cached instance. Assert.AreSame(device1, device2); - await DeviceLostTests.RemoveDeviceAsync(device1); + GraphicsDeviceHelper.RemoveDevice(device1); // The device is lost but not disposed, so the same instance should be returned yet again GraphicsDevice device3 = GraphicsDevice.GetDefault(); @@ -48,17 +41,8 @@ public class GetDefaultDeviceTests // The device is correctly marked as disposed Assert.ThrowsException(() => device1.IsDoublePrecisionSupportAvailable()); - unsafe void VerifyDisposeForDevice1(ComPtr d3D12Device) - { - _ = d3D12Device.Get()->AddRef(); - - uint refCount = d3D12Device.Get()->Release(); - - // Now there should just be this one last reference left to the native device - Assert.AreEqual(refCount, 1u); - } - - VerifyDisposeForDevice1(d3D12Device); + // Now there should just be this one last reference left to the native device + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(in d3D12Device)); } // Calling GraphicsDevice.GetDefault() after disposing it should always succeed... @@ -71,76 +55,64 @@ public class GetDefaultDeviceTests // The LUID should match though, as the same adapter should be returned Assert.AreEqual(device1.Luid, device4.Luid); - unsafe void GetDefault_VerifyContract_Part2() - { - using ComPtr d3D12Device = default; + GraphicsDeviceHelper.RemoveDevice(device4); - // Increment the reference count on the internal device, causing it to remain alive - InteropServices.GetID3D12Device(device4, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + using (ComPtr d3D12Device = default) + { + GraphicsDeviceHelper.GetD3D12Device(device4, in d3D12Device); device4.Dispose(); - _ = d3D12Device.Get()->AddRef(); - - uint refCount = d3D12Device.Get()->Release(); + // The device is correctly marked as disposed + Assert.ThrowsException(() => device4.IsDoublePrecisionSupportAvailable()); // Sanity check that this is in fact the only reference keeping the device alive - Assert.AreEqual(refCount, 1u); + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(in d3D12Device)); HRESULT removalReason = d3D12Device.Get()->GetDeviceRemovedReason(); // Sanity check that the device is in fact removed - Assert.AreEqual((int)removalReason, DXGI.DXGI_ERROR_DEVICE_REMOVED); + Assert.AreEqual(DXGI.DXGI_ERROR_DEVICE_REMOVED, (int)removalReason); // Calling GraphicsDevice.GetDefault() will now throw, because the native device has not been disposed properly Assert.ThrowsException(() => GraphicsDevice.GetDefault()); } - - await DeviceLostTests.RemoveDeviceAsync(device4); - - GetDefault_VerifyContract_Part2(); } [TestMethod] - public unsafe void GetDefault_DisposeAndUseNewInstance() + public void GetDefault_DisposeAndUseNewInstance() { + GraphicsDevice device1 = GraphicsDevice.GetDefault(); + using (ComPtr d3D12Device = default) { - GraphicsDevice device = GraphicsDevice.GetDefault(); - - using (device.AllocateReadOnlyBuffer(128)) + using (device1.AllocateReadOnlyBuffer(128)) { } - InteropServices.GetID3D12Device(device, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + GraphicsDeviceHelper.GetD3D12Device(device1, in d3D12Device); - device.Dispose(); + device1.Dispose(); - _ = d3D12Device.Get()->AddRef(); - - uint refCount = d3D12Device.Get()->Release(); - - Assert.AreEqual(refCount, 1u); + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(in d3D12Device)); } // Just same test but twice, just for good measure using (ComPtr d3D12Device = default) { - GraphicsDevice device = GraphicsDevice.GetDefault(); + GraphicsDevice device2 = GraphicsDevice.GetDefault(); - using (device.AllocateReadOnlyBuffer(128)) + Assert.AreNotSame(device1, device2); + + using (device2.AllocateReadOnlyBuffer(128)) { } - InteropServices.GetID3D12Device(device, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + GraphicsDeviceHelper.GetD3D12Device(device2, in d3D12Device); - device.Dispose(); + device2.Dispose(); - _ = d3D12Device.Get()->AddRef(); - - uint refCount = d3D12Device.Get()->Release(); - - Assert.AreEqual(refCount, 1u); + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(in d3D12Device)); } } } diff --git a/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs b/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs new file mode 100644 index 00000000..017d1118 --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs @@ -0,0 +1,94 @@ +using System; +using System.Threading.Tasks; +using ComputeSharp.Interop; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable CA1416 + +namespace ComputeSharp.Tests.DeviceLost.Helpers; + +/// +/// A helper to do common checks on native device objects. +/// +internal static class GraphicsDeviceHelper +{ + /// + /// Gets the underlying object from a instance. + /// + /// The input instance. + /// The underlying object for . + public static unsafe void GetD3D12Device(GraphicsDevice graphicsDevice, in ComPtr d3D12Device) + { + InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + } + + /// + /// Gets the reference count for a given object. + /// + /// The target object to get the reference count for. + public static unsafe uint GetD3D12DeviceRefCount(in ComPtr d3D12Device) + { + // Tests using this helper have to ensure a GraphicsDevice instance correctly destroys the underlying + // device when disposed. To verify this, we first get the underlying ID3D12Device* object, which causes + // its reference count to be incremented by 1. Assuming GraphicsDevice is working correctly, once + // it is disposed, the underlying ID3D12Device* object should have its ref count set to just 1, + // which is the one we added when doing QueryInterface on it. To verify this, we first increment + // that, and then release it to get the updated count. If everything is correct, the ref count + // we got back should be 1, with the last one just being from our own ID3D12Device* local. We + // can't just do Release() and check that, as that'd cause the ref count to just go to 0 but + // without clearing the pointer stored in the ComPtr local, which would then crash when + // going out of scope and trying to dereference that object to call Release() on it. + _ = d3D12Device.Get()->AddRef(); + + return d3D12Device.Get()->Release(); + } + + /// + /// Removes the underlying device for a given instance. + /// + /// The target instance. + public static unsafe void RemoveDevice(GraphicsDevice graphicsDevice) + { + ID3D12Device5* d3D12Device = default; + Guid d3D12Device5Guid = typeof(ID3D12Device5).GUID; + + if (InteropServices.TryGetID3D12Device(graphicsDevice, &d3D12Device5Guid, (void**)&d3D12Device) != 0) + { + Assert.Inconclusive(); + } + + try + { + d3D12Device->RemoveDevice(); + } + finally + { + if (d3D12Device is not null) + { + d3D12Device->Release(); + } + } + } + + /// + /// Removes the underlying device for a given instance and waits for it to be reported. + /// + /// The target instance. + public static async Task RemoveDeviceAsync(GraphicsDevice graphicsDevice) + { + TaskCompletionSource tcs = new(); + + graphicsDevice.DeviceLost += (s, e) => tcs.SetResult(null); + + RemoveDevice(graphicsDevice); + + await Task.WhenAny(tcs.Task, Task.Delay(1000)); + + if (!tcs.Task.IsCompleted) + { + Assert.Fail(); + } + } +} From 22fccc032c14ca8b6a2f1cd74a188cf179c8c2a1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 31 Jul 2022 15:16:40 +0200 Subject: [PATCH 55/64] Fix race conditions in device removed unit tests --- .../DeviceLostTests.cs | 23 +++---- .../GetDefaultDeviceTests.cs | 16 +++-- .../Helpers/GraphicsDeviceHelper.cs | 64 +++++++++---------- 3 files changed, 50 insertions(+), 53 deletions(-) diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs index e3077d35..927cd1c6 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.DeviceLost.Helpers; @@ -17,24 +18,18 @@ public class DeviceLostTests { using GraphicsDevice graphicsDevice = device.Get(); - TaskCompletionSource<(object? Sender, DeviceLostReason Reason)> tcs = new(); + List<(object? Sender, DeviceLostReason Reason)> args = new(); // Register the device lost callback - graphicsDevice.DeviceLost += (s, e) => tcs.SetResult((s, e)); + graphicsDevice.DeviceLost += (s, e) => args.Add((s, e)); - GraphicsDeviceHelper.RemoveDevice(graphicsDevice); + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); - // Wait up to a second for the event to be raised (it's raised asynchronously on a thread pool thread) - await Task.WhenAny(tcs.Task, Task.Delay(1000)); - - // Ensure the event has been raised, and get the results - Assert.IsTrue(tcs.Task.IsCompleted); - - (object? sender, DeviceLostReason reason) = await tcs.Task; - - Assert.IsNotNull(sender); - Assert.AreSame(sender, graphicsDevice); - Assert.AreEqual(reason, DeviceLostReason.DeviceRemoved); + Assert.AreEqual(1, args.Count); + Assert.IsNotNull(args[0].Sender); + Assert.IsNotNull(args[0].Reason); + Assert.AreSame(args[0].Sender, graphicsDevice); + Assert.AreEqual(args[0].Reason, DeviceLostReason.DeviceRemoved); } [CombinatorialTestMethod] diff --git a/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs b/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs index c1071b4c..bbfe9ddd 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using ComputeSharp.Tests.DeviceLost.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using TerraFX.Interop.DirectX; @@ -11,7 +12,7 @@ namespace ComputeSharp.Tests.DeviceLost; public class GetDefaultDeviceTests { [TestMethod] - public unsafe void GetDefault_VerifyContract() + public async Task GetDefault_VerifyContract() { GraphicsDevice device1 = GraphicsDevice.GetDefault(); @@ -28,7 +29,7 @@ public class GetDefaultDeviceTests // GraphicsDevice.GetDefault() again will always return the same cached instance. Assert.AreSame(device1, device2); - GraphicsDeviceHelper.RemoveDevice(device1); + await GraphicsDeviceHelper.RemoveDeviceAsync(device1); // The device is lost but not disposed, so the same instance should be returned yet again GraphicsDevice device3 = GraphicsDevice.GetDefault(); @@ -55,7 +56,7 @@ public class GetDefaultDeviceTests // The LUID should match though, as the same adapter should be returned Assert.AreEqual(device1.Luid, device4.Luid); - GraphicsDeviceHelper.RemoveDevice(device4); + await GraphicsDeviceHelper.RemoveDeviceAsync(device4); using (ComPtr d3D12Device = default) { @@ -69,10 +70,13 @@ public class GetDefaultDeviceTests // Sanity check that this is in fact the only reference keeping the device alive Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(in d3D12Device)); - HRESULT removalReason = d3D12Device.Get()->GetDeviceRemovedReason(); + unsafe + { + HRESULT removalReason = d3D12Device.Get()->GetDeviceRemovedReason(); - // Sanity check that the device is in fact removed - Assert.AreEqual(DXGI.DXGI_ERROR_DEVICE_REMOVED, (int)removalReason); + // Sanity check that the device is in fact removed + Assert.AreEqual(DXGI.DXGI_ERROR_DEVICE_REMOVED, (int)removalReason); + } // Calling GraphicsDevice.GetDefault() will now throw, because the native device has not been disposed properly Assert.ThrowsException(() => GraphicsDevice.GetDefault()); diff --git a/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs b/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs index 017d1118..ecbf11ef 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs @@ -45,50 +45,48 @@ internal static class GraphicsDeviceHelper return d3D12Device.Get()->Release(); } - /// - /// Removes the underlying device for a given instance. - /// - /// The target instance. - public static unsafe void RemoveDevice(GraphicsDevice graphicsDevice) - { - ID3D12Device5* d3D12Device = default; - Guid d3D12Device5Guid = typeof(ID3D12Device5).GUID; - - if (InteropServices.TryGetID3D12Device(graphicsDevice, &d3D12Device5Guid, (void**)&d3D12Device) != 0) - { - Assert.Inconclusive(); - } - - try - { - d3D12Device->RemoveDevice(); - } - finally - { - if (d3D12Device is not null) - { - d3D12Device->Release(); - } - } - } - /// /// Removes the underlying device for a given instance and waits for it to be reported. /// /// The target instance. + /// + /// Removing a device will cause the device removed callback to be invoked on a separate thread, to get a + /// reference tracking lease for the device and then raise the event. If this is not awaited, it means + /// that that callback might race against a thread just calling Dispose(), so that that thread would not + /// actually cause the object to release resources until the device removed callback has also released its + /// own lease. To avoid issues related to this, the event should always be awaited after removing a device. + /// public static async Task RemoveDeviceAsync(GraphicsDevice graphicsDevice) { TaskCompletionSource tcs = new(); graphicsDevice.DeviceLost += (s, e) => tcs.SetResult(null); + static unsafe void RemoveDevice(GraphicsDevice graphicsDevice) + { + ID3D12Device5* d3D12Device = default; + Guid d3D12Device5Guid = typeof(ID3D12Device5).GUID; + + if (InteropServices.TryGetID3D12Device(graphicsDevice, &d3D12Device5Guid, (void**)&d3D12Device) != 0) + { + Assert.Inconclusive(); + } + + try + { + d3D12Device->RemoveDevice(); + } + finally + { + if (d3D12Device is not null) + { + d3D12Device->Release(); + } + } + } + RemoveDevice(graphicsDevice); - await Task.WhenAny(tcs.Task, Task.Delay(1000)); - - if (!tcs.Task.IsCompleted) - { - Assert.Fail(); - } + await tcs.Task; } } From f1306a462169f73daa9c9d54bf32d0c4012c9767 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 31 Jul 2022 15:20:55 +0200 Subject: [PATCH 56/64] Add unit test for multiple device removals --- .../DeviceLostTests.cs | 9 ++++ .../Helpers/GraphicsDeviceHelper.cs | 50 ++++++++++--------- 2 files changed, 36 insertions(+), 23 deletions(-) diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs index 927cd1c6..17139d71 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs @@ -30,6 +30,15 @@ public class DeviceLostTests Assert.IsNotNull(args[0].Reason); Assert.AreSame(args[0].Sender, graphicsDevice); Assert.AreEqual(args[0].Reason, DeviceLostReason.DeviceRemoved); + + // Trying to remove the device again does nothing + GraphicsDeviceHelper.RemoveDevice(graphicsDevice); + GraphicsDeviceHelper.RemoveDevice(graphicsDevice); + GraphicsDeviceHelper.RemoveDevice(graphicsDevice); + GraphicsDeviceHelper.RemoveDevice(graphicsDevice); + + // The event can only be raised once + Assert.AreEqual(1, args.Count); } [CombinatorialTestMethod] diff --git a/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs b/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs index ecbf11ef..39a13cd0 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs @@ -45,6 +45,33 @@ internal static class GraphicsDeviceHelper return d3D12Device.Get()->Release(); } + /// + /// Removes the underlying device for a given instance. + /// + /// The target instance. + public static unsafe void RemoveDevice(GraphicsDevice graphicsDevice) + { + ID3D12Device5* d3D12Device = default; + Guid d3D12Device5Guid = typeof(ID3D12Device5).GUID; + + if (InteropServices.TryGetID3D12Device(graphicsDevice, &d3D12Device5Guid, (void**)&d3D12Device) != 0) + { + Assert.Inconclusive(); + } + + try + { + d3D12Device->RemoveDevice(); + } + finally + { + if (d3D12Device is not null) + { + d3D12Device->Release(); + } + } + } + /// /// Removes the underlying device for a given instance and waits for it to be reported. /// @@ -62,29 +89,6 @@ internal static class GraphicsDeviceHelper graphicsDevice.DeviceLost += (s, e) => tcs.SetResult(null); - static unsafe void RemoveDevice(GraphicsDevice graphicsDevice) - { - ID3D12Device5* d3D12Device = default; - Guid d3D12Device5Guid = typeof(ID3D12Device5).GUID; - - if (InteropServices.TryGetID3D12Device(graphicsDevice, &d3D12Device5Guid, (void**)&d3D12Device) != 0) - { - Assert.Inconclusive(); - } - - try - { - d3D12Device->RemoveDevice(); - } - finally - { - if (d3D12Device is not null) - { - d3D12Device->Release(); - } - } - } - RemoveDevice(graphicsDevice); await tcs.Task; From 42c862c148442d4942ea82ad988ebeed1828611f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 31 Jul 2022 16:13:45 +0200 Subject: [PATCH 57/64] Fix disposing resources after device on .NET 6 --- .../Extensions/Interop/ComPtrExtensions.cs | 19 ++----------------- src/ComputeSharp/Graphics/GraphicsDevice.cs | 11 +++++++++-- .../DeviceDisposalTests.cs | 5 ----- 3 files changed, 11 insertions(+), 24 deletions(-) diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/ComPtrExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/ComPtrExtensions.cs index 86e597ea..40e28633 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/ComPtrExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/ComPtrExtensions.cs @@ -8,6 +8,7 @@ namespace ComputeSharp.Core.Extensions; /// internal static class ComPtrExtensions { +#if NET6_0_OR_GREATER /// /// Invokes on the wrapped object for an input value. /// @@ -16,20 +17,11 @@ internal static class ComPtrExtensions /// A instance of type . [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe uint AddRef(this ComPtr ptr) -#if NET6_0_OR_GREATER where T : unmanaged, IUnknown.Interface -#else - where T : unmanaged -#endif { if (ptr.Get() is not null) { -#if NET6_0_OR_GREATER return ptr.Get()->AddRef(); -#else - return ((IUnknown*)ptr.Get())->AddRef(); -#endif - } return 0; @@ -44,19 +36,11 @@ internal static class ComPtrExtensions /// A instance of type . [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe uint Release(this ref ComPtr ptr) -#if NET6_0_OR_GREATER where T : unmanaged, IUnknown.Interface -#else - where T : unmanaged -#endif { if (ptr.Get() is not null) { -#if NET6_0_OR_GREATER uint count = ptr.Get()->Release(); -#else - uint count = ((IUnknown*)ptr.Get())->Release(); -#endif if (count == 0) { @@ -68,6 +52,7 @@ internal static class ComPtrExtensions return 0; } +#endif /// /// Reinterprets the current instance as one of type . diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 9f243bff..2847205e 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -444,9 +444,16 @@ public sealed unsafe partial class GraphicsDevice : NativeObject this.computeCommandListPool.Dispose(); this.copyCommandListPool.Dispose(); this.shaderResourceViewDescriptorAllocator.Dispose(); + + // On .NET 6, D3D12MA is used. In this case, the pool and allocator must be kept alive + // until all associated resources are returned and destroyed. Because of this, when the + // device is disposed (since there might be outstanding resources that are still alive), + // the pool and allocator are only released, but not disposed. This allows reosurces to + // also release them when disposed (since each resource keeps a reference back to the + // parent device). When the last one is disposed, the pool and allocator will be deleted. #if NET6_0_OR_GREATER - this.pool.Dispose(); - this.allocator.Dispose(); + this.pool.Release(); + this.allocator.Release(); #endif UnregisterDeviceLostCallback(this); diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs index 83ce5707..7d2c3be4 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs @@ -82,11 +82,6 @@ public partial class DeviceDisposalTests [AllDevices] public void DeviceDisposal_DisposedResourcesAfterDevice_ReferenceCounting(Device device) { -#if NET6_0_OR_GREATER - // TODO: investigate ref count with resources disposed after device when using D3D12MA - Assert.Inconclusive(); -#endif - using ComPtr d3D12Device = default; ConstantBuffer r1; From 5b2e0bd6e5ba9d147da482b5d140542c4d17beda Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 31 Jul 2022 17:34:04 +0200 Subject: [PATCH 58/64] Fix solution configuration, makr x64 the default --- ComputeSharp.sln | 116 ++--------------------------------------------- 1 file changed, 3 insertions(+), 113 deletions(-) diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 54268e97..b64a7a9f 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -122,338 +122,228 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ComputeSharp.NuGet", "Compu tests\ComputeSharp.NuGet\Program.cs = tests\ComputeSharp.NuGet\Program.cs EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Tests.DeviceLost", "tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj", "{5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.DeviceLost", "tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj", "{5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|ARM64 = Debug|ARM64 Debug|x64 = Debug|x64 - Release|Any CPU = Release|Any CPU - Release|ARM64 = Release|ARM64 + Debug|ARM64 = Debug|ARM64 Release|x64 = Release|x64 + Release|ARM64 = Release|ARM64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {314EB353-E7E3-4146-8111-685CC83EC1DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {314EB353-E7E3-4146-8111-685CC83EC1DE}.Debug|Any CPU.Build.0 = Debug|Any CPU {314EB353-E7E3-4146-8111-685CC83EC1DE}.Debug|ARM64.ActiveCfg = Debug|Any CPU {314EB353-E7E3-4146-8111-685CC83EC1DE}.Debug|ARM64.Build.0 = Debug|Any CPU {314EB353-E7E3-4146-8111-685CC83EC1DE}.Debug|x64.ActiveCfg = Debug|Any CPU {314EB353-E7E3-4146-8111-685CC83EC1DE}.Debug|x64.Build.0 = Debug|Any CPU - {314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|Any CPU.Build.0 = Release|Any CPU {314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|ARM64.ActiveCfg = Release|Any CPU {314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|ARM64.Build.0 = Release|Any CPU {314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|x64.ActiveCfg = Release|Any CPU {314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|x64.Build.0 = Release|Any CPU - {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Debug|Any CPU.Build.0 = Debug|Any CPU {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Debug|ARM64.ActiveCfg = Debug|Any CPU {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Debug|ARM64.Build.0 = Debug|Any CPU {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Debug|x64.ActiveCfg = Debug|Any CPU {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Debug|x64.Build.0 = Debug|Any CPU - {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Release|Any CPU.Build.0 = Release|Any CPU {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Release|ARM64.ActiveCfg = Release|Any CPU {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Release|ARM64.Build.0 = Release|Any CPU {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Release|x64.ActiveCfg = Release|Any CPU {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Release|x64.Build.0 = Release|Any CPU - {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Debug|Any CPU.Build.0 = Debug|Any CPU {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Debug|ARM64.ActiveCfg = Debug|Any CPU {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Debug|ARM64.Build.0 = Debug|Any CPU {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Debug|x64.ActiveCfg = Debug|Any CPU {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Debug|x64.Build.0 = Debug|Any CPU - {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|Any CPU.ActiveCfg = Release|Any CPU - {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|Any CPU.Build.0 = Release|Any CPU {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|ARM64.ActiveCfg = Release|Any CPU {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|ARM64.Build.0 = Release|Any CPU {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|x64.ActiveCfg = Release|Any CPU {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|x64.Build.0 = Release|Any CPU - {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|Any CPU.Build.0 = Debug|Any CPU {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|ARM64.ActiveCfg = Debug|Any CPU {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|ARM64.Build.0 = Debug|Any CPU {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|x64.ActiveCfg = Debug|Any CPU {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|x64.Build.0 = Debug|Any CPU - {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|Any CPU.Build.0 = Release|Any CPU {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|ARM64.ActiveCfg = Release|Any CPU {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|ARM64.Build.0 = Release|Any CPU {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|x64.ActiveCfg = Release|Any CPU {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|x64.Build.0 = Release|Any CPU - {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Debug|Any CPU.Build.0 = Debug|Any CPU {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Debug|ARM64.ActiveCfg = Debug|Any CPU {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Debug|ARM64.Build.0 = Debug|Any CPU {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Debug|x64.ActiveCfg = Debug|Any CPU {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Debug|x64.Build.0 = Debug|Any CPU - {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Release|Any CPU.Build.0 = Release|Any CPU {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Release|ARM64.ActiveCfg = Release|Any CPU {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Release|ARM64.Build.0 = Release|Any CPU {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Release|x64.ActiveCfg = Release|Any CPU {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Release|x64.Build.0 = Release|Any CPU - {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|Any CPU.Build.0 = Debug|Any CPU {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|ARM64.ActiveCfg = Debug|Any CPU {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|ARM64.Build.0 = Debug|Any CPU {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|x64.ActiveCfg = Debug|Any CPU {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|x64.Build.0 = Debug|Any CPU - {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|Any CPU.Build.0 = Release|Any CPU {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|ARM64.ActiveCfg = Release|Any CPU {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|ARM64.Build.0 = Release|Any CPU {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|x64.ActiveCfg = Release|Any CPU {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|x64.Build.0 = Release|Any CPU - {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Debug|Any CPU.Build.0 = Debug|Any CPU {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Debug|ARM64.ActiveCfg = Debug|Any CPU {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Debug|ARM64.Build.0 = Debug|Any CPU {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Debug|x64.ActiveCfg = Debug|Any CPU {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Debug|x64.Build.0 = Debug|Any CPU - {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Release|Any CPU.Build.0 = Release|Any CPU {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Release|ARM64.ActiveCfg = Release|Any CPU {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Release|ARM64.Build.0 = Release|Any CPU {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Release|x64.ActiveCfg = Release|Any CPU {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Release|x64.Build.0 = Release|Any CPU - {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Debug|Any CPU.Build.0 = Debug|Any CPU {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Debug|ARM64.ActiveCfg = Debug|Any CPU {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Debug|ARM64.Build.0 = Debug|Any CPU {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Debug|x64.ActiveCfg = Debug|Any CPU {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Debug|x64.Build.0 = Debug|Any CPU - {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Release|Any CPU.Build.0 = Release|Any CPU {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Release|ARM64.ActiveCfg = Release|Any CPU {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Release|ARM64.Build.0 = Release|Any CPU {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Release|x64.ActiveCfg = Release|Any CPU {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Release|x64.Build.0 = Release|Any CPU - {BF52326F-E415-49E6-8595-62762216762B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BF52326F-E415-49E6-8595-62762216762B}.Debug|Any CPU.Build.0 = Debug|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Debug|ARM64.ActiveCfg = Debug|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Debug|ARM64.Build.0 = Debug|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Debug|x64.ActiveCfg = Debug|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Debug|x64.Build.0 = Debug|Any CPU - {BF52326F-E415-49E6-8595-62762216762B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BF52326F-E415-49E6-8595-62762216762B}.Release|Any CPU.Build.0 = Release|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Release|ARM64.ActiveCfg = Release|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Release|ARM64.Build.0 = Release|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Release|x64.ActiveCfg = Release|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Release|x64.Build.0 = Release|Any CPU - {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|Any CPU.ActiveCfg = Debug|x64 - {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|Any CPU.Build.0 = Debug|x64 {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|ARM64.ActiveCfg = Debug|ARM64 {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|ARM64.Build.0 = Debug|ARM64 {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|x64.ActiveCfg = Debug|x64 {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|x64.Build.0 = Debug|x64 - {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|Any CPU.ActiveCfg = Release|x64 - {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|Any CPU.Build.0 = Release|x64 {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|ARM64.ActiveCfg = Release|ARM64 {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|ARM64.Build.0 = Release|ARM64 {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|x64.ActiveCfg = Release|x64 {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|x64.Build.0 = Release|x64 - {7C625EC4-F599-4350-A915-F046DF2406D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7C625EC4-F599-4350-A915-F046DF2406D3}.Debug|Any CPU.Build.0 = Debug|Any CPU {7C625EC4-F599-4350-A915-F046DF2406D3}.Debug|ARM64.ActiveCfg = Debug|Any CPU {7C625EC4-F599-4350-A915-F046DF2406D3}.Debug|ARM64.Build.0 = Debug|Any CPU {7C625EC4-F599-4350-A915-F046DF2406D3}.Debug|x64.ActiveCfg = Debug|Any CPU {7C625EC4-F599-4350-A915-F046DF2406D3}.Debug|x64.Build.0 = Debug|Any CPU - {7C625EC4-F599-4350-A915-F046DF2406D3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7C625EC4-F599-4350-A915-F046DF2406D3}.Release|Any CPU.Build.0 = Release|Any CPU {7C625EC4-F599-4350-A915-F046DF2406D3}.Release|ARM64.ActiveCfg = Release|Any CPU {7C625EC4-F599-4350-A915-F046DF2406D3}.Release|ARM64.Build.0 = Release|Any CPU {7C625EC4-F599-4350-A915-F046DF2406D3}.Release|x64.ActiveCfg = Release|Any CPU {7C625EC4-F599-4350-A915-F046DF2406D3}.Release|x64.Build.0 = Release|Any CPU - {1F37A704-3CDF-45BB-8114-ED9137E5F2CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1F37A704-3CDF-45BB-8114-ED9137E5F2CF}.Debug|Any CPU.Build.0 = Debug|Any CPU {1F37A704-3CDF-45BB-8114-ED9137E5F2CF}.Debug|ARM64.ActiveCfg = Debug|Any CPU {1F37A704-3CDF-45BB-8114-ED9137E5F2CF}.Debug|ARM64.Build.0 = Debug|Any CPU {1F37A704-3CDF-45BB-8114-ED9137E5F2CF}.Debug|x64.ActiveCfg = Debug|Any CPU {1F37A704-3CDF-45BB-8114-ED9137E5F2CF}.Debug|x64.Build.0 = Debug|Any CPU - {1F37A704-3CDF-45BB-8114-ED9137E5F2CF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1F37A704-3CDF-45BB-8114-ED9137E5F2CF}.Release|Any CPU.Build.0 = Release|Any CPU {1F37A704-3CDF-45BB-8114-ED9137E5F2CF}.Release|ARM64.ActiveCfg = Release|Any CPU {1F37A704-3CDF-45BB-8114-ED9137E5F2CF}.Release|ARM64.Build.0 = Release|Any CPU {1F37A704-3CDF-45BB-8114-ED9137E5F2CF}.Release|x64.ActiveCfg = Release|Any CPU {1F37A704-3CDF-45BB-8114-ED9137E5F2CF}.Release|x64.Build.0 = Release|Any CPU - {FA18BA9F-76BF-4DE0-8D24-02FC7657E6CB}.Debug|Any CPU.ActiveCfg = Debug|x64 - {FA18BA9F-76BF-4DE0-8D24-02FC7657E6CB}.Debug|Any CPU.Build.0 = Debug|x64 {FA18BA9F-76BF-4DE0-8D24-02FC7657E6CB}.Debug|ARM64.ActiveCfg = Debug|ARM64 {FA18BA9F-76BF-4DE0-8D24-02FC7657E6CB}.Debug|ARM64.Build.0 = Debug|ARM64 {FA18BA9F-76BF-4DE0-8D24-02FC7657E6CB}.Debug|x64.ActiveCfg = Debug|x64 {FA18BA9F-76BF-4DE0-8D24-02FC7657E6CB}.Debug|x64.Build.0 = Debug|x64 - {FA18BA9F-76BF-4DE0-8D24-02FC7657E6CB}.Release|Any CPU.ActiveCfg = Release|x64 - {FA18BA9F-76BF-4DE0-8D24-02FC7657E6CB}.Release|Any CPU.Build.0 = Release|x64 {FA18BA9F-76BF-4DE0-8D24-02FC7657E6CB}.Release|ARM64.ActiveCfg = Release|ARM64 {FA18BA9F-76BF-4DE0-8D24-02FC7657E6CB}.Release|ARM64.Build.0 = Release|ARM64 {FA18BA9F-76BF-4DE0-8D24-02FC7657E6CB}.Release|x64.ActiveCfg = Release|x64 {FA18BA9F-76BF-4DE0-8D24-02FC7657E6CB}.Release|x64.Build.0 = Release|x64 - {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Debug|Any CPU.ActiveCfg = Debug|x64 - {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Debug|Any CPU.Build.0 = Debug|x64 - {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Debug|Any CPU.Deploy.0 = Debug|x64 {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Debug|ARM64.ActiveCfg = Debug|ARM64 {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Debug|ARM64.Build.0 = Debug|ARM64 {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Debug|ARM64.Deploy.0 = Debug|ARM64 {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Debug|x64.ActiveCfg = Debug|x64 {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Debug|x64.Build.0 = Debug|x64 {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Debug|x64.Deploy.0 = Debug|x64 - {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Release|Any CPU.ActiveCfg = Release|x64 - {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Release|Any CPU.Build.0 = Release|x64 - {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Release|Any CPU.Deploy.0 = Release|x64 {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Release|ARM64.ActiveCfg = Release|ARM64 {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Release|ARM64.Build.0 = Release|ARM64 {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Release|ARM64.Deploy.0 = Release|ARM64 {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Release|x64.ActiveCfg = Release|x64 {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Release|x64.Build.0 = Release|x64 {0071701E-B9C5-4098-BE5F-EF556C4553C6}.Release|x64.Deploy.0 = Release|x64 - {AFAAFDC9-BE42-45D4-8C79-0EE8C8EDBF52}.Debug|Any CPU.ActiveCfg = Debug|x64 - {AFAAFDC9-BE42-45D4-8C79-0EE8C8EDBF52}.Debug|Any CPU.Build.0 = Debug|x64 {AFAAFDC9-BE42-45D4-8C79-0EE8C8EDBF52}.Debug|ARM64.ActiveCfg = Debug|ARM64 {AFAAFDC9-BE42-45D4-8C79-0EE8C8EDBF52}.Debug|ARM64.Build.0 = Debug|ARM64 {AFAAFDC9-BE42-45D4-8C79-0EE8C8EDBF52}.Debug|x64.ActiveCfg = Debug|x64 {AFAAFDC9-BE42-45D4-8C79-0EE8C8EDBF52}.Debug|x64.Build.0 = Debug|x64 - {AFAAFDC9-BE42-45D4-8C79-0EE8C8EDBF52}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AFAAFDC9-BE42-45D4-8C79-0EE8C8EDBF52}.Release|Any CPU.Build.0 = Release|Any CPU {AFAAFDC9-BE42-45D4-8C79-0EE8C8EDBF52}.Release|ARM64.ActiveCfg = Release|ARM64 {AFAAFDC9-BE42-45D4-8C79-0EE8C8EDBF52}.Release|ARM64.Build.0 = Release|ARM64 {AFAAFDC9-BE42-45D4-8C79-0EE8C8EDBF52}.Release|x64.ActiveCfg = Release|x64 {AFAAFDC9-BE42-45D4-8C79-0EE8C8EDBF52}.Release|x64.Build.0 = Release|x64 - {FBD388A5-7855-4408-98FF-E689F509DB5A}.Debug|Any CPU.ActiveCfg = Debug|x64 - {FBD388A5-7855-4408-98FF-E689F509DB5A}.Debug|Any CPU.Build.0 = Debug|x64 - {FBD388A5-7855-4408-98FF-E689F509DB5A}.Debug|Any CPU.Deploy.0 = Debug|x64 {FBD388A5-7855-4408-98FF-E689F509DB5A}.Debug|ARM64.ActiveCfg = Debug|ARM64 {FBD388A5-7855-4408-98FF-E689F509DB5A}.Debug|ARM64.Build.0 = Debug|ARM64 {FBD388A5-7855-4408-98FF-E689F509DB5A}.Debug|ARM64.Deploy.0 = Debug|ARM64 {FBD388A5-7855-4408-98FF-E689F509DB5A}.Debug|x64.ActiveCfg = Debug|x64 {FBD388A5-7855-4408-98FF-E689F509DB5A}.Debug|x64.Build.0 = Debug|x64 {FBD388A5-7855-4408-98FF-E689F509DB5A}.Debug|x64.Deploy.0 = Debug|x64 - {FBD388A5-7855-4408-98FF-E689F509DB5A}.Release|Any CPU.ActiveCfg = Release|x64 - {FBD388A5-7855-4408-98FF-E689F509DB5A}.Release|Any CPU.Build.0 = Release|x64 - {FBD388A5-7855-4408-98FF-E689F509DB5A}.Release|Any CPU.Deploy.0 = Release|x64 {FBD388A5-7855-4408-98FF-E689F509DB5A}.Release|ARM64.ActiveCfg = Release|ARM64 {FBD388A5-7855-4408-98FF-E689F509DB5A}.Release|ARM64.Build.0 = Release|ARM64 {FBD388A5-7855-4408-98FF-E689F509DB5A}.Release|ARM64.Deploy.0 = Release|ARM64 {FBD388A5-7855-4408-98FF-E689F509DB5A}.Release|x64.ActiveCfg = Release|x64 {FBD388A5-7855-4408-98FF-E689F509DB5A}.Release|x64.Build.0 = Release|x64 {FBD388A5-7855-4408-98FF-E689F509DB5A}.Release|x64.Deploy.0 = Release|x64 - {4A8FCE22-851C-442A-8BC9-3EC3FD00B637}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4A8FCE22-851C-442A-8BC9-3EC3FD00B637}.Debug|Any CPU.Build.0 = Debug|Any CPU {4A8FCE22-851C-442A-8BC9-3EC3FD00B637}.Debug|ARM64.ActiveCfg = Debug|Any CPU {4A8FCE22-851C-442A-8BC9-3EC3FD00B637}.Debug|ARM64.Build.0 = Debug|Any CPU {4A8FCE22-851C-442A-8BC9-3EC3FD00B637}.Debug|x64.ActiveCfg = Debug|Any CPU {4A8FCE22-851C-442A-8BC9-3EC3FD00B637}.Debug|x64.Build.0 = Debug|Any CPU - {4A8FCE22-851C-442A-8BC9-3EC3FD00B637}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4A8FCE22-851C-442A-8BC9-3EC3FD00B637}.Release|Any CPU.Build.0 = Release|Any CPU {4A8FCE22-851C-442A-8BC9-3EC3FD00B637}.Release|ARM64.ActiveCfg = Release|Any CPU {4A8FCE22-851C-442A-8BC9-3EC3FD00B637}.Release|ARM64.Build.0 = Release|Any CPU {4A8FCE22-851C-442A-8BC9-3EC3FD00B637}.Release|x64.ActiveCfg = Release|Any CPU {4A8FCE22-851C-442A-8BC9-3EC3FD00B637}.Release|x64.Build.0 = Release|Any CPU - {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Debug|Any CPU.ActiveCfg = Debug|x64 - {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Debug|Any CPU.Build.0 = Debug|x64 {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Debug|ARM64.ActiveCfg = Debug|ARM64 {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Debug|ARM64.Build.0 = Debug|ARM64 {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Debug|x64.ActiveCfg = Debug|x64 {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Debug|x64.Build.0 = Debug|x64 - {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Release|Any CPU.ActiveCfg = Release|x64 - {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Release|Any CPU.Build.0 = Release|x64 {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Release|ARM64.ActiveCfg = Release|ARM64 {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Release|ARM64.Build.0 = Release|ARM64 {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Release|x64.ActiveCfg = Release|x64 {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Release|x64.Build.0 = Release|x64 - {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|Any CPU.Build.0 = Debug|Any CPU {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|ARM64.ActiveCfg = Debug|Any CPU {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|ARM64.Build.0 = Debug|Any CPU {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|x64.ActiveCfg = Debug|Any CPU {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|x64.Build.0 = Debug|Any CPU - {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|Any CPU.Build.0 = Release|Any CPU {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|ARM64.ActiveCfg = Release|Any CPU {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|ARM64.Build.0 = Release|Any CPU {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|x64.ActiveCfg = Release|Any CPU {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|x64.Build.0 = Release|Any CPU - {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|Any CPU.Build.0 = Debug|Any CPU {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|ARM64.ActiveCfg = Debug|Any CPU {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|ARM64.Build.0 = Debug|Any CPU {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|x64.ActiveCfg = Debug|Any CPU {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|x64.Build.0 = Debug|Any CPU - {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|Any CPU.ActiveCfg = Release|Any CPU - {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|Any CPU.Build.0 = Release|Any CPU {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|ARM64.ActiveCfg = Release|Any CPU {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|ARM64.Build.0 = Release|Any CPU {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|x64.ActiveCfg = Release|Any CPU {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|x64.Build.0 = Release|Any CPU - {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|Any CPU.Build.0 = Debug|Any CPU {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|ARM64.ActiveCfg = Debug|Any CPU {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|ARM64.Build.0 = Debug|Any CPU {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|x64.ActiveCfg = Debug|Any CPU {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|x64.Build.0 = Debug|Any CPU - {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|Any CPU.Build.0 = Release|Any CPU {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|ARM64.ActiveCfg = Release|Any CPU {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|ARM64.Build.0 = Release|Any CPU {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|x64.ActiveCfg = Release|Any CPU {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|x64.Build.0 = Release|Any CPU - {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|Any CPU.Build.0 = Debug|Any CPU {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|ARM64.ActiveCfg = Debug|Any CPU {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|ARM64.Build.0 = Debug|Any CPU {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|x64.ActiveCfg = Debug|Any CPU {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|x64.Build.0 = Debug|Any CPU - {E44053BD-A761-47FB-AA78-087A599672EA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E44053BD-A761-47FB-AA78-087A599672EA}.Release|Any CPU.Build.0 = Release|Any CPU {E44053BD-A761-47FB-AA78-087A599672EA}.Release|ARM64.ActiveCfg = Release|Any CPU {E44053BD-A761-47FB-AA78-087A599672EA}.Release|ARM64.Build.0 = Release|Any CPU {E44053BD-A761-47FB-AA78-087A599672EA}.Release|x64.ActiveCfg = Release|Any CPU {E44053BD-A761-47FB-AA78-087A599672EA}.Release|x64.Build.0 = Release|Any CPU - {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|Any CPU.Build.0 = Debug|Any CPU {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|ARM64.ActiveCfg = Debug|Any CPU {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|ARM64.Build.0 = Debug|Any CPU {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|x64.ActiveCfg = Debug|Any CPU {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|x64.Build.0 = Debug|Any CPU - {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|Any CPU.Build.0 = Release|Any CPU {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|ARM64.ActiveCfg = Release|Any CPU {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|ARM64.Build.0 = Release|Any CPU {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|x64.ActiveCfg = Release|Any CPU {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|x64.Build.0 = Release|Any CPU - {94178D51-0097-4AD2-B3D0-827E40D62F2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {94178D51-0097-4AD2-B3D0-827E40D62F2E}.Debug|Any CPU.Build.0 = Debug|Any CPU {94178D51-0097-4AD2-B3D0-827E40D62F2E}.Debug|ARM64.ActiveCfg = Debug|Any CPU {94178D51-0097-4AD2-B3D0-827E40D62F2E}.Debug|ARM64.Build.0 = Debug|Any CPU {94178D51-0097-4AD2-B3D0-827E40D62F2E}.Debug|x64.ActiveCfg = Debug|Any CPU {94178D51-0097-4AD2-B3D0-827E40D62F2E}.Debug|x64.Build.0 = Debug|Any CPU - {94178D51-0097-4AD2-B3D0-827E40D62F2E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {94178D51-0097-4AD2-B3D0-827E40D62F2E}.Release|Any CPU.Build.0 = Release|Any CPU {94178D51-0097-4AD2-B3D0-827E40D62F2E}.Release|ARM64.ActiveCfg = Release|Any CPU {94178D51-0097-4AD2-B3D0-827E40D62F2E}.Release|ARM64.Build.0 = Release|Any CPU {94178D51-0097-4AD2-B3D0-827E40D62F2E}.Release|x64.ActiveCfg = Release|Any CPU {94178D51-0097-4AD2-B3D0-827E40D62F2E}.Release|x64.Build.0 = Release|Any CPU - {14EF12A3-90E6-4683-BD71-9896AF87026B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {14EF12A3-90E6-4683-BD71-9896AF87026B}.Debug|Any CPU.Build.0 = Debug|Any CPU {14EF12A3-90E6-4683-BD71-9896AF87026B}.Debug|ARM64.ActiveCfg = Debug|Any CPU {14EF12A3-90E6-4683-BD71-9896AF87026B}.Debug|ARM64.Build.0 = Debug|Any CPU {14EF12A3-90E6-4683-BD71-9896AF87026B}.Debug|x64.ActiveCfg = Debug|Any CPU {14EF12A3-90E6-4683-BD71-9896AF87026B}.Debug|x64.Build.0 = Debug|Any CPU - {14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|Any CPU.Build.0 = Release|Any CPU {14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|ARM64.ActiveCfg = Release|Any CPU {14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|ARM64.Build.0 = Release|Any CPU {14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|x64.ActiveCfg = Release|Any CPU {14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|x64.Build.0 = Release|Any CPU - {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Debug|Any CPU.Build.0 = Debug|Any CPU {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Debug|ARM64.ActiveCfg = Debug|Any CPU {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Debug|ARM64.Build.0 = Debug|Any CPU {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Debug|x64.ActiveCfg = Debug|Any CPU {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Debug|x64.Build.0 = Debug|Any CPU - {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Release|Any CPU.Build.0 = Release|Any CPU {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Release|ARM64.ActiveCfg = Release|Any CPU {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Release|ARM64.Build.0 = Release|Any CPU {5DE90C85-ED26-4B5A-A0D7-2FF966A210AC}.Release|x64.ActiveCfg = Release|Any CPU From 7396d0c974e0ead92a23079834b477f20c08030e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 31 Jul 2022 17:38:56 +0200 Subject: [PATCH 59/64] Add Releasr Arm64 to pipeline script --- .github/workflows/dotnet.yml | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index a91dfdb1..f8701fb0 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -9,7 +9,7 @@ env: jobs: # Build the whole ComputeSharp solution, in Debug - build-solution-debug: + build-solution-debug-x64: runs-on: windows-2022 steps: - name: Git checkout @@ -35,7 +35,7 @@ jobs: if-no-files-found: error # Build the whole ComputeSharp solution, in Release - build-solution-release: + build-solution-release-x64: runs-on: windows-2022 steps: - name: Git checkout @@ -54,6 +54,26 @@ jobs: run: msbuild -t:restore,build /p:Configuration=Release /p:Platform=x64 shell: cmd + # Build the solution in Release Arm64 too to double-check that target + build-solution-release-arm64: + runs-on: windows-2022 + steps: + - name: Git checkout + uses: actions/checkout@v2 + - name: Add msbuild to PATH + uses: microsoft/setup-msbuild@v1.0.3 + - name: Setup .NET Core 3.1 SDK + uses: actions/setup-dotnet@v1 + with: + dotnet-version: 3.1.x + - name: Setup .NET 6 SDK + uses: actions/setup-dotnet@v1 + with: + dotnet-version: 6.0.x + - name: Build + run: msbuild -t:restore,build /p:Configuration=Release /p:Platform=arm64 + shell: cmd + # Build the .msbuildproj projects and the UWP/WinUI projects to generate all the NuGet packages. # This workflow also uploads the resulting packages as artifacts. build-packages: @@ -101,7 +121,7 @@ jobs: # Run all the DX12 unit tests referencing the ComputeSharp project directly run-dx12-tests: if: success() - needs: [build-solution-debug, build-solution-release] + needs: [build-solution-debug-x64, build-solution-release-x64, build-solution-release-arm64] runs-on: windows-2022 steps: - name: Git checkout @@ -148,7 +168,7 @@ jobs: # Run all the DX12 device lost unit tests (run the separately to minimize issues) run-dx12-device-lost-tests: if: success() - needs: [build-solution-debug, build-solution-release] + needs: [build-solution-debug-x64, build-solution-release-x64, build-solution-release-arm64] runs-on: windows-2022 steps: - name: Git checkout @@ -174,7 +194,7 @@ jobs: # Run all the D2D1 unit tests (referencing ComputeSharp.D2D1) run-d2d1-tests: if: success() - needs: [build-solution-debug, build-solution-release] + needs: [build-solution-debug-x64, build-solution-release-x64, build-solution-release-arm64] runs-on: windows-2022 steps: - name: Git checkout @@ -193,7 +213,7 @@ jobs: # Run all the local samples to ensure they build and run with no errors run-dx12-samples: if: success() - needs: [build-solution-debug, build-solution-release] + needs: [build-solution-debug-x64, build-solution-release-x64, build-solution-release-arm64] runs-on: windows-2022 steps: - name: Git checkout From 480004be21ab7a7da5f7220a317c08a5592bc860 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 31 Jul 2022 18:07:17 +0200 Subject: [PATCH 60/64] Add DeviceLostEventArgs type --- .../Graphics/DeviceLostEventArgs.cs | 23 +++++++++++++++++++ .../Graphics/GraphicsDevice.DeviceLost.cs | 2 +- src/ComputeSharp/Graphics/GraphicsDevice.cs | 2 +- .../DeviceLostTests.cs | 6 ++--- 4 files changed, 28 insertions(+), 5 deletions(-) create mode 100644 src/ComputeSharp/Graphics/DeviceLostEventArgs.cs diff --git a/src/ComputeSharp/Graphics/DeviceLostEventArgs.cs b/src/ComputeSharp/Graphics/DeviceLostEventArgs.cs new file mode 100644 index 00000000..f817501f --- /dev/null +++ b/src/ComputeSharp/Graphics/DeviceLostEventArgs.cs @@ -0,0 +1,23 @@ +using System; + +namespace ComputeSharp; + +/// +/// The arguments for the event. +/// +public sealed class DeviceLostEventArgs : EventArgs +{ + /// + /// Creates a new instance with the specified arguments. + /// + /// The value for the event. + internal DeviceLostEventArgs(DeviceLostReason reason) + { + Reason = reason; + } + + /// + /// Gets the reason that caused the device to be lost. + /// + public DeviceLostReason Reason { get; } +} diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index 2950963f..1bd8209a 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -96,7 +96,7 @@ unsafe partial class GraphicsDevice _ => DeviceLostReason.UnspecifiedError }; - device.DeviceLost?.Invoke(device, reason); + device.DeviceLost?.Invoke(device, new DeviceLostEventArgs(reason)); } ThreadPool.QueueUserWorkItem(static state => RaiseDeviceLostEvent((GraphicsDevice)state!), this); diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 2847205e..53f6af10 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -137,7 +137,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject /// the event is raised asynchronously with respect to the device being lost, and on a thread pool thread. /// /// - public event EventHandler? DeviceLost; + public event EventHandler? DeviceLost; /// /// Creates a new instance for the input . diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs index 17139d71..58895f94 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs @@ -18,7 +18,7 @@ public class DeviceLostTests { using GraphicsDevice graphicsDevice = device.Get(); - List<(object? Sender, DeviceLostReason Reason)> args = new(); + List<(object? Sender, DeviceLostEventArgs Args)> args = new(); // Register the device lost callback graphicsDevice.DeviceLost += (s, e) => args.Add((s, e)); @@ -27,9 +27,9 @@ public class DeviceLostTests Assert.AreEqual(1, args.Count); Assert.IsNotNull(args[0].Sender); - Assert.IsNotNull(args[0].Reason); + Assert.IsNotNull(args[0].Args); Assert.AreSame(args[0].Sender, graphicsDevice); - Assert.AreEqual(args[0].Reason, DeviceLostReason.DeviceRemoved); + Assert.AreEqual(args[0].Args.Reason, DeviceLostReason.DeviceRemoved); // Trying to remove the device again does nothing GraphicsDeviceHelper.RemoveDevice(graphicsDevice); From a86775f550f976f357c0f1659d327a7395bf3da9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 31 Jul 2022 18:20:35 +0200 Subject: [PATCH 61/64] Add RenderingFailedEventArgs type --- .../Views/MainView.xaml.cs | 8 +++--- src/ComputeSharp.UI/ComputeSharp.UI.projitems | 1 + .../AnimatedComputeShaderPanel.Properties.cs | 2 +- .../Controls/ComputeShaderPanel.Properties.cs | 2 +- .../Controls/RenderingFailedEventArgs.cs | 27 +++++++++++++++++++ .../Helpers/SwapChainManager.Rendering.cs | 2 +- .../Helpers/SwapChainManager.cs | 2 +- 7 files changed, 36 insertions(+), 8 deletions(-) create mode 100644 src/ComputeSharp.UI/Controls/RenderingFailedEventArgs.cs diff --git a/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml.cs b/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml.cs index 1ed45642..2b3f0f9e 100644 --- a/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml.cs +++ b/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml.cs @@ -50,17 +50,17 @@ public sealed partial class MainView : UserControl } // Logs rendering failed in the main panel - private void MainShaderPanel_RenderingFailed(AnimatedComputeShaderPanel sender, Exception args) + private void MainShaderPanel_RenderingFailed(AnimatedComputeShaderPanel sender, RenderingFailedEventArgs args) { - Ioc.Default.GetRequiredService().Log(args, (nameof(Error), Error.RenderingFailedOnMainPanel)); + Ioc.Default.GetRequiredService().Log(args.Exception, (nameof(Error), Error.RenderingFailedOnMainPanel)); RenderingErrorInfoBar.IsOpen = true; } // Logs rendering failed in a secondary panel - private void SelectionShaderPanel_RenderingFailed(AnimatedComputeShaderPanel sender, Exception args) + private void SelectionShaderPanel_RenderingFailed(AnimatedComputeShaderPanel sender, RenderingFailedEventArgs args) { - Ioc.Default.GetRequiredService().Log(args, (nameof(Error), Error.RenderingFailedOnSelectionPanel)); + Ioc.Default.GetRequiredService().Log(args.Exception, (nameof(Error), Error.RenderingFailedOnSelectionPanel)); RenderingErrorInfoBar.IsOpen = true; } diff --git a/src/ComputeSharp.UI/ComputeSharp.UI.projitems b/src/ComputeSharp.UI/ComputeSharp.UI.projitems index 8d9208f4..0944f819 100644 --- a/src/ComputeSharp.UI/ComputeSharp.UI.projitems +++ b/src/ComputeSharp.UI/ComputeSharp.UI.projitems @@ -13,6 +13,7 @@ + diff --git a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs index 2a08c9d5..b7b1556d 100644 --- a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs @@ -36,7 +36,7 @@ partial class AnimatedComputeShaderPanel /// /// Raised whenever rendering fails. /// - public event TypedEventHandler? RenderingFailed + public event TypedEventHandler? RenderingFailed { add => this.swapChainManager.RenderingFailed += value; remove => this.swapChainManager.RenderingFailed -= value; diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs index aed165f1..73c01768 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs @@ -36,7 +36,7 @@ partial class ComputeShaderPanel /// /// Raised whenever rendering fails. /// - public event TypedEventHandler? RenderingFailed + public event TypedEventHandler? RenderingFailed { add => this.swapChainManager.RenderingFailed += value; remove => this.swapChainManager.RenderingFailed -= value; diff --git a/src/ComputeSharp.UI/Controls/RenderingFailedEventArgs.cs b/src/ComputeSharp.UI/Controls/RenderingFailedEventArgs.cs new file mode 100644 index 00000000..c4e13778 --- /dev/null +++ b/src/ComputeSharp.UI/Controls/RenderingFailedEventArgs.cs @@ -0,0 +1,27 @@ +using System; + +#if WINDOWS_UWP +namespace ComputeSharp.Uwp; +#else +namespace ComputeSharp.WinUI; +#endif + +/// +/// The arguments for the and events. +/// +public sealed class RenderingFailedEventArgs : EventArgs +{ + /// + /// Creates a new instance with the specified arguments. + /// + /// The that caused the rendering to fail. + internal RenderingFailedEventArgs(Exception exception) + { + Exception = exception; + } + + /// + /// Gets the that caused the rendering to fail. + /// + public Exception Exception { get; } +} diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs index 7cd9f29b..aa6860b0 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -422,7 +422,7 @@ partial class SwapChainManager /// The being thrown that caused rendering to stop. private void OnRenderingFailed(Exception e) { - _ = this.dispatcherQueue.TryEnqueue(() => RenderingFailed?.Invoke(this.owner, e)); + _ = this.dispatcherQueue.TryEnqueue(() => RenderingFailed?.Invoke(this.owner, new RenderingFailedEventArgs(e))); } /// diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index aa1fc4ef..0e82cbc5 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -220,7 +220,7 @@ internal sealed unsafe partial class SwapChainManager : NativeObject /// /// Raised whenever rendering fails. /// - public event TypedEventHandler? RenderingFailed; + public event TypedEventHandler? RenderingFailed; /// /// Raised whenever the parent control is disposed and all underlying resources are released. From b0709526ef8d890f9694b95085bbc4aebd25fb78 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 31 Jul 2022 18:27:03 +0200 Subject: [PATCH 62/64] Add ability to create shader panels for target devices --- .../Controls/AnimatedComputeShaderPanel.cs | 13 +++++++++++-- src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs | 13 +++++++++++-- src/ComputeSharp.UI/Helpers/SwapChainManager.cs | 5 +++-- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs index 8265c55b..9c3710ae 100644 --- a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs @@ -34,9 +34,18 @@ public sealed partial class AnimatedComputeShaderPanel : SwapChainPanel, IDispos /// /// Creates a new instance. /// - public unsafe AnimatedComputeShaderPanel() + public AnimatedComputeShaderPanel() + : this(GraphicsDevice.GetDefault()) { - this.swapChainManager = new SwapChainManager(this); + } + + /// + /// Creates a new instance. + /// + /// The instance to use to render frames. + public AnimatedComputeShaderPanel(GraphicsDevice device) + { + this.swapChainManager = new SwapChainManager(this, device); this.Loaded += AnimatedComputeShaderPanel_Loaded; this.Unloaded += AnimatedComputeShaderPanel_Unloaded; diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs index af51a4bd..fae6d793 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs @@ -34,9 +34,18 @@ public sealed partial class ComputeShaderPanel : SwapChainPanel, IDisposable /// /// Creates a new instance. /// - public unsafe ComputeShaderPanel() + public ComputeShaderPanel() + : this(GraphicsDevice.GetDefault()) { - this.swapChainManager = new SwapChainManager(this); + } + + /// + /// Creates a new instance. + /// + /// The instance to use to render frames. + public ComputeShaderPanel(GraphicsDevice device) + { + this.swapChainManager = new SwapChainManager(this, device); this.Loaded += ComputeShaderPanel_Loaded; this.Unloaded += ComputeShaderPanel_Unloaded; diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 0e82cbc5..279df0c2 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -231,10 +231,11 @@ internal sealed unsafe partial class SwapChainManager : NativeObject /// Initializes a new instance of the type. /// /// The input swap chain instance being used. - public SwapChainManager(TOwner owner) + /// The instance to use to render frames. + public SwapChainManager(TOwner owner, GraphicsDevice device) { this.owner = owner; - this.device = GraphicsDevice.GetDefault(); + this.device = device; // Extract the ISwapChainPanelNative reference from the current panel, then query the // IDXGISwapChain reference just created and set that as the swap chain panel to use. From 276355d680e29caa7cce19d014c537b264736428 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 31 Jul 2022 23:35:03 +0200 Subject: [PATCH 63/64] Split device lost tests at class level --- .github/workflows/dotnet.yml | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index f8701fb0..4ae54c9b 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -165,7 +165,9 @@ jobs: run: dotnet test tests\ComputeSharp.Tests.SourceGenerators\ComputeSharp.Tests.SourceGenerators.csproj -v n -l "console;verbosity=detailed" shell: cmd - # Run all the DX12 device lost unit tests (run the separately to minimize issues) + # Run all the DX12 device lost unit tests (run the separately to minimize issues). + # These tests are run one class at a time to ensure there's no accidental conflicts between any of them. This is because + # the code paths being tested in this project are heavily dependent on process-wide mutable state (ie. DirectX 12 devices). run-dx12-device-lost-tests: if: success() needs: [build-solution-debug-x64, build-solution-release-x64, build-solution-release-arm64] @@ -181,14 +183,32 @@ jobs: uses: actions/setup-dotnet@v1 with: dotnet-version: 6.0.x - - name: Run ComputeSharp.Tests.DeviceLost (.NET 6) - run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj -c Release -f net6.0 -v n -l "console;verbosity=detailed" + - name: Run ComputeSharp.Tests.DeviceLost "DeviceDisposal" (.NET 6) + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj --filter "TestCategory=DeviceDisposal" -c Release -f net6.0 -v n -l "console;verbosity=detailed" shell: cmd - - name: Run ComputeSharp.Tests.DeviceLost (.NET Core 3.1) - run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj -c Release -f netcoreapp3.1 /p:Platform=x64 -v n -l "console;verbosity=detailed" + - name: Run ComputeSharp.Tests.DeviceLost "DeviceLost" (.NET 6) + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj --filter "TestCategory=DeviceLost" -c Release -f net6.0 -v n -l "console;verbosity=detailed" shell: cmd - - name: Run ComputeSharp.Tests.DeviceLost (.NET Framework 4.7.2) - run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj -c Release -f net472 /p:Platform=x64 -v n -l "console;verbosity=detailed" + - name: Run ComputeSharp.Tests.DeviceLost "GetDefaultDevice" (.NET 6) + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj --filter "TestCategory=GetDefaultDevice" -c Release -f net6.0 -v n -l "console;verbosity=detailed" + shell: cmd + - name: Run ComputeSharp.Tests.DeviceLost "DeviceDisposal" (.NET Core 3.1) + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj --filter "TestCategory=DeviceDisposal" -c Release -f netcoreapp3.1 -v n -l "console;verbosity=detailed" + shell: cmd + - name: Run ComputeSharp.Tests.DeviceLost "DeviceLost" (.NET Core 3.1) + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj --filter "TestCategory=DeviceLost" -c Release -f netcoreapp3.1 -v n -l "console;verbosity=detailed" + shell: cmd + - name: Run ComputeSharp.Tests.DeviceLost "GetDefaultDevice" (.NET Core 3.1) + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj --filter "TestCategory=GetDefaultDevice" -c Release -f netcoreapp3.1 -v n -l "console;verbosity=detailed" + shell: cmd + - name: Run ComputeSharp.Tests.DeviceLost "DeviceDisposal" (.NET Framework 4.7.2) + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj --filter "TestCategory=DeviceDisposal" -c Release -f net472 -v n -l "console;verbosity=detailed" + shell: cmd + - name: Run ComputeSharp.Tests.DeviceLost "DeviceLost" (.NET Framework 4.7.2) + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj --filter "TestCategory=DeviceLost" -c Release -f net472 -v n -l "console;verbosity=detailed" + shell: cmd + - name: Run ComputeSharp.Tests.DeviceLost "GetDefaultDevice" (.NET Framework 4.7.2) + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj --filter "TestCategory=GetDefaultDevice" -c Release -f net472 -v n -l "console;verbosity=detailed" shell: cmd # Run all the D2D1 unit tests (referencing ComputeSharp.D2D1) From 91722437c43e2dd47c0d4104a132740f8a8f93cf Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 1 Aug 2022 00:13:09 +0200 Subject: [PATCH 64/64] Fix GC hole in device lost unit tests --- .../Helpers/GraphicsDeviceHelper.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs b/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs index 39a13cd0..8160a5fa 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs @@ -21,7 +21,10 @@ internal static class GraphicsDeviceHelper /// The underlying object for . public static unsafe void GetD3D12Device(GraphicsDevice graphicsDevice, in ComPtr d3D12Device) { - InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)d3D12Device.GetAddressOf()); + fixed (ID3D12Device** ppvObject = d3D12Device) + { + InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)ppvObject); + } } ///