diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index e307114c..4ae54c9b 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 @@ -145,10 +165,56 @@ 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). + # 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] + 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 "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 "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 "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) 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 @@ -167,7 +233,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 @@ -368,7 +434,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-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: @@ -384,7 +450,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-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: diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 06fd1a98..b64a7a9f 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -122,328 +122,232 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ComputeSharp.NuGet", "Compu tests\ComputeSharp.NuGet\Program.cs = tests\ComputeSharp.NuGet\Program.cs EndProjectSection EndProject +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|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|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 +379,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/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.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/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/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 912de608..b7b1556d 100644 --- a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs @@ -36,12 +36,21 @@ 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; } + /// + /// 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/AnimatedComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs index 7fb592ae..9c3710ae 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. @@ -33,9 +34,18 @@ public sealed partial class AnimatedComputeShaderPanel : SwapChainPanel /// /// 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; @@ -76,4 +86,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.Properties.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs index 7c76dc3c..73c01768 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs @@ -36,12 +36,21 @@ 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; } + /// + /// 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/Controls/ComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs index 560f1950..fae6d793 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. @@ -33,9 +34,18 @@ public sealed partial class ComputeShaderPanel : SwapChainPanel /// /// 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; @@ -76,4 +86,10 @@ public sealed partial class ComputeShaderPanel : SwapChainPanel { this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY); } + + /// + public void Dispose() + { + this.swapChainManager.Dispose(); + } } 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 6ac85a0a..aa6860b0 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,14 +27,14 @@ partial class SwapChainManager /// The instance to use to render frames. public async void StartRenderLoop(IFrameRequestQueue? frameRequestQueue, IShaderRunner shaderRunner) { - ThrowIfDisposed(); - Guard.IsNotNull(shaderRunner); + using var _0 = GetReferenceTrackingLease(); + using (await this.setupSemaphore.LockAsync()) { this.renderCancellationTokenSource?.Cancel(); - + await this.renderSemaphore.WaitAsync(); Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); @@ -55,8 +55,10 @@ partial class SwapChainManager /// public async void StopRenderLoop() { - ThrowIfDisposed(); - + // 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(); @@ -69,7 +71,7 @@ partial class SwapChainManager /// Whether or not to use dynamic resolution. public async void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); using (await this.setupSemaphore.LockAsync()) { @@ -103,7 +105,7 @@ partial class SwapChainManager /// Whether or not to use vertical sync. public async void QueueVerticalSyncModeChange(bool isVerticalSyncEnabled) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); using (await this.setupSemaphore.LockAsync()) { @@ -138,7 +140,7 @@ partial class SwapChainManager /// The height of the render resolution. public void QueueResize(double width, double height) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); this.width = (float)width; this.height = (float)height; @@ -153,7 +155,7 @@ partial class SwapChainManager /// The composition scale on the Y axis public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); this.compositionScaleX = (float)compositionScaleX; this.compositionScaleY = (float)compositionScaleY; @@ -167,7 +169,7 @@ partial class SwapChainManager /// The resolution scale factor to use. public void QueueResolutionScaleChange(double resolutionScale) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); this.resolutionScale = (float)resolutionScale; @@ -187,10 +189,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 var _0 = GetReferenceTrackingLease(); + RenderLoopWithDynamicResolution(); } else { + using var _0 = GetReferenceTrackingLease(); + RenderLoop(); } @@ -415,7 +422,15 @@ 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))); + } + + /// + /// Raises . + /// + private void OnDisposed() + { + _ = this.dispatcherQueue.TryEnqueue(() => Disposed?.Invoke(this.owner, EventArgs.Empty)); } /// diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 66417e4d..279df0c2 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; @@ -49,6 +48,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. /// @@ -89,6 +93,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. /// @@ -207,39 +220,45 @@ 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. + /// + public event TypedEventHandler? Disposed; /// /// 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 = 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. - 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 } // Get the underlying ID3D12Device in use fixed (ID3D12Device** d3D12Device = this.d3D12Device) { - GraphicsDevice.Default.D3D12Device->QueryInterface(Win32.__uuidof(), (void**)d3D12Device).Assert(); + this.device.D3D12Device->QueryInterface(Win32.__uuidof(), (void**)d3D12Device).Assert(); } // Create the direct command queue to use @@ -330,7 +349,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); @@ -394,7 +413,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 = this.device.AllocateReadWriteTexture2D((int)resizedWidth, (int)resizeHeight); } } @@ -497,23 +516,68 @@ internal sealed unsafe partial class SwapChainManager : NativeObject } /// - protected override void OnDispose() + private protected override void OnDispose() { - 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!; - @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); + @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(); + @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); + } } } 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); } 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(); } } 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/DeviceLostReason.cs b/src/ComputeSharp/Graphics/DeviceLostReason.cs new file mode 100644 index 00000000..b27f1132 --- /dev/null +++ b/src/ComputeSharp/Graphics/DeviceLostReason.cs @@ -0,0 +1,50 @@ +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +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 = 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 = 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 = DXGI.DXGI_ERROR_DEVICE_RESET, + + /// + /// The driver encountered a problem and was put into the device removed state. + /// + 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 = 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 = E.E_FAIL +} diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs index 393fe304..bf7c5ee9 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs @@ -150,7 +150,9 @@ public static partial class GraphicsDeviceExtensions { Guard.IsNotNull(device); - device.ThrowIfDisposed(); + using var _0 = device.GetReferenceTrackingLease(); + + device.ThrowIfDeviceLost(); return new(device); } 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/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/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs new file mode 100644 index 00000000..1bd8209a --- /dev/null +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -0,0 +1,196 @@ +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 = WaitForSingleObjectCallbackForRegisterDeviceLostCallback; +#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. + /// + private void QueueRaiseDeviceLostEventIfNeeded() + { + using var _0 = TryGetReferenceTrackingLease(out bool leaseTaken); + + if (!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 = 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, + DXGI.DXGI_ERROR_ACCESS_DENIED => DeviceLostReason.AccessDenied, + _ => DeviceLostReason.UnspecifiedError + }; + + device.DeviceLost?.Invoke(device, new DeviceLostEventArgs(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. + /// 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); + + // 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 = 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*)GCHandle.ToIntPtr(handle), + dwMilliseconds: Windows.INFINITE, + dwFlags: 0); + + deviceHandle = handle; + deviceRemovedEvent = eventHandle; + deviceRemovedWaitHandle = waitHandle; + } + + /// + /// Unregisters a callback setup by . + /// + /// The current instance. + private static void UnregisterDeviceLostCallback(GraphicsDevice device) + { + // 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(); + } + + _ = Windows.CloseHandle(device.deviceRemovedEvent); + } + + /// + /// 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) + { + GCHandle handle = GCHandle.FromIntPtr((IntPtr)pContext); + GraphicsDevice? device = Unsafe.As(handle.Target); + + // 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(); + + // 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(); + } + } +} diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs index 6d2a3ac5..02f7f4a7 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; @@ -31,9 +32,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 +132,7 @@ unsafe partial class GraphicsDevice } /// - /// A context to support . + /// A context to support . /// private struct CallbackContext { @@ -191,18 +192,30 @@ unsafe partial class GraphicsDevice HANDLE waitHandle; - _ = Windows.RegisterWaitForSingleObject( + device.DangerousAddRef(); + + int result = Windows.RegisterWaitForSingleObject( 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, dwFlags: 0); + // The register is successful if the return value is nonzero + if (result == 0) + { + device.DangerousRelease(); + + NativeMemory.Free(callbackContext); + + ThrowHelper.ThrowWin32Exception("Failed to register the compute context completion callback."); + } + return waitForFenceValueTaskSource; } @@ -212,7 +225,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; @@ -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.DangerousRelease(); + _ = Windows.CloseHandle(eventHandle); NativeMemory.Free(callbackContext); diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs index 242f51bd..e17a64dd 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs @@ -9,16 +9,40 @@ 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. + /// 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. /// - /// 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 . + /// 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. /// - public static GraphicsDevice Default => DeviceHelper.DefaultFactory.Value; + /// 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() + { + return DeviceHelper.GetDefaultDeviceFromCacheOrCreateInstance(); + } /// /// Enumerates all the currently available devices supporting the minimum necessary feature level. diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 616a888a..53f6af10 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -1,5 +1,8 @@ -using System.Diagnostics; +using System; +using System.Collections.Generic; +using System.Diagnostics; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using CommunityToolkit.Diagnostics; using ComputeSharp.Graphics.Commands.Interop; #if NET6_0_OR_GREATER @@ -8,12 +11,14 @@ 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; 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 +89,56 @@ 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 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. + /// + 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. + /// + /// + /// + /// "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 . /// @@ -126,6 +181,11 @@ public sealed unsafe partial class GraphicsDevice : NativeObject this.pool = this.allocator.Get()->CreatePoolForCacheCoherentUMA(); } #endif + + this.deviceRemovedReason = S.S_OK; + this.cachedPipelineData = new List(); + + RegisterDeviceLostCallback(this, out this.deviceHandle, out this.deviceRemovedEvent, out this.deviceRemovedWaitHandle); } /// @@ -192,7 +252,9 @@ public sealed unsafe partial class GraphicsDevice : NativeObject /// Whether the current device supports double precision floating point operations in shaders. public bool IsDoublePrecisionSupportAvailable() { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + + ThrowIfDeviceLost(); var d3D12OptionsData = this.d3D12Device.Get()->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS); @@ -208,7 +270,9 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadOnlyTexture2DSupportedForType() where T : unmanaged { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + + ThrowIfDeviceLost(); return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D); } @@ -222,7 +286,9 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadWriteTexture2DSupportedForType() where T : unmanaged { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + + ThrowIfDeviceLost(); return this.d3D12Device.Get()->IsDxgiFormatSupported( DXGIFormatHelper.GetForType(), @@ -238,7 +304,9 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadOnlyTexture3DSupportedForType() where T : unmanaged { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + + ThrowIfDeviceLost(); return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D); } @@ -252,7 +320,9 @@ public sealed unsafe partial class GraphicsDevice : NativeObject public bool IsReadWriteTexture3DSupportedForType() where T : unmanaged { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + + ThrowIfDeviceLost(); return this.d3D12Device.Get()->IsDxgiFormatSupported( DXGIFormatHelper.GetForType(), @@ -281,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) @@ -347,7 +432,7 @@ public sealed unsafe partial class GraphicsDevice : NativeObject } /// - protected override void OnDispose() + private protected override void OnDispose() { DeviceHelper.NotifyDisposedDevice(this); @@ -359,10 +444,29 @@ 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); + + // 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/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/Helpers/DeviceHelper.Factory.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs index 8445a801..cd010295 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. /// @@ -55,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/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs index 6a818106..313d92fa 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); } diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs index d31e3065..54ae9364 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.cs @@ -27,36 +27,12 @@ internal static partial class DeviceHelper /// private const uint WarpDeviceId = 0x8C; - /// - /// The instance used to produce the default instance. - /// - public static readonly Lazy DefaultFactory = new(GetDefaultDevice); - - /// - /// 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. /// /// 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 +55,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 +83,42 @@ 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 (createDeviceResult.IsDeviceLostReason()) { - 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 +130,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 +143,28 @@ 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 (createDeviceResult.IsDeviceLostReason()) + { + 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; } } diff --git a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index 57b879ab..6b1c589a 100644 --- a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -64,7 +64,8 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(buffer); - buffer.ThrowIfDisposed(); + using var _0 = buffer.GetReferenceTrackingLease(); + buffer.ThrowIfDeviceMismatch(device); D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = buffer.D3D12GpuDescriptorHandle; @@ -85,7 +86,8 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - texture.ThrowIfDisposed(); + using var _0 = texture.GetReferenceTrackingLease(); + texture.ThrowIfDeviceMismatch(device); D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; @@ -106,7 +108,8 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - texture.ThrowIfDisposed(); + using var _0 = texture.GetReferenceTrackingLease(); + texture.ThrowIfDeviceMismatch(device); D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; @@ -196,7 +199,8 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - texture.ThrowIfDisposed(); + using var _0 = texture.GetReferenceTrackingLease(); + texture.ThrowIfDeviceMismatch(device); D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; @@ -217,7 +221,8 @@ public static class GraphicsResourceHelper { Guard.IsNotNull(texture); - texture.ThrowIfDisposed(); + using var _0 = texture.GetReferenceTrackingLease(); + texture.ThrowIfDeviceMismatch(device); D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; diff --git a/src/ComputeSharp/Graphics/Interop/InteropServices.cs b/src/ComputeSharp/Graphics/Interop/InteropServices.cs index 288679f7..5427cb64 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + 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.GetReferenceTrackingLease(); + return texture.D3D12Resource->QueryInterface(riid, ppvObject); } } diff --git a/src/ComputeSharp/Graphics/Interop/NativeObject.ReferenceTracking.cs b/src/ComputeSharp/Graphics/Interop/NativeObject.ReferenceTracking.cs new file mode 100644 index 00000000..a5c914d3 --- /dev/null +++ b/src/ComputeSharp/Graphics/Interop/NativeObject.ReferenceTracking.cs @@ -0,0 +1,174 @@ +using System; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.Interop; + +#pragma warning disable CS0618 + +/// +partial class NativeObject +{ + /// + /// Adds an untracked reference to the underlying object. This needs to be released with . + /// + /// Thrown if the tracked object has been disposed. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void DangerousAddRef() + { + _ = GetReferenceTrackingLease(); + } + + /// + /// Decrements the reference count for the underlying object. A call to this API has to match a previous call. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void DangerousRelease() + { + ReturnReferenceTrackingLease(); + } + + /// + /// 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)] + internal Lease GetReferenceTrackingLease() + { + Lease lease = TryGetReferenceTrackingLease(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); + } + + 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. + internal Lease TryGetReferenceTrackingLease(out bool leaseTaken) + { + bool success = true; + + lock (this.lockObject) + { + if (this.isDisposeRequested) + { + success = false; + } + else + { + this.leasesCount++; + } + } + + NativeObject? nativeObject; + + if (success) + { + leaseTaken = true; + nativeObject = this; + } + else + { + leaseTaken = false; + nativeObject = null; + } + + return new(nativeObject); + } + + /// + private void RequestDispose() + { + 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) + { + OnDispose(); + } + } + + /// + /// Returns a given lease (ie. decrements the ref count for the tracked object). + /// + private void ReturnReferenceTrackingLease() + { + 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) + { + OnDispose(); + } + } + + /// + /// A reference tracking lease to extend the lifetime of a given instance while in a given scope. + /// + internal struct Lease : IDisposable + { + /// + /// The instance being wrapped, if any. + /// + private NativeObject? nativeObject; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance being wrapped, if any. + [Obsolete("This constructor is only meant to be called from within NativeObject.")] + public Lease(NativeObject? nativeObject) + { + this.nativeObject = nativeObject; + } + + /// + public void Dispose() + { + NativeObject? nativeObject = this.nativeObject; + + this.nativeObject = null; + + if (nativeObject is not null) + { + nativeObject.ReturnReferenceTrackingLease(); + } + } + } +} diff --git a/src/ComputeSharp/Graphics/Interop/NativeObject.cs b/src/ComputeSharp/Graphics/Interop/NativeObject.cs index 28d49e0b..1057f476 100644 --- a/src/ComputeSharp/Graphics/Interop/NativeObject.cs +++ b/src/ComputeSharp/Graphics/Interop/NativeObject.cs @@ -1,88 +1,56 @@ using System; -using System.Runtime.CompilerServices; -using System.Threading; -using ComputeSharp.Graphics.Helpers; namespace ComputeSharp.Interop; /// /// Base class for a class. /// -public abstract class NativeObject : IDisposable +public abstract partial class NativeObject : IDisposable { /// - /// Indicates whether or not the current instance has been disposed. + /// An object to use to synchronize the reference tracking operations. /// - private volatile int isDisposed; + 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.lockObject = new object(); + this.leasesCount = 0; + this.isDisposeRequested = false; + } /// /// 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; + RequestDispose(); } /// - [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; - } + RequestDispose(); - if (Interlocked.CompareExchange(ref this.isDisposed, 1, 0) == 0) - { - [MethodImpl(MethodImplOptions.NoInlining)] - void DisposeAndSuppressFinalize() - { - OnDispose(); - - GC.SuppressFinalize(this); - } - - DisposeAndSuppressFinalize(); - } + GC.SuppressFinalize(this); } /// - /// Releases unmanaged and (optionally) managed resources. + /// Releases all resources (including unmanaged ones) for the tracked object. /// - protected abstract void OnDispose(); - - /// - /// Throws an if the current instance has been disposed. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void ThrowIfDisposed() - { - 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. - void Throw() => throw new ObjectDisposedException(ToString()); - - Throw(); - } - } + /// 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 4d5b5561..bb15e4c7 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; @@ -64,8 +65,6 @@ 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(); - if (resourceType == ResourceType.Constant) { Guard.IsBetweenOrEqualTo(length, 1, D3D12.D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT); @@ -76,6 +75,10 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource Guard.IsBetweenOrEqualTo(length, 1, (uint.MaxValue / elementSizeInBytes) & ~255); } + using var _0 = device.GetReferenceTrackingLease(); + + device.ThrowIfDeviceLost(); + if (TypeInfo.IsDoubleOrContainsDoubles && device.D3D12Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS).DoublePrecisionFloatShaderOps == 0) { @@ -200,7 +203,7 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource internal abstract void CopyFrom(ref T source, int destinationOffset, int count); /// - protected override void OnDispose() + private protected sealed override void OnDispose() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER @@ -230,7 +233,8 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource /// internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + ThrowIfDeviceMismatch(device); return ( @@ -241,7 +245,8 @@ public unsafe abstract class Buffer : NativeObject, IGraphicsResource /// internal unsafe ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + 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 98c99bdf..81a977de 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs @@ -32,14 +32,15 @@ public abstract class StructuredBuffer : Buffer /// internal override unsafe void CopyTo(ref T destination, int sourceOffset, int count) { - GraphicsDevice.ThrowIfDisposed(); - - ThrowIfDisposed(); - Guard.IsBetweenOrEqualTo(count, 0, Length); Guard.IsInRange(sourceOffset, 0, Length); Guard.IsLessThanOrEqualTo(sourceOffset + count, Length, nameof(sourceOffset)); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + if (GraphicsDevice.IsCacheCoherentUMA) { using ID3D12ResourceMap resource = D3D12Resource->Map(); @@ -103,13 +104,6 @@ public abstract class StructuredBuffer : Buffer /// internal override unsafe void CopyTo(Buffer destination, int sourceOffset, int destinationOffset, int count) { - GraphicsDevice.ThrowIfDisposed(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - Guard.IsBetweenOrEqualTo(count, 0, Length); Guard.IsBetweenOrEqualTo(count, 0, destination.Length); Guard.IsInRange(sourceOffset, 0, Length); @@ -117,6 +111,14 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(destinationOffset, 0, destination.Length); Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + if (!destination.IsPaddingPresent) { nint sourceByteOffset = (nint)sourceOffset * sizeof(T); @@ -147,13 +149,6 @@ 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(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - Guard.IsBetweenOrEqualTo(count, 0, Length); Guard.IsBetweenOrEqualTo(count, 0, destination.Length); Guard.IsInRange(sourceOffset, 0, Length); @@ -161,6 +156,14 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(destinationOffset, 0, destination.Length); Guard.IsLessThanOrEqualTo(destinationOffset + count, destination.Length, nameof(destinationOffset)); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + if (GraphicsDevice.IsCacheCoherentUMA) { using ID3D12ResourceMap resource = D3D12Resource->Map(); @@ -190,14 +193,15 @@ public abstract class StructuredBuffer : Buffer /// internal override unsafe void CopyFrom(ref T source, int offset, int length) { - GraphicsDevice.ThrowIfDisposed(); - - ThrowIfDisposed(); - Guard.IsBetweenOrEqualTo(length, 0, Length); Guard.IsInRange(offset, 0, Length); Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + if (GraphicsDevice.IsCacheCoherentUMA) { using ID3D12ResourceMap resource = D3D12Resource->Map(); @@ -265,13 +269,6 @@ 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(); - - ThrowIfDisposed(); - - source.ThrowIfDeviceMismatch(GraphicsDevice); - source.ThrowIfDisposed(); - Guard.IsBetweenOrEqualTo(count, 0, Length); Guard.IsBetweenOrEqualTo(count, 0, source.Length); Guard.IsInRange(sourceOffset, 0, source.Length); @@ -279,6 +276,14 @@ public abstract class StructuredBuffer : Buffer Guard.IsInRange(destinationOffset, 0, Length); Guard.IsLessThanOrEqualTo(destinationOffset + count, Length, nameof(destinationOffset)); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = source.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + source.ThrowIfDeviceMismatch(GraphicsDevice); + 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 dacc203e..a2d2688d 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs @@ -72,11 +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) { - device.ThrowIfDisposed(); - 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.GetReferenceTrackingLease(); + + device.ThrowIfDeviceLost(); + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) { UnsupportedTextureTypeException.ThrowForTexture2D(); @@ -168,10 +170,6 @@ 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(); - - ThrowIfDisposed(); - Guard.IsInRange(sourceOffsetX, 0, Width); Guard.IsInRange(sourceOffsetY, 0, Height); Guard.IsBetweenOrEqualTo(width, 1, Width); @@ -180,6 +178,11 @@ 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.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + GraphicsDevice.D3D12Device->GetCopyableFootprint( DXGIFormatHelper.GetForType(), (uint)width, @@ -257,13 +260,6 @@ 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(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - Guard.IsInRange(sourceOffsetX, 0, Width); Guard.IsInRange(sourceOffsetY, 0, Height); Guard.IsInRange(destinationOffsetX, 0, destination.Width); @@ -277,6 +273,14 @@ 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.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + D3D12_COMMAND_LIST_TYPE d3D12CommandListType = this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE @@ -325,13 +329,6 @@ 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(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - Guard.IsInRange(sourceOffsetX, 0, Width); Guard.IsInRange(sourceOffsetY, 0, Height); Guard.IsInRange(destinationOffsetX, 0, destination.Width); @@ -345,6 +342,14 @@ 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.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) @@ -388,10 +393,6 @@ 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(); - - ThrowIfDisposed(); - Guard.IsInRange(destinationOffsetX, 0, Width); Guard.IsInRange(destinationOffsetY, 0, Height); Guard.IsBetweenOrEqualTo(width, 1, Width); @@ -400,6 +401,11 @@ 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.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + GraphicsDevice.D3D12Device->GetCopyableFootprint( DXGIFormatHelper.GetForType(), (uint)width, @@ -475,13 +481,6 @@ 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(); - - ThrowIfDisposed(); - - source.ThrowIfDeviceMismatch(GraphicsDevice); - source.ThrowIfDisposed(); - Guard.IsInRange(sourceOffsetX, 0, source.Width); Guard.IsInRange(sourceOffsetY, 0, source.Height); Guard.IsInRange(destinationOffsetX, 0, Width); @@ -495,6 +494,14 @@ 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.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = source.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + source.ThrowIfDeviceMismatch(GraphicsDevice); + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) @@ -528,7 +535,7 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra } /// - protected override void OnDispose() + private protected override void OnDispose() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER @@ -576,7 +583,8 @@ 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(); + using var _0 = GetReferenceTrackingLease(); + ThrowIfDeviceMismatch(device); isNormalized = DXGIFormatHelper.IsNormalizedType(); @@ -587,7 +595,8 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + ThrowIfDeviceMismatch(device); return D3D12Resource; @@ -596,7 +605,8 @@ 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) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + ThrowIfDeviceMismatch(device); D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState; @@ -612,7 +622,8 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + 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 70e7361d..9da307fd 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs @@ -73,12 +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) { - device.ThrowIfDisposed(); - 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 var _0 = device.GetReferenceTrackingLease(); + + device.ThrowIfDeviceLost(); + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) { UnsupportedTextureTypeException.ThrowForTexture3D(); @@ -180,10 +182,6 @@ 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(); - - ThrowIfDisposed(); - Guard.IsInRange(sourceOffsetX, 0, Width); Guard.IsInRange(sourceOffsetY, 0, Height); Guard.IsInRange(sourceOffsetZ, 0, Depth); @@ -195,6 +193,11 @@ 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.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + GraphicsDevice.D3D12Device->GetCopyableFootprint( DXGIFormatHelper.GetForType(), (uint)width, @@ -278,13 +281,6 @@ 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(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - Guard.IsInRange(sourceOffsetX, 0, Width); Guard.IsInRange(sourceOffsetY, 0, Height); Guard.IsInRange(sourceOffsetZ, 0, Depth); @@ -304,6 +300,14 @@ 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.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + D3D12_COMMAND_LIST_TYPE d3D12CommandListType = this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE @@ -355,13 +359,6 @@ 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(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - Guard.IsInRange(sourceOffsetX, 0, Width); Guard.IsInRange(sourceOffsetY, 0, Height); Guard.IsInRange(sourceOffsetZ, 0, Depth); @@ -381,6 +378,14 @@ 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.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) @@ -426,10 +431,6 @@ 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(); - - ThrowIfDisposed(); - Guard.IsInRange(destinationOffsetX, 0, Width); Guard.IsInRange(destinationOffsetY, 0, Height); Guard.IsInRange(destinationOffsetZ, 0, Depth); @@ -441,6 +442,11 @@ 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.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + GraphicsDevice.D3D12Device->GetCopyableFootprint( DXGIFormatHelper.GetForType(), (uint)width, @@ -522,13 +528,6 @@ 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(); - - ThrowIfDisposed(); - - source.ThrowIfDeviceMismatch(GraphicsDevice); - source.ThrowIfDisposed(); - Guard.IsInRange(sourceOffsetX, 0, source.Width); Guard.IsInRange(sourceOffsetY, 0, source.Height); Guard.IsInRange(sourceOffsetZ, 0, source.Depth); @@ -548,6 +547,14 @@ 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.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = source.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + source.ThrowIfDeviceMismatch(GraphicsDevice); + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) @@ -581,7 +588,7 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra } /// - protected override void OnDispose() + private protected override void OnDispose() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER @@ -629,7 +636,8 @@ 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(); + using var _0 = GetReferenceTrackingLease(); + ThrowIfDeviceMismatch(device); isNormalized = DXGIFormatHelper.IsNormalizedType(); @@ -640,7 +648,8 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + ThrowIfDeviceMismatch(device); return D3D12Resource; @@ -649,7 +658,8 @@ 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) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + ThrowIfDeviceMismatch(device); D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState; @@ -665,7 +675,8 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + 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 edd1d028..b227b2f8 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs @@ -44,11 +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) { - device.ThrowIfDisposed(); - // 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.GetReferenceTrackingLease(); + + device.ThrowIfDeviceLost(); + GraphicsDevice = device; Length = length; @@ -92,7 +94,7 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); return new MemoryManager(this).Memory; } @@ -104,14 +106,14 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); return new(this.mappedData, Length); } } /// - protected override void OnDispose() + private protected sealed override void OnDispose() { this.d3D12Resource.Dispose(); #if NET6_0_OR_GREATER @@ -172,7 +174,7 @@ public abstract unsafe class TransferBuffer : NativeObject, IGraphicsResource { Guard.IsEqualTo(elementIndex, 0); - this.buffer.ThrowIfDisposed(); + 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 ec77a7af..61c0c892 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs @@ -50,11 +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) { - device.ThrowIfDisposed(); - 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.GetReferenceTrackingLease(); + + device.ThrowIfDeviceLost(); + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D)) { UnsupportedTextureTypeException.ThrowForTexture2D(); @@ -113,14 +115,14 @@ public unsafe abstract class TransferTexture2D : NativeObject, IGraphicsResou [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - ThrowIfDisposed(); + using var _0 = this.GetReferenceTrackingLease(); return new(this.mappedData, Width, Height, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); } } /// - protected override void OnDispose() + 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 e4f48331..5f310119 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs @@ -51,12 +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) { - device.ThrowIfDisposed(); - 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 var _0 = device.GetReferenceTrackingLease(); + + device.ThrowIfDeviceLost(); + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D)) { UnsupportedTextureTypeException.ThrowForTexture3D(); @@ -121,14 +123,14 @@ public unsafe abstract class TransferTexture3D : NativeObject, IGraphicsResou [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - ThrowIfDisposed(); + using var _0 = this.GetReferenceTrackingLease(); return new(this.mappedData, Width, Height, Depth, (int)this.d3D12PlacedSubresourceFootprint.Footprint.RowPitch); } } /// - protected override void OnDispose() + private protected sealed override void OnDispose() { 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 e08040ea..f7002cdc 100644 --- a/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/ConstantBuffer{T}.cs @@ -57,14 +57,15 @@ public sealed class ConstantBuffer : Buffer /// internal override unsafe void CopyTo(ref T destination, int offset, int length) { - GraphicsDevice.ThrowIfDisposed(); - - ThrowIfDisposed(); - Guard.IsBetweenOrEqualTo(length, 0, Length); Guard.IsInRange(offset, 0, Length); Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + using ID3D12ResourceMap resource = D3D12Resource->Map(); fixed (void* destinationPointer = &destination) @@ -83,13 +84,6 @@ public sealed class ConstantBuffer : Buffer /// internal override unsafe void CopyTo(Buffer destination, int sourceOffset, int destinationOffset, int length) { - GraphicsDevice.ThrowIfDisposed(); - - ThrowIfDisposed(); - - destination.ThrowIfDeviceMismatch(GraphicsDevice); - destination.ThrowIfDisposed(); - Guard.IsBetweenOrEqualTo(length, 0, Length); Guard.IsBetweenOrEqualTo(length, 0, destination.Length); Guard.IsInRange(sourceOffset, 0, Length); @@ -97,6 +91,14 @@ public sealed class ConstantBuffer : Buffer Guard.IsInRange(destinationOffset, 0, destination.Length); Guard.IsLessThanOrEqualTo(destinationOffset + length, destination.Length, nameof(destinationOffset)); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + if (destination is ConstantBuffer buffer) { using ID3D12ResourceMap sourceMap = D3D12Resource->Map(); @@ -117,14 +119,15 @@ public sealed class ConstantBuffer : Buffer /// internal override unsafe void CopyFrom(ref T source, int offset, int length) { - GraphicsDevice.ThrowIfDisposed(); - - ThrowIfDisposed(); - Guard.IsBetweenOrEqualTo(length, 0, Length); Guard.IsInRange(offset, 0, Length); Guard.IsLessThanOrEqualTo(offset + length, Length, nameof(offset)); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + using ID3D12ResourceMap resource = D3D12Resource->Map(); fixed (void* sourcePointer = &source) diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs index 55cb5933..0e0373ee 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs @@ -24,9 +24,11 @@ partial class ReadWriteTexture2D /// internal IReadOnlyNormalizedTexture2D AsReadOnly() { - GraphicsDevice.ThrowIfDisposed(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); - ThrowIfDisposed(); ThrowIfIsNotInReadOnlyState(); ReadOnly? readOnlyWrapper = this.readOnlyWrapper; @@ -46,7 +48,7 @@ partial class ReadWriteTexture2D } /// - protected override void OnDispose() + private protected override void OnDispose() { base.OnDispose(); @@ -105,9 +107,9 @@ partial class ReadWriteTexture2D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); - this.owner.ThrowIfDisposed(); this.owner.ThrowIfDeviceMismatch(device); return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; @@ -122,9 +124,9 @@ partial class ReadWriteTexture2D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); - this.owner.ThrowIfDisposed(); this.owner.ThrowIfDeviceMismatch(device); return this.owner.D3D12Resource; @@ -137,7 +139,7 @@ partial class ReadWriteTexture2D } /// - protected override void OnDispose() + 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 fdb58dd9..4b89fcf0 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs @@ -24,9 +24,11 @@ partial class ReadWriteTexture2D /// public IReadOnlyTexture2D AsReadOnly() { - GraphicsDevice.ThrowIfDisposed(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); - ThrowIfDisposed(); ThrowIfIsNotInReadOnlyState(); ReadOnly? readOnlyWrapper = this.readOnlyWrapper; @@ -49,7 +51,7 @@ partial class ReadWriteTexture2D } /// - protected override void OnDispose() + private protected override void OnDispose() { base.OnDispose(); @@ -108,9 +110,9 @@ partial class ReadWriteTexture2D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); - this.owner.ThrowIfDisposed(); this.owner.ThrowIfDeviceMismatch(device); return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; @@ -125,9 +127,9 @@ partial class ReadWriteTexture2D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); - this.owner.ThrowIfDisposed(); this.owner.ThrowIfDeviceMismatch(device); return this.owner.D3D12Resource; @@ -140,7 +142,7 @@ partial class ReadWriteTexture2D } /// - protected override void OnDispose() + 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 270c7135..5c756a31 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs @@ -24,9 +24,11 @@ partial class ReadWriteTexture3D /// public IReadOnlyNormalizedTexture3D AsReadOnly() { - GraphicsDevice.ThrowIfDisposed(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); - ThrowIfDisposed(); ThrowIfIsNotInReadOnlyState(); ReadOnly? readOnlyWrapper = this.readOnlyWrapper; @@ -46,7 +48,7 @@ partial class ReadWriteTexture3D } /// - protected override void OnDispose() + private protected override void OnDispose() { base.OnDispose(); @@ -108,9 +110,9 @@ partial class ReadWriteTexture3D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); - this.owner.ThrowIfDisposed(); this.owner.ThrowIfDeviceMismatch(device); return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; @@ -125,9 +127,9 @@ partial class ReadWriteTexture3D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); - this.owner.ThrowIfDisposed(); this.owner.ThrowIfDeviceMismatch(device); return this.owner.D3D12Resource; @@ -140,7 +142,7 @@ partial class ReadWriteTexture3D } /// - protected override void OnDispose() + 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 5d38517d..2fd55a24 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs @@ -24,9 +24,11 @@ partial class ReadWriteTexture3D /// public IReadOnlyTexture3D AsReadOnly() { - GraphicsDevice.ThrowIfDisposed(); + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); - ThrowIfDisposed(); ThrowIfIsNotInReadOnlyState(); ReadOnly? readOnlyWrapper = this.readOnlyWrapper; @@ -46,7 +48,7 @@ partial class ReadWriteTexture3D } /// - protected override void OnDispose() + private protected override void OnDispose() { base.OnDispose(); @@ -108,9 +110,9 @@ partial class ReadWriteTexture3D /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); - this.owner.ThrowIfDisposed(); this.owner.ThrowIfDeviceMismatch(device); return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; @@ -125,9 +127,9 @@ partial class ReadWriteTexture3D /// ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) { - ThrowIfDisposed(); + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); - this.owner.ThrowIfDisposed(); this.owner.ThrowIfDeviceMismatch(device); return this.owner.D3D12Resource; @@ -140,7 +142,7 @@ partial class ReadWriteTexture3D } /// - protected override void OnDispose() + private protected override void OnDispose() { if (this.owner.GraphicsDevice is GraphicsDevice device) { diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs index 46c03c31..d7021e83 100644 --- a/src/ComputeSharp/Shaders/ComputeContext.cs +++ b/src/ComputeSharp/Shaders/ComputeContext.cs @@ -18,6 +18,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 { /// @@ -38,6 +47,10 @@ public struct ComputeContext : IDisposable, IAsyncDisposable { this.device = device; this.commandList = default; + + // 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.DangerousAddRef(); } /// @@ -286,14 +299,25 @@ public struct ComputeContext : IDisposable, IAsyncDisposable { ThrowInvalidOperationExceptionIfDeviceIsNull(); + GraphicsDevice device = this.device; + this.device = null; if (!this.commandList.IsAllocated) { + device.DangerousRelease(); + return; } - this.commandList.ExecuteAndWaitForCompletion(); + try + { + this.commandList.ExecuteAndWaitForCompletion(); + } + finally + { + device.DangerousRelease(); + } } /// @@ -302,10 +326,14 @@ public struct ComputeContext : IDisposable, IAsyncDisposable { ThrowInvalidOperationExceptionIfDeviceIsNull(); + GraphicsDevice device = this.device; + this.device = null; if (!this.commandList.IsAllocated) { + device.DangerousRelease(); + #if NET6_0_OR_GREATER return ValueTask.CompletedTask; #else @@ -313,7 +341,14 @@ public struct ComputeContext : IDisposable, IAsyncDisposable #endif } - return this.commandList.ExecuteAndWaitForCompletionAsync(); + try + { + return this.commandList.ExecuteAndWaitForCompletionAsync(); + } + finally + { + device.DangerousRelease(); + } } /// 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/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(); 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.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/ComputeSharp.Tests.DeviceLost.csproj b/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj new file mode 100644 index 00000000..24bb2044 --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj @@ -0,0 +1,43 @@ + + + + net472;netcoreapp3.1;net6.0 + false + AnyCPU;x64;ARM64 + + + + + + + + + + + + + + + + + + + + + + $(NoWarn);CS0649 + + + + + + + + + + + + + + diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs new file mode 100644 index 00000000..7d2c3be4 --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs @@ -0,0 +1,178 @@ +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; + +namespace ComputeSharp.Tests.DeviceLost; + +[TestClass] +[TestCategory("DeviceDisposal")] +public partial class DeviceDisposalTests +{ + [TestMethod] + public void DeviceDisposal_GetDefault_ReferenceCounting() + { + using ComPtr d3D12Device = default; + + using (GraphicsDevice graphicsDevice = GraphicsDevice.GetDefault()) + { + GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device); + } + + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device)); + } + + [CombinatorialTestMethod] + [AllDevices] + public void DeviceDisposal_ReferenceCounting(Device device) + { + using ComPtr d3D12Device = default; + + using (GraphicsDevice graphicsDevice = device.Get()) + { + GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device); + } + + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device)); + } + + [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 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); + 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); + + GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device); + } + + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device)); + } + + [CombinatorialTestMethod] + [AllDevices] + public 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); + + GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device); + } + + r1.Dispose(); + r2.Dispose(); + r3.Dispose(); + r4.Dispose(); + r5.Dispose(); + + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device)); + } + + [CombinatorialTestMethod] + [AllDevices] + public 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)); + } + + GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device); + } + + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device)); + } + + [EmbeddedBytecode(DispatchAxis.X)] + [AutoConstructor] + private partial struct InitializeShader : IComputeShader + { + private readonly ReadWriteBuffer buffer; + + public void Execute() + { + buffer[ThreadIds.X] = ThreadIds.X; + } + } + + [CombinatorialTestMethod] + [AllDevices] + public 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)); + } + + GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device); + } + + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device)); + } + + [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); + } + } +} diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs new file mode 100644 index 00000000..58895f94 --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.DeviceLost.Helpers; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests.DeviceLost; + +[TestClass] +[TestCategory("DeviceLost")] +public class DeviceLostTests +{ + [CombinatorialTestMethod] + [AllDevices] + public async Task DeviceLost_RaiseEvent(Device device) + { + using GraphicsDevice graphicsDevice = device.Get(); + + List<(object? Sender, DeviceLostEventArgs Args)> args = new(); + + // Register the device lost callback + graphicsDevice.DeviceLost += (s, e) => args.Add((s, e)); + + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); + + Assert.AreEqual(1, args.Count); + Assert.IsNotNull(args[0].Sender); + Assert.IsNotNull(args[0].Args); + Assert.AreSame(args[0].Sender, graphicsDevice); + Assert.AreEqual(args[0].Args.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] + [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 GraphicsDeviceHelper.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 GraphicsDeviceHelper.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 GraphicsDeviceHelper.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 GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); + + _ = graphicsDevice.IsDoublePrecisionSupportAvailable(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_IsReadOnlyTexture2DSupportedForType(Device device) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); + + _ = graphicsDevice.IsReadOnlyTexture2DSupportedForType(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_IsReadWriteTexture2DSupportedForType(Device device) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); + + _ = graphicsDevice.IsReadWriteTexture2DSupportedForType(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_IsReadOnlyTexture3DSupportedForType(Device device) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); + + _ = graphicsDevice.IsReadOnlyTexture3DSupportedForType(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_IsReadWriteTexture3DSupportedForType(Device device) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); + + _ = graphicsDevice.IsReadWriteTexture3DSupportedForType(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public async Task DeviceLost_CreateComputeContext(Device device) + { + using GraphicsDevice graphicsDevice = device.Get(); + + await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice); + + using var _ = graphicsDevice.CreateComputeContext(); + } +} 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.DeviceLost/GetDefaultDeviceTests.cs b/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs new file mode 100644 index 00000000..bbfe9ddd --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/GetDefaultDeviceTests.cs @@ -0,0 +1,122 @@ +using System; +using System.Threading.Tasks; +using ComputeSharp.Tests.DeviceLost.Helpers; +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); + + using (ComPtr d3D12Device = default) + { + GraphicsDeviceHelper.GetD3D12Device(device1, in d3D12Device); + + 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 GraphicsDeviceHelper.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); + + // Dispose the device, which should make its actual release logic execute + device1.Dispose(); + + // The device is correctly marked as disposed + Assert.ThrowsException(() => device1.IsDoublePrecisionSupportAvailable()); + + // 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... + 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); + + await GraphicsDeviceHelper.RemoveDeviceAsync(device4); + + using (ComPtr d3D12Device = default) + { + GraphicsDeviceHelper.GetD3D12Device(device4, in d3D12Device); + + device4.Dispose(); + + // 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(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(in d3D12Device)); + + unsafe + { + HRESULT removalReason = d3D12Device.Get()->GetDeviceRemovedReason(); + + // 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()); + } + } + + [TestMethod] + public void GetDefault_DisposeAndUseNewInstance() + { + GraphicsDevice device1 = GraphicsDevice.GetDefault(); + + using (ComPtr d3D12Device = default) + { + using (device1.AllocateReadOnlyBuffer(128)) + { + } + + GraphicsDeviceHelper.GetD3D12Device(device1, in d3D12Device); + + device1.Dispose(); + + Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(in d3D12Device)); + } + + // Just same test but twice, just for good measure + using (ComPtr d3D12Device = default) + { + GraphicsDevice device2 = GraphicsDevice.GetDefault(); + + Assert.AreNotSame(device1, device2); + + using (device2.AllocateReadOnlyBuffer(128)) + { + } + + GraphicsDeviceHelper.GetD3D12Device(device2, in d3D12Device); + + device2.Dispose(); + + 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..8160a5fa --- /dev/null +++ b/tests/ComputeSharp.Tests.DeviceLost/Helpers/GraphicsDeviceHelper.cs @@ -0,0 +1,99 @@ +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) + { + fixed (ID3D12Device** ppvObject = d3D12Device) + { + InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof(), (void**)ppvObject); + } + } + + /// + /// 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. + /// + /// 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); + + RemoveDevice(graphicsDevice); + + await tcs.Task; + } +} 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] 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 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 - - 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; + } + } +} 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/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/Extensions/DeviceExtensions.cs b/tests/ComputeSharp.Tests/Extensions/DeviceExtensions.cs index 3996fa5e..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,14 +38,21 @@ 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.Discrete => DiscreteDevice, + Device.Warp => WarpDevice, _ => 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!; diff --git a/tests/ComputeSharp.Tests/InitializationTests.cs b/tests/ComputeSharp.Tests/InitializationTests.cs index fa703600..3609519c 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] @@ -28,16 +28,6 @@ public partial class InitializationTests Assert.IsTrue(gpu.WavefrontSize != 0); } - [TestMethod] - public void DisposeDefault() - { - using var before = GraphicsDevice.Default.AllocateReadOnlyBuffer(128); - - GraphicsDevice.Default.Dispose(); - - using var after = GraphicsDevice.Default.AllocateReadOnlyBuffer(128); - } - [TestMethod] public void EnumerateDevices() { @@ -45,7 +35,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 +54,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); 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)