diff --git a/ComputeSharp.sln b/ComputeSharp.sln index b6780dc1..066d9426 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}" @@ -28,13 +26,33 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_SolutionItems", "_SolutionItems", "{1A9C4108-F61A-4ABE-B5CF-F524521EAE2D}" ProjectSection(SolutionItems) = preProject .gitignore = .gitignore + global.json = global.json LICENSE = LICENSE README.md = README.md EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.SourceGenerators", "src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj", "{EB52CB67-4162-4722-874B-44EA8DA5450E}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SourceGenerators", "src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj", "{EB52CB67-4162-4722-874B-44EA8DA5450E}" +EndProject +Project("{13B669BE-BB05-4DDF-9536-439F39A36129}") = "ComputeSharp.Package", "src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj", "{0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{FB17EF84-9208-47AC-921F-680CB1DAD8BA}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Sample.Local", "samples\ComputeSharp.Sample.Local\ComputeSharp.Sample.Local.csproj", "{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}" +EndProject +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("{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 + 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 @@ -90,14 +108,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 @@ -122,6 +132,46 @@ Global {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|Any CPU.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 + {0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Debug|x64.ActiveCfg = Debug|Any CPU + {0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Debug|x64.Build.0 = Debug|Any CPU + {0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {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 + {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 + {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 @@ -129,9 +179,14 @@ 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} + {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/global.json b/global.json new file mode 100644 index 00000000..2cb2ac9b --- /dev/null +++ b/global.json @@ -0,0 +1,5 @@ +{ + "sdk": { + "version": "5.0.100" + } +} \ No newline at end of file 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.Benchmark/ComputeSharp.Benchmark.csproj b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj index 99d0ea05..06bb8291 100644 --- a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj +++ b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj @@ -11,11 +11,10 @@ - + - + \ No newline at end of file diff --git a/samples/ComputeSharp.Benchmark/Dnn.cs b/samples/ComputeSharp.Benchmark/Dnn.cs index 8ab2cfaa..c6a3cc53 100644 --- a/samples/ComputeSharp.Benchmark/Dnn.cs +++ b/samples/ComputeSharp.Benchmark/Dnn.cs @@ -73,15 +73,15 @@ namespace ComputeSharp.Benchmark /// Kernel for . /// [AutoConstructor] - private readonly partial struct FullyConnectedForwardKernel : IComputeShader + public readonly partial struct FullyConnectedForwardKernel : IComputeShader { - private readonly int n; - private readonly int m; - private readonly int p; - private readonly ReadOnlyBuffer x; - private readonly ReadOnlyBuffer w; - private readonly ReadOnlyBuffer b; - private readonly ReadWriteBuffer y; + public readonly int n; + public readonly int m; + public readonly int p; + public readonly ReadOnlyBuffer x; + public readonly ReadOnlyBuffer w; + public readonly ReadOnlyBuffer b; + public readonly ReadWriteBuffer y; /// public void Execute(ThreadIds ids) diff --git a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj index 422f73dd..88210549 100644 --- a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj +++ b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj @@ -6,13 +6,7 @@ - - - - - - PreserveNewest - + @@ -21,11 +15,10 @@ - + diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs index c756217e..84e05a55 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs @@ -1,4 +1,5 @@ -using SixLabors.ImageSharp; +using System.Numerics; +using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; @@ -7,7 +8,7 @@ namespace ComputeSharp.BokehBlur.Processors /// /// Applies bokeh blur processing to the image. /// - public sealed class HlslBokehBlurProcessor : IImageProcessor + public sealed partial class HlslBokehBlurProcessor : IImageProcessor { /// /// The default radius used by the parameterless constructor. @@ -63,5 +64,87 @@ namespace ComputeSharp.BokehBlur.Processors { return new HlslBokehBlurProcessor(this, configuration, source, sourceRectangle); } + + /// + /// Kernel for the vertical convolution pass. + /// + [AutoConstructor] + internal partial struct VerticalConvolutionProcessor : IComputeShader + { + public int width; + public int maxY; + public int maxX; + public int kernelLength; + + public ReadOnlyBuffer source; + public ReadWriteBuffer target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 real = Vector4.Zero; + Vector4 imaginary = Vector4.Zero; + int radiusY = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + + for (int i = 0; i < kernelLength; i++) + { + int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + Vector4 color = source[offsetY * width + offsetX]; + Complex64 factors = kernel[i]; + + real += factors.Real * color; + imaginary += factors.Imaginary * color; + } + + int offsetXY = ids.Y * width + ids.X; + + target[offsetXY].Real = real; + target[offsetXY].Imaginary = imaginary; + } + } + + /// + /// Kernel for the horizontal convolution pass. + /// + [AutoConstructor] + internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader + { + public int width; + public int maxY; + public int maxX; + public int kernelLength; + public float z; + public float w; + + public ReadWriteBuffer source; + public ReadWriteBuffer target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 real = Vector4.Zero; + Vector4 imaginary = Vector4.Zero; + int radiusX = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); + + for (int i = 0; i < kernelLength; i++) + { + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + var offsetXY = offsetY * width + offsetX; + ComplexVector4 source4 = source[offsetXY]; + Complex64 factors = kernel[i]; + + real += factors.Real * source4.Real - factors.Imaginary * source4.Imaginary; + imaginary += factors.Real * source4.Imaginary + factors.Imaginary * source4.Real; + } + + target[ids.Y * width + ids.X] += real * z + imaginary * w; + } + } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index f22b9abd..bbc41abb 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -301,7 +301,7 @@ namespace ComputeSharp.BokehBlur.Processors int height = Source.Height; int width = Source.Width; - VerticalConvolutionProcessor shader = new( + HlslBokehBlurProcessor.VerticalConvolutionProcessor shader = new( width, maxY: height - 1, maxX: width - 1, @@ -313,47 +313,6 @@ namespace ComputeSharp.BokehBlur.Processors Gpu.Default.For(width, height, in shader); } - /// - /// Kernel for . - /// - [AutoConstructor] - private partial struct VerticalConvolutionProcessor : IComputeShader - { - public int width; - public int maxY; - public int maxX; - public int kernelLength; - - public ReadOnlyBuffer source; - public ReadWriteBuffer target; - public ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 real = Vector4.Zero; - Vector4 imaginary = Vector4.Zero; - int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - - for (int i = 0; i < kernelLength; i++) - { - int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); - Vector4 color = source[offsetY * width + offsetX]; - Complex64 factors = kernel[i]; - - real += factors.Real * color; - imaginary += factors.Imaginary * color; - } - - int offsetXY = ids.Y * width + ids.X; - - target[offsetXY].Real = real; - target[offsetXY].Imaginary = imaginary; - } - } - /// /// Performs an horizontal 1D complex convolution with the specified parameters. /// @@ -373,7 +332,7 @@ namespace ComputeSharp.BokehBlur.Processors int height = Source.Height; int width = Source.Width; - HorizontalConvolutionAndAccumulatePartialsProcessor shader = new( + HlslBokehBlurProcessor.HorizontalConvolutionAndAccumulatePartialsProcessor shader = new( width, maxY: height - 1, maxX: width - 1, @@ -387,47 +346,6 @@ namespace ComputeSharp.BokehBlur.Processors Gpu.Default.For(width, height, in shader); } - /// - /// Kernel for . - /// - [AutoConstructor] - private partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader - { - public int width; - public int maxY; - public int maxX; - public int kernelLength; - public float z; - public float w; - - public ReadWriteBuffer source; - public ReadWriteBuffer target; - public ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 real = Vector4.Zero; - Vector4 imaginary = Vector4.Zero; - int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); - - for (int i = 0; i < kernelLength; i++) - { - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); - var offsetXY = offsetY * width + offsetX; - ComplexVector4 source4 = source[offsetXY]; - Complex64 factors = kernel[i]; - - real += factors.Real * source4.Real - factors.Imaginary * source4.Imaginary; - imaginary += factors.Real * source4.Imaginary + factors.Imaginary * source4.Real; - } - - target[ids.Y * width + ids.X] += real * z + imaginary * w; - } - } - /// /// Applies the gamma correction/highlight to the input pixel buffer and returns an instance with values. /// diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs index f7aca904..b0d22c81 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs @@ -1,4 +1,5 @@ -using SixLabors.ImageSharp; +using System.Numerics; +using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; @@ -7,7 +8,7 @@ namespace ComputeSharp.BokehBlur.Processors /// /// Defines Gaussian blur by a (Sigma, Radius) pair. /// - public sealed class HlslGaussianBlurProcessor : IImageProcessor + public sealed partial class HlslGaussianBlurProcessor : IImageProcessor { /// /// The default value for . @@ -52,5 +53,79 @@ namespace ComputeSharp.BokehBlur.Processors { return new HlslGaussianBlurProcessor(this, configuration, source, sourceRectangle); } + + /// + /// Kernel for the vertical convolution pass. + /// + [AutoConstructor] + internal readonly partial struct VerticalConvolutionProcessor : IComputeShader + { + public readonly int width; + public readonly int maxY; + public readonly int maxX; + public readonly int kernelLength; + + public readonly ReadWriteBuffer source; + public readonly ReadWriteBuffer target; + public readonly ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 result = Vector4.Zero; + int radiusY = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + + for (int i = 0; i < kernelLength; i++) + { + int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + Vector4 color = source[offsetY * width + offsetX]; + + result += kernel[i] * color; + } + + int offsetXY = ids.Y * width + ids.X; + target[offsetXY] = result; + } + } + + /// + /// Kernel for the horizontal convolution pass. + /// + [AutoConstructor] + internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader + { + public readonly int width; + public readonly int maxY; + public readonly int maxX; + public readonly int kernelLength; + + public readonly ReadWriteBuffer source; + public readonly ReadWriteBuffer target; + public readonly ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 result = Vector4.Zero; + int radiusX = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); + int offsetXY; + + for (int i = 0; i < kernelLength; i++) + { + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + offsetXY = offsetY * width + offsetX; + Vector4 color = source[offsetXY]; + + result += kernel[i] * color; + } + + offsetXY = ids.Y * width + ids.X; + target[offsetXY] = result; + } + } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 31ca80cc..4ea8671c 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -13,7 +13,7 @@ namespace ComputeSharp.BokehBlur.Processors /// Applies Gaussian blur processing to an image. /// /// The pixel format. - internal class HlslGaussianBlurProcessor : ImageProcessor + internal sealed class HlslGaussianBlurProcessor : ImageProcessor where TPixel : unmanaged, IPixel { /// @@ -124,51 +124,16 @@ namespace ComputeSharp.BokehBlur.Processors int height = Source.Height; int width = Source.Width; - Gpu.Default.For(width, height, new VerticalConvolutionProcessor - { - width = width, - maxY = height - 1, - maxX = width - 1, - kernelLength = kernel.Length, - source = source, - target = target, - kernel = kernel - }); - } + HlslGaussianBlurProcessor.VerticalConvolutionProcessor shader = new( + width, + maxY: height - 1, + maxX: width - 1, + kernel.Length, + source, + target, + kernel); - /// - /// Kernel for . - /// - private struct VerticalConvolutionProcessor : IComputeShader - { - public int width; - public int maxY; - public int maxX; - public int kernelLength; - - public ReadWriteBuffer source; - public ReadWriteBuffer target; - public ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 result = Vector4.Zero; - int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - - for (int i = 0; i < kernelLength; i++) - { - int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); - Vector4 color = source[offsetY * width + offsetX]; - - result += kernel[i] * color; - } - - int offsetXY = ids.Y * width + ids.X; - target[offsetXY] = result; - } + Gpu.Default.For(width, height, in shader); } /// @@ -186,53 +151,16 @@ namespace ComputeSharp.BokehBlur.Processors int height = Source.Height; int width = Source.Width; - Gpu.Default.For(width, height, new HorizontalConvolutionProcessor - { - width = width, - maxY = height - 1, - maxX = width - 1, - kernelLength = kernel.Length, - source = source, - target = target, - kernel = kernel - }); - } + HlslGaussianBlurProcessor.HorizontalConvolutionProcessor shader = new( + width, + maxY: height - 1, + maxX: width - 1, + kernel.Length, + source, + target, + kernel); - /// - /// Kernel for . - /// - private struct HorizontalConvolutionProcessor : IComputeShader - { - public int width; - public int maxY; - public int maxX; - public int kernelLength; - - public ReadWriteBuffer source; - public ReadWriteBuffer target; - public ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 result = Vector4.Zero; - int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); - int offsetXY; - - for (int i = 0; i < kernelLength; i++) - { - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); - offsetXY = offsetY * width + offsetX; - Vector4 color = source[offsetXY]; - - result += kernel[i] * color; - } - - offsetXY = ids.Y * width + ids.X; - target[offsetXY] = result; - } + Gpu.Default.For(width, height, in shader); } } } diff --git a/samples/ComputeSharp.Sample.Local/ComputeSharp.Sample.Local.csproj b/samples/ComputeSharp.Sample.Local/ComputeSharp.Sample.Local.csproj new file mode 100644 index 00000000..7c96952c --- /dev/null +++ b/samples/ComputeSharp.Sample.Local/ComputeSharp.Sample.Local.csproj @@ -0,0 +1,18 @@ + + + + Exe + net5.0 + + + + + + + + + + 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 95% rename from samples/ComputeSharp.Sample/Program.cs rename to samples/ComputeSharp.Sample.Shared/Program.cs index db49f66a..b56d467d 100644 --- a/samples/ComputeSharp.Sample/Program.cs +++ b/samples/ComputeSharp.Sample.Shared/Program.cs @@ -42,9 +42,9 @@ namespace ComputeSharp.Sample /// Kernel for . /// [AutoConstructor] - private readonly partial struct MainKernel : IComputeShader + internal readonly partial struct MainKernel : IComputeShader { - private readonly ReadWriteBuffer buffer; + public readonly ReadWriteBuffer buffer; /// public void Execute(ThreadIds ids) diff --git a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj b/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj deleted file mode 100644 index fb05ec61..00000000 --- a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - Exe - net5.0 - - - - - - - - diff --git a/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs similarity index 96% rename from src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs rename to src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs index b1db45a8..163d3d5d 100644 --- a/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs @@ -5,7 +5,7 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; -namespace ComputeSharp +namespace ComputeSharp.__Internals { /// /// An attribute that contains info on a processed compute shader that can be executed. @@ -13,7 +13,7 @@ namespace ComputeSharp /// This attribute is not meant to be directly used by applications using ComputeSharp. [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This attribute is meant to be used from the source generator only")] + [Obsolete("This attribute is not intended to be used directly by user code")] public sealed class IComputeShaderSourceAttribute : Attribute { /// diff --git a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs similarity index 83% rename from src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs rename to src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs index 9fd1fbd1..195ea4d2 100644 --- a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs @@ -5,9 +5,8 @@ using System.Diagnostics.Contracts; using System.Reflection; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; -using Microsoft.Toolkit.Diagnostics; -namespace ComputeSharp +namespace ComputeSharp.__Internals { /// /// An attribute that contains info on a processed shader method that can be executed within a shader. @@ -16,7 +15,7 @@ namespace ComputeSharp /// This attribute is not meant to be directly used by applications using ComputeSharp. [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This attribute is meant to be used from the source generator only")] + [Obsolete("This attribute is not intended to be used directly by user code")] public sealed class ShaderMethodSourceAttribute : Attribute { /// @@ -79,9 +78,12 @@ 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(); + var attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes(); string methodName = function.Method.GetFullName(); foreach (var attribute in attributes) @@ -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 abf25208..85cab145 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -3,12 +3,11 @@ netstandard2.0;net5.0 true - 9.0 - enable + 9.0 - + diff --git a/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs b/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs index ddb6232e..c31a043b 100644 --- a/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs +++ b/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics.Contracts; using System.Text; +using ComputeSharp.__Internals; using ComputeSharp.Core.Extensions; #pragma warning disable CS0618 diff --git a/src/ComputeSharp.Graphics/Helpers/AlignmentHelper.cs b/src/ComputeSharp.Core/Helpers/AlignmentHelper.cs similarity index 97% rename from src/ComputeSharp.Graphics/Helpers/AlignmentHelper.cs rename to src/ComputeSharp.Core/Helpers/AlignmentHelper.cs index 6191c0c3..20baf93f 100644 --- a/src/ComputeSharp.Graphics/Helpers/AlignmentHelper.cs +++ b/src/ComputeSharp.Core/Helpers/AlignmentHelper.cs @@ -1,7 +1,7 @@ using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; -namespace ComputeSharp.Graphics.Helpers +namespace ComputeSharp.Core.Helpers { /// /// A with helper methods to work with alignment and padding. diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index 363c2a9a..e95116b7 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -1,6 +1,7 @@ using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; +using ComputeSharp.Core.Helpers; using ComputeSharp.Exceptions; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index e98b35cd..8c720d45 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -2,12 +2,12 @@ net5.0 - enable true - + + diff --git a/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs new file mode 100644 index 00000000..cf210dd2 --- /dev/null +++ b/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -0,0 +1,68 @@ +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Buffers.Abstract; +using TerraFX.Interop; + +namespace ComputeSharp.__Internals +{ + /// + /// A helper class with some proxy methods to expose to generated code in external projects. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This type is not intended to be used directly by user code")] + public static class GraphicsResourceHelper + { + /// + /// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The input instance to check. + /// The target instance in use. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong ValidateAndGetGpuDescriptorHandle(Buffer buffer, GraphicsDevice device) + where T : unmanaged + { + buffer.ThrowIfDisposed(); + buffer.ThrowIfDeviceMismatch(device); + + return Unsafe.As(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle)); + } + + /// + /// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The input instance to check. + /// The target instance in use. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong ValidateAndGetGpuDescriptorHandle(Texture2D buffer, GraphicsDevice device) + where T : unmanaged + { + buffer.ThrowIfDisposed(); + buffer.ThrowIfDeviceMismatch(device); + + return Unsafe.As(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle)); + } + + /// + /// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The input instance to check. + /// The target instance in use. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong ValidateAndGetGpuDescriptorHandle(Texture3D buffer, GraphicsDevice device) + where T : unmanaged + { + buffer.ThrowIfDisposed(); + buffer.ThrowIfDeviceMismatch(device); + + return Unsafe.As(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle)); + } + } +} diff --git a/src/ComputeSharp.Package/ComputeSharp.Package.msbuildproj b/src/ComputeSharp.Package/ComputeSharp.Package.msbuildproj new file mode 100644 index 00000000..d14cc0c8 --- /dev/null +++ b/src/ComputeSharp.Package/ComputeSharp.Package.msbuildproj @@ -0,0 +1,26 @@ + + + net5.0 + + + + ComputeSharp + A .NET 5 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders + New interlocked intrinsics APIs, performance and memory optimizations + 2.0.0 + https://github.com/Sergio0694/ComputeSharp.git + https://github.com/Sergio0694/ComputeSharp + Sergio Pedri + Sergio Pedri + Copyright (c) 2020 Sergio Pedri + MIT + false + https://i.imgur.com/ntvmD6P.png + dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu + + + + + + + \ No newline at end of file diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index a085e449..4c325294 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -2,7 +2,6 @@ net5.0 - enable true diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs deleted file mode 100644 index 816911bc..00000000 --- a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using Microsoft.Toolkit.Diagnostics; - -namespace ComputeSharp.Shaders.Extensions -{ - /// - /// A that provides extension methods for the type. - /// - internal static class ILGeneratorExtensions - { - /// - /// Puts the appropriate , , or instruction to read a member onte the stream of instructions. - /// - /// The input instance to use to emit instructions. - /// The member to read. - public static void EmitReadMember(this ILGenerator il, MemberInfo member) - { - switch (member) - { - case FieldInfo field: - il.Emit(field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, field); - break; - case PropertyInfo property when property.CanRead: - il.EmitCall(property.GetMethod!.IsStatic ? OpCodes.Call : OpCodes.Callvirt, property.GetMethod, null); - break; - default: ThrowHelper.ThrowArgumentException("The input MemberInfo instance can't be read"); return; - } - } - - /// - /// Puts the appropriate , and instructions to advance a reference onto the stream of instructions. - /// - /// The type of reference at the top of the stack. - /// The input instance to use to emit instructions. - /// The offset to use to advance the current reference on top of the execution stack. - public static void EmitAddOffset(this ILGenerator il, int offset) => il.EmitAddOffset(Unsafe.SizeOf() * offset); - - /// - /// Puts the appropriate , and instructions to advance a reference onto the stream of instructions. - /// - /// The input instance to use to emit instructions. - /// The offset in bytes to use to advance the current reference on top of the execution stack. - public static void EmitAddOffset(this ILGenerator il, int offset) - { - // Push the offset to the stack - if (offset < -128) il.Emit(OpCodes.Ldc_I4, offset); - else if (offset < 0) il.Emit(OpCodes.Ldc_I4_S, (sbyte)offset); - else if (offset <= 8) - { - il.Emit(offset switch - { - 0 => OpCodes.Ldc_I4_0, - 1 => OpCodes.Ldc_I4_1, - 2 => OpCodes.Ldc_I4_2, - 3 => OpCodes.Ldc_I4_3, - 4 => OpCodes.Ldc_I4_4, - 5 => OpCodes.Ldc_I4_5, - 6 => OpCodes.Ldc_I4_6, - 7 => OpCodes.Ldc_I4_7, - 8 => OpCodes.Ldc_I4_8, - _ => ThrowHelper.ThrowArgumentException("Invalid offset value") - }); - } - else if (offset <= 127) il.Emit(OpCodes.Ldc_I4_S, (byte)offset); - else il.Emit(OpCodes.Ldc_I4, offset); - - // Converts the offset to native int and adds to the address - il.Emit(OpCodes.Conv_I); - il.Emit(OpCodes.Add); - } - - /// - /// Puts the appropriate or instruction to write to a reference onto the stream of instructions. - /// - /// The input instance to use to emit instructions. - /// The type of value being written to the current reference on top of the execution stack. - public static void EmitStoreToAddress(this ILGenerator il, Type type) - { - if (type.IsValueType) - { - // Pick the optimal opcode to set a value type - OpCode opcode = Marshal.SizeOf(type) switch - { - // Use the faster op codes for sizes <= 8 - 1 when type == typeof(byte) || type == typeof(sbyte) => OpCodes.Stind_I1, - 2 when type == typeof(short) || type == typeof(ushort) => OpCodes.Stind_I2, - 4 when type == typeof(float) => OpCodes.Stind_R4, - 4 when type == typeof(int) || type == typeof(uint) => OpCodes.Stind_I4, - 8 when type == typeof(double) => OpCodes.Stind_R8, - 8 when type == typeof(long) || type == typeof(ulong) => OpCodes.Stind_I8, - - // Default to stobj for all other value types - _ => OpCodes.Stobj - }; - - // Also pass the type token if stobj is used - if (opcode == OpCodes.Stobj) il.Emit(opcode, type); - else il.Emit(opcode); - } - else il.Emit(OpCodes.Stind_Ref); - } - } -} diff --git a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs deleted file mode 100644 index 72771697..00000000 --- a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Diagnostics.Contracts; - -namespace ComputeSharp.Shaders.Extensions -{ - /// - /// A that provides extension methods for the type. - /// - internal static class TypeExtensions - { - /// - /// Gets whether or not the input represents a . - /// - /// The input type to analyze. - [Pure] - public static bool IsDelegate(this Type type) - { - return type.IsSubclassOf(typeof(Delegate)); - } - } -} diff --git a/src/ComputeSharp.Shaders/Helpers/DynamicMethod{T}.cs b/src/ComputeSharp.Shaders/Helpers/DynamicMethod{T}.cs deleted file mode 100644 index 7a1a6ec0..00000000 --- a/src/ComputeSharp.Shaders/Helpers/DynamicMethod{T}.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Diagnostics.Contracts; -using System.Linq; - -namespace System.Reflection.Emit -{ - /// - /// A that can be used to easily create dynamic methods. - /// - /// The type of that will be used to wrap the new methods. - internal static class DynamicMethod - where T : Delegate - { - /// - /// The return type of the . - /// - private static readonly Type ReturnType; - - /// - /// The types of the arguments of the . - /// - private static readonly Type[] ParameterTypes; - - /// - /// Loads all the necessary info for the current parameter. - /// - static DynamicMethod() - { - MethodInfo method = typeof(T).GetMethod("Invoke")!; - - ReturnType = method.ReturnType; - ParameterTypes = new[] { typeof(object) }.Concat(method.GetParameters().Select(static p => p.ParameterType)).ToArray(); - } - - /// - /// Creates a new for the target owner. For performance reasons, - /// the underlying dynamic method will be created with an extra parameter, and then bound to - /// a instance. This is to emulate the behavior of instance methods, which unlike static ones - /// don't need to go through the shuffle thunk when the delegate is invoked. This would be needed to redirect the - /// invocation to a stub that performs parameters swapping, as the Invoke method is an instance one with the parameters - /// starting from offset 1, while the target static method would expect them to start from offset 0. This solution - /// allows the delegate created for the dynamic method to avoid having a shuffle thunk at all, and with it only having - /// to replace the hidden instance argument when being invoked, resulting in much better performance. Because of this, - /// it is expected that will emit the bytecode assuming that there is an extra unused argument - /// at offset 0. As a result of this, all argument load and store opcodes will need to be shifted by one position forwards. - /// - /// An that builds the IL bytecode for the new method. - /// A new dynamic method wrapped as a . - [Pure] - public static T New(Action builder) - { - DynamicMethod method = new(string.Empty, ReturnType, ParameterTypes, true); - - builder(method.GetILGenerator()); - - return method.CreateDelegate(null); - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs index 4f1eb61f..ca016a1c 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs @@ -12,9 +12,9 @@ namespace ComputeSharp.Shaders.Translation.Models internal readonly ref struct DispatchData { /// - /// The array with the captured buffers. + /// The array (actually values) with the captured buffers. /// - private readonly D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray; + private readonly ulong[] resourcesArray; /// /// The number of values in . @@ -34,11 +34,11 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// Creates a new instance with the specified parameters. /// - /// The array with the captured buffers. + /// The array with the captured buffers. /// The number of instances in . /// The array with all the captured variables, with proper padding. /// The actual size in bytes to use from . - public DispatchData(D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) + public DispatchData(ulong[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) { this.resourcesArray = resourcesArray; this.variablesArray = variablesArray; @@ -54,9 +54,10 @@ namespace ComputeSharp.Shaders.Translation.Models [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); + ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); + ref D3D12_GPU_DESCRIPTOR_HANDLE r1 = ref Unsafe.As(ref r0); - return MemoryMarshal.CreateReadOnlySpan(ref r0, this.resourcesCount); + return MemoryMarshal.CreateReadOnlySpan(ref r1, this.resourcesCount); } } @@ -79,7 +80,7 @@ namespace ComputeSharp.Shaders.Translation.Models /// public void Dispose() { - ArrayPool.Shared.Return(this.resourcesArray); + ArrayPool.Shared.Return(this.resourcesArray); ArrayPool.Shared.Return(this.variablesArray); } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index 38c19d3a..78c5b1ea 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() { + InitializeDxcLibrariesLoading(); + using ComPtr dxcCompiler = default; using ComPtr dxcLibrary = default; using ComPtr dxcIncludeHandler = default; @@ -51,6 +56,64 @@ namespace ComputeSharp.Shaders.Translation DxcIncludeHandler = dxcIncludeHandler.Move(); } + /// + /// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries. + /// + private static void InitializeDxcLibrariesLoading() + { + // 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); + + // 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. + /// 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 isNuGetRuntimeLibrariesDirectoryPresent) + { + if (libraryName is not "dxcompiler") return IntPtr.Zero; + + if (isNuGetRuntimeLibrariesDirectoryPresent) + { + string + dxcompilerPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxcompiler.dll"), + dxilPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxil.dll"); + + // 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; + } + } + else + { + // 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)) + { + return handle; + } + } + + return IntPtr.Zero; + } + /// /// Compiles a new HLSL shader from the input source code. /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index d065911d..d6139881 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -1,11 +1,7 @@ using System; -using System.Collections.Generic; using System.Diagnostics.Contracts; -using System.Linq; using System.Reflection; -using System.Reflection.Emit; using System.Runtime.CompilerServices; -using ComputeSharp.Shaders.Extensions; namespace ComputeSharp.Shaders.Translation { @@ -38,16 +34,11 @@ namespace ComputeSharp.Shaders.Translation { Id = HashCode.Combine(typeof(T)); - // Get the valid delegates for delegate checking - FieldInfo[] delegateFieldInfos = ( - from fieldInfo in typeof(T).GetFields() - where fieldInfo.FieldType.IsDelegate() - select fieldInfo).ToArray(); - - // If at least one delegate is present, build the hasher method - if (delegateFieldInfos.Length > 0) + // Get the generated hasher, if one if present + if (typeof(T).Assembly.GetType("ComputeSharp.__Internals.HashCodeProvider") is Type type && + type.GetMethod("CombineHash", new[] { typeof(int), typeof(T).MakeByRefType() }) is MethodInfo method) { - Hasher = BuildDynamicHasher(delegateFieldInfos); + Hasher = method.CreateDelegate>(); } } } @@ -80,43 +71,5 @@ namespace ComputeSharp.Shaders.Translation /// The final hash value for the input closure. private delegate int Hasher(int hash, in T shader) where T : struct, IComputeShader; - - /// - /// Builds a new instance for the target and sequence of values. - /// - /// The type of compute shader currently in use. - /// The list of captured fields to inspect. - [Pure] - private static Hasher BuildDynamicHasher(IReadOnlyCollection fieldInfos) - where T : struct, IComputeShader - { - return DynamicMethod>.New(il => - { - MethodInfo - getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method))!.GetMethod!, - getHashCodeInfo = typeof(object).GetMethod(nameof(object.GetHashCode))!; - foreach (FieldInfo fieldInfo in fieldInfos) - { - // (hashcode << 5) + hashcode - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Ldc_I4_5); - il.Emit(OpCodes.Shl); - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Add); - - // hashcode += shader.Function[#].Method.GetHashCode(); - il.Emit(OpCodes.Ldarg_2); - il.Emit(OpCodes.Ldfld, fieldInfo); - il.EmitCall(OpCodes.Callvirt, getMethodInfo, null); - il.EmitCall(OpCodes.Callvirt, getHashCodeInfo, null); - il.Emit(OpCodes.Add); - il.Emit(OpCodes.Starg_S, (byte)1); - } - - // Return the computed hash - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Ret); - }); - } } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs new file mode 100644 index 00000000..270c40e1 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs @@ -0,0 +1,87 @@ +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.Graphics; +using ComputeSharp.Shaders.Translation.Models; +using TerraFX.Interop; + +namespace ComputeSharp.Shaders.Translation +{ + /// + internal sealed partial class ShaderLoader + { + /// + /// A that loads all the captured members from a shader instance. + /// + /// The to use to run the shader. + /// The shader instance to load the data from. + /// + /// A reference to the buffer with all the captured instances. + /// This is just represented as a reference, to avoid exposing the type publicly. + /// + /// A reference to the buffer to use to store all the captured value types. + /// The returned value indicates the total number of written bytes into . + private delegate int DispatchDataLoader(GraphicsDevice device, in T shader, ref ulong r0, ref byte r1); + + /// + /// The number of captured graphics resources (buffers). + /// + private int totalResourceCount; + + /// + /// The cached instance to load dispatch data before execution. + /// + private DispatchDataLoader? dispatchDataLoader; + + /// + /// The of instances mapping the captured variables in the current shader. + /// + private readonly List capturedFields = new(); + + /// + /// Gets a new instance with all the captured data for the current shader instance. + /// + /// The to use to run the shader. + /// The input instance representing the compute shader to run. + /// The number of iterations to run on the X axis. + /// The number of iterations to run on the Y axis. + /// The number of iterations to run on the Z axis. + [Pure] + public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z) + { + // Resources and variables buffers + ulong[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); + byte[] variables = ArrayPool.Shared.Rent(4096); + + ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources); + ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables); + + // Set the x, y and z counters + Unsafe.As(ref r1) = x; + Unsafe.Add(ref Unsafe.As(ref r1), 1) = y; + Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; + + // Invoke the dynamic method to extract the captured data + int totalVariablesByteSize = this.dispatchDataLoader!(device, in shader, ref r0, ref r1); + + return new(resources, this.totalResourceCount, variables, totalVariablesByteSize); + } + + /// + /// Initializes the instance that loads the dispatch data for the current shader type. + /// + private void InitializeDispatchDataLoader() + { + // Get the generated data loader + Type[] argumentTypes = new[] { typeof(GraphicsDevice), typeof(T).MakeByRefType(), typeof(ulong).MakeByRefType(), typeof(byte).MakeByRefType() }; + Type type = typeof(T).Assembly.GetType("ComputeSharp.__Internals.DispatchDataLoader")!; + MethodInfo method = type.GetMethod("LoadDispatchData", argumentTypes)!; + + this.dispatchDataLoader = method.CreateDelegate(); + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs deleted file mode 100644 index 40ff7baa..00000000 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs +++ /dev/null @@ -1,170 +0,0 @@ -using System.Buffers; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Helpers; -using ComputeSharp.Graphics.Interop; -using ComputeSharp.Shaders.Extensions; -using ComputeSharp.Shaders.Mappings; -using ComputeSharp.Shaders.Translation.Models; -using Microsoft.Toolkit.Diagnostics; -using TerraFX.Interop; -using FX = TerraFX.Interop.Windows; - -namespace ComputeSharp.Shaders.Translation -{ - /// - internal sealed partial class ShaderLoader - { - /// - /// A that loads all the captured members from a shader instance. - /// - /// The to use to run the shader. - /// The shader instance to load the data from. - /// A reference to the buffer with all the captured instances. - /// A reference to the buffer to use to store all the captured value types. - private delegate void DispatchDataLoader(GraphicsDevice device, in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1); - - /// - /// The number of captured graphics resources (buffers). - /// - private int totalResourceCount; - - /// - /// The size in bytes of the buffer with the captured variables. - /// - /// Initially set to 3 values for X, Y and Z threads counts. - private int totalVariablesByteSize = 3 * sizeof(int); - - /// - /// The cached instance to load dispatch data before execution. - /// - private DispatchDataLoader? dispatchDataLoader; - - /// - /// The of instances mapping the captured variables in the current shader. - /// - private readonly List capturedFields = new(); - - /// - /// Gets a new instance with all the captured data for the current shader instance. - /// - /// The to use to run the shader. - /// The input instance representing the compute shader to run. - /// The number of iterations to run on the X axis. - /// The number of iterations to run on the Y axis. - /// The number of iterations to run on the Z axis. - [Pure] - public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z) - { - // Resources and variables buffers - D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); - byte[] variables = ArrayPool.Shared.Rent(this.totalVariablesByteSize); - - ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources); - ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables); - - // Set the x, y and z counters - Unsafe.As(ref r1) = x; - Unsafe.Add(ref Unsafe.As(ref r1), 1) = y; - Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; - - // Invoke the dynamic method to extract the captured data - this.dispatchDataLoader!(device, in shader, ref r0, ref r1); - - return new(resources, this.totalResourceCount, variables, this.totalVariablesByteSize); - } - - /// - /// Builds a new instance that loads the dispatch data for the current shader type. - /// - private void BuildDispatchDataLoader() - { - // The delegate signature is . - // Due to how DynamicMethod is implemented (see notes in the XML docs for DynamicMethod.New), - // all offsets for the input arguments are shifted by one. Because of this, we have the following: - // - // ldarg.1 = GraphicsDevice - // ldarg.2 = in T shader - // ldarg.3 = ref D3D12_GPU_DESCRIPTOR_HANDLE r0 - // ldarg.4 = ref byte r1 - this.dispatchDataLoader = DynamicMethod.New(il => - { - foreach (FieldInfo fieldInfo in this.capturedFields) - { - if (HlslKnownTypes.IsKnownBufferType(fieldInfo.FieldType)) - { - // Load the offset address into the resource buffers - il.Emit(OpCodes.Ldarg_3); - - if (totalResourceCount > 0) - { - il.EmitAddOffset(this.totalResourceCount); - } - - il.Emit(OpCodes.Ldarg_2); - il.EmitReadMember(fieldInfo); - - // Call NativeObject.ThrowIfDisposed() - il.Emit(OpCodes.Dup); - il.EmitCall(OpCodes.Callvirt, typeof(NativeObject).GetMethod( - nameof(NativeObject.ThrowIfDisposed), - BindingFlags.Instance | BindingFlags.NonPublic)!, null); - - // Call ThrowIfDeviceMismatch(GraphicsDevice) - il.Emit(OpCodes.Dup); - il.Emit(OpCodes.Ldarg_1); - il.EmitCall(OpCodes.Callvirt, fieldInfo.FieldType.GetMethod( - nameof(Buffer.ThrowIfDeviceMismatch), - BindingFlags.Instance | BindingFlags.NonPublic)!, null); - - // Access D3D12GpuDescriptorHandle - il.EmitReadMember(fieldInfo.FieldType.GetField( - nameof(Buffer.D3D12GpuDescriptorHandle), - BindingFlags.Instance | BindingFlags.NonPublic)!); - il.EmitStoreToAddress(typeof(D3D12_GPU_DESCRIPTOR_HANDLE)); - - this.totalResourceCount++; - } - else if (HlslKnownTypes.IsKnownScalarType(fieldInfo.FieldType) || - HlslKnownTypes.IsKnownVectorType(fieldInfo.FieldType)) - { - // Calculate the right offset with 16-bytes padding (HLSL constant buffer) - int elementSizeInBytes = Marshal.SizeOf(fieldInfo.FieldType); - - this.totalVariablesByteSize = AlignmentHelper.AlignToBoundary( - this.totalVariablesByteSize, - elementSizeInBytes, - FX.D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT); - - // Load the target address into the variables buffer - il.Emit(OpCodes.Ldarg_S, (byte)4); - il.EmitAddOffset(totalVariablesByteSize); - - il.Emit(OpCodes.Ldarg_2); - il.EmitReadMember(fieldInfo); - il.EmitStoreToAddress(fieldInfo.FieldType); - - this.totalVariablesByteSize += elementSizeInBytes; - } - else ThrowHelper.ThrowArgumentException("Invalid captured member type"); - } - - il.Emit(OpCodes.Ret); - }); - - // After all the captured fields have been processed, ansure the reported byte size for - // the local variables is padded to the standard alignment for constant buffers. This is - // necessary to enable loading all the dispatch data after reinterpreting it to a sequence - // of values of size 16 bytes (in particular, Int4 is used), without reading out of bounds. - this.totalVariablesByteSize = AlignmentHelper.Pad( - this.totalVariablesByteSize, - FX.D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT); - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 989207a2..92ee855b 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -4,6 +4,7 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; +using ComputeSharp.__Internals; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Renderer.Models; using Microsoft.Toolkit.Diagnostics; @@ -113,7 +114,7 @@ namespace ComputeSharp.Shaders.Translation @this.LoadFieldsInfo(box); @this.LoadMethodMetadata(); - @this.BuildDispatchDataLoader(); + @this.InitializeDispatchDataLoader(); return @this; } @@ -163,6 +164,7 @@ namespace ComputeSharp.Shaders.Translation this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); + this.totalResourceCount++; } else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType)) { @@ -171,6 +173,7 @@ namespace ComputeSharp.Shaders.Translation this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); + this.totalResourceCount++; } else if (HlslKnownTypes.IsReadWriteResourceType(fieldType)) { @@ -179,6 +182,7 @@ namespace ComputeSharp.Shaders.Translation this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); + this.totalResourceCount++; } else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) { diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 1c9c7e2d..04f729f7 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -1,18 +1,52 @@ - + netstandard2.0 9.0 - enable + + analyzers\dotnet\cs + false + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs new file mode 100644 index 00000000..bc1b3312 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Text; +using ComputeSharp.Core.Helpers; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators +{ + [Generator] + public class IComputeShaderDataLoaderGenerator : ISourceGenerator + { + /// + public void Initialize(GeneratorInitializationContext context) + { + } + + /// + public void Execute(GeneratorExecutionContext context) + { + // Find all the struct declarations + ImmutableArray structDeclarations = ( + from tree in context.Compilation.SyntaxTrees + from structDeclaration in tree.GetRoot().DescendantNodes().OfType() + select structDeclaration).ToImmutableArray(); + + // Type attributes + AttributeListSyntax[] attributes = new[] + { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This type is not intended to be used directly by user code")))))) + }; + + foreach (StructDeclarationSyntax structDeclaration in structDeclarations) + { + SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree); + INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!; + + // Only process compute shader types + if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue; + + TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); + BlockSyntax block = Block(GetDispatchDataLoadingStatements(structDeclarationSymbol)); + + // Create a static method to create the combined hashcode for a given shader type. + // This code takes a block syntax and produces a compilation unit as follows: + // + // using System; + // using System.ComponentModel; + // + // namespace ComputeSharp.__Internals + // { + // internal static partial class DispatchDataLoader + // { + // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] + // [System.Obsolete("This method is not intended to be called directly by user code")] + // public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1) + // { + // ... + // } + // } + // } + var source = + CompilationUnit().AddUsings( + UsingDirective(IdentifierName("System")), + UsingDirective(IdentifierName("System.ComponentModel")), + UsingDirective(IdentifierName("System.Runtime.CompilerServices"))).AddMembers( + NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers( + ClassDeclaration("DispatchDataLoader").AddModifiers( + Token(SyntaxKind.InternalKeyword), + Token(SyntaxKind.StaticKeyword), + Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers( + MethodDeclaration( + PredefinedType(Token(SyntaxKind.IntKeyword)), + Identifier("LoadDispatchData")).AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This method is not intended to be called directly by user code"))))))).AddModifiers( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword)).AddParameterListParameters( + Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.Graphics.GraphicsDevice")), + Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType), + Parameter(Identifier("r0")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ULongKeyword))), + Parameter(Identifier("r1")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .WithBody(block))) + .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) + .NormalizeWhitespace() + .ToFullString(); + + // Clear the attribute list to avoid duplicates + attributes = Array.Empty(); + + // Add the method source attribute + context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + } + } + + /// + /// Gets a sequence of statements to load the dispatch data for a given shader + /// + /// The input instance to process. + /// The sequence of instances to load shader dispatch data. + [Pure] + private static IEnumerable GetDispatchDataLoadingStatements(INamedTypeSymbol structDeclarationSymbol) + { + int + resourceOffset = 0, + rawDataOffset = sizeof(int) * 3; + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; + string typeName = typeSymbol.GetFullMetadataName(); + + if (HlslKnownTypes.IsTypedResourceType(typeName)) + { + yield return ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"), + ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)"))); + } + else if (HlslKnownTypes.IsScalarOrVectorType(typeName)) + { + var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName); + + // Calculate the right offset with 16-bytes padding (HLSL constant buffer). + // Since we're in a constant buffer, we need to both pad the starting offset + // to be aligned to the packing size of the type, and also to align the initial + // offset to ensure that values do not cross 16 bytes boundaries either. + rawDataOffset = AlignmentHelper.AlignToBoundary( + AlignmentHelper.Pad(rawDataOffset, fieldPack), + fieldSize, + 16); + + yield return ExpressionStatement( + ParseExpression($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), shader.{fieldSymbol.Name})")); + + rawDataOffset += fieldSize; + } + } + + // After all the captured fields have been processed, ansure the reported byte size for + // the local variables is padded to the standard alignment for constant buffers. This is + // necessary to enable loading all the dispatch data after reinterpreting it to a sequence + // of values of size 16 bytes (in particular, Int4 is used), without reading out of bounds. + rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); + + yield return ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset))); + } + } +} + diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs new file mode 100644 index 00000000..ae194820 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Text; +using ComputeSharp.SourceGenerators.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators +{ + [Generator] + public class IComputeShaderHashCodeGenerator : ISourceGenerator + { + /// + public void Initialize(GeneratorInitializationContext context) + { + } + + /// + public void Execute(GeneratorExecutionContext context) + { + // Find all the struct declarations + ImmutableArray structDeclarations = ( + from tree in context.Compilation.SyntaxTrees + from structDeclaration in tree.GetRoot().DescendantNodes().OfType() + select structDeclaration).ToImmutableArray(); + + // Type attributes + AttributeListSyntax[] attributes = new[] + { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This type is not intended to be used directly by user code")))))) + }; + + foreach (StructDeclarationSyntax structDeclaration in structDeclarations) + { + SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree); + INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!; + + // Only process compute shader types + if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue; + + TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); + BlockSyntax block = Block(GetDelegateHashCodeStatements(structDeclarationSymbol)); + + if (block.Statements.Count == 1) continue; + + // Create a static method to create the combined hashcode for a given shader type. + // This code takes a block syntax and produces a compilation unit as follows: + // + // using System; + // using System.ComponentModel; + // + // namespace ComputeSharp.__Internals + // { + // internal static partial class HashCodeProvider + // { + // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] + // [System.Obsolete("This method is not intended to be called directly by user code")] + // public static int CombineHashCode(int hash, in ShaderType shader) + // { + // return ...; + // } + // } + // } + var source = + CompilationUnit().AddUsings( + UsingDirective(IdentifierName("System")), + UsingDirective(IdentifierName("System.ComponentModel"))).AddMembers( + NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers( + ClassDeclaration("HashCodeProvider").AddModifiers( + Token(SyntaxKind.InternalKeyword), + Token(SyntaxKind.StaticKeyword), + Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers( + MethodDeclaration( + PredefinedType(Token(SyntaxKind.IntKeyword)), + Identifier("CombineHash")).AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This method is not intended to be called directly by user code"))))))).AddModifiers( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword)).AddParameterListParameters( + Parameter(Identifier("hash")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType)) + .WithBody(block)))) + .NormalizeWhitespace() + .ToFullString(); + + // Clear the attribute list to avoid duplicates + attributes = Array.Empty(); + + // Add the method source attribute + context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + } + } + + /// + /// Gets a sequence of statements to process the hashcode of the captured delegates. + /// + /// The input instance to process. + /// The sequence of instances to hash the captured delegates. + [Pure] + private static IEnumerable GetDelegateHashCodeStatements(INamedTypeSymbol structDeclarationSymbol) + { + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; + + if (typeSymbol.TypeKind != TypeKind.Delegate) continue; + + // hash += hash << 5; + yield return ExpressionStatement(ParseExpression($"hash += hash << 5")); + + // hash += shader.Field[#i].Method.GetHashCode(); + yield return ExpressionStatement(ParseExpression($"hash += shader.{fieldSymbol.Name}.Method.GetHashCode()")); + } + + yield return ReturnStatement(IdentifierName("hash")); + } + } +} + diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index f80986f1..a90ba55c 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -3,6 +3,7 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using System.Text; +using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; using ComputeSharp.SourceGenerators.SyntaxRewriters; @@ -81,7 +82,8 @@ namespace ComputeSharp.SourceGenerators // Create the compilation unit with the source attribute var source = - CompilationUnit().AddAttributeLists( + CompilationUnit().AddUsings( + UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddAttributeLists( AttributeList(SingletonSeparatedList( Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(structDeclarationSymbol.GetFullMetadataName()))), diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs index 0736932b..e05ff7a8 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics.Contracts; using System.Numerics; namespace ComputeSharp.SourceGenerators.Mappings @@ -9,9 +10,9 @@ namespace ComputeSharp.SourceGenerators.Mappings internal static class HlslKnownSizes { /// - /// Gets the mapping of supported known sizes to HLSL type names. + /// The mapping of supported known sizes to HLSL type names. /// - public static IReadOnlyDictionary KnownSizes { get; } = new Dictionary + private static IReadOnlyDictionary KnownSizes = new Dictionary { [typeof(bool).FullName] = (4, 4), [typeof(int).FullName] = (4, 4), @@ -43,5 +44,16 @@ namespace ComputeSharp.SourceGenerators.Mappings [typeof(Double3).FullName] = (24, 8), [typeof(Double3).FullName] = (32, 8) }; + + /// + /// Gets the size and alignment info for a specified primitive type. + /// + /// The type name to get info for. + /// The size and and alignment for the input type. + [Pure] + public static (int Size, int Pack) GetTypeInfo(string typeName) + { + return KnownSizes[typeName]; + } } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index b4332b8e..43ba20b4 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -78,6 +78,18 @@ namespace ComputeSharp.SourceGenerators.Mappings }; } + /// + /// Checks whether or not a given type name matches a typed resource type. + /// + /// The input type name to check. + /// Whether or not represents a typed resource type. + public static bool IsScalarOrVectorType(string typeName) + { + return + KnownTypes.ContainsKey(typeName) && + typeName != typeof(ThreadIds).FullName; + } + /// /// Gets the mapped HLSL-compatible type name for the input type symbol. /// diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 277ec2c5..7ce2bf63 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -3,6 +3,7 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using System.Text; +using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 54bca4f1..9d310d55 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -2,9 +2,8 @@ net5.0 - preview - enable - true + 9.0 + true @@ -12,8 +11,16 @@ - - + + diff --git a/src/ComputeSharp/ComputeSharp.nuspec b/src/ComputeSharp/ComputeSharp.nuspec deleted file mode 100644 index 46218663..00000000 --- a/src/ComputeSharp/ComputeSharp.nuspec +++ /dev/null @@ -1,26 +0,0 @@ - - - - ComputeSharp - 2.0.0 - ComputeSharp - Sergio Pedri - Sergio Pedri - MIT - https://github.com/Sergio0694/ComputeSharp - https://i.imgur.com/ntvmD6P.png - false - A .NET 5 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders - New interlocked intrinsics APIs, performance and memory optimizations - Copyright (c) 2020 Sergio Pedri - dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu - - - - - - - - - - diff --git a/src/ComputeSharp/Libraries/dxcompiler.dll b/src/ComputeSharp/Libraries/dxcompiler.dll new file mode 100644 index 00000000..58a39df1 Binary files /dev/null and b/src/ComputeSharp/Libraries/dxcompiler.dll differ diff --git a/src/ComputeSharp/Libraries/dxil.dll b/src/ComputeSharp/Libraries/dxil.dll new file mode 100644 index 00000000..598d4aee Binary files /dev/null and b/src/ComputeSharp/Libraries/dxil.dll differ diff --git a/src/Directory.Build.props b/src/Directory.Build.props new file mode 100644 index 00000000..84867398 --- /dev/null +++ b/src/Directory.Build.props @@ -0,0 +1,9 @@ + + + enable + + + + + + \ No newline at end of file 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 @@ - - diff --git a/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs b/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs deleted file mode 100644 index 0c1a5453..00000000 --- a/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Reflection.Emit; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace ComputeSharp.Tests.Internals -{ - [TestClass] - [TestCategory("DynamicMethod")] - public class DynamicMethodTests - { - [TestMethod] - public void TestFunc() - { - Func square = DynamicMethod>.New(il => - { - // Due to the instance method trick, the first parameter is at offset 1. - // See the docs on DynamicMethod.New for more info on how this works. - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Dup); - il.Emit(OpCodes.Mul); - il.Emit(OpCodes.Ret); - }); - - int result = square(2); // result = 2 * 2 - - Assert.IsTrue(result == 4); - } - } -} 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..6f1add7c --- /dev/null +++ b/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs @@ -0,0 +1,196 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; + +namespace ComputeSharp.Tests.NativeLibrariesResolver +{ + [TestClass] + public class NativeLibrariesResolverTests + { + static NativeLibrariesResolverTests() + { + 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"); + + 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(); + Process.Start("dotnet", $"restore {sampleProjectPath}").WaitForExit(); + } + + /// + /// Gets the directory of the ComputeSharp.Sample.NuGet project. + /// + 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", so in this case we restore packages as well + 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); + + string 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); + + string 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); + + string 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); + + string 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) + { + // Publishing without specifying an RID is not supported + Exec(SampleProjectDirectory, "dotnet", $"publish -c {configuration} -r win-x64 --no-restore"); + + 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) + { + ProcessStartInfo startInfo = new() + { + UseShellExecute = true, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + FileName = filePath, + Arguments = arguments, + WorkingDirectory = workingDirectory + }; + + 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 => "", + RID.Win_x64 => "-r win-x64", + _ => 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 => "", + RID.Win_x64 => "win-x64", + _ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID)) + }; + + /// + /// A build configuration. + /// + public enum Configuration + { + Debug, + Release + } + + /// + /// A runtime identifier. + /// + public enum RID + { + None, + Win_x64, + } + } +} diff --git a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj index 722a7e0f..d4f1c821 100644 --- a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj +++ b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj @@ -14,11 +14,10 @@ - +