From 992355f38218e0812a4a1beb9e44d6ae320c3a4e Mon Sep 17 00:00:00 2001 From: SingleAccretion Date: Mon, 14 Dec 2020 15:25:57 +0300 Subject: [PATCH 01/16] Added targets that allow for the runtime dependencies of ProjectReference'd analyzers to be passed to the compiler --- Directory.Build.targets | 40 +++++++++++++++++++ .../ComputeSharp.Core.csproj | 14 +++---- 2 files changed, 47 insertions(+), 7 deletions(-) create mode 100644 Directory.Build.targets diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 00000000..ae395b8f --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj index c820d0b9..deb643c7 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -10,19 +10,19 @@ - false - true + packages the dependencies directly alongside the main binary), and public dependencies when packing the main project. + Notably, when building the source generator for sample projects via ProjectReferences, we do not want the packages to be private.--> + false + true - false + false - - + + From 202df86227bb6106ca3e5c18ff90b9d58f0e1932 Mon Sep 17 00:00:00 2001 From: SingleAccretion Date: Mon, 14 Dec 2020 15:47:51 +0300 Subject: [PATCH 02/16] Added missing quotes --- Directory.Build.targets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Build.targets b/Directory.Build.targets index ae395b8f..2d4b2af1 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -4,7 +4,7 @@ Outputs="@(ResolvedAssemblyToPublish)"> + Condition="'%(Extension)' == '.dll' AND '%(FileName)' != '$(MSBuildProjectName)'" /> From 4f92a04d54f08e31a925dd7a9082970959f09155 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 14 Dec 2020 18:03:35 +0100 Subject: [PATCH 03/16] Added local ref/nuget sample projects --- ComputeSharp.sln | 41 ++++++++++++++----- nuget.config | 1 + .../ComputeSharp.Sample.Local.csproj} | 7 ++-- .../ComputeSharp.Sample.NuGet.csproj | 14 +++++++ .../ComputeSharp.Sample.Shared.projitems | 14 +++++++ .../ComputeSharp.Sample.Shared.shproj | 13 ++++++ .../Program.cs | 0 7 files changed, 75 insertions(+), 15 deletions(-) rename samples/{ComputeSharp.Sample/ComputeSharp.Sample.csproj => ComputeSharp.Sample.Local/ComputeSharp.Sample.Local.csproj} (57%) create mode 100644 samples/ComputeSharp.Sample.NuGet/ComputeSharp.Sample.NuGet.csproj create mode 100644 samples/ComputeSharp.Sample.Shared/ComputeSharp.Sample.Shared.projitems create mode 100644 samples/ComputeSharp.Sample.Shared/ComputeSharp.Sample.Shared.shproj rename samples/{ComputeSharp.Sample => ComputeSharp.Sample.Shared}/Program.cs (100%) diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 01e8f1c0..8901a2f3 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -17,8 +17,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Benchmark", "s EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.ImageProcessing", "samples\ComputeSharp.ImageProcessing\ComputeSharp.ImageProcessing.csproj", "{524CC5DD-1DEE-4A30-9515-AB90965E5207}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Sample", "samples\ComputeSharp.Sample\ComputeSharp.Sample.csproj", "{7A48A85D-8866-4DED-A404-653ED09BF396}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests", "tests\ComputeSharp.Tests\ComputeSharp.Tests.csproj", "{E91F4D24-922A-4921-A8D7-9C45A143C45D}" @@ -39,7 +37,18 @@ Project("{13B669BE-BB05-4DDF-9536-439F39A36129}") = "ComputeSharp.Package", "src EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{FB17EF84-9208-47AC-921F-680CB1DAD8BA}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Sample.Local", "samples\ComputeSharp.Sample.Local\ComputeSharp.Sample.Local.csproj", "{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Sample.NuGet", "samples\ComputeSharp.Sample.NuGet\ComputeSharp.Sample.NuGet.csproj", "{C423C061-64F7-4C12-8E5F-75C5351D6308}" +EndProject +Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.Sample.Shared", "samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.shproj", "{8CEFC324-CA6C-4845-9AD9-70B92BD87057}" +EndProject Global + GlobalSection(SharedMSBuildProjectFiles) = preSolution + samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{7048deea-0a6f-46a0-b951-b682a8f1cb75}*SharedItemsImports = 5 + samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{8cefc324-ca6c-4845-9ad9-70b92bd87057}*SharedItemsImports = 13 + samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{c423c061-64f7-4c12-8e5f-75c5351d6308}*SharedItemsImports = 5 + EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 @@ -95,14 +104,6 @@ Global {524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|Any CPU.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 - {7A48A85D-8866-4DED-A404-653ED09BF396}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7A48A85D-8866-4DED-A404-653ED09BF396}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7A48A85D-8866-4DED-A404-653ED09BF396}.Debug|x64.ActiveCfg = Debug|Any CPU - {7A48A85D-8866-4DED-A404-653ED09BF396}.Debug|x64.Build.0 = Debug|Any CPU - {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|Any CPU.Build.0 = Release|Any CPU - {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|x64.ActiveCfg = Release|Any CPU - {7A48A85D-8866-4DED-A404-653ED09BF396}.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|x64.ActiveCfg = Debug|Any CPU @@ -135,6 +136,22 @@ Global {0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Release|Any CPU.Build.0 = Release|Any CPU {0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Release|x64.ActiveCfg = Release|Any CPU {0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.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|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|x64.ActiveCfg = Release|Any CPU + {7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Release|x64.Build.0 = Release|Any CPU + {C423C061-64F7-4C12-8E5F-75C5351D6308}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C423C061-64F7-4C12-8E5F-75C5351D6308}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C423C061-64F7-4C12-8E5F-75C5351D6308}.Debug|x64.ActiveCfg = Debug|Any CPU + {C423C061-64F7-4C12-8E5F-75C5351D6308}.Debug|x64.Build.0 = Debug|Any CPU + {C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|Any CPU.Build.0 = Release|Any CPU + {C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|x64.ActiveCfg = Release|Any CPU + {C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -142,10 +159,12 @@ Global GlobalSection(NestedProjects) = preSolution {34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {524CC5DD-1DEE-4A30-9515-AB90965E5207} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} - {7A48A85D-8866-4DED-A404-653ED09BF396} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {E91F4D24-922A-4921-A8D7-9C45A143C45D} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} {0A6AE752-2A1D-40F8-B9E7-46B60F5321A3} = {FB17EF84-9208-47AC-921F-680CB1DAD8BA} + {7048DEEA-0A6F-46A0-B951-B682A8F1CB75} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} + {C423C061-64F7-4C12-8E5F-75C5351D6308} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} + {8CEFC324-CA6C-4845-9AD9-70B92BD87057} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/nuget.config b/nuget.config index af57fd7e..a06b48ea 100644 --- a/nuget.config +++ b/nuget.config @@ -3,5 +3,6 @@ + diff --git a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj b/samples/ComputeSharp.Sample.Local/ComputeSharp.Sample.Local.csproj similarity index 57% rename from samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj rename to samples/ComputeSharp.Sample.Local/ComputeSharp.Sample.Local.csproj index 8b2bf452..6eb24def 100644 --- a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj +++ b/samples/ComputeSharp.Sample.Local/ComputeSharp.Sample.Local.csproj @@ -7,10 +7,9 @@ - + + + diff --git a/samples/ComputeSharp.Sample.NuGet/ComputeSharp.Sample.NuGet.csproj b/samples/ComputeSharp.Sample.NuGet/ComputeSharp.Sample.NuGet.csproj new file mode 100644 index 00000000..bdf283bf --- /dev/null +++ b/samples/ComputeSharp.Sample.NuGet/ComputeSharp.Sample.NuGet.csproj @@ -0,0 +1,14 @@ + + + + Exe + net5.0 + + + + + + + + + diff --git a/samples/ComputeSharp.Sample.Shared/ComputeSharp.Sample.Shared.projitems b/samples/ComputeSharp.Sample.Shared/ComputeSharp.Sample.Shared.projitems new file mode 100644 index 00000000..f30f1996 --- /dev/null +++ b/samples/ComputeSharp.Sample.Shared/ComputeSharp.Sample.Shared.projitems @@ -0,0 +1,14 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + 8cefc324-ca6c-4845-9ad9-70b92bd87057 + + + ComputeSharp.Sample.Shared + + + + + \ No newline at end of file diff --git a/samples/ComputeSharp.Sample.Shared/ComputeSharp.Sample.Shared.shproj b/samples/ComputeSharp.Sample.Shared/ComputeSharp.Sample.Shared.shproj new file mode 100644 index 00000000..51735cd3 --- /dev/null +++ b/samples/ComputeSharp.Sample.Shared/ComputeSharp.Sample.Shared.shproj @@ -0,0 +1,13 @@ + + + + 8cefc324-ca6c-4845-9ad9-70b92bd87057 + 14.0 + + + + + + + + diff --git a/samples/ComputeSharp.Sample/Program.cs b/samples/ComputeSharp.Sample.Shared/Program.cs similarity index 100% rename from samples/ComputeSharp.Sample/Program.cs rename to samples/ComputeSharp.Sample.Shared/Program.cs From 26572f84e41db48ffaf4f772cd6eadeeef118afe Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 14 Dec 2020 18:08:18 +0100 Subject: [PATCH 04/16] Added some comments to the .targets file --- Directory.Build.targets | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Directory.Build.targets b/Directory.Build.targets index 2d4b2af1..f8a7e174 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,4 +1,7 @@ + + @@ -20,11 +23,9 @@ Condition="'@(AnalyzerProjectReference)' != ''" AfterTargets="ComputeAnalyzerProjectReferences" BeforeTargets="CoreCompile"> - - + From 914d56a3a86fb7e9c749c9613e24703b9051b78e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 15 Dec 2020 17:08:33 +0100 Subject: [PATCH 05/16] Added APIs to check texture ND format support --- .../Extensions/ID3D12DeviceExtensions.cs | 19 +++++++++++ src/ComputeSharp.Graphics/GraphicsDevice.cs | 32 +++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs index 5e3d17f6..8a6f278c 100644 --- a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs @@ -9,6 +9,7 @@ using static TerraFX.Interop.D3D12_COMMAND_QUEUE_PRIORITY; using static TerraFX.Interop.D3D12_CPU_PAGE_PROPERTY; using static TerraFX.Interop.D3D12_DESCRIPTOR_HEAP_FLAGS; using static TerraFX.Interop.D3D12_DESCRIPTOR_HEAP_TYPE; +using static TerraFX.Interop.D3D12_FEATURE; using static TerraFX.Interop.D3D12_FENCE_FLAGS; using static TerraFX.Interop.D3D12_MEMORY_POOL; using static TerraFX.Interop.D3D12_HEAP_FLAGS; @@ -448,5 +449,23 @@ namespace ComputeSharp.Graphics.Extensions return feature; } + + /// + /// Checks whether or not a given DXGI format is supported for the specified resource type. + /// + /// The target to use to check features for. + /// The type to check support for. + /// The resource type to check support for. + /// Whether or not the input device supports the requested format for the specified resource type. + [Pure] + public static unsafe bool IsDxgiFormatSupported(this ref ID3D12Device d3D12Device, DXGI_FORMAT dxgiFormat, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport1) + { + D3D12_FEATURE_DATA_FORMAT_SUPPORT d3D12FeatureDataFormatSupport = default; + d3D12FeatureDataFormatSupport.Format = dxgiFormat; + + d3D12Device.CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &d3D12FeatureDataFormatSupport, (uint)sizeof(D3D12_FEATURE_DATA_FORMAT_SUPPORT)).Assert(); + + return (d3D12FeatureDataFormatSupport.Support1 & d3D12FormatSupport1) != 0; + } } } diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index a5e18802..92503ee7 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics.Commands; @@ -10,6 +11,7 @@ using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; using static TerraFX.Interop.D3D12_FEATURE; +using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; namespace ComputeSharp.Graphics { @@ -126,6 +128,36 @@ namespace ComputeSharp.Graphics /// internal ID3D12Device* D3D12Device => this.d3D12Device; + /// + /// Checks whether the current device supports the creation of + /// resources for a specified type . + /// + /// The type of values to check support for. + /// Whether instances can be created by the current device. + [Pure] + public bool IsTexture2DSupportedForType() + where T : unmanaged + { + ThrowIfDisposed(); + + return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D); + } + + /// + /// Checks whether the current device supports the creation of + /// resources for a specified type . + /// + /// The type of values to check support for. + /// Whether instances can be created by the current device. + [Pure] + public bool IsTexture3DSupportedForType() + where T : unmanaged + { + ThrowIfDisposed(); + + return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D); + } + /// internal void RentShaderResourceViewDescriptorHandles( out D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle, From 1f1ba3532410eda99d367890547d54a97a176594 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 15 Dec 2020 17:09:15 +0100 Subject: [PATCH 06/16] Added format validation to create texture ND types --- .../Buffers/Abstract/Texture2D{T}.cs | 6 ++ .../Buffers/Abstract/Texture3D{T}.cs | 6 ++ .../GraphicsDeviceMismatchException.cs | 3 - .../UnsupportedTextureTypeException.cs | 70 +++++++++++++++++++ 4 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/Texture2D{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/Texture2D{T}.cs index 57cf2a07..963c3b5f 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/Texture2D{T}.cs @@ -9,6 +9,7 @@ using ComputeSharp.Graphics.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; +using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; using static TerraFX.Interop.D3D12_RESOURCE_STATES; using static TerraFX.Interop.D3D12_SRV_DIMENSION; using static TerraFX.Interop.D3D12_UAV_DIMENSION; @@ -63,6 +64,11 @@ namespace ComputeSharp.Graphics.Buffers.Abstract Guard.IsBetweenOrEqualTo(width, 1, FX.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION, nameof(width)); Guard.IsBetweenOrEqualTo(height, 1, FX.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION, nameof(height)); + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D)) + { + UnsupportedTextureTypeException.ThrowForTexture2D(); + } + GraphicsDevice = device; Width = width; Height = height; diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/Texture3D{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/Texture3D{T}.cs index db758741..6539319a 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/Texture3D{T}.cs @@ -9,6 +9,7 @@ using ComputeSharp.Graphics.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; +using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; using static TerraFX.Interop.D3D12_RESOURCE_STATES; using static TerraFX.Interop.D3D12_SRV_DIMENSION; using static TerraFX.Interop.D3D12_UAV_DIMENSION; @@ -65,6 +66,11 @@ namespace ComputeSharp.Graphics.Buffers.Abstract Guard.IsBetweenOrEqualTo(height, 1, FX.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION, nameof(height)); Guard.IsBetweenOrEqualTo(depth, 1, FX.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION, nameof(depth)); + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D)) + { + UnsupportedTextureTypeException.ThrowForTexture2D(); + } + GraphicsDevice = device; Width = width; Height = height; diff --git a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs index ef4e927d..6790ec38 100644 --- a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs +++ b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs @@ -52,7 +52,6 @@ namespace ComputeSharp.Exceptions /// The type of values in the input buffer. /// The input that was used. /// The target instance that was used. - [Pure] internal static void Throw(Buffer buffer, GraphicsDevice device) where T : unmanaged { @@ -65,7 +64,6 @@ namespace ComputeSharp.Exceptions /// The type of values in the input buffer. /// The input that was used. /// The target instance that was used. - [Pure] internal static void Throw(Texture2D texture, GraphicsDevice device) where T : unmanaged { @@ -78,7 +76,6 @@ namespace ComputeSharp.Exceptions /// The type of values in the input buffer. /// The input that was used. /// The target instance that was used. - [Pure] internal static void Throw(Texture3D texture, GraphicsDevice device) where T : unmanaged { diff --git a/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs b/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs new file mode 100644 index 00000000..e7f1e242 --- /dev/null +++ b/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs @@ -0,0 +1,70 @@ +using System; +using System.Diagnostics.Contracts; +using System.Text; +using ComputeSharp.Graphics; +using Microsoft.Toolkit.Diagnostics; + +namespace ComputeSharp.Exceptions +{ + /// + /// A custom that indicates when a texture was attempted to be created with an unsupported type. + /// + public sealed class UnsupportedTextureTypeException : InvalidOperationException + { + /// + /// Creates a new instance. + /// + /// The message that describes the error. + private UnsupportedTextureTypeException(string message) + : base(message) + { + } + + /// + /// Creates a new instance from the specified parameters. + /// + /// The rank of the texture that couldn't be created. + /// The element type of texture that was being created. + /// A new instance with a formatted error message. + [Pure] + private static UnsupportedTextureTypeException Create(int rank, Type type) + { + StringBuilder builder = new(256); + + builder.AppendLine($"The device in use does not support creating {rank}D textures of type {type}."); + builder.Append($"Make sure to check the support at runtime by using {nameof(GraphicsDevice)}."); + + builder.AppendLine(rank switch + { + 2 => $"{nameof(GraphicsDevice.IsTexture2DSupportedForType)}().", + 3 => $"{nameof(GraphicsDevice.IsTexture3DSupportedForType)}().", + _ => ThrowHelper.ThrowArgumentException("Invalid texture rank") + }); + + builder.AppendLine($"As a possible workaround on older devices, consider using a texture type of lower rank, or a linear buffer."); + builder.ToString(); + + return new(builder.ToString()); + } + + /// + /// Throws a new instance from the specified parameters. + /// + /// The type of values in the texture that couldn't be created. + internal static void ThrowForTexture2D() + where T : unmanaged + { + throw Create(2, typeof(T)); + } + + /// + /// Throws a new instance from the specified parameters. + /// + /// The type of values in the texture that couldn't be created. + internal static void ThrowForTexture3D() + where T : unmanaged + { + throw Create(3, typeof(T)); + } + } +} \ No newline at end of file From 10a2a1c28b2bb5c187768ad7732c5111c873ade5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 15 Dec 2020 17:10:45 +0100 Subject: [PATCH 07/16] Lowered requirement to FL11_0 and SM6_0 --- src/ComputeSharp.Graphics/Helpers/DeviceHelper.Enumerator.cs | 4 ++-- src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs | 2 +- src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.Enumerator.cs b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.Enumerator.cs index 0c6b73cb..daefc4ec 100644 --- a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.Enumerator.cs +++ b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.Enumerator.cs @@ -126,7 +126,7 @@ namespace ComputeSharp.Graphics.Helpers HRESULT createDeviceResult = FX.D3D12CreateDevice( dxgiAdapter1.AsIUnknown().Get(), - D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_12_0, + D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_11_0, FX.__uuidof(), null); @@ -137,7 +137,7 @@ namespace ComputeSharp.Graphics.Helpers FX.D3D12CreateDevice( dxgiAdapter1.AsIUnknown().Get(), - D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_12_0, + D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_11_0, FX.__uuidof(), d3D12Device.GetVoidAddressOf()).Assert(); diff --git a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs index 86c880b7..4f4e08fe 100644 --- a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs @@ -95,7 +95,7 @@ namespace ComputeSharp.Graphics.Helpers HRESULT createDeviceResult = FX.D3D12CreateDevice( dxgiAdapter1.AsIUnknown().Get(), - D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_12_0, + D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_11_0, FX.__uuidof(), (void**)d3D12Device); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index d5e62752..38c19d3a 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs @@ -76,7 +76,7 @@ namespace ComputeSharp.Shaders.Translation // Try to compile the new compute shader fixed (char* shaderName = "") fixed (char* entryPoint = nameof(IComputeShader.Execute)) - fixed (char* shaderProfile = "cs_6_1") + fixed (char* shaderProfile = "cs_6_0") fixed (char* optimization = "-O3") { DxcCompiler.Get()->Compile( From 99529c3688a9d704d3c00eba1af00cee8d30a7d5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 19 Dec 2020 12:54:34 +0100 Subject: [PATCH 08/16] Removed ComputeSharp.Core reference from generator --- .../Attributes/ShaderMethodSourceAttribute.cs | 14 ++++++- .../ComputeSharp.Core.csproj | 2 +- .../ComputeSharp.Graphics.csproj | 1 + .../ComputeSharp.SourceGenerators.csproj | 37 +++++++++++++++++-- 4 files changed, 47 insertions(+), 7 deletions(-) diff --git a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs index 236d9f78..594e01ff 100644 --- a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs @@ -5,7 +5,6 @@ using System.Diagnostics.Contracts; using System.Reflection; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; -using Microsoft.Toolkit.Diagnostics; namespace ComputeSharp { @@ -79,7 +78,10 @@ namespace ComputeSharp [Pure] internal static ShaderMethodSourceAttribute GetForDelegate(Delegate function) { - Guard.IsTrue(function.Method.IsStatic, "Captured delegates need to wrap static methods"); + if (!function.Method.IsStatic) + { + ThrowArgumentExceptionForNonStaticShader(); + } var attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes(); string methodName = function.Method.GetFullName(); @@ -94,5 +96,13 @@ namespace ComputeSharp return MissingMethodSourceException.Throw(function); } + + /// + /// Throws an when a given is not static. + /// + private static void ThrowArgumentExceptionForNonStaticShader() + { + throw new ArgumentException("Captured delegates in a shader need to wrap a static method.", "function"); + } } } \ No newline at end of file diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj index deb643c7..17666dbb 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -19,7 +19,7 @@ - + diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index d5fab37a..945a84ec 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -6,6 +6,7 @@ + diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 467bb2d1..d2b96445 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -10,13 +10,42 @@ false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - From 41e9af11e79db7ced7ab2c61ae24270542a0428a Mon Sep 17 00:00:00 2001 From: SingleAccretion Date: Wed, 23 Dec 2020 19:38:51 +0300 Subject: [PATCH 09/16] Deleted all the infrastructure to reference source generators locally. Added a separate test project for source generators to avoid conflicts due to SGs including files from other projects directly. --- ComputeSharp.sln | 23 ++++++++++- Directory.Build.targets | 41 ------------------- .../ComputeSharp.Core.csproj | 17 +------- src/ComputeSharp/ComputeSharp.csproj | 6 +-- ...rp.Tests.Internals.SourceGenerators.csproj | 19 +++++++++ .../SourceGeneratorTests.cs | 0 .../ComputeSharp.Tests.Internals.csproj | 2 - 7 files changed, 42 insertions(+), 66 deletions(-) delete mode 100644 Directory.Build.targets create mode 100644 tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj rename tests/{ComputeSharp.Tests.Internals => ComputeSharp.Tests.Internals.SourceGenerators}/SourceGeneratorTests.cs (100%) diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 8901a2f3..715e9770 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -37,12 +37,14 @@ Project("{13B669BE-BB05-4DDF-9536-439F39A36129}") = "ComputeSharp.Package", "src EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{FB17EF84-9208-47AC-921F-680CB1DAD8BA}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Sample.Local", "samples\ComputeSharp.Sample.Local\ComputeSharp.Sample.Local.csproj", "{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Sample.Local", "samples\ComputeSharp.Sample.Local\ComputeSharp.Sample.Local.csproj", "{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Sample.NuGet", "samples\ComputeSharp.Sample.NuGet\ComputeSharp.Sample.NuGet.csproj", "{C423C061-64F7-4C12-8E5F-75C5351D6308}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Sample.NuGet", "samples\ComputeSharp.Sample.NuGet\ComputeSharp.Sample.NuGet.csproj", "{C423C061-64F7-4C12-8E5F-75C5351D6308}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.Sample.Shared", "samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.shproj", "{8CEFC324-CA6C-4845-9AD9-70B92BD87057}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Tests.Internals.SourceGenerators", "tests\ComputeSharp.Tests.Internals.SourceGenerators\ComputeSharp.Tests.Internals.SourceGenerators.csproj", "{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}" +EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{7048deea-0a6f-46a0-b951-b682a8f1cb75}*SharedItemsImports = 5 @@ -152,6 +154,22 @@ Global {C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|Any CPU.Build.0 = Release|Any CPU {C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|x64.ActiveCfg = Release|Any CPU {C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|x64.Build.0 = Release|Any CPU + {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Debug|x64.ActiveCfg = Debug|Any CPU + {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Debug|x64.Build.0 = Debug|Any CPU + {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Release|Any CPU.Build.0 = Release|Any CPU + {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Release|x64.ActiveCfg = Release|Any CPU + {149173F5-D0CE-4FEC-A040-DE472707D6B2}.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|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|x64.ActiveCfg = Release|Any CPU + {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -165,6 +183,7 @@ Global {7048DEEA-0A6F-46A0-B951-B682A8F1CB75} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {C423C061-64F7-4C12-8E5F-75C5351D6308} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {8CEFC324-CA6C-4845-9AD9-70B92BD87057} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} + {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/Directory.Build.targets b/Directory.Build.targets deleted file mode 100644 index f8a7e174..00000000 --- a/Directory.Build.targets +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj index 17666dbb..85cab145 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -3,26 +3,11 @@ netstandard2.0;net5.0 true - 9.0 - - - - - - false - true - - false + 9.0 - - - diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 3954a5b5..9d310d55 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -3,11 +3,7 @@ net5.0 9.0 - true - - - - lib\$(TargetFramework) + true diff --git a/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj b/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj new file mode 100644 index 00000000..b0e8280b --- /dev/null +++ b/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj @@ -0,0 +1,19 @@ + + + + net5.0 + false + + + + + + + + + + + + + + diff --git a/tests/ComputeSharp.Tests.Internals/SourceGeneratorTests.cs b/tests/ComputeSharp.Tests.Internals.SourceGenerators/SourceGeneratorTests.cs similarity index 100% rename from tests/ComputeSharp.Tests.Internals/SourceGeneratorTests.cs rename to tests/ComputeSharp.Tests.Internals.SourceGenerators/SourceGeneratorTests.cs diff --git a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj index 3515164a..5fd0b827 100644 --- a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj +++ b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj @@ -9,11 +9,9 @@ - - From 604ca2fea7e3942c1e5e3d69a5622fb2867bcf3d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 13:57:00 +0100 Subject: [PATCH 10/16] Added custom DXC/DXIL libraries resolver --- .../ComputeSharp.Graphics.csproj | 2 +- .../Translation/ShaderCompiler.cs | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index 945a84ec..8c720d45 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index 38c19d3a..3992bc49 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs @@ -1,7 +1,10 @@ using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; +using System.IO; +using System.Reflection; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; using TerraFX.Interop; @@ -34,6 +37,8 @@ namespace ComputeSharp.Shaders.Translation /// static ShaderCompiler() { + FX.ResolveLibrary += ResolveLibrary; + using ComPtr dxcCompiler = default; using ComPtr dxcLibrary = default; using ComPtr dxcIncludeHandler = default; @@ -51,6 +56,24 @@ namespace ComputeSharp.Shaders.Translation DxcIncludeHandler = dxcIncludeHandler.Move(); } + /// + /// A custom resolver to override the default library resolution behavior for the DXC and DXIL libraries. + /// + /// + private static IntPtr ResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) + { + if (libraryName != "dxcompiler" && libraryName != "dxil") return IntPtr.Zero; + + string libraryPath = Path.GetFullPath(@$"runtimes\win-x64\native\{libraryName}.dll"); + + if (NativeLibrary.TryLoad(libraryPath, out IntPtr handle)) + { + return handle; + } + + return IntPtr.Zero; + } + /// /// Compiles a new HLSL shader from the input source code. /// From db21568970e2e890f66d1ebf6ea648c01a2ef4d8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 16:02:58 +0100 Subject: [PATCH 11/16] Fixed loading of dxil.dll --- src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index 3992bc49..02a1e56e 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs @@ -39,6 +39,11 @@ namespace ComputeSharp.Shaders.Translation { FX.ResolveLibrary += ResolveLibrary; + fixed (char* p = @"runtimes\win-x64\native") + { + FX.SetDllDirectoryW((ushort*)p).Assert(); + } + using ComPtr dxcCompiler = default; using ComPtr dxcLibrary = default; using ComPtr dxcIncludeHandler = default; @@ -62,7 +67,7 @@ namespace ComputeSharp.Shaders.Translation /// private static IntPtr ResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) { - if (libraryName != "dxcompiler" && libraryName != "dxil") return IntPtr.Zero; + if (libraryName != "dxcompiler") return IntPtr.Zero; string libraryPath = Path.GetFullPath(@$"runtimes\win-x64\native\{libraryName}.dll"); From 6b50fe22619c775ec82cae2a6d64161621c1796a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 16:46:20 +0100 Subject: [PATCH 12/16] Fixed error handling for SetDllDirectoryW --- .../Translation/ShaderCompiler.cs | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index 02a1e56e..6eb47106 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs @@ -7,6 +7,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; +using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; @@ -37,12 +38,7 @@ namespace ComputeSharp.Shaders.Translation /// static ShaderCompiler() { - FX.ResolveLibrary += ResolveLibrary; - - fixed (char* p = @"runtimes\win-x64\native") - { - FX.SetDllDirectoryW((ushort*)p).Assert(); - } + InitializeDxcLibrariesLoading(); using ComPtr dxcCompiler = default; using ComPtr dxcLibrary = default; @@ -61,6 +57,21 @@ namespace ComputeSharp.Shaders.Translation DxcIncludeHandler = dxcIncludeHandler.Move(); } + /// + /// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries. + /// + private static void InitializeDxcLibrariesLoading() + { + FX.ResolveLibrary += ResolveLibrary; + + fixed (char* p = @"runtimes\win-x64\native") + { + int result = FX.SetDllDirectoryW((ushort*)p); + + if (result == 0) ThrowHelper.ThrowWin32Exception(); + } + } + /// /// A custom resolver to override the default library resolution behavior for the DXC and DXIL libraries. /// From fa2c74f7dbfb6840a06fe27bc0292cfe6560b13e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 16:50:25 +0100 Subject: [PATCH 13/16] Skipped library loading fixup in publish mode --- .../Translation/ShaderCompiler.cs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index 6eb47106..06b89783 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs @@ -62,13 +62,23 @@ namespace ComputeSharp.Shaders.Translation /// private static void InitializeDxcLibrariesLoading() { - FX.ResolveLibrary += ResolveLibrary; + string + dxcompilerPath = Path.GetFullPath(@$"runtimes\win-x64\native\dxcompiler.dll"), + dxilPath = Path.GetFullPath(@$"runtimes\win-x64\native\dxil.dll"); - fixed (char* p = @"runtimes\win-x64\native") + if (File.Exists(dxcompilerPath)) { - int result = FX.SetDllDirectoryW((ushort*)p); + FX.ResolveLibrary += ResolveLibrary; + } - if (result == 0) ThrowHelper.ThrowWin32Exception(); + if (File.Exists(dxilPath)) + { + fixed (char* p = @"runtimes\win-x64\native") + { + int result = FX.SetDllDirectoryW((ushort*)p); + + if (result == 0) ThrowHelper.ThrowWin32Exception(); + } } } From e1b89cda755293d7f6dc870a7d8da445dd0bc9e8 Mon Sep 17 00:00:00 2001 From: SingleAccretion Date: Wed, 30 Dec 2020 00:48:19 +0300 Subject: [PATCH 14/16] (Finally) fixed the loading of native libraries and added tests verifying that --- ComputeSharp.sln | 21 +-- .../Translation/ShaderCompiler.cs | 54 ++++--- ...Sharp.Tests.NativeLibrariesResolver.csproj | 16 ++ .../NativeLibrariesResolverTests.cs | 152 ++++++++++++++++++ 4 files changed, 212 insertions(+), 31 deletions(-) create mode 100644 tests/ComputeSharp.Tests.NativeLibrariesResolver/ComputeSharp.Tests.NativeLibrariesResolver.csproj create mode 100644 tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 715e9770..066d9426 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -43,7 +43,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Sample.NuGet", EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.Sample.Shared", "samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.shproj", "{8CEFC324-CA6C-4845-9AD9-70B92BD87057}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Tests.Internals.SourceGenerators", "tests\ComputeSharp.Tests.Internals.SourceGenerators\ComputeSharp.Tests.Internals.SourceGenerators.csproj", "{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.Internals.SourceGenerators", "tests\ComputeSharp.Tests.Internals.SourceGenerators\ComputeSharp.Tests.Internals.SourceGenerators.csproj", "{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Tests.NativeLibrariesResolver", "tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj", "{BF52326F-E415-49E6-8595-62762216762B}" EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution @@ -154,14 +156,6 @@ Global {C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|Any CPU.Build.0 = Release|Any CPU {C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|x64.ActiveCfg = Release|Any CPU {C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|x64.Build.0 = Release|Any CPU - {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Debug|x64.ActiveCfg = Debug|Any CPU - {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Debug|x64.Build.0 = Debug|Any CPU - {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Release|Any CPU.Build.0 = Release|Any CPU - {149173F5-D0CE-4FEC-A040-DE472707D6B2}.Release|x64.ActiveCfg = Release|Any CPU - {149173F5-D0CE-4FEC-A040-DE472707D6B2}.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|x64.ActiveCfg = Debug|Any CPU @@ -170,6 +164,14 @@ Global {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Release|Any CPU.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|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|x64.ActiveCfg = Release|Any CPU + {BF52326F-E415-49E6-8595-62762216762B}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -184,6 +186,7 @@ Global {C423C061-64F7-4C12-8E5F-75C5351D6308} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {8CEFC324-CA6C-4845-9AD9-70B92BD87057} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} + {BF52326F-E415-49E6-8595-62762216762B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index 06b89783..75e77b7d 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs @@ -62,39 +62,49 @@ namespace ComputeSharp.Shaders.Translation /// private static void InitializeDxcLibrariesLoading() { - string - dxcompilerPath = Path.GetFullPath(@$"runtimes\win-x64\native\dxcompiler.dll"), - dxilPath = Path.GetFullPath(@$"runtimes\win-x64\native\dxil.dll"); + // We are probing for a "dotnet run" scenario + string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, @$"runtimes\win-x64\native"); + bool probeNuGetDirectory = Directory.Exists(nugetNativeLibsPath); - if (File.Exists(dxcompilerPath)) - { - FX.ResolveLibrary += ResolveLibrary; - } - - if (File.Exists(dxilPath)) - { - fixed (char* p = @"runtimes\win-x64\native") - { - int result = FX.SetDllDirectoryW((ushort*)p); - - if (result == 0) ThrowHelper.ThrowWin32Exception(); - } - } + // We fail to load "dxil.dll" when doing "dotnet bin\Debug\net5.0\MyApp.dll" + FX.ResolveLibrary += (n, a, s) => ResolveLibrary(n, a, s, probeNuGetDirectory); } /// /// A custom resolver to override the default library resolution behavior for the DXC and DXIL libraries. + /// Meant to enable "dotnet run"-like scenarios for projects without RIDs by loading native dependencies from where the SDK puts them. /// /// - private static IntPtr ResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) + private static IntPtr ResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, bool probeNuGetDirectory) { if (libraryName != "dxcompiler") return IntPtr.Zero; - string libraryPath = Path.GetFullPath(@$"runtimes\win-x64\native\{libraryName}.dll"); - - if (NativeLibrary.TryLoad(libraryPath, out IntPtr handle)) + if (probeNuGetDirectory) { - return handle; + string dxcompilerPath = Path.Combine(AppContext.BaseDirectory, @$"runtimes\win-x64\native\dxcompiler.dll"); + string dxilPath = Path.Combine(AppContext.BaseDirectory, @$"runtimes\win-x64\native\dxil.dll"); + + // We are loading the dependency of dxcompiler.dll, dxil.dll, first, so that it is automatically picked up + // from memory by dxcompiler.dll on it being loaded + // This is necessary because .NET does not currently provide great facilities for loading + // native dependencies of native dependencies + if (NativeLibrary.TryLoad(dxilPath, out _) && NativeLibrary.TryLoad(dxcompilerPath, out IntPtr handle)) + { + return handle; + } + } + else + { + // It may come as a surprise we need this, but apparently we do + // The suspicion is that's because Windows doesn't know anything about .NET's + // "App directory" concept, only "Process directory", and when we invoke "dotnet bin\Managed.dll" + // Neither our current directory ("bin"), nor our "Process directory" ("C:\Program Files\dotnet") contain the native dependency + // Which means LoadLibraryEx fails to load it + if (NativeLibrary.TryLoad("dxil", assembly, searchPath, out _) && + NativeLibrary.TryLoad("dxcompiler", assembly, searchPath, out IntPtr handle)) + { + return handle; + } } return IntPtr.Zero; diff --git a/tests/ComputeSharp.Tests.NativeLibrariesResolver/ComputeSharp.Tests.NativeLibrariesResolver.csproj b/tests/ComputeSharp.Tests.NativeLibrariesResolver/ComputeSharp.Tests.NativeLibrariesResolver.csproj new file mode 100644 index 00000000..36d9d5ca --- /dev/null +++ b/tests/ComputeSharp.Tests.NativeLibrariesResolver/ComputeSharp.Tests.NativeLibrariesResolver.csproj @@ -0,0 +1,16 @@ + + + + net5.0 + 9.0 + false + + + + + + + + + + diff --git a/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs b/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs new file mode 100644 index 00000000..27dedca6 --- /dev/null +++ b/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs @@ -0,0 +1,152 @@ +using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; + +namespace ComputeSharp.Tests.NativeLibrariesResolver +{ + [TestClass] + public class NativeLibrariesResolverTests + { + static NativeLibrariesResolverTests() + { + var path = Path.GetDirectoryName(typeof(NativeLibrariesResolverTests).Assembly.Location); + while (Path.GetFileName(path) is not "ComputeSharp") + { + path = Path.GetDirectoryName(path); + } + + SampleProjectDirectory = Path.Combine(path, "samples", "ComputeSharp.Sample.NuGet"); + var sampleProjectPath = Path.Combine(SampleProjectDirectory, "ComputeSharp.Sample.NuGet.csproj"); + + var packagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.msbuildproj"); + Process.Start("dotnet", $"pack {packagingProjectPath} -c Release").WaitForExit(); + // We use "--no-restore" where possible to speed up the tests + Process.Start("dotnet", $"restore {sampleProjectPath}").WaitForExit(); + } + + private static string SampleProjectDirectory { get; } + + [TestMethod] + [DataRow(Configuration.Debug, RID.None)] + [DataRow(Configuration.Debug, RID.Win_x64)] + [DataRow(Configuration.Release, RID.None)] + [DataRow(Configuration.Release, RID.Win_x64)] + public void DotnetRunWorks(Configuration configuration, RID rid) + { + // "dotnet run" fails with "--no-restore" + Assert.AreEqual(0, Exec(SampleProjectDirectory, "dotnet", $"run -c {configuration} {ToOption(rid)}")); + } + + [TestMethod] + [DataRow(Configuration.Debug, RID.None)] + [DataRow(Configuration.Debug, RID.Win_x64)] + [DataRow(Configuration.Release, RID.None)] + [DataRow(Configuration.Release, RID.Win_x64)] + public void DotnetBuildWithRunningDotnetHostFromProjectDirectoryWorks(Configuration configuration, RID rid) + { + BuildSampleProject(configuration, rid); + var realtivePathToDll = Path.Combine("bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.dll"); + Assert.AreEqual(0, Exec(SampleProjectDirectory, "dotnet", realtivePathToDll)); + } + + [TestMethod] + [DataRow(Configuration.Debug, RID.None)] + [DataRow(Configuration.Debug, RID.Win_x64)] + [DataRow(Configuration.Release, RID.None)] + [DataRow(Configuration.Release, RID.Win_x64)] + public void DotnetBuildWithRunningDotnetHostDirectlyWorks(Configuration configuration, RID rid) + { + BuildSampleProject(configuration, rid); + var pathToDllDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}"); + Assert.AreEqual(0, Exec(pathToDllDirectory, "dotnet", "ComputeSharp.Sample.NuGet.dll")); + } + + [TestMethod] + [DataRow(Configuration.Debug, RID.None)] + [DataRow(Configuration.Debug, RID.Win_x64)] + [DataRow(Configuration.Release, RID.None)] + [DataRow(Configuration.Release, RID.Win_x64)] + public void DotnetBuildWithRunningAppHostFromProjectDirectoryWorks(Configuration configuration, RID rid) + { + BuildSampleProject(configuration, rid); + var relativePathToAppHost = Path.Combine("bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.exe"); + Assert.AreEqual(0, Exec(SampleProjectDirectory, relativePathToAppHost, "")); + } + + [TestMethod] + [DataRow(Configuration.Debug, RID.None)] + [DataRow(Configuration.Debug, RID.Win_x64)] + [DataRow(Configuration.Release, RID.None)] + [DataRow(Configuration.Release, RID.Win_x64)] + public void DotnetBuildWithRunningAppHostDirectlyWorks(Configuration configuration, RID rid) + { + BuildSampleProject(configuration, rid); + var pathToAppHostDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}"); + Assert.AreEqual(0, Exec(pathToAppHostDirectory, "ComputeSharp.Sample.NuGet.exe", "")); + } + + [TestMethod] + [DataRow(Configuration.Debug)] + [DataRow(Configuration.Release)] + public void DotnetPublishWorks(Configuration configuration) + { + // We do not support publishing without the RID + Exec(SampleProjectDirectory, "dotnet", $"publish -c {configuration} -r win-x64 --no-restore"); + var pathToAppHost = Path.Combine("bin", $"{configuration}", "net5.0", "win-x64", "publish", "ComputeSharp.Sample.NuGet.exe"); + Assert.AreEqual(0, Exec(SampleProjectDirectory, pathToAppHost, "")); + } + + private static void BuildSampleProject(Configuration configuration, RID rid) + { + Exec(SampleProjectDirectory, "dotnet", $"build -c {configuration} {ToOption(rid)} --no-restore"); + } + + private static int Exec(string workingDirectory, string filePath, string arguments) + { + var startInfo = new ProcessStartInfo + { + UseShellExecute = true, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + FileName = filePath, + Arguments = arguments, + WorkingDirectory = workingDirectory + }; + + var process = Process.Start(startInfo); + process.WaitForExit(); + + return process.ExitCode; + } + + private static string ToOption(RID rid) => rid switch + { + RID.None => "", + RID.Win_x64 => "-r win-x64", + _ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID)) + }; + + private static string ToDirectory(RID rid) => rid switch + { + RID.None => "", + RID.Win_x64 => "win-x64", + _ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID)) + }; + + public enum Configuration + { + Debug, + Release + } + + public enum RID + { + None, + Win_x64, + } + } +} From 9146efc596cd4dc2a4821ff2fa22c7602893a9b3 Mon Sep 17 00:00:00 2001 From: SingleAccretion Date: Wed, 30 Dec 2020 01:01:10 +0300 Subject: [PATCH 15/16] Fixed formatting of ComputeSharp.Sample.Local --- .../ComputeSharp.Sample.Local.csproj | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/samples/ComputeSharp.Sample.Local/ComputeSharp.Sample.Local.csproj b/samples/ComputeSharp.Sample.Local/ComputeSharp.Sample.Local.csproj index 6eb24def..7c96952c 100644 --- a/samples/ComputeSharp.Sample.Local/ComputeSharp.Sample.Local.csproj +++ b/samples/ComputeSharp.Sample.Local/ComputeSharp.Sample.Local.csproj @@ -7,7 +7,10 @@ - + From 7cf7bf6c8558adaeb247d6729030a0a591e9c13d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 23:36:02 +0100 Subject: [PATCH 16/16] Improved some comments --- .../Translation/ShaderCompiler.cs | 46 ++++++----- .../NativeLibrariesResolverTests.cs | 76 +++++++++++++++---- 2 files changed, 85 insertions(+), 37 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index 75e77b7d..78c5b1ea 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs @@ -7,7 +7,6 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; -using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; @@ -62,32 +61,35 @@ namespace ComputeSharp.Shaders.Translation /// private static void InitializeDxcLibrariesLoading() { - // We are probing for a "dotnet run" scenario - string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, @$"runtimes\win-x64\native"); - bool probeNuGetDirectory = Directory.Exists(nugetNativeLibsPath); + // Test whether the native libraries are present in the same folder of the executable + // (which is the case when the program was built with a runtime identifier), or whether + // they are in the "runtimes\win-x64\native" folder in the executable directory. + string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native"); + bool isNuGetRuntimeLibrariesDirectoryPresent = Directory.Exists(nugetNativeLibsPath); - // We fail to load "dxil.dll" when doing "dotnet bin\Debug\net5.0\MyApp.dll" - FX.ResolveLibrary += (n, a, s) => ResolveLibrary(n, a, s, probeNuGetDirectory); + // Register a custom library resolver for the two DXC libraries. We need to either manually load the two + // libraries from the NuGet directory, if an RID is not in use, or we need to ensure that dxil.dll is + // loaded correctly in case the program was executed with the host being in another directory. + // This happens when doing eg. "dotnet bin\Debug\net5.0\MyApp.dll", which would crash at runtime. + FX.ResolveLibrary += (n, a, s) => ResolveLibrary(n, a, s, isNuGetRuntimeLibrariesDirectoryPresent); } /// /// A custom resolver to override the default library resolution behavior for the DXC and DXIL libraries. - /// Meant to enable "dotnet run"-like scenarios for projects without RIDs by loading native dependencies from where the SDK puts them. + /// This either loads the libraries from the NuGet directory, or just ensures that DXIL is always loaded. /// /// - private static IntPtr ResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, bool probeNuGetDirectory) + private static IntPtr ResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, bool isNuGetRuntimeLibrariesDirectoryPresent) { - if (libraryName != "dxcompiler") return IntPtr.Zero; + if (libraryName is not "dxcompiler") return IntPtr.Zero; - if (probeNuGetDirectory) + if (isNuGetRuntimeLibrariesDirectoryPresent) { - string dxcompilerPath = Path.Combine(AppContext.BaseDirectory, @$"runtimes\win-x64\native\dxcompiler.dll"); - string dxilPath = Path.Combine(AppContext.BaseDirectory, @$"runtimes\win-x64\native\dxil.dll"); + string + dxcompilerPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxcompiler.dll"), + dxilPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxil.dll"); - // We are loading the dependency of dxcompiler.dll, dxil.dll, first, so that it is automatically picked up - // from memory by dxcompiler.dll on it being loaded - // This is necessary because .NET does not currently provide great facilities for loading - // native dependencies of native dependencies + // Load DXIL first so that DXC doesn't fail to load it, and then DXIL, both from the NuGet path if (NativeLibrary.TryLoad(dxilPath, out _) && NativeLibrary.TryLoad(dxcompilerPath, out IntPtr handle)) { return handle; @@ -95,11 +97,13 @@ namespace ComputeSharp.Shaders.Translation } else { - // It may come as a surprise we need this, but apparently we do - // The suspicion is that's because Windows doesn't know anything about .NET's - // "App directory" concept, only "Process directory", and when we invoke "dotnet bin\Managed.dll" - // Neither our current directory ("bin"), nor our "Process directory" ("C:\Program Files\dotnet") contain the native dependency - // Which means LoadLibraryEx fails to load it + // Even when the two libraries are correctly copied next to the executable in use, we load them + // manually to ensure the operation is successful. This is to avoid failures in cases such as when + // doing "dotnet bin\MyApp.dll", ie. when the host is in another path than the executable in use. + // This is probably because DXIL is a native dependency for DXC, but the way Windows loads these + // libraries doesn't take into account the .NET concepts of "app directory": neither the current "bin" + // directory nor the "process directory", which is "C:\Program Files\dotnet", actually contain the + // native library we need, hence the runtime crash. Manually loading the library this way solves this. if (NativeLibrary.TryLoad("dxil", assembly, searchPath, out _) && NativeLibrary.TryLoad("dxcompiler", assembly, searchPath, out IntPtr handle)) { diff --git a/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs b/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs index 27dedca6..6f1add7c 100644 --- a/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs +++ b/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs @@ -1,9 +1,6 @@ -using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; using System.ComponentModel; using System.Diagnostics; -using System.Globalization; using System.IO; namespace ComputeSharp.Tests.NativeLibrariesResolver @@ -13,21 +10,29 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver { static NativeLibrariesResolverTests() { - var path = Path.GetDirectoryName(typeof(NativeLibrariesResolverTests).Assembly.Location); + string path = Path.GetDirectoryName(typeof(NativeLibrariesResolverTests).Assembly.Location); + while (Path.GetFileName(path) is not "ComputeSharp") { path = Path.GetDirectoryName(path); } SampleProjectDirectory = Path.Combine(path, "samples", "ComputeSharp.Sample.NuGet"); - var sampleProjectPath = Path.Combine(SampleProjectDirectory, "ComputeSharp.Sample.NuGet.csproj"); - var packagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.msbuildproj"); + string + sampleProjectPath = Path.Combine(SampleProjectDirectory, "ComputeSharp.Sample.NuGet.csproj"), + packagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.msbuildproj"); + + // Run dotnet pack and on the packaging project, to ensure the local NuGet package is + // available. Then run dotnet restore on the sample project. This is done so that + // other tests can skip the restore step to run faster, as there's lots of them. Process.Start("dotnet", $"pack {packagingProjectPath} -c Release").WaitForExit(); - // We use "--no-restore" where possible to speed up the tests Process.Start("dotnet", $"restore {sampleProjectPath}").WaitForExit(); } + /// + /// Gets the directory of the ComputeSharp.Sample.NuGet project. + /// private static string SampleProjectDirectory { get; } [TestMethod] @@ -37,7 +42,7 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver [DataRow(Configuration.Release, RID.Win_x64)] public void DotnetRunWorks(Configuration configuration, RID rid) { - // "dotnet run" fails with "--no-restore" + // "dotnet run" fails with "--no-restore", so in this case we restore packages as well Assert.AreEqual(0, Exec(SampleProjectDirectory, "dotnet", $"run -c {configuration} {ToOption(rid)}")); } @@ -49,7 +54,9 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver public void DotnetBuildWithRunningDotnetHostFromProjectDirectoryWorks(Configuration configuration, RID rid) { BuildSampleProject(configuration, rid); - var realtivePathToDll = Path.Combine("bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.dll"); + + string realtivePathToDll = Path.Combine("bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.dll"); + Assert.AreEqual(0, Exec(SampleProjectDirectory, "dotnet", realtivePathToDll)); } @@ -61,7 +68,9 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver public void DotnetBuildWithRunningDotnetHostDirectlyWorks(Configuration configuration, RID rid) { BuildSampleProject(configuration, rid); - var pathToDllDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}"); + + string pathToDllDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}"); + Assert.AreEqual(0, Exec(pathToDllDirectory, "dotnet", "ComputeSharp.Sample.NuGet.dll")); } @@ -73,7 +82,9 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver public void DotnetBuildWithRunningAppHostFromProjectDirectoryWorks(Configuration configuration, RID rid) { BuildSampleProject(configuration, rid); - var relativePathToAppHost = Path.Combine("bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.exe"); + + string relativePathToAppHost = Path.Combine("bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.exe"); + Assert.AreEqual(0, Exec(SampleProjectDirectory, relativePathToAppHost, "")); } @@ -85,7 +96,9 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver public void DotnetBuildWithRunningAppHostDirectlyWorks(Configuration configuration, RID rid) { BuildSampleProject(configuration, rid); - var pathToAppHostDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}"); + + string pathToAppHostDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}"); + Assert.AreEqual(0, Exec(pathToAppHostDirectory, "ComputeSharp.Sample.NuGet.exe", "")); } @@ -94,20 +107,34 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver [DataRow(Configuration.Release)] public void DotnetPublishWorks(Configuration configuration) { - // We do not support publishing without the RID + // Publishing without specifying an RID is not supported Exec(SampleProjectDirectory, "dotnet", $"publish -c {configuration} -r win-x64 --no-restore"); - var pathToAppHost = Path.Combine("bin", $"{configuration}", "net5.0", "win-x64", "publish", "ComputeSharp.Sample.NuGet.exe"); + + string pathToAppHost = Path.Combine("bin", $"{configuration}", "net5.0", "win-x64", "publish", "ComputeSharp.Sample.NuGet.exe"); + Assert.AreEqual(0, Exec(SampleProjectDirectory, pathToAppHost, "")); } + /// + /// Builds the sample project with a specific configuration and target runtime. + /// + /// The configuration to use to build the project. + /// The RID to use to build the project. private static void BuildSampleProject(Configuration configuration, RID rid) { Exec(SampleProjectDirectory, "dotnet", $"build -c {configuration} {ToOption(rid)} --no-restore"); } + /// + /// Executes a specified process from the command line and returns the exit code. + /// + /// The working directory to execute the process. + /// The target file path for the process to execute. + /// The arguments to invoke the process. + /// The exit code for the executed process. private static int Exec(string workingDirectory, string filePath, string arguments) { - var startInfo = new ProcessStartInfo + ProcessStartInfo startInfo = new() { UseShellExecute = true, CreateNoWindow = true, @@ -117,12 +144,18 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver WorkingDirectory = workingDirectory }; - var process = Process.Start(startInfo); + Process process = Process.Start(startInfo); + process.WaitForExit(); return process.ExitCode; } + /// + /// Gets a text representation of a cmd option for the dotnet tool, for the given . + /// + /// The input value. + /// A text representation for . private static string ToOption(RID rid) => rid switch { RID.None => "", @@ -130,6 +163,11 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver _ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID)) }; + /// + /// Gets a text representation of the build folder for the given . + /// + /// The input value. + /// A text representation for . private static string ToDirectory(RID rid) => rid switch { RID.None => "", @@ -137,12 +175,18 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver _ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID)) }; + /// + /// A build configuration. + /// public enum Configuration { Debug, Release } + /// + /// A runtime identifier. + /// public enum RID { None,