diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml
new file mode 100644
index 00000000..891bb15b
--- /dev/null
+++ b/.github/workflows/dotnet.yml
@@ -0,0 +1,155 @@
+name: .NET
+
+on: [push, pull_request]
+
+jobs:
+
+ # Build the ComputeSharp project directly. This is the project that
+ # would be built when running any of the local samples or unit tests.
+ build-project:
+ runs-on: windows-latest
+ steps:
+ - name: Git checkout
+ uses: actions/checkout@v2
+ - name: Setup .NET SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: 5.0.x
+ - name: Create local NuGet feed
+ run: mkdir src\ComputeSharp.Package\bin\Release
+ shell: cmd
+ - name: Build
+ run: dotnet build src\ComputeSharp\ComputeSharp.csproj -c Release
+ shell: cmd
+
+ # Run all the unit tests referencing the ComputeSharp project directly.
+ run-tests:
+ if: success()
+ needs: [build-project]
+ runs-on: windows-latest
+ steps:
+ - name: Git checkout
+ uses: actions/checkout@v2
+ - name: Setup .NET SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: 5.0.x
+ - name: Create local NuGet feed
+ run: mkdir src\ComputeSharp.Package\bin\Release
+ shell: cmd
+ - name: Run ComputeSharp.Tests
+ run: dotnet test tests\ComputeSharp.Tests\ComputeSharp.Tests.csproj -v n -l "console;verbosity=detailed"
+ shell: cmd
+ - name: Run ComputeSharp.Tests.Internals
+ run: dotnet test tests\ComputeSharp.Tests.Internals\ComputeSharp.Tests.Internals.csproj -v n -l "console;verbosity=detailed"
+ shell: cmd
+ - name: Run ComputeSharp.Tests.Internals.SourceGenerators
+ run: dotnet test tests\ComputeSharp.Tests.Internals.SourceGenerators\ComputeSharp.Tests.Internals.SourceGenerators.csproj -v n -l "console;verbosity=detailed"
+ shell: cmd
+
+ # Run all the local samples to ensure they build and run with no errors.
+ run-samples:
+ if: success()
+ needs: [run-tests]
+ runs-on: windows-latest
+ steps:
+ - name: Git checkout
+ uses: actions/checkout@v2
+ - name: Setup .NET SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: 5.0.x
+ - name: Create local NuGet feed
+ run: mkdir src\ComputeSharp.Package\bin\Release
+ shell: cmd
+ - name: Build ComputeSharp.Sample.Local
+ run: dotnet build samples\ComputeSharp.Sample.Local\ComputeSharp.Sample.Local.csproj -c Release
+ shell: cmd
+ - name: Run ComputeSharp.Sample.Local
+ run: dotnet samples\ComputeSharp.Sample.Local\bin\Release\net5.0\ComputeSharp.Sample.Local.dll
+ shell: cmd
+ - name: Build ComputeSharp.ImageProcessing.csproj
+ run: dotnet build samples\ComputeSharp.ImageProcessing\ComputeSharp.ImageProcessing.csproj -c Release
+ shell: cmd
+ - name: Run ComputeSharp.ImageProcessing.csproj
+ run: dotnet samples\ComputeSharp.ImageProcessing\bin\Release\net5.0\ComputeSharp.ImageProcessing.dll
+ shell: cmd
+ - name: Build ComputeSharp.Benchmark.csproj
+ run: dotnet build samples\ComputeSharp.Benchmark\ComputeSharp.Benchmark.csproj -c Release
+ shell: cmd
+ - name: Build ComputeSharp.SwapChain.csproj
+ run: dotnet build samples\ComputeSharp.SwapChain\ComputeSharp.SwapChain.csproj -c Release
+ shell: cmd
+
+ # Buils the .msbuildproj project to generate the NuGet package.
+ # This workflow also uploads the resulting package as an artifact.
+ build-package:
+ runs-on: windows-latest
+ steps:
+ - name: Git checkout
+ uses: actions/checkout@v2
+ - name: Setup .NET SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: 5.0.x
+ - name: Create local NuGet feed
+ run: mkdir src\ComputeSharp.Package\bin\Release
+ shell: cmd
+ - name: Build
+ run: dotnet build src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj -c Release
+ shell: cmd
+ - name: Upload package artifact
+ uses: actions/upload-artifact@v2
+ with:
+ name: ComputeSharp.nupkg
+ path: src\ComputeSharp.Package\bin\Release\*.nupkg
+
+ # Download the NuGet package generated in the previous job and use it
+ # to build and run the sample project referencing it. This is used as
+ # a test to ensure the NuGet package works in a consuming project.
+ verify-package:
+ if: success()
+ needs: [build-package]
+ runs-on: windows-latest
+ steps:
+ - name: Git checkout
+ uses: actions/checkout@v2
+ - name: Setup .NET SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: 5.0.x
+ - name: Create local NuGet feed
+ run: mkdir src\ComputeSharp.Package\bin\Release
+ shell: cmd
+ - name: Download package artifact
+ uses: actions/download-artifact@v2
+ with:
+ name: ComputeSharp.nupkg
+ path: src\ComputeSharp.Package\bin\Release\ComputeSharp.nupkg
+ - name: Build ComputeSharp.Sample.NuGet
+ run: dotnet build samples\ComputeSharp.Sample.NuGet\ComputeSharp.Sample.NuGet.csproj -c Release
+ shell: cmd
+ - name: Run ComputeSharp.Sample.NuGet
+ run: dotnet samples\ComputeSharp.Sample.NuGet\bin\Release\net5.0\ComputeSharp.Sample.NuGet.dll
+ shell: cmd
+
+ # Run the extra tests to validate a number of build and publishing configurations.
+ # This is used to ensure the native dependencies can always be loaded correctly
+ # regardless of whether the app is shipping with R2R, self-contained, etc.
+ verify-libs:
+ if: success()
+ needs: [verify-package]
+ runs-on: windows-latest
+ steps:
+ - name: Git checkout
+ uses: actions/checkout@v2
+ - name: Setup .NET SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: 5.0.x
+ - name: Create local NuGet feed
+ run: mkdir src\ComputeSharp.Package\bin\Release
+ shell: cmd
+ - name: Run ComputeSharp.Tests.NativeLibrariesResolver
+ run: dotnet test tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj -v n -l "console;verbosity=detailed"
+ shell: cmd
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 23c39fe0..0d7a3e0d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -24,6 +24,9 @@ bld/
[Oo]bj/
[Ll]og/
+# Debug view types
+!**/Resources/Debug
+
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
@@ -329,6 +332,8 @@ ASALocalRun/
# MFractors (Xamarin productivity tool) working folder
.mfractor/
-# Sample bokeh blur image
-**/*_bokeh.jpg
-**/*_gaussian.jpg
+# Sample images
+samples/**/city_*.jpg
+
+# XML docs files
+src/**/ComputeSharp*.xml
\ No newline at end of file
diff --git a/ComputeSharp.sln b/ComputeSharp.sln
index 4f97f672..24463506 100644
--- a/ComputeSharp.sln
+++ b/ComputeSharp.sln
@@ -5,20 +5,12 @@ VisualStudioVersion = 16.0.29201.188
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp", "src\ComputeSharp\ComputeSharp.csproj", "{314EB353-E7E3-4146-8111-685CC83EC1DE}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Core", "src\ComputeSharp.Core\ComputeSharp.Core.csproj", "{9F9581FB-6EF7-418E-BFA5-0EFED874E980}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Graphics", "src\ComputeSharp.Graphics\ComputeSharp.Graphics.csproj", "{2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Shaders", "src\ComputeSharp.Shaders\ComputeSharp.Shaders.csproj", "{23AE6EED-79CD-4ADD-9A85-0148BD957D19}"
-EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Benchmark", "samples\ComputeSharp.Benchmark\ComputeSharp.Benchmark.csproj", "{34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}"
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,11 +20,35 @@ 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("{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("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.NativeLibrariesResolver", "tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj", "{BF52326F-E415-49E6-8595-62762216762B}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SwapChain", "samples\ComputeSharp.SwapChain\ComputeSharp.SwapChain.csproj", "{E7C9247D-016B-4819-AF9F-0E9B3591E04B}"
+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
@@ -48,30 +64,6 @@ Global
{314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|Any CPU.Build.0 = Release|Any CPU
{314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|x64.ActiveCfg = Release|Any CPU
{314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|x64.Build.0 = Release|Any CPU
- {9F9581FB-6EF7-418E-BFA5-0EFED874E980}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {9F9581FB-6EF7-418E-BFA5-0EFED874E980}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {9F9581FB-6EF7-418E-BFA5-0EFED874E980}.Debug|x64.ActiveCfg = Debug|Any CPU
- {9F9581FB-6EF7-418E-BFA5-0EFED874E980}.Debug|x64.Build.0 = Debug|Any CPU
- {9F9581FB-6EF7-418E-BFA5-0EFED874E980}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {9F9581FB-6EF7-418E-BFA5-0EFED874E980}.Release|Any CPU.Build.0 = Release|Any CPU
- {9F9581FB-6EF7-418E-BFA5-0EFED874E980}.Release|x64.ActiveCfg = Release|Any CPU
- {9F9581FB-6EF7-418E-BFA5-0EFED874E980}.Release|x64.Build.0 = Release|Any CPU
- {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Debug|x64.ActiveCfg = Debug|Any CPU
- {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Debug|x64.Build.0 = Debug|Any CPU
- {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Release|Any CPU.Build.0 = Release|Any CPU
- {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Release|x64.ActiveCfg = Release|Any CPU
- {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Release|x64.Build.0 = Release|Any CPU
- {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Debug|x64.ActiveCfg = Debug|Any CPU
- {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Debug|x64.Build.0 = Debug|Any CPU
- {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Release|Any CPU.Build.0 = Release|Any CPU
- {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Release|x64.ActiveCfg = Release|Any CPU
- {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Release|x64.Build.0 = Release|Any CPU
{34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Debug|x64.ActiveCfg = Debug|Any CPU
@@ -88,14 +80,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
@@ -112,6 +96,62 @@ Global
{E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Release|Any CPU.Build.0 = Release|Any CPU
{E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Release|x64.ActiveCfg = Release|Any CPU
{E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Release|x64.Build.0 = Release|Any CPU
+ {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|x64.Build.0 = Debug|Any CPU
+ {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|Any CPU.Build.0 = Release|Any CPU
+ {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|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
+ {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|x64.Build.0 = Debug|Any CPU
+ {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|x64.ActiveCfg = Release|Any CPU
+ {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -119,9 +159,15 @@ 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}
+ {E7C9247D-016B-4819-AF9F-0E9B3591E04B} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC}
diff --git a/Directory.Build.props b/Directory.Build.props
new file mode 100644
index 00000000..71e2d6cb
--- /dev/null
+++ b/Directory.Build.props
@@ -0,0 +1,10 @@
+
+
+ true
+ 9.0
+ enable
+ true
+ Sergio Pedri
+ Copyright (c) 2021 Sergio Pedri
+
+
\ No newline at end of file
diff --git a/README.md b/README.md
index 2d87a6c9..4e2dc0b4 100644
--- a/README.md
+++ b/README.md
@@ -1,23 +1,22 @@
-
-[](https://www.nuget.org/packages/ComputeSharp/) [](https://www.nuget.org/stats/packages/ComputeSharp?groupby=Version)
-
-## Major update in the works! 🚀
-
-The currently available NuGet package refers to the `1.x` version of **ComputeSharp**, with the codebase from the `master` branch. I'm currently working on a new major update targeting .NET 5, featuring a completely rewritten backend using native DirectX bindings and the use of C# source generators to prepare the shader code. This will greatly improve the performance of the library (especially cold start performance, which is over **10x** faster already) and use much less memory at runtime. I also plan to introduce support for a number of new features, such as the ability to use custom struct types in shaders. The current status of this work can be seen from the development branches.
-
-Thank you for the support!
+
+ [](https://www.nuget.org/packages/ComputeSharp/) [](https://www.nuget.org/stats/packages/ComputeSharp?groupby=Version)
# What is it?
-**ComputeSharp** is a .NET Standard 2.1 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders. The available APIs let you allocate GPU buffers and write compute shaders as simple lambda expressions or local methods, with all the captured variables being handled automatically and passed to the running shader.
+**ComputeSharp** is a .NET 5 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders. The available APIs let you access GPU devices, allocate GPU buffers and textures, move data between them and the RAM, write compute shaders entirely in C# and have them run on the GPU. The goal of this project is to make GPU computing easy to use for all .NET developers! 🚀
# Table of Contents
- [Installing from NuGet](#installing-from-nuget)
- [Quick start](#quick-start)
- - [Capturing variables](#capturing-variables)
- - [Advanced usage](#advanced-usage)
+ - [Capturing variables](#capturing-variables)
+ - [GPU resource types](#gpu-resource-types)
+ - [HLSL vector and matrix types](#hlsl-vector-and-matrix-types)
+ - [HLSL intrinsics](#hlsl-intrinsics)
+ - [Working with images](#working-with-images)
+ - [Shader metaprogramming](#shader-metaprogramming)
- [Requirements](#requirements)
+- [Sponsors](#sponsors)
- [Special thanks](#special-thanks)
# Installing from NuGet
@@ -32,40 +31,52 @@ More details available [here](https://www.nuget.org/packages/ComputeSharp/).
# Quick start
-**ComputeSharp** exposes a `Gpu` class that acts as entry point for all public APIs. It exposes the `Gpu.Default` property that lets you access the main GPU device on the current machine, which can be used to allocate buffers and perform operations.
+**ComputeSharp** exposes a `Gpu` class that acts as entry point for all public APIs. The available `Gpu.Default` property that lets you access the main GPU device on the current machine, which can be used to allocate buffers and perform operations. If your machine doesn't have a supported GPU (or if it doesn't have a GPU at all), **ComputeSharp** will automatically create a [WARP device](https://docs.microsoft.com/windows/win32/direct3darticles/directx-warp) instead, which will still let you use the library normally, with shaders running on the CPU instead through an emulation layer. This means that you don't need to manually write a fallback path in case no GPU is available - **ComputeSharp** will automatically handle this for you.
-The following sample shows how to allocate a writeable buffer, populate it with a compute shader, and read it back.
+Let's suppose we want to run a simple compute shader that multiplies all items in a target buffer by two. The first step is to create the GPU buffer and copy our data to it:
+
+```csharp
+// Get some sample data
+int[] array = Enumerable.Range(0, 100).ToArray();
+
+// Allocate a GPU buffer and copy the data to it.
+// We want the shader to modify the items in-place, so we
+// can allocate a single read-write buffer to work on.
+using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(array);
+```
+
+The `AllocateReadWriteBuffer` extension takes care of creating a `ReadWriteBuffer` instance with the same size and contents of the input array. There are a number of overloads available as well, to create buffers of different types and with custom length.
+
+Next, we need to define the GPU shader to run. To do this, we'll need to define a `struct` type implementing the `IComputeShader` interface. This type will contain the code we want to run on the GPU, as well as fields representing the values we want to capture and pass to the GPU (such as GPU resources, or arbitrary values we need). In this case, we only need to capture the buffer to work on, so the shader type will look like this:
```C#
-// Define a simple shader
-public readonly struct MyShader : IComputeShader
+[AutoConstructor]
+public readonly struct MultiplyByTwo : IComputeShader
{
public readonly ReadWriteBuffer buffer;
- public MyShader(ReadWriteBuffer buffer)
+ public void Execute()
{
- this.buffer = buffer;
- }
-
- public void Execute(ThreadIds ids)
- {
- buffer[ids.X] = ids.X;
+ buffer[ThreadIds.X] *= 2;
}
}
+```
-// Allocate a writeable buffer on the GPU, with the contents of the array
-using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1000);
+We're using the `[AutoConstructor]` attribute included in **ComputeSharp**, which creates a constructor for our type automatically. The shader body is also using a special `ThreadIds` class, which is one of the available special classes to access dispatch parameters from within a shader body. In this case, `ThreadIds` lets us access the current invocation index for the shader, just like if we were accessing the classic `i` variable from within a `for` loop.
-// Run the shader
-Gpu.Default.For(1000, new MyShader(buffer));
+We can now finally run the GPU shader and copy the data back to our array:
+
+```csharp
+// Launch the shader
+Gpu.Default.For(buffer.Length, new MyShader(buffer));
// Get the data back
-float[] array = buffer.GetData();
+buffer.CopyTo(array);
```
## Capturing variables
-If the shader in C# is capturing some local variable, those will be automatically copied over to the GPU, so that the HLSL shader will be able to access them just like you'd expect. Additionally, **ComputeSharp** can also resolve static fields being used in a shader. The captured variables need to be convertible to valid HLSL types: either scalar types (`int`, `uint`, `float`, etc.) or known HLSL structs (eg. `Vector3`). Here is a list of the variable types currently supported by the library:
+Shaders can store either GPU resources or custom values in their fields, so that they can be accessed when running on the GPU as well. This can be useful to pass some extra parameters to a shader (eg. some factor to multiply values by), that don't belong to a GPU buffer of their own. The captured variables need to be of a supported scalar or vector type so that they can be correctly used by the GPU shader in HLSL. Here is a list of the variable types currently supported by the library:
✅ .NET scalar types: `bool`, `int`, `uint`, `float`, `double`
@@ -73,85 +84,190 @@ If the shader in C# is capturing some local variable, those will be automaticall
✅ HLSL types: `Bool`, `Bool2`, `Bool3`, `Bool4`, `Float2`, `Float3`, `Float4`, `Int2`, `Int3`, `Int4`, `UInt2`, `Uint3`, etc.
-✅ `static` fields of both scalar, vector or buffer types
+✅ HLSL matrix types: `Float2x2`, `Float3x3`, `Float3x4`, `Float4x4`, `Float1x4`, `Float4x`, etc.
-✅ `static` properties, same as with fields
+✅ Custom `struct` types containing any of the types above, as well as other valid custom `struct` types
-✅ `Func`s or delegates with a valid HLSL signature, with the target method being `static`
+## GPU resource types
-✅ `Func`s, local methods or delegates with no captured variables
+There are a number of extension APIs for the `GraphicsDevice` class that can be used to allocate GPU resources. Here is a breakdown of the main resource types that are available:
-✅ `static` fields and properties with a supported delegate type
+- `ReadWriteBuffer`: this type can be viewed as the equivalent of the `T[]` type, and can contain a writeable sequence of any of the supported types mentioned above. It is very flexible and works well in most situations. If you're just getting started with this library and are not sure about what kind of buffer to use, this is usually a good choice.
+- `ReadOnlyBuffer`: this type represents a sequence of items that the GPU cannot write to. It is particularly useful to declare intent from within a compute shader and to avoid accidentally writing to data that is not supposed to change during the execution of a shader.
+- `ConstantBuffer`: this type is meant to be used for small sequences of items that never change during the execution of a shader. Compared to `ReadOnlyBuffer` is has more constraints, but can benefit from better caching on the GPU side (it is recommended to verify with proper benchmarking that this type is appropriate to use). Items within a `ConstantBuffer` instance are packed to 16 bytes, which helps the GPU to have a particularly fast access time to them, but the total size of the buffer is limited to around 64KB. Copying to and from this buffer can also have additional overhead, as the GPU needs to account for the possible padding for each item (as the 16 bytes alignment is not present on the CPU side). If you're in doubt about which buffer type to use, just use either `ReadOnlyBuffer` or `ReadWriteBuffer`, depending on whether or not you also need write access to that buffer on the GPU side.
+- `ReadOnlyTexture2D` and `ReadWriteTexture2D`: these types represent a 2D texture with elements of a specific type. Note that textures are not just 2D arrays, and have additional characteristics and limitations. Items in a texture are stored with a tiled layout instead of with the classic row-major order that .NET `T[,]` arrays have, and this allows them to be extremely fast when accessing small areas of neighbouring items (due to better cache locality). This can offer a big performance speedup in operations that have a similar memory access pattern, such as blur effect or convolutions in general. Textures also have limitations in the type of items they can contain (eg. custom `struct` types are not supported), and you can check if a specific type is supported at runtime with the `GraphicsDevice.IsReadOnlyTexture2DSupportedForType()` and `IsReadWriteTexture2DSupportedForType()` methods.
+- `ReadOnlyTexture3D` and `ReadWriteTexture3D`: these are just like 2D textures, but in 3 dimensions. The same characteristics and limitations apply, with the addition of the fact that the depth axis has a much smaller limit on the size it can have. The `GraphicsDevice.IsReadOnlyTexture3DSupportedForType()` and `IsReadWriteTexture3DSupportedForType()` methods can be used to check for type support at runtime.
+- `ReadOnlyTexture2D` and `ReadWriteTexture2D`: these texture types are particularly useful when doing image processing from a compute shader, as they allow the CPU to perform pixel format conversion automatically. The two type parameters indicate the type of items in a texture when exposed on the CPU side (as `T` items) or on the GPU side (as `TPixel` items). The type parameter `T` can be any of the existing pixel formats available in **ComputeSharp** (such as `Rgba32` and `Bgra32`), while the `TPixel` parameter represents the type of elements the GPU will be working with (for instance, `Float4` for `Rgba32`). These texture types have a number of benefits such as lower memory usage and reduced overhead on the CPU (as there is no need to manually do the pixel format conversion when copying data back and forth from the GPU).
+- `ReadOnlyTexture3D` and `ReadWriteTexture3D`: these types are just like their 2D equivalent types, with the same support for automatic pixel format conversion on the GPU side.
+- `UploadBuffer`: this type can be used in more advanced scenarios where performance is particularly important. It represents a buffer that can be copied directly to a GPU buffer (such as a `ReadOnlyBuffer`), without the need to create a temporary transfer buffer to do so. If there is a large number of copy operations being performed to GPU buffers, it can be beneficial to create a single `UploadBuffer` instance to load data to copy to the GPU, and execute the copy from there.
+- `ReadBackBuffer`: this type is another advanced buffer type that is analogous to `UploadBuffer`, but that can be used to copy data back from a GPU buffer. In particular, this buffer can also be accessed quickly by the GPU when reading or writing data from it, so it can also be used for further processing of data on the CPU side, without the need to copy the data onto another buffer first (such as a .NET array).
+- `UploadTexture2D`, `UploadTexture3D`, `ReadBackTexture2D` and `ReadBackTexture3D`: these types are conceptually similar to `UploadBuffer` and `ReadBackBuffer`, with the main difference being that they can be used to copy data back and forth from 2D and 3D textures respectively.
-## Allocating GPU buffers
+> **NOTE:** although the various APIs to allocate buffers are simply generic methods with a `T : unmanaged` constrain, they should only be used with C# types that are supported (see notes above). Additionally, the `bool` type should not be used in buffers due to C#/HLSL differences: use the `Bool` type instead (or just an `int` buffer).
-There are a number of extension APIs for the `GraphicsDevice` class that can be used to allocate GPU buffers of three types: `ConstantBuffer`, `ReadOnlyBuffer` and `ReadWriteBuffer`. The first is packed to 16 bytes and provides the fastest possible access for buffer elements, but it has a limited maximum size (around 64KB) and requires additional overhead when copying data to and from it if the size of each element is not a multiple of 16. The other buffer types are tightly packed and work great for all kinds of operations, and can be thought of the HLSL equivalent of `T[]` arrays in C#. If you're in doubt about which buffer type to use, just use either `ReadOnlyBuffer` or `ReadWriteBuffer`, depending on whether or not you also need write access to that buffer on the GPU side.
+## HLSL vector and matrix types
-**NOTE:** although the APIs to allocate buffers are simply generic methods with a `T : unmanaged` constrain, they should only be used with C# types that are fully mapped to HLSL types. That means either `int`, `uint`, `float`, `double`, .NET vector types or HLSL types. The `bool` type should not be used in buffers due to C#/HLSL differences: use the `Bool` type instead.
+As mentioned in the [Capturing variables](#capturing-variables) paragraph, **ComputeSharp** also exposes matrix types that can be used in compute shaders. These values store individual component values in row-major order (for consistency with .NET arrays) and can be indexed in several ways just like with HLSL vector types. One noticeable difference compared to HLSL vector types though is the lack of explicit properties to extract swizzled vectors (eg. `Float4.XZY` returns a `Float3` value with the `X`, `Z` and `Y` components). Due to the number of possible combinations being simply too high in the case of matrix types (eg. `Float4x4` alone would have had over 160k properties), the ability to extract swizzled vectors ([see here](https://docs.microsoft.com/windows/win32/direct3dhlsl/dx-graphics-hlsl-per-component-math)) can be achieved through the use of a special indexer property and values from the `MatrixIndex` type. Here is how it can be used:
-## Advanced usage
+```csharp
+Float4x4 matrix = default;
-**ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for constant and readonly buffers, and more. Additionally, most of the [HLSL intrinsic functions](https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions) are available through the `Hlsl` class. Here is a more advanced sample showcasing all these features.
+// Standard indexer for rows and individual items
+Float4 row = matrix[0];
+float item = matrix[0][1];
-```C#
-// Define a class with some utility static functions
-public static class Activations
+// Swizzled indexers, which can be made less verbose to
+// write by adding this using static directive to the file
+using static ComputeSharp.MatrixIndex;
+
+Float4 diagonal = matrix[M11, M22, M33, M44];
+Float4 vertices = matrix[M11, M14, M44, M41];
+```
+
+Matrix types also include a number of built-in operators to work with vector types, and the `Hlsl` class detailed below (see [HLSL intrinsics](#hlsl-intrinsics)) also includes several overloads for the available methods to work on both matrix and vector types at the same time (eg. for row/matrix multiplication).
+
+## HLSL intrinsics
+
+**ComputeSharp** offers support for all HLSL intrinsics that can be used from compute shaders. These are special functions (usually representing mathematical operations) that are optimized on the GPU and can execute very efficiently. Some of them can be mapped automatically from methods in the `System.Math` type (such as `Math.Sin` and `Math.Cos`), but if you want to have direct access to all of them you can just use the methods in the `Hlsl` class from a compute shader, and **ComputeSharp** will rewrite all those calls to use the native intrinsics in the compute shaders where those are used.
+
+Here's an example of a shader that applies the [softmax function](https://en.wikipedia.org/wiki/Rectifier_(neural_networks)) to all the items in a given buffer:
+
+```csharp
+[AutoConstructor]
+public readonly struct SoftmaxActivation : IComputeShader
{
- public static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x));
-}
-
-// Define the shader
-public readonly struct ActivationShader : IComputeShader
-{
- private readonly int width;
-
- public readonly ReadOnlyBuffer x;
- public readonly ReadWriteBuffer y;
-
- public ActivationShader(
- int width,
- ReadOnlyBuffer x,
- ReadWriteBuffer y)
- {
- this.width = width;
- this.x = x;
- this.y = y;
- }
+ public readonly ReadWriteBuffer buffer;
+ public readonly float k;
public void Execute(ThreadIds ids)
{
- int offset = ids.X + ids.Y * width;
- float pow = Hlsl.Pow(x[offset], 2);
- y[offset] = Activations.Sigmoid(pow);
+ float exp = Hlsl.Exp(k * buffer[ThreadIds.X]);
+ float log = Hlsl.Log(1 + exp);
+
+ buffer[ThreadIds.X] = log / k;
}
}
+```
-int height = 10, width = 10;
-float[] x = new float[height * width]; // Array to sum to y
-float[] y = new float[height * width]; // Result array (assume both had some values)
+## Working with images
-using ReadOnlyBuffer xBuffer = Gpu.Default.AllocateReadOnlyBuffer(x);
-using ReadWriteBuffer yBuffer = Gpu.Default.AllocateReadWriteBuffer(y);
+As mentioned in the [GPU resource types](#gpu-resource-types) paragraph, there are several texture types that are specialized to work on image pixels, such as `ReadWriteTexture2D`. Let's imagine we want to write a compute shader that applies some image processing filter: we will need to load an image (eg. using [ImageSharp](https://github.com/SixLabors/ImageSharp), or just the `System.Drawing` APIs) and then process it on the GPU, but without spending time on the CPU to convert pixels from a format such as RGBA32 to the normalized `float` values we want our shader to work on. We can do this by utilizing the `ReadWriteTexture2D` type as follows:
+
+```csharp
+// Load a bitmap from a specified path and then lock the pixel data.
+// The locked pixels are in the BGRA32 format, which is the one we need.
+var bitmap = new Bitmap("myImage.jpg");
+var bitmapData = bitmap.LockBits(
+ new Rectangle(0, 0, bitmap.Width, bitmap.Height),
+ ImageLockMode.ReadWrite,
+ PixelFormat.Format32bppArgb);
+
+try
+{
+ // Create a span over the locked pixel data, of type Bgra32 (from ComputeSharp)
+ var bitmapSpan = new Span((Bgra32*)bitmapData.Scan0, bitmapData.Width * bitmapData.Height);
+
+ // Allocate a 2D texture by directly reading from the pixel data
+ using var texture = Gpu.Default.AllocateReadWriteTexture2D(bitmapSpan, bitmap.Width, bitmap.Height);
+
+ // Run our shader on the texture we just created
+ Gpu.Default.For(bitmap.Width, bitmap.Height, new GaussianBlur(texture));
+
+ // When the shader has completed, copy the processed texture back
+ texture.CopyTo(bitmapSpan);
+}
+finally
+{
+ bitmap.UnlockBits(bitmapData);
+}
+
+bitmap.Save("myImage.jpg");
+```
+
+With the compute shader being like this:
+
+```csharp
+[AutoConstructor]
+public readonly partial struct GaussianBlur : IComputeShader
+{
+ public readonly IReadWriteTexture2D texture;
+
+ // Other captured resources or values here...
+
+ public void Execute()
+ {
+ // Our image processing logic here. In this example, we are just
+ // applying a naive grayscale effect to all pixels in the image.
+ Float3 rgb = texture[ThreadIds.XY].RGB;
+ float avg = Hlsl.Dot(rgb, new(0.0722f, 0.7152f, 0.2126f));
+
+ texture[ThreadIds.XY].RGB = avg;
+ }
+}
+```
+
+> **NOTE:** this is just an example to illustrate how these texture types can help with automatic pixel format conversion. You're free to use any library of choice to load and save image data, as well as to how to structure your compute shaders representing image effects. This is just one of the infinite possible effects that could be achieved by using **ComputeSharp**.
+
+## Shader metaprogramming
+
+One of the reasons why **ComputeSharp** compiles shaders at runtime is that it allows it to support a number of dynamic scenarios, including shader metaprogramming. What this means is that it's possible to have a shader that captures an instance of a `Delegate` type (provided the signature matches the supported types mentioned above), and reuse it with different methods. The library will automatically run different variations of the shaders depending on what methods they are capturing. Here is an example:
+
+```csharp
+// Define a function we want to use in our shader. Captured functions
+// need to be static methods annotated with [ShaderAttribute].
+[ShaderMethod]
+public static float Square(float x) => x * x;
+
+[AutoConstructor]
+public readonly struct ApplyFunction : IComputeShader
+{
+ public readonly ReadWriteBuffer buffer;
+ public readonly Func function;
+
+ public void Execute()
+ {
+ buffer[ThreadIds.X] = function(buffer[ThreadIds.X]);
+ }
+}
+```
+
+Then we can simply create a new `Func` instance and use that to construct a new instance of the `ApplyFunction` type, to execute that shader on a target buffer. **ComputeSharp** will build or reuse a version of that shader with the supplied captured function and execute it on the GPU:
+
+```csharp
+float[] array = LoadSampleData();
+
+// Allocate the buffer and copy data to it
+using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(array);
// Run the shader
-Gpu.Default.For(width, height, new ActivationShader(width, xBuffer, yBuffer));
+Gpu.Default.For(width, height, new ApplyFunction(buffer, Square));
-// Get the data back and write it to the y array
-yBuffer.GetData(y);
+// Copy the processed data back as usual
+buffer.CopyTo(array);
```
# Requirements
-The **ComputeSharp** library requires .NET Standard 2.1 support, and it is available for applications targeting:
-- .NET Core >= 3.0
-- Windows (x86 or x64)
+The **ComputeSharp** library has the following requirements:
+- .NET 5
+- Windows x64
-Additionally, you need an IDE with .NET Core 3.1 and C# 8.0 support to compile the library and samples on your PC.
+Additionally, in order to compile the library or a project using it, you need a recent build of Visual Studio 2019 or another IDE that has support for Roslyn source generators, as **ComputeSharp** relies on this feature to create the HLSL shader sources and to extract other shader metadata that is necessary to setup and execute the code at runtime. You can learn more about source generators [here](https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/).
+
+# Sponsors
+
+Huge thanks to these sponsors for directly supporting my work on **ComputeSharp**, it means a lot! 🙌
+
+
+
+
# Special thanks
-The **ComputeSharp** library is based on some of the code from the [DX12GameEngine](https://github.com/Aminator/DirectX12GameEngine) repository by [Amin Delavar](https://github.com/Aminator). Additionally, **ComputeSharp** uses NuGet packages from the following repositories (excluding those from Microsoft):
+The **ComputeSharp** library was originally based on some of the code from the [DX12GameEngine](https://github.com/Aminator/DirectX12GameEngine) repository by [Amin Delavar](https://github.com/Aminator).
-- [Vortice.Windows](https://github.com/amerkoleci/Vortice.Windows)
-- [ILSpy](https://github.com/icsharpcode/ILSpy)
-- [Stubble](https://github.com/StubbleOrg/Stubble)
+Additionally, **ComputeSharp** uses NuGet packages from the following repositories:
+
+- [Microsoft.Toolkit.Diagnostics](https://github.com/windows-toolkit/WindowsCommunityToolkit)
+- [TerraFX.Interop.Windows](https://github.com/terrafx/terrafx.interop.windows)
+- [TerraFX.Interop.D3D12MemoryAllocator](https://github.com/terrafx/terrafx.interop.d3d12memoryallocator)
\ No newline at end of file
diff --git a/global.json b/global.json
new file mode 100644
index 00000000..9685cb85
--- /dev/null
+++ b/global.json
@@ -0,0 +1,5 @@
+{
+ "sdk": {
+ "version": "5.0.x"
+ }
+}
\ No newline at end of file
diff --git a/nuget.config b/nuget.config
new file mode 100644
index 00000000..c5173dab
--- /dev/null
+++ b/nuget.config
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
diff --git a/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs b/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs
new file mode 100644
index 00000000..5282758b
--- /dev/null
+++ b/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs
@@ -0,0 +1,162 @@
+using System;
+using System.Buffers;
+using BenchmarkDotNet.Attributes;
+using BenchmarkDotNet.Engines;
+
+namespace ComputeSharp.Benchmark.Blas
+{
+ ///
+ /// A that benchmarks the APIs in the class, on both CPU and GPU.
+ ///
+ [SimpleJob(RunStrategy.Monitoring)]
+ public class BlasBenchmark : IDisposable
+ {
+ ///
+ /// The number of samples.
+ ///
+ private const int C = 128;
+
+ ///
+ /// The nummber of rows in the matrix.
+ ///
+ private const int N = 512;
+
+ ///
+ /// The number of columns in the matrix (same as the number of rows in the matrix)
+ ///
+ private const int M = 512;
+
+ ///
+ /// The number of columns in the matrix.
+ ///
+ private const int P = 256;
+
+ ///
+ /// The input tensor.
+ ///
+ private float[]? X;
+
+ ///
+ /// The weights tensor.
+ ///
+ private float[]? W;
+
+ ///
+ /// The bias tensor.
+ ///
+ private float[]? B;
+
+ ///
+ /// The result tensor.
+ ///
+ private float[]? Y;
+
+ ///
+ /// The input tensor (GPU).
+ ///
+ private ReadOnlyBuffer? BufferX;
+
+ ///
+ /// The weights tensor (GPU).
+ ///
+ private ReadOnlyBuffer? BufferW;
+
+ ///
+ /// The bias tensor (GPU).
+ ///
+ private ReadOnlyBuffer? BufferB;
+
+ ///
+ /// The result tensor (GPU).
+ ///
+ private ReadWriteBuffer? BufferY;
+
+ ///
+ /// A instance to initialize the tensors.
+ ///
+ private readonly Random Random = new Random();
+
+ ///
+ /// Initial setup for a benchmarking session.
+ ///
+ [GlobalSetup]
+ public void Setup()
+ {
+ // Creates a new random normalized float[] array of a given size
+ float[] CreateRandomArray(int size)
+ {
+ float[] array = ArrayPool.Shared.Rent(size);
+
+ foreach (ref float x in array.AsSpan())
+ {
+ x = (float)Random.NextDouble();
+ }
+
+ return array;
+ }
+
+ X = CreateRandomArray(C * N * M);
+ W = CreateRandomArray(M * P);
+ B = CreateRandomArray(P);
+ Y = CreateRandomArray(C * N * P);
+
+ BufferX = Gpu.Default.AllocateReadOnlyBuffer(X);
+ BufferW = Gpu.Default.AllocateReadOnlyBuffer(W);
+ BufferB = Gpu.Default.AllocateReadOnlyBuffer(B);
+ BufferY = Gpu.Default.AllocateReadWriteBuffer(Y);
+
+ Cpu();
+ GpuWithNoTemporaryBuffers();
+ GpuWithTemporaryBuffers();
+ }
+
+ ///
+ [GlobalCleanup]
+ public void Dispose()
+ {
+ ArrayPool.Shared.Return(X!);
+ ArrayPool.Shared.Return(W!);
+ ArrayPool.Shared.Return(B!);
+ ArrayPool.Shared.Return(Y!);
+
+ BufferX!.Dispose();
+ BufferW!.Dispose();
+ BufferB!.Dispose();
+ BufferY!.Dispose();
+ }
+
+ ///
+ /// Runs a fully connected forward operation on the CPU.
+ ///
+ [Benchmark(Baseline = true)]
+ public void Cpu()
+ {
+ BlasHelpers.FullyConnectedForwardCpu(C, N, M, P, X!, W!, B!, Y!);
+ }
+
+ ///
+ /// Runs a fully connected forward operation on the GPU.
+ ///
+ [Benchmark]
+ public void GpuWithNoTemporaryBuffers()
+ {
+ BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, BufferX!, BufferW!, BufferB!, BufferY!);
+ }
+
+ ///
+ /// Runs a fully connected forward operation on the GPU, creating temporary GPU buffers to perform the operations.
+ ///
+ [Benchmark]
+ public void GpuWithTemporaryBuffers()
+ {
+ using ReadOnlyBuffer x = Gpu.Default.AllocateReadOnlyBuffer(X!);
+ using ReadOnlyBuffer w = Gpu.Default.AllocateReadOnlyBuffer(W!);
+ using ReadOnlyBuffer b = Gpu.Default.AllocateReadOnlyBuffer(B!);
+ using ReadWriteBuffer y = Gpu.Default.AllocateReadWriteBuffer(Y!.Length);
+
+ BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, x, w, b, y);
+
+ y.CopyTo(Y);
+ }
+ }
+}
diff --git a/samples/ComputeSharp.Benchmark/Dnn.cs b/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs
similarity index 51%
rename from samples/ComputeSharp.Benchmark/Dnn.cs
rename to samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs
index 904ddd78..d1e3df0a 100644
--- a/samples/ComputeSharp.Benchmark/Dnn.cs
+++ b/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs
@@ -1,24 +1,24 @@
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
-namespace ComputeSharp.Benchmark
+namespace ComputeSharp.Benchmark.Blas
{
///
- /// A that contains primitives to run certain operations of a neural network
+ /// A that contains primitives to run certain operations of a neural network.
///
- internal static class Dnn
+ internal static partial class BlasHelpers
{
///
- /// Executes the forward pass on a fully connected layer on the CPU
+ /// Executes the forward pass on a fully connected layer on the CPU.
///
- /// The number of samples in the input tensor
- /// The number of rows in the input matrix
- /// The number of columns in the input matrix
- /// The number of columns in the output matrix
- /// The input tensor
- /// The weights tensor
- /// The bias tensor
- /// The result tensor
+ /// The number of samples in the input tensor.
+ /// The number of rows in the input matrix.
+ /// The number of columns in the input matrix.
+ /// The number of columns in the output matrix.
+ /// The input tensor.
+ /// The weights tensor.
+ /// The bias tensor.
+ /// The result tensor.
public static void FullyConnectedForwardCpu(int c, int n, int m, int p, float[] x, float[] w, float[] b, float[] y)
{
void Kernel(int s)
@@ -51,69 +51,58 @@ namespace ComputeSharp.Benchmark
}
///
- /// Executes the forward pass on a fully connected layer on the GPU
+ /// Executes the forward pass on a fully connected layer on the GPU.
///
- /// The number of samples in the input tensor
- /// The number of rows in the input matrix
- /// The number of columns in the input matrix
- /// The number of columns in the output matrix
- /// The input tensor
- /// The weights tensor
- /// The bias tensor
- /// The result tensor
+ /// The device to run the computation on.
+ /// The number of samples in the input tensor.
+ /// The number of rows in the input matrix.
+ /// The number of columns in the input matrix.
+ /// The number of columns in the output matrix.
+ /// The input tensor.
+ /// The weights tensor.
+ /// The bias tensor.
+ /// The result tensor.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void FullyConnectedForwardGpu(
- int c, int n, int m, int p,
- ReadOnlyBuffer x, ReadOnlyBuffer w, ReadOnlyBuffer b, ReadWriteBuffer y)
+ GraphicsDevice device,
+ int c,
+ int n,
+ int m,
+ int p,
+ ReadOnlyBuffer x,
+ ReadOnlyBuffer w,
+ ReadOnlyBuffer b,
+ ReadWriteBuffer y)
{
- Gpu.Default.For(c, n, p, new FullyConnectedForwardKernel(n, m, p, x, w, b, y));
+ device.For(c, n, p, new FullyConnectedForwardKernel(n, m, p, x, w, b, y));
}
///
- /// Kernel for
+ /// Kernel for .
///
- private readonly struct FullyConnectedForwardKernel : IComputeShader
+ [AutoConstructor]
+ 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;
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public FullyConnectedForwardKernel(
- int n,
- int m,
- int p,
- ReadOnlyBuffer x,
- ReadOnlyBuffer w,
- ReadOnlyBuffer b,
- ReadWriteBuffer y)
- {
- this.n = n;
- this.m = m;
- this.p = p;
- this.x = x;
- this.w = w;
- this.b = b;
- this.y = 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)
+ public void Execute()
{
- int x_offset = ids.X * n * p + ids.Y * m;
+ int x_offset = ThreadIds.X * n * p + ThreadIds.Y * m;
float result = 0f;
for (int k = 0; k < m; k++)
{
- result += x[x_offset + k] * w[k * p + ids.Z];
+ result += x[x_offset + k] * w[k * p + ThreadIds.Z];
}
- y[ids.X * n * p + ids.Y * p + ids.Z] = result + b[ids.Z];
+ y[ThreadIds.X * n * p + ThreadIds.Y * p + ThreadIds.Z] = result + b[ThreadIds.Z];
}
}
}
diff --git a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj
index 0c070ff3..44e91014 100644
--- a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj
+++ b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj
@@ -2,15 +2,32 @@
Exe
- netcoreapp3.1
+ net5.0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
\ No newline at end of file
diff --git a/samples/ComputeSharp.Benchmark/DnnBenchmark.cs b/samples/ComputeSharp.Benchmark/DnnBenchmark.cs
deleted file mode 100644
index f7fc3936..00000000
--- a/samples/ComputeSharp.Benchmark/DnnBenchmark.cs
+++ /dev/null
@@ -1,158 +0,0 @@
-using System;
-using System.Buffers;
-using System.Diagnostics.Contracts;
-using System.Runtime.CompilerServices;
-using BenchmarkDotNet.Attributes;
-
-namespace ComputeSharp.Benchmark
-{
- ///
- /// A that benchmarks the APIs in the class, on both CPU and GPU
- ///
- public class DnnBenchmark : IDisposable
- {
- ///
- /// The number of samples
- ///
- private const int C = 128;
-
- ///
- /// The nummber of rows in the matrix
- ///
- private const int N = 512;
-
- ///
- /// The number of columns in the matrix (same as the number of rows in the matrix)
- ///
- private const int M = 512;
-
- ///
- /// The number of columns in the matrix
- ///
- private const int P = 256;
-
- ///
- /// The input tensor
- ///
- private float[] X;
-
- ///
- /// The weights tensor
- ///
- private float[] W;
-
- ///
- /// The bias tensor
- ///
- private float[] B;
-
- ///
- /// The result tensor
- ///
- private float[] Y;
-
- ///
- /// The input tensor
- ///
- private ReadOnlyBuffer BufferX;
-
- ///
- /// The weights tensor
- ///
- private ReadOnlyBuffer BufferW;
-
- ///
- /// The bias tensor
- ///
- private ReadOnlyBuffer BufferB;
-
- ///
- /// The result tensor
- ///
- private ReadWriteBuffer BufferY;
-
- ///
- /// A instance to initialize the tensors
- ///
- private readonly Random Random = new Random();
-
- ///
- /// Initial setup for a benchmarking session
- ///
- [GlobalSetup]
- public void Setup()
- {
- X = CreateRandomArray(C * N * M);
- W = CreateRandomArray(M * P);
- B = CreateRandomArray(P);
- Y = CreateRandomArray(C * N * P);
-
- BufferX = Gpu.Default.AllocateReadOnlyBuffer(X);
- BufferW = Gpu.Default.AllocateReadOnlyBuffer(W);
- BufferB = Gpu.Default.AllocateReadOnlyBuffer(B);
- BufferY = Gpu.Default.AllocateReadWriteBuffer(Y);
- }
-
- ///
- /// Clears the memory from the current session
- ///
- [GlobalCleanup]
- public void Dispose()
- {
- ArrayPool.Shared.Return(X);
- ArrayPool.Shared.Return(W);
- ArrayPool.Shared.Return(B);
- ArrayPool.Shared.Return(Y);
-
- BufferX.Dispose();
- BufferW.Dispose();
- BufferB.Dispose();
- BufferY.Dispose();
- }
-
- ///
- /// Creates a new array of the specified size
- ///
- /// The size of the new random array to create
- [Pure]
- private float[] CreateRandomArray(int size)
- {
- float[] array = ArrayPool.Shared.Rent(size);
- ref float r = ref array[0];
- for (int i = 0; i < size; i++)
- {
- Unsafe.Add(ref r, i) = (float)Random.NextDouble();
- }
-
- return array;
- }
-
- ///
- /// Runs a fully connected forward operation on the CPU
- ///
- [Benchmark(Baseline = true)]
- public void Cpu() => Dnn.FullyConnectedForwardCpu(C, N, M, P, X, W, B, Y);
-
- ///
- /// Runs a fully connected forward operation on the GPU
- ///
- [Benchmark]
- public void GpuWithNoTemporaryBuffers() => Dnn.FullyConnectedForwardGpu(C, N, M, P, BufferX, BufferW, BufferB, BufferY);
-
- ///
- /// Runs a fully connected forward operation on the GPU, creating temporary GPU buffers to perform the operations
- ///
- [Benchmark]
- public void GpuWithTemporaryBuffers()
- {
- using ReadOnlyBuffer x = Gpu.Default.AllocateReadOnlyBuffer(X);
- using ReadOnlyBuffer w = Gpu.Default.AllocateReadOnlyBuffer(W);
- using ReadOnlyBuffer b = Gpu.Default.AllocateReadOnlyBuffer(B);
- using ReadWriteBuffer y = Gpu.Default.AllocateReadWriteBuffer(Y);
-
- Dnn.FullyConnectedForwardGpu(C, N, M, P, x, w, b, y);
-
- y.GetData(Y);
- }
- }
-}
diff --git a/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs b/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs
new file mode 100644
index 00000000..ef208625
--- /dev/null
+++ b/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs
@@ -0,0 +1,91 @@
+using System;
+using System.IO;
+using System.Reflection;
+using BenchmarkDotNet.Attributes;
+using BenchmarkDotNet.Configs;
+using BenchmarkDotNet.Engines;
+using ComputeSharp.BokehBlur.Processors;
+using SixLabors.ImageSharp;
+using SixLabors.ImageSharp.Processing;
+using SixLabors.ImageSharp.Processing.Processors.Convolution;
+using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
+
+namespace ComputeSharp.Benchmark.Imaging
+{
+ ///
+ /// A that benchmarks the image processors against the reference in ImageSharp.
+ ///
+ [SimpleJob(RunStrategy.Monitoring)]
+ [CategoriesColumn]
+ [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
+ public class ImagingBenchmark : IDisposable
+ {
+ ///
+ /// The loaded image.
+ ///
+ private Image? image;
+
+ ///
+ /// Initial setup for a benchmarking session.
+ ///
+ [GlobalSetup]
+ public void Setup()
+ {
+ string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg");
+
+ this.image = Image.Load(path);
+
+ Bokeh_Cpu();
+ Bokeh_Gpu();
+ Gaussian_Cpu();
+ Gaussian_Gpu();
+ }
+
+ ///
+ [GlobalCleanup]
+ public void Dispose()
+ {
+ this.image!.Dispose();
+ }
+
+ ///
+ /// Runs a bokeh blur effect on the CPU.
+ ///
+ [Benchmark(Baseline = true)]
+ [BenchmarkCategory("BOKEH")]
+ public void Bokeh_Cpu()
+ {
+ this.image!.Mutate(c => c.ApplyProcessor(new BokehBlurProcessor(80, 2, 3)));
+ }
+
+ ///
+ /// Runs a bokeh blur effect on the GPU.
+ ///
+ [Benchmark]
+ [BenchmarkCategory("BOKEH")]
+ public void Bokeh_Gpu()
+ {
+ this.image!.Mutate(c => c.ApplyProcessor(new HlslBokehBlurProcessor(80, 2)));
+ }
+
+ ///
+ /// Runs a gaussian blur effect on the CPU.
+ ///
+ [Benchmark(Baseline = true)]
+ [BenchmarkCategory("GAUSSIAN")]
+ public void Gaussian_Cpu()
+ {
+ this.image!.Mutate(c => c.ApplyProcessor(new GaussianBlurProcessor(80)));
+ }
+
+ ///
+ /// Runs a gaussian blur effect on the GPU.
+ ///
+ [Benchmark]
+ [BenchmarkCategory("GAUSSIAN")]
+ public void Gaussian_Gpu()
+ {
+ this.image!.Mutate(c => c.ApplyProcessor(new HlslGaussianBlurProcessor(80)));
+ }
+ }
+}
diff --git a/samples/ComputeSharp.Benchmark/Program.cs b/samples/ComputeSharp.Benchmark/Program.cs
index 3667f4c3..0c321dcc 100644
--- a/samples/ComputeSharp.Benchmark/Program.cs
+++ b/samples/ComputeSharp.Benchmark/Program.cs
@@ -4,15 +4,15 @@ namespace ComputeSharp.Benchmark
{
public class Program
{
- public static void Main()
+ public static void Main(string[] args)
{
- /* =================
- * BenchmarkDotNet
- * ================
- * In order to run this benchmark, compile this project in Release mode,
- * then go to its bin\Release\netcoreapp3.0 folder, open a cmd prompt
- * and type "dotnet ComputeSharp.Benchmark.dll */
- BenchmarkRunner.Run();
+ // =================
+ // BenchmarkDotNet
+ // ================
+ // In order to run this benchmark, compile this project in Release mode,
+ // then go to its bin\Release\netcoreapp3.0 folder, open a cmd prompt
+ // and type "dotnet ComputeSharp.Benchmark.dll" to execute it.
+ BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);
}
}
}
diff --git a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj
index 44109545..bdeeafa3 100644
--- a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj
+++ b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj
@@ -2,25 +2,23 @@
Exe
- netcoreapp3.1
+ net5.0
-
+
-
- PreserveNewest
-
-
-
-
-
+
+
diff --git a/samples/ComputeSharp.ImageProcessing/Primitives/Complex64.cs b/samples/ComputeSharp.ImageProcessing/Primitives/Complex64.cs
new file mode 100644
index 00000000..e14516c1
--- /dev/null
+++ b/samples/ComputeSharp.ImageProcessing/Primitives/Complex64.cs
@@ -0,0 +1,46 @@
+// Copyright (c) Six Labors.
+// Licensed under the Apache License, Version 2.0.
+
+using System.Runtime.CompilerServices;
+
+namespace SixLabors.ImageSharp
+{
+ ///
+ /// Represents a complex number, where the real and imaginary parts are stored as values.
+ ///
+ ///
+ /// This is a more efficient version of the type.
+ ///
+ internal readonly struct Complex64
+ {
+ ///
+ /// The real part of the complex number.
+ ///
+ public readonly float Real;
+
+ ///
+ /// The imaginary part of the complex number.
+ ///
+ public readonly float Imaginary;
+
+ ///
+ /// Initializes a new instance of the struct.
+ ///
+ /// The real part in the complex number.
+ /// The imaginary part in the complex number.
+ public Complex64(float real, float imaginary)
+ {
+ this.Real = real;
+ this.Imaginary = imaginary;
+ }
+
+ ///
+ /// Performs the multiplication operation between a instance and a scalar.
+ ///
+ /// The value to multiply.
+ /// The scalar to use to multiply the value.
+ /// The result.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Complex64 operator *(Complex64 value, float scalar) => new Complex64(value.Real * scalar, value.Imaginary * scalar);
+ }
+}
\ No newline at end of file
diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs
index 2ae2eef1..25e9dfc9 100644
--- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs
+++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs
@@ -1,67 +1,85 @@
-using SixLabors.ImageSharp;
+using System.Runtime.CompilerServices;
+using Microsoft.Toolkit.Diagnostics;
+using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
+using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors
{
///
- /// Applies bokeh blur processing to the image
+ /// 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
+ /// The default radius used by the parameterless constructor.
///
public const int DefaultRadius = 32;
///
- /// The default component count used by the parameterless constructor
+ /// The default component count used by the parameterless constructor.
///
public const int DefaultComponents = 2;
///
- /// The default gamma used by the parameterless constructor
+ /// Initializes a new instance of the class.
///
- public const float DefaultGamma = 3f;
-
- ///
- /// Initializes a new instance of the class
- ///
- public HlslBokehBlurProcessor() : this(DefaultRadius, DefaultComponents, DefaultGamma) { }
-
- ///
- /// Initializes a new instance of the class
- ///
- /// The size of the area to sample
- /// The number of components to use to approximate the original 2D bokeh blur convolution kernel
- /// The gamma highlight factor to use to further process the image
- public HlslBokehBlurProcessor(int radius, int components, float gamma)
+ public HlslBokehBlurProcessor()
+ : this(Gpu.Default, DefaultRadius, DefaultComponents)
{
- Radius = radius;
- Components = components;
- Gamma = gamma;
}
///
- /// Gets the radius
+ /// Initializes a new instance of the class.
+ ///
+ /// The size of the area to sample.
+ /// The number of components to use to approximate the original 2D bokeh blur convolution kernel.
+ public HlslBokehBlurProcessor(int radius, int components)
+ : this(Gpu.Default, radius, components)
+ {
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The associated with the current instance.
+ /// The size of the area to sample.
+ /// The number of components to use to approximate the original 2D bokeh blur convolution kernel.
+ public HlslBokehBlurProcessor(GraphicsDevice device, int radius, int components)
+ {
+ GraphicsDevice = device;
+ Radius = radius;
+ Components = components;
+ }
+
+ ///
+ /// Gets the associated with the current instance.
+ ///
+ public GraphicsDevice GraphicsDevice { get; }
+
+ ///
+ /// Gets the radius.
///
public int Radius { get; }
///
- /// Gets the number of components
+ /// Gets the number of components.
///
public int Components { get; }
- ///
- /// Gets the gamma highlight factor to use when applying the effect
- ///
- public float Gamma { get; }
-
///
public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle)
where TPixel : unmanaged, IPixel
{
- return new HlslBokehBlurProcessor(this, configuration, source, sourceRectangle);
+ if (typeof(TPixel) != typeof(ImageSharpRgba32))
+ {
+ ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format");
+ }
+
+ var processor = new Implementation(this, configuration, Unsafe.As>(source), sourceRectangle);
+
+ return Unsafe.As>(processor);
}
}
}
diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs
index b400ecce..eddd54af 100644
--- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs
+++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs
@@ -1,563 +1,426 @@
using System;
-using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Generic;
-using System.Diagnostics.Contracts;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
+using Microsoft.Toolkit.Diagnostics;
using SixLabors.ImageSharp;
-using SixLabors.ImageSharp.Advanced;
-using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
+using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors
{
- ///
- /// Applies bokeh blur processing to the image
- ///
- /// The pixel format
- /// This processor is based on the code from Mike Pound, see github.com/mikepound/convolve
- public sealed class HlslBokehBlurProcessor : ImageProcessor
- where TPixel : unmanaged, IPixel
+ ///
+ public sealed partial class HlslBokehBlurProcessor
{
///
- /// The kernel radius
+ /// Applies bokeh blur processing to the image.
///
- private readonly int Radius;
-
- ///
- /// The gamma highlight factor to use when applying the effect
- ///
- private readonly float Gamma;
-
- ///
- /// The maximum size of the kernel in either direction
- ///
- private readonly int KernelSize;
-
- ///
- /// The number of components to use when applying the bokeh blur
- ///
- private readonly int ComponentsCount;
-
- ///
- /// The kernel parameters to use for the current instance (a: X, b: Y, A: Z, B: W)
- ///
- private readonly Vector4[] KernelParameters;
-
- ///
- /// The kernel components for the current instance
- ///
- private readonly Vector2[][] Kernels;
-
- ///
- /// The scaling factor for kernel values
- ///
- private readonly float KernelsScale;
-
- ///
- /// The mapping of initialized complex kernels and parameters, to speed up the initialization of new instances
- ///
- private static readonly ConcurrentDictionary<(int Radius, int ComponentsCount), (Vector4[] Parameters, float Scale, Vector2[][] Kernels)> Cache = new ConcurrentDictionary<(int, int), (Vector4[], float, Vector2[][])>();
-
- ///
- /// Initializes a new instance of the class
- ///
- /// The defining the processor parameters
- /// The configuration which allows altering default behaviour or extending the library
- /// The source instance to modify
- /// The source that indicates the area to edit
- public HlslBokehBlurProcessor(HlslBokehBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle)
- : base(configuration, source, sourceRectangle)
+ /// This processor is based on the code from Mike Pound, see github.com/mikepound/convolve.
+ public sealed partial class Implementation : ImageProcessor
{
- Radius = definition.Radius;
- KernelSize = Radius * 2 + 1;
- ComponentsCount = definition.Components;
- Gamma = definition.Gamma;
+ ///
+ /// The instance in use.
+ ///
+ private readonly GraphicsDevice GraphicsDevice;
- // Reuse the initialized values from the cache, if possible
- var parameters = (Radius, ComponentsCount);
- if (Cache.TryGetValue(parameters, out var info))
+ ///
+ /// The kernel radius.
+ ///
+ private readonly int Radius;
+
+ ///
+ /// The maximum size of the kernel in either direction.
+ ///
+ private readonly int KernelSize;
+
+ ///
+ /// The number of components to use when applying the bokeh blur.
+ ///
+ private readonly int ComponentsCount;
+
+ ///
+ /// The kernel parameters to use for the current instance (a: X, b: Y, A: Z, B: W)
+ ///
+ private readonly Vector4[] KernelParameters;
+
+ ///
+ /// The kernel components for the current instance.
+ ///
+ private readonly Complex64[][] Kernels;
+
+ ///
+ /// The scaling factor for kernel values.
+ ///
+ private readonly float KernelsScale;
+
+ ///
+ /// The mapping of initialized complex kernels and parameters, to speed up the initialization of new instances.
+ ///
+ private static readonly ConcurrentDictionary<(int Radius, int ComponentsCount), (Vector4[] Parameters, float Scale, Complex64[][] Kernels)> Cache = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The defining the processor parameters.
+ /// The configuration which allows altering default behaviour or extending the library.
+ /// The source instance to modify.
+ /// The source that indicates the area to edit.
+ public Implementation(HlslBokehBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle)
+ : base(configuration, source, sourceRectangle)
{
- KernelParameters = info.Parameters;
- KernelsScale = info.Scale;
- Kernels = info.Kernels;
- }
- else
- {
- // Initialize the complex kernels and parameters with the current arguments
- (KernelParameters, KernelsScale) = GetParameters();
- Kernels = CreateComplexKernels();
- NormalizeKernels();
+ GraphicsDevice = definition.GraphicsDevice;
+ Radius = definition.Radius;
+ KernelSize = Radius * 2 + 1;
+ ComponentsCount = definition.Components;
- // Store them in the cache for future use
- Cache.TryAdd(parameters, (KernelParameters, KernelsScale, Kernels));
- }
- }
-
- ///
- /// Gets the kernel scales to adjust the component values in each kernel
- ///
- private static IReadOnlyList KernelScales { get; } = new[] { 1.4f, 1.2f, 1.2f, 1.2f, 1.2f, 1.2f };
-
- ///
- /// Gets the available bokeh blur kernel parameters
- ///
- private static IReadOnlyList KernelComponents { get; } = new[]
- {
- // 1 component
- new[] { new Vector4(0.862325f, 1.624835f, 0.767583f, 1.862321f) },
-
- // 2 components
- new[]
- {
- new Vector4(0.886528f, 5.268909f, 0.411259f, -0.548794f),
- new Vector4(1.960518f, 1.558213f, 0.513282f, 4.56111f)
- },
-
- // 3 components
- new[]
- {
- new Vector4(2.17649f, 5.043495f, 1.621035f, -2.105439f),
- new Vector4(1.019306f, 9.027613f, -0.28086f, -0.162882f),
- new Vector4(2.81511f, 1.597273f, -0.366471f, 10.300301f)
- },
-
- // 4 components
- new[]
- {
- new Vector4(4.338459f, 1.553635f, -5.767909f, 46.164397f),
- new Vector4(3.839993f, 4.693183f, 9.795391f, -15.227561f),
- new Vector4(2.791880f, 8.178137f, -3.048324f, 0.302959f),
- new Vector4(1.342190f, 12.328289f, 0.010001f, 0.244650f)
- },
-
- // 5 components
- new[]
- {
- new Vector4(4.892608f, 1.685979f, -22.356787f, 85.91246f),
- new Vector4(4.71187f, 4.998496f, 35.918936f, -28.875618f),
- new Vector4(4.052795f, 8.244168f, -13.212253f, -1.578428f),
- new Vector4(2.929212f, 11.900859f, 0.507991f, 1.816328f),
- new Vector4(1.512961f, 16.116382f, 0.138051f, -0.01f)
- },
-
- // 6 components
- new[]
- {
- new Vector4(5.143778f, 2.079813f, -82.326596f, 111.231024f),
- new Vector4(5.612426f, 6.153387f, 113.878661f, 58.004879f),
- new Vector4(5.982921f, 9.802895f, 39.479083f, -162.028887f),
- new Vector4(6.505167f, 11.059237f, -71.286026f, 95.027069f),
- new Vector4(3.869579f, 14.81052f, 1.405746f, -3.704914f),
- new Vector4(2.201904f, 19.032909f, -0.152784f, -0.107988f)
- }
- };
-
- ///
- /// Gets the kernel parameters and scaling factor for the current count value in the current instance
- ///
- private (Vector4[] Parameters, float Scale) GetParameters()
- {
- // Prepare the kernel components
- int index = Math.Max(0, Math.Min(ComponentsCount - 1, KernelComponents.Count));
- return (KernelComponents[index], KernelScales[index]);
- }
-
- ///
- /// Creates the collection of complex 1D kernels with the specified parameters
- ///
- private Vector2[][] CreateComplexKernels()
- {
- var kernels = new Vector2[KernelParameters.Length][];
- ref Vector4 baseRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
- for (int i = 0; i < KernelParameters.Length; i++)
- {
- ref Vector4 paramsRef = ref Unsafe.Add(ref baseRef, i);
- kernels[i] = CreateComplex1DKernel(paramsRef.X, paramsRef.Y);
- }
-
- return kernels;
- }
-
- ///
- /// Creates a complex 1D kernel with the specified parameters
- ///
- /// The exponential parameter for each complex component
- /// The angle component for each complex component
- private Vector2[] CreateComplex1DKernel(float a, float b)
- {
- var kernel = new Vector2[KernelSize];
- ref Vector2 baseRef = ref MemoryMarshal.GetReference(kernel.AsSpan());
- int r = Radius, n = -r;
-
- for (int i = 0; i < KernelSize; i++, n++)
- {
- // Incrementally compute the range values
- float value = n * KernelsScale * (1f / r);
- value *= value;
-
- // Fill in the complex kernel values
- Unsafe.Add(ref baseRef, i) = new Vector2(
- MathF.Exp(-a * value) * MathF.Cos(b * value),
- MathF.Exp(-a * value) * MathF.Sin(b * value));
- }
-
- return kernel;
- }
-
- ///
- /// Normalizes the kernels with respect to A * real + B * imaginary
- ///
- private void NormalizeKernels()
- {
- // Calculate the complex weighted sum
- float total = 0;
- Span kernelsSpan = Kernels.AsSpan();
- ref Vector2[] baseKernelsRef = ref MemoryMarshal.GetReference(kernelsSpan);
- ref Vector4 baseParamsRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
-
- for (int i = 0; i < KernelParameters.Length; i++)
- {
- ref Vector2[] kernelRef = ref Unsafe.Add(ref baseKernelsRef, i);
- int length = kernelRef.Length;
- ref Vector2 valueRef = ref kernelRef[0];
- ref Vector4 paramsRef = ref Unsafe.Add(ref baseParamsRef, i);
-
- for (int j = 0; j < length; j++)
+ // Reuse the initialized values from the cache, if possible
+ var parameters = (Radius, ComponentsCount);
+ if (Cache.TryGetValue(parameters, out var info))
{
- for (int k = 0; k < length; k++)
+ KernelParameters = info.Parameters;
+ KernelsScale = info.Scale;
+ Kernels = info.Kernels;
+ }
+ else
+ {
+ // Initialize the complex kernels and parameters with the current arguments
+ (KernelParameters, KernelsScale) = GetParameters();
+ Kernels = CreateComplexKernels();
+ NormalizeKernels();
+
+ // Store them in the cache for future use
+ Cache.TryAdd(parameters, (KernelParameters, KernelsScale, Kernels));
+ }
+ }
+
+ ///
+ /// Gets the kernel scales to adjust the component values in each kernel.
+ ///
+ private static IReadOnlyList KernelScales { get; } = new[] { 1.4f, 1.2f, 1.2f, 1.2f, 1.2f, 1.2f };
+
+ ///
+ /// Gets the available bokeh blur kernel parameters.
+ ///
+ private static IReadOnlyList KernelComponents { get; } = new[]
+ {
+ // 1 component
+ new[] { new Vector4(0.862325f, 1.624835f, 0.767583f, 1.862321f) },
+
+ // 2 components
+ new[]
+ {
+ new Vector4(0.886528f, 5.268909f, 0.411259f, -0.548794f),
+ new Vector4(1.960518f, 1.558213f, 0.513282f, 4.56111f)
+ },
+
+ // 3 components
+ new[]
+ {
+ new Vector4(2.17649f, 5.043495f, 1.621035f, -2.105439f),
+ new Vector4(1.019306f, 9.027613f, -0.28086f, -0.162882f),
+ new Vector4(2.81511f, 1.597273f, -0.366471f, 10.300301f)
+ },
+
+ // 4 components
+ new[]
+ {
+ new Vector4(4.338459f, 1.553635f, -5.767909f, 46.164397f),
+ new Vector4(3.839993f, 4.693183f, 9.795391f, -15.227561f),
+ new Vector4(2.791880f, 8.178137f, -3.048324f, 0.302959f),
+ new Vector4(1.342190f, 12.328289f, 0.010001f, 0.244650f)
+ },
+
+ // 5 components
+ new[]
+ {
+ new Vector4(4.892608f, 1.685979f, -22.356787f, 85.91246f),
+ new Vector4(4.71187f, 4.998496f, 35.918936f, -28.875618f),
+ new Vector4(4.052795f, 8.244168f, -13.212253f, -1.578428f),
+ new Vector4(2.929212f, 11.900859f, 0.507991f, 1.816328f),
+ new Vector4(1.512961f, 16.116382f, 0.138051f, -0.01f)
+ },
+
+ // 6 components
+ new[]
+ {
+ new Vector4(5.143778f, 2.079813f, -82.326596f, 111.231024f),
+ new Vector4(5.612426f, 6.153387f, 113.878661f, 58.004879f),
+ new Vector4(5.982921f, 9.802895f, 39.479083f, -162.028887f),
+ new Vector4(6.505167f, 11.059237f, -71.286026f, 95.027069f),
+ new Vector4(3.869579f, 14.81052f, 1.405746f, -3.704914f),
+ new Vector4(2.201904f, 19.032909f, -0.152784f, -0.107988f)
+ }
+ };
+
+ ///
+ /// Gets the kernel parameters and scaling factor for the current count value in the current instance.
+ ///
+ private (Vector4[] Parameters, float Scale) GetParameters()
+ {
+ // Prepare the kernel components
+ int index = Math.Max(0, Math.Min(ComponentsCount - 1, KernelComponents.Count));
+ return (KernelComponents[index], KernelScales[index]);
+ }
+
+ ///
+ /// Creates the collection of complex 1D kernels with the specified parameters.
+ ///
+ private Complex64[][] CreateComplexKernels()
+ {
+ var kernels = new Complex64[KernelParameters.Length][];
+ ref Vector4 baseRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
+ for (int i = 0; i < KernelParameters.Length; i++)
+ {
+ ref Vector4 paramsRef = ref Unsafe.Add(ref baseRef, i);
+ kernels[i] = CreateComplex1DKernel(paramsRef.X, paramsRef.Y);
+ }
+
+ return kernels;
+ }
+
+ ///
+ /// Creates a complex 1D kernel with the specified parameters.
+ ///
+ /// The exponential parameter for each complex component.
+ /// The angle component for each complex component.
+ private Complex64[] CreateComplex1DKernel(float a, float b)
+ {
+ var kernel = new Complex64[KernelSize];
+ ref Complex64 baseRef = ref MemoryMarshal.GetReference(kernel.AsSpan());
+ int r = Radius, n = -r;
+
+ for (int i = 0; i < KernelSize; i++, n++)
+ {
+ // Incrementally compute the range values
+ float value = n * KernelsScale * (1f / r);
+ value *= value;
+
+ // Fill in the complex kernel values
+ Unsafe.Add(ref baseRef, i) = new Complex64(
+ MathF.Exp(-a * value) * MathF.Cos(b * value),
+ MathF.Exp(-a * value) * MathF.Sin(b * value));
+ }
+
+ return kernel;
+ }
+
+ ///
+ /// Normalizes the kernels with respect to A * real + B * imaginary.
+ ///
+ private void NormalizeKernels()
+ {
+ // Calculate the complex weighted sum
+ float total = 0;
+ Span kernelsSpan = Kernels.AsSpan();
+ ref Complex64[] baseKernelsRef = ref MemoryMarshal.GetReference(kernelsSpan);
+ ref Vector4 baseParamsRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
+
+ for (int i = 0; i < KernelParameters.Length; i++)
+ {
+ ref Complex64[] kernelRef = ref Unsafe.Add(ref baseKernelsRef, i);
+ int length = kernelRef.Length;
+ ref Complex64 valueRef = ref kernelRef[0];
+ ref Vector4 paramsRef = ref Unsafe.Add(ref baseParamsRef, i);
+
+ for (int j = 0; j < length; j++)
{
- ref Vector2 jRef = ref Unsafe.Add(ref valueRef, j);
- ref Vector2 kRef = ref Unsafe.Add(ref valueRef, k);
- total +=
- paramsRef.Z * (jRef.X * kRef.X - jRef.Y * kRef.Y)
- + paramsRef.W * (jRef.X * kRef.Y + jRef.Y * kRef.X);
+ for (int k = 0; k < length; k++)
+ {
+ ref Complex64 jRef = ref Unsafe.Add(ref valueRef, j);
+ ref Complex64 kRef = ref Unsafe.Add(ref valueRef, k);
+ total +=
+ paramsRef.Z * (jRef.Real * kRef.Real - jRef.Imaginary * kRef.Imaginary)
+ + paramsRef.W * (jRef.Real * kRef.Imaginary + jRef.Imaginary * kRef.Real);
+ }
+ }
+ }
+
+ // Normalize the kernels
+ float scalar = 1f / MathF.Sqrt(total);
+ for (int i = 0; i < kernelsSpan.Length; i++)
+ {
+ ref Complex64[] kernelsRef = ref Unsafe.Add(ref baseKernelsRef, i);
+ int length = kernelsRef.Length;
+ ref Complex64 valueRef = ref kernelsRef[0];
+
+ for (int j = 0; j < length; j++)
+ {
+ Unsafe.Add(ref valueRef, j) *= scalar;
}
}
}
- // Normalize the kernels
- float scalar = 1f / MathF.Sqrt(total);
- for (int i = 0; i < kernelsSpan.Length; i++)
+ ///
+ protected override void OnFrameApply(ImageFrame source)
{
- ref Vector2[] kernelsRef = ref Unsafe.Add(ref baseKernelsRef, i);
- int length = kernelsRef.Length;
- ref Vector2 valueRef = ref kernelsRef[0];
-
- for (int j = 0; j < length; j++)
+ if (!source.TryGetSinglePixelSpan(out Span pixelSpan))
{
- Unsafe.Add(ref valueRef, j) *= scalar;
+ ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory");
}
- }
- }
- ///
- protected override void OnFrameApply(ImageFrame source)
- {
- foreach (Memory memory in source.GetPixelMemoryGroup())
- {
+ Span span = MemoryMarshal.Cast(pixelSpan);
+
+ using ReadWriteTexture2D texture = GraphicsDevice.AllocateReadWriteTexture2D(span, source.Width, source.Height);
+ using ReadWriteTexture2D temporary = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height, AllocationMode.Clear);
+ using ReadWriteTexture2D reals = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height);
+ using ReadWriteTexture2D imaginaries = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height);
+ using ReadOnlyBuffer kernel = GraphicsDevice.AllocateReadOnlyBuffer(KernelSize);
+
// Preliminary gamma highlight pass
- using IMemoryOwner source4 = GetExposedVector4Buffer(memory);
-
- using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span);
- using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size);
- using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size * 2);
- using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize);
-
- ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters
+ GraphicsDevice.For(source.Height, new(texture));
// Perform two 1D convolutions for each component in the current instance
for (int j = 0; j < Kernels.Length; j++)
{
- kernelBuffer.SetData(Kernels[j]);
- Vector4 parameters = Unsafe.Add(ref param0, j);
+ Vector4 parameters = KernelParameters[j];
- ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer);
- ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W);
+ kernel.CopyFrom(Kernels[j]);
+
+ GraphicsDevice.For(
+ source.Width,
+ source.Height,
+ new(texture, reals, imaginaries, kernel));
+
+ GraphicsDevice.For(
+ source.Width,
+ source.Height,
+ new(parameters.Z, parameters.W, reals, imaginaries, temporary, kernel));
}
// Apply the inverse gamma exposure pass
- processingBuffer.GetData(source4.Memory.Span);
+ GraphicsDevice.For(source.Height, new(temporary, texture));
// Write the final pixel data
- ApplyInverseGammaExposure(source4.Memory, memory);
+ texture.CopyTo(span);
}
- }
- ///
- /// Performs a vertical 1D complex convolution with the specified parameters
- ///
- /// The source to read data from
- /// The target to write the results to
- /// The with the values for the current complex kernel
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void ApplyVerticalConvolution(
- ReadOnlyBuffer source,
- ReadWriteBuffer target,
- ReadOnlyBuffer kernel)
- {
- int height = Source.Height;
- int width = Source.Width;
-
- Gpu.Default.For(width, height, new VerticalConvolutionProcessor
+ ///
+ /// Kernel for the vertical convolution pass.
+ ///
+ [AutoConstructor]
+ internal partial struct VerticalConvolutionProcessor : IComputeShader
{
- width = width,
- maxY = height - 1,
- maxX = width - 1,
- kernelLength = kernel.Size,
- source = source,
- target = target,
- kernel = kernel
- });
- }
+ public IReadWriteTexture2D source;
+ public ReadWriteTexture2D reals;
+ public ReadWriteTexture2D imaginaries;
+ public ReadOnlyBuffer kernel;
- ///
- /// Kernel for
- ///
- private 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++)
+ ///
+ public void Execute()
{
- int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
- int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
- Vector4 color = source[offsetY * width + offsetX];
- Vector2 factors = kernel[i];
+ Vector4 real = Vector4.Zero;
+ Vector4 imaginary = Vector4.Zero;
+ int maxY = source.Height;
+ int maxX = source.Width;
+ int kernelLength = kernel.Length;
+ int radiusY = kernelLength >> 1;
- real += factors.X * color;
- imaginary += factors.Y * color;
- }
+ for (int i = 0; i < kernelLength; i++)
+ {
+ int offsetY = Hlsl.Clamp(ThreadIds.Y + i - radiusY, 0, maxY);
+ int offsetX = Hlsl.Clamp(ThreadIds.X, 0, maxX);
+ Vector4 color = source[offsetX, offsetY];
+ Complex64 factors = kernel[i];
- int offsetXY = ids.Y * width * 2 + ids.X * 2;
- target[offsetXY] = real;
- target[offsetXY + 1] = imaginary;
- }
- }
+ real += factors.Real * color;
+ imaginary += factors.Imaginary * color;
+ }
- ///
- /// Performs an horizontal 1D complex convolution with the specified parameters
- ///
- /// The source to read data from
- /// The target to write the results to
- /// The with the values for the current complex kernel
- /// The weight factor for the real component of the complex pixel values
- /// The weight factor for the imaginary component of the complex pixel values
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void ApplyHorizontalConvolutionAndAccumulatePartials(
- ReadWriteBuffer source,
- ReadWriteBuffer target,
- ReadOnlyBuffer kernel,
- float z,
- float w)
- {
- int height = Source.Height;
- int width = Source.Width;
-
- Gpu.Default.For(width, height, new HorizontalConvolutionAndAccumulatePartialsProcessor
- {
- width = width,
- maxY = height - 1,
- maxX = width - 1,
- kernelLength = kernel.Size,
- z = z,
- w = w,
- source = source,
- target = target,
- kernel = kernel
- });
- }
-
- ///
- /// Kernel for
- ///
- private 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 * 2 + offsetX * 2;
- Vector4 sourceReal = source[offsetXY];
- Vector4 sourceImaginary = source[offsetXY + 1];
- Vector2 factors = kernel[i];
-
- real += factors.X * sourceReal - factors.Y * sourceImaginary;
- imaginary += factors.X * sourceImaginary + factors.Y * sourceReal;
- }
-
- 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.
- ///
- /// The source image
- [Pure]
- private IMemoryOwner GetExposedVector4Buffer(Memory source)
- {
- IMemoryOwner target = Configuration.MemoryAllocator.Allocate(source.Length);
-
- float exp = Gamma;
- int width = Source.Width;
- int height = source.Length / width;
-
- ParallelRowIterator.IterateRows(
- Configuration,
- new Rectangle(0, 0, width, height),
- new GetExposedVector4BufferProcessor(width, exp, source, target.Memory, Configuration));
-
- return target;
- }
-
- ///
- /// The processor for
- ///
- private readonly struct GetExposedVector4BufferProcessor : IRowOperation
- {
- private readonly int width;
- private readonly float exp;
-
- private readonly Memory source;
- private readonly Memory target;
- private readonly Configuration configuration;
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public GetExposedVector4BufferProcessor(
- int width,
- float exp,
- Memory source,
- Memory target,
- Configuration configuration)
- {
- this.width = width;
- this.exp = exp;
- this.source = source;
- this.target = target;
- this.configuration = configuration;
- }
-
- ///
- public void Invoke(int y)
- {
- int offset = y * width;
-
- Span rowTPixel = source.Span.Slice(offset, width);
- Span rowVector4 = target.Span.Slice(offset, width);
-
- PixelOperations.Instance.ToVector4(configuration, rowTPixel, rowVector4);
-
- foreach (ref Vector4 v in rowVector4)
- {
- v.X = MathF.Pow(v.X, exp);
- v.Y = MathF.Pow(v.Y, exp);
- v.Z = MathF.Pow(v.Z, exp);
+ reals[ThreadIds.XY] = real;
+ imaginaries[ThreadIds.XY] = imaginary;
}
}
- }
- ///
- /// Applies the inverse gamma exposure pass to compute the final pixel values for a target image
- ///
- /// The source buffer to read from
- /// The target image
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void ApplyInverseGammaExposure(Memory source, Memory target)
- {
- int width = Source.Width;
- int height = source.Length / width;
- float expGamma = 1 / Gamma;
-
- ParallelRowIterator.IterateRows(
- Configuration,
- new Rectangle(0, 0, width, height),
- new ApplyInverseGammaExposureProcessor(width, expGamma, source, target, Configuration));
- }
-
- ///
- /// The processor for
- ///
- private readonly struct ApplyInverseGammaExposureProcessor : IRowOperation
- {
- private readonly int width;
- private readonly float exp;
-
- private readonly Memory source;
- private readonly Memory target;
- private readonly Configuration configuration;
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public ApplyInverseGammaExposureProcessor(
- int width,
- float exp,
- Memory source,
- Memory target,
- Configuration configuration)
+ ///
+ /// Kernel for the horizontal convolution pass.
+ ///
+ [AutoConstructor]
+ internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
{
- this.width = width;
- this.exp = exp;
- this.source = source;
- this.target = target;
- this.configuration = configuration;
+ public float z;
+ public float w;
+
+ public ReadWriteTexture2D reals;
+ public ReadWriteTexture2D imaginaries;
+ public ReadWriteTexture2D target;
+ public ReadOnlyBuffer kernel;
+
+ ///
+ public void Execute()
+ {
+ Vector4 real = Vector4.Zero;
+ Vector4 imaginary = Vector4.Zero;
+ int maxY = target.Height;
+ int maxX = target.Width;
+ int kernelLength = kernel.Length;
+ int radiusX = kernelLength >> 1;
+ int offsetY = Hlsl.Clamp(ThreadIds.Y, 0, maxY);
+
+ for (int i = 0; i < kernelLength; i++)
+ {
+ int offsetX = Hlsl.Clamp(ThreadIds.X + i - radiusX, 0, maxX);
+ Vector4 sourceReal = reals[offsetX, offsetY];
+ Vector4 sourceImaginary = imaginaries[offsetX, offsetY];
+ Complex64 factors = kernel[i];
+
+ real += factors.Real * sourceReal - factors.Imaginary * sourceImaginary;
+ imaginary += factors.Real * sourceImaginary + factors.Imaginary * sourceReal;
+ }
+
+ target[ThreadIds.XY] += real * z + imaginary * w;
+ }
}
- ///
- public void Invoke(int y)
+ ///
+ /// Kernel for the gamma highlight pass.
+ ///
+ [AutoConstructor]
+ internal readonly partial struct GammaHighlightProcessor : IComputeShader
{
- int offset = y * width;
+ public readonly IReadWriteTexture2D source;
- Span rowVector4 = source.Span.Slice(offset, width);
- Span rowTPixel = target.Span.Slice(offset, width);
-
- Vector4 low = Vector4.Zero;
- var high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
-
- foreach (ref Vector4 v in rowVector4)
+ ///
+ public void Execute()
{
- var clamp = Vector4.Clamp(v, low, high);
- v.X = MathF.Pow(clamp.X, exp);
- v.Y = MathF.Pow(clamp.Y, exp);
- v.Z = MathF.Pow(clamp.Z, exp);
- }
+ int width = source.Width;
- PixelOperations.Instance.FromVector4Destructive(configuration, rowVector4, rowTPixel);
+ for (int i = 0; i < width; i++)
+ {
+ Float4 v = source[i, ThreadIds.X];
+
+ v.XYZ = v.XYZ * v.XYZ * v.XYZ;
+
+ source[i, ThreadIds.X] = v;
+ }
+ }
+ }
+
+ ///
+ /// Kernel for the inverse gamma highlight pass.
+ ///
+ [AutoConstructor]
+ internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader
+ {
+ public readonly ReadWriteTexture2D source;
+ public readonly IReadWriteTexture2D target;
+
+ ///
+ public void Execute()
+ {
+ int width = source.Width;
+
+ for (int i = 0; i < width; i++)
+ {
+ Float4 v = source[i, ThreadIds.X];
+
+ v = Hlsl.Clamp(v, 0, float.MaxValue);
+ v.XYZ = Hlsl.Pow(v.XYZ, 1 / 3f);
+
+ target[i, ThreadIds.X] = v;
+ }
+ }
}
}
}
diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs
index d628edad..159e1965 100644
--- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs
+++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs
@@ -1,13 +1,16 @@
-using SixLabors.ImageSharp;
+using System.Runtime.CompilerServices;
+using Microsoft.Toolkit.Diagnostics;
+using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
+using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors
{
///
- /// Defines Gaussian blur by a (Sigma, Radius) pair
+ /// Defines Gaussian blur by a (Sigma, Radius) pair.
///
- public sealed class HlslGaussianBlurProcessor : IImageProcessor
+ public sealed partial class HlslGaussianBlurProcessor : IImageProcessor
{
///
/// The default value for .
@@ -15,34 +18,57 @@ namespace ComputeSharp.BokehBlur.Processors
public const float DefaultSigma = 3f;
///
- /// Initializes a new instance of the class
+ /// Initializes a new instance of the class.
///
- public HlslGaussianBlurProcessor() : this(DefaultSigma, 9) { }
-
- ///
- /// Initializes a new instance of the class
- ///
- /// The radius value representing the size of the area to sample
- public HlslGaussianBlurProcessor(int radius) : this(radius / 3F, radius) { }
-
- ///
- /// Initializes a new instance of the class
- ///
- /// The sigma value representing the weight of the blur
- /// The radius value representing the size of the area to sample (this should be at least twice the sigma value)
- public HlslGaussianBlurProcessor(float sigma, int radius)
+ public HlslGaussianBlurProcessor()
+ : this(Gpu.Default, DefaultSigma, 9)
{
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The radius value representing the size of the area to sample.
+ public HlslGaussianBlurProcessor(int radius)
+ : this(Gpu.Default, radius / 3F, radius)
+ {
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The associated with the current instance.
+ /// The radius value representing the size of the area to sample.
+ public HlslGaussianBlurProcessor(GraphicsDevice device, int radius)
+ : this(device, radius / 3F, radius)
+ {
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The associated with the current instance.
+ /// The sigma value representing the weight of the blur.
+ /// The radius value representing the size of the area to sample (this should be at least twice the sigma value)
+ public HlslGaussianBlurProcessor(GraphicsDevice device, float sigma, int radius)
+ {
+ GraphicsDevice = device;
Sigma = sigma;
Radius = radius;
}
///
- /// Gets the sigma value representing the weight of the blur
+ /// The instance in use.
+ ///
+ private readonly GraphicsDevice GraphicsDevice;
+
+ ///
+ /// Gets the sigma value representing the weight of the blur.
///
public float Sigma { get; }
///
- /// Gets the radius defining the size of the area to sample
+ /// Gets the radius defining the size of the area to sample.
///
public int Radius { get; }
@@ -50,7 +76,14 @@ namespace ComputeSharp.BokehBlur.Processors
public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle)
where TPixel : unmanaged, IPixel
{
- return new HlslGaussianBlurProcessor(this, configuration, source, sourceRectangle);
+ if (typeof(TPixel) != typeof(ImageSharpRgba32))
+ {
+ ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format");
+ }
+
+ var processor = new Implementation(this, configuration, Unsafe.As>(source), sourceRectangle);
+
+ return Unsafe.As>(processor);
}
}
}
diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs
index 1cd556b2..e3b5a7c4 100644
--- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs
+++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs
@@ -1,237 +1,178 @@
using System;
-using System.Buffers;
using System.Numerics;
using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using Microsoft.Toolkit.Diagnostics;
using SixLabors.ImageSharp;
-using SixLabors.ImageSharp.Advanced;
-using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
+using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors
{
- ///
- /// Applies Gaussian blur processing to an image.
- ///
- /// The pixel format.
- internal class HlslGaussianBlurProcessor : ImageProcessor
- where TPixel : unmanaged, IPixel
+ ///
+ public sealed partial class HlslGaussianBlurProcessor
{
///
- /// The 1D kernel to apply
+ /// Applies Gaussian blur processing to an image.
///
- private readonly float[] Kernel;
-
- ///
- /// Initializes a new instance of the class
- ///
- /// The defining the processor parameters
- /// The configuration which allows altering default behaviour or extending the library
- /// The source for the current processor instance
- /// The source area to process for the current processor instance
- public HlslGaussianBlurProcessor(HlslGaussianBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle)
- : base(configuration, source, sourceRectangle)
+ internal sealed partial class Implementation : ImageProcessor
{
- int kernelSize = definition.Radius * 2 + 1;
- Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma);
- }
+ ///
+ /// The instance in use.
+ ///
+ private readonly GraphicsDevice GraphicsDevice;
- ///
- /// Creates a 1 dimensional Gaussian kernel using the Gaussian G(x) function
- ///
- private static float[] CreateGaussianBlurKernel(int size, float weight)
- {
- float[] kernel = new float[size];
- ref float rKernel = ref kernel[0];
+ ///
+ /// The 1D kernel to apply.
+ ///
+ private readonly float[] Kernel;
- float sum = 0F;
- float midpoint = (size - 1) / 2F;
-
- for (int i = 0; i < size; i++)
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The defining the processor parameters.
+ /// The configuration which allows altering default behaviour or extending the library.
+ /// The source for the current processor instance.
+ /// The source area to process for the current processor instance.
+ public Implementation(HlslGaussianBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle)
+ : base(configuration, source, sourceRectangle)
{
- float x = i - midpoint;
- float gx = Gaussian(x, weight);
- sum += gx;
- Unsafe.Add(ref rKernel, i) = gx;
+ int kernelSize = definition.Radius * 2 + 1;
+
+ GraphicsDevice = definition.GraphicsDevice;
+ Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma);
}
- // Normalize kernel so that the sum of all weights equals 1
- for (int i = 0; i < size; i++)
+ ///
+ /// Creates a 1 dimensional Gaussian kernel using the Gaussian G(x) function.
+ ///
+ private static float[] CreateGaussianBlurKernel(int size, float weight)
{
- Unsafe.Add(ref rKernel, i) /= sum;
- }
+ float[] kernel = new float[size];
+ ref float rKernel = ref kernel[0];
- return kernel;
- }
+ float sum = 0F;
+ float midpoint = (size - 1) / 2F;
- ///
- /// Implementation of 1D Gaussian G(x) function
- ///
- /// The x provided to G(x)
- /// The spread of the blur
- /// The Gaussian G(x)
- private static float Gaussian(float x, float sigma)
- {
- const float Numerator = 1.0f;
- float denominator = MathF.Sqrt(2 * MathF.PI) * sigma;
-
- float exponentNumerator = -x * x;
- float exponentDenominator = 2 * sigma * sigma;
-
- float left = Numerator / denominator;
- float right = MathF.Exp(exponentNumerator / exponentDenominator);
-
- return left * right;
- }
-
- ///
- protected override void OnFrameApply(ImageFrame source)
- {
- foreach (Memory memory in source.GetPixelMemoryGroup())
- {
- Span spanTPixel = memory.Span;
-
- using IMemoryOwner group4 = Configuration.MemoryAllocator.Allocate(spanTPixel.Length);
-
- Span spanVector4 = group4.Memory.Span;
-
- PixelOperations.Instance.ToVector4(Configuration, spanTPixel, spanVector4);
-
- using ReadWriteBuffer sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(spanVector4);
- using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size);
- using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel);
-
- ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer);
- ApplyHorizontalConvolution(firstPassBuffer, sourceBuffer, kernelBuffer);
-
- sourceBuffer.GetData(spanVector4);
-
- PixelOperations.Instance.FromVector4Destructive(Configuration, spanVector4, spanTPixel);
- }
- }
-
- ///
- /// Performs a vertical 1D complex convolution with the specified parameters
- ///
- /// The source to read data from
- /// The target to write the results to
- /// The with the values for the current complex kernel
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void ApplyVerticalConvolution(
- ReadWriteBuffer source,
- ReadWriteBuffer target,
- ReadOnlyBuffer kernel)
- {
- 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.Size,
- source = source,
- target = target,
- kernel = 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++)
+ for (int i = 0; i < size; 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;
+ float x = i - midpoint;
+ float gx = Gaussian(x, weight);
+ sum += gx;
+ Unsafe.Add(ref rKernel, i) = gx;
}
- int offsetXY = ids.Y * width + ids.X;
- target[offsetXY] = result;
- }
- }
-
- ///
- /// Performs an horizontal 1D complex convolution with the specified parameters
- ///
- /// The source to read data from
- /// The target to write the results to
- /// The with the values for the current complex kernel
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void ApplyHorizontalConvolution(
- ReadWriteBuffer source,
- ReadWriteBuffer target,
- ReadOnlyBuffer kernel)
- {
- 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.Size,
- source = source,
- target = target,
- kernel = 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++)
+ // Normalize kernel so that the sum of all weights equals 1
+ for (int i = 0; i < size; i++)
{
- int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
- offsetXY = offsetY * width + offsetX;
- Vector4 color = source[offsetXY];
-
- result += kernel[i] * color;
+ Unsafe.Add(ref rKernel, i) /= sum;
}
- offsetXY = ids.Y * width + ids.X;
- target[offsetXY] = result;
+ return kernel;
+ }
+
+ ///
+ /// Implementation of 1D Gaussian G(x) function.
+ ///
+ /// The x provided to G(x)
+ /// The spread of the blur.
+ /// The Gaussian G(x)
+ private static float Gaussian(float x, float sigma)
+ {
+ const float Numerator = 1.0f;
+ float denominator = MathF.Sqrt(2 * MathF.PI) * sigma;
+
+ float exponentNumerator = -x * x;
+ float exponentDenominator = 2 * sigma * sigma;
+
+ float left = Numerator / denominator;
+ float right = MathF.Exp(exponentNumerator / exponentDenominator);
+
+ return left * right;
+ }
+
+ ///
+ protected override void OnFrameApply(ImageFrame source)
+ {
+ if (!source.TryGetSinglePixelSpan(out Span pixelSpan))
+ {
+ ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory");
+ }
+
+ Span span = MemoryMarshal.Cast(pixelSpan);
+
+ using ReadWriteTexture2D sourceTexture = GraphicsDevice.AllocateReadWriteTexture2D(span, source.Width, source.Height);
+ using ReadWriteTexture2D firstPassTexture = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height);
+ using ReadOnlyBuffer kernelBuffer = GraphicsDevice.AllocateReadOnlyBuffer(Kernel);
+
+ GraphicsDevice.For(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer));
+ GraphicsDevice.For(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer));
+
+ sourceTexture.CopyTo(span);
+ }
+
+ ///
+ /// Kernel for the vertical convolution pass.
+ ///
+ [AutoConstructor]
+ internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
+ {
+ public readonly IReadWriteTexture2D source;
+ public readonly IReadWriteTexture2D target;
+ public readonly ReadOnlyBuffer kernel;
+
+ ///
+ public void Execute()
+ {
+ Vector4 result = Vector4.Zero;
+ int maxY = source.Height - 1;
+ int maxX = source.Width - 1;
+ int kernelLength = kernel.Length;
+ int radiusY = kernelLength >> 1;
+
+ for (int i = 0; i < kernelLength; i++)
+ {
+ int offsetY = Hlsl.Clamp(ThreadIds.Y + i - radiusY, 0, maxY);
+ int offsetX = Hlsl.Clamp(ThreadIds.X, 0, maxX);
+ Vector4 color = source[offsetX, offsetY];
+
+ result += kernel[i] * color;
+ }
+
+ target[ThreadIds.XY] = result;
+ }
+ }
+
+ ///
+ /// Kernel for the horizontal convolution pass.
+ ///
+ [AutoConstructor]
+ internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader
+ {
+ public readonly IReadWriteTexture2D source;
+ public readonly IReadWriteTexture2D target;
+ public readonly ReadOnlyBuffer kernel;
+
+ ///