diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml
index 1d2b6b8f..52e944dc 100644
--- a/.github/workflows/dotnet.yml
+++ b/.github/workflows/dotnet.yml
@@ -2,6 +2,10 @@ name: .NET
on: [push, pull_request]
+env:
+ EXCLUDE_RUN_ID_FROM_PACKAGE: false
+ EXCLUDE_SUFFIX_FROM_VERSION: false
+
jobs:
# Build the whole ComputeSharp solution, in Debug
@@ -44,8 +48,49 @@ jobs:
run: msbuild -t:restore,build /p:Configuration=Release /p:Platform=x64
shell: cmd
- # Run all the unit tests referencing the ComputeSharp project directly
- run-tests:
+ # Build the .msbuildproj projects and the UWP/WinUI projects to generate all the NuGet packages.
+ # This workflow also uploads the resulting packages as artifacts.
+ build-packages:
+ runs-on: windows-2022
+ steps:
+ - name: Git checkout
+ uses: actions/checkout@v2
+ - name: Add msbuild to PATH
+ uses: microsoft/setup-msbuild@v1.0.3
+ - name: Setup .NET 6 SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: 6.0.x
+ - name: Build ComputeSharp.Core package
+ run: dotnet build src\ComputeSharp.Core.Package\ComputeSharp.Core.Package.msbuildproj -c Release
+ shell: cmd
+ - name: Build ComputeSharp package
+ run: dotnet build src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj -c Release
+ shell: cmd
+ - name: Build ComputeSharp.Dynamic package
+ run: dotnet build src\ComputeSharp.Dynamic.Package\ComputeSharp.Dynamic.Package.msbuildproj -c Release
+ shell: cmd
+ - name: Build ComputeSharp.D2D1 package
+ run: dotnet build src\ComputeSharp.D2D1.Package\ComputeSharp.D2D1.Package.msbuildproj -c Release
+ shell: cmd
+ - name: Build ComputeSharp.Uwp package
+ run: msbuild src\ComputeSharp.Uwp\ComputeSharp.Uwp.csproj -t:restore,build,pack /p:Configuration=Release
+ shell: cmd
+ - name: Restore ComputeSharp.WinUI project
+ run: msbuild src\ComputeSharp.WinUI\ComputeSharp.WinUI.csproj -t:restore /p:Configuration=Release
+ shell: cmd
+ - name: Build ComputeSharp.WinUI package
+ run: msbuild src\ComputeSharp.WinUI\ComputeSharp.WinUI.csproj -t:pack /p:Configuration=Release
+ shell: cmd # Packing needs to be done separately and with no previous build target for it to work correctly
+ - name: Upload package artifacts
+ uses: actions/upload-artifact@v2
+ with:
+ name: nuget_preview
+ path: artifacts\*.nupkg
+ if-no-files-found: error
+
+ # Run all the DX12 unit tests referencing the ComputeSharp project directly
+ run-dx12-tests:
if: success()
needs: [build-solution-debug, build-solution-release]
runs-on: windows-2022
@@ -91,10 +136,26 @@ jobs:
run: dotnet test tests\ComputeSharp.Tests.SourceGenerators\ComputeSharp.Tests.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:
+ # Run all the D2D1 unit tests (referencing ComputeSharp.D2D1)
+ run-d2d1-tests:
if: success()
- needs: [run-tests]
+ needs: [build-solution-debug, build-solution-release]
+ runs-on: windows-2022
+ steps:
+ - name: Git checkout
+ uses: actions/checkout@v2
+ - name: Setup .NET 6 SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: 6.0.x
+ - name: Run ComputeSharp.D2D1.Tests
+ run: dotnet test tests\ComputeSharp.D2D1.Tests\ComputeSharp.D2D1.Tests.csproj -c Release -v n -l "console;verbosity=detailed"
+ shell: cmd
+
+ # Run all the local samples to ensure they build and run with no errors
+ run-dx12-samples:
+ if: success()
+ needs: [build-solution-debug, build-solution-release]
runs-on: windows-2022
steps:
- name: Git checkout
@@ -156,42 +217,12 @@ jobs:
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:
+ # Download the NuGet packages generated in the previous job and use them
+ # to build and run the sample project referencing them. This is used as
+ # a test to ensure the NuGet packages work in a consuming project.
+ verify-packages:
if: success()
- needs: [build-solution-debug, build-solution-release]
- runs-on: windows-2022
- steps:
- - name: Git checkout
- uses: actions/checkout@v2
- - name: Setup .NET 6 SDK
- uses: actions/setup-dotnet@v1
- with:
- dotnet-version: 6.0.x
- - name: Build ComputeSharp package
- run: dotnet build src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj -c Release /p:ContinuousIntegrationBuild=True
- shell: cmd
- - name: Upload ComputeSharp package artifact
- uses: actions/upload-artifact@v2
- with:
- name: ComputeSharp.nupkg
- path: src\ComputeSharp.Package\bin\Release\*.nupkg
- - name: Build ComputeSharp.Dynamic package
- run: dotnet build src\ComputeSharp.Dynamic.Package\ComputeSharp.Dynamic.Package.msbuildproj -c Release /p:ContinuousIntegrationBuild=True
- shell: cmd
- - name: Upload ComputeSharp.Dynamic package artifact
- uses: actions/upload-artifact@v2
- with:
- name: ComputeSharp.Dynamic.nupkg
- path: src\ComputeSharp.Dynamic.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]
+ needs: [build-packages]
runs-on: windows-2022
steps:
- name: Git checkout
@@ -201,18 +232,13 @@ jobs:
with:
dotnet-version: 6.0.x
- name: Create local NuGet feed
- run: mkdir src\ComputeSharp.Package\bin\Release
+ run: mkdir artifacts
shell: cmd
- - name: Download ComputeSharp package artifact
+ - name: Download package artifacts
uses: actions/download-artifact@v2
with:
- name: ComputeSharp.nupkg
- path: src\ComputeSharp.Package\bin\Release\ComputeSharp.nupkg
- - name: Download ComputeSharp.Dynamic package artifact
- uses: actions/download-artifact@v2
- with:
- name: ComputeSharp.Dynamic.nupkg
- path: src\ComputeSharp.Dynamic.Package\bin\Release\ComputeSharp.Dynamic.nupkg
+ name: nuget_preview
+ path: artifacts
- name: Build ComputeSharp.Sample.NuGet (.NET 6)
run: dotnet build samples\ComputeSharp.Sample.NuGet\ComputeSharp.Sample.NuGet.csproj -c Release -f net6.0
shell: cmd
@@ -237,7 +263,7 @@ jobs:
# regardless of whether the app is shipping with R2R, self-contained, etc.
verify-package-native-libs:
if: success()
- needs: [verify-package]
+ needs: [build-packages]
runs-on: windows-2022
steps:
- name: Git checkout
@@ -248,55 +274,4 @@ jobs:
dotnet-version: 6.0.x
- name: Run ComputeSharp.Tests.NativeLibrariesResolver
run: dotnet test tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj -v n -l "console;verbosity=detailed"
- shell: cmd
-
- # Build the WinUI project again to generate a NuGet package from it.
- # This workflow also uploads the resulting package as an artifact.
- build-package-winui:
- if: success()
- needs: [verify-package]
- runs-on: windows-2022
- steps:
- - name: Git checkout
- uses: actions/checkout@v2
- - name: Add msbuild to PATH
- uses: microsoft/setup-msbuild@v1.0.3
- - name: Setup .NET SDK
- uses: actions/setup-dotnet@v1
- with:
- dotnet-version: 6.0.x
- - name: Build
- run: msbuild src\ComputeSharp.WinUI\ComputeSharp.WinUI.csproj -t:restore /p:Configuration=Release /p:ContinuousIntegrationBuild=True
- shell: cmd
- - name: Build
- run: msbuild src\ComputeSharp.WinUI\ComputeSharp.WinUI.csproj -t:pack /p:Configuration=Release /p:ContinuousIntegrationBuild=True
- shell: cmd # Packing needs to be done separately and with no previous build target for it to work correctly
- - name: Upload package artifact
- uses: actions/upload-artifact@v2
- with:
- name: ComputeSharp.WinUI.nupkg
- path: src\ComputeSharp.WinUI\bin\Release\*.nupkg
-
- # Build the UWP project again to generate a NuGet package from it.
- # This workflow also uploads the resulting package as an artifact, like the WinUI one.
- build-package-uwp:
- if: success()
- needs: [verify-package]
- runs-on: windows-2022
- steps:
- - name: Git checkout
- uses: actions/checkout@v2
- - name: Add msbuild to PATH
- uses: microsoft/setup-msbuild@v1.0.3
- - name: Setup .NET SDK
- uses: actions/setup-dotnet@v1
- with:
- dotnet-version: 6.0.x
- - name: Build
- run: msbuild src\ComputeSharp.Uwp\ComputeSharp.Uwp.csproj -t:restore,build,pack /p:Configuration=Release /p:ContinuousIntegrationBuild=True
- shell: cmd
- - name: Upload package artifact
- uses: actions/upload-artifact@v2
- with:
- name: ComputeSharp.Uwp.nupkg
- path: src\ComputeSharp.Uwp\bin\Release\*.nupkg
\ No newline at end of file
+ shell: cmd
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index b444c010..a49e5f52 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,6 +27,10 @@ bld/
[Oo]bj/
[Ll]og/
+# Include the bundled libraries
+!**/Libraries/x64/
+!**/Libraries/arm64/
+
# Debug view types
!**/Resources/Debug
diff --git a/ComputeSharp.sln b/ComputeSharp.sln
index fe3ef9c6..b8413535 100644
--- a/ComputeSharp.sln
+++ b/ComputeSharp.sln
@@ -30,9 +30,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SourceGenerato
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{FB17EF84-9208-47AC-921F-680CB1DAD8BA}"
ProjectSection(SolutionItems) = preProject
+ src\ComputeSharp.Core.Package\ComputeSharp.Core.Package.msbuildproj = src\ComputeSharp.Core.Package\ComputeSharp.Core.Package.msbuildproj
+ src\ComputeSharp.D2D1.Package\ComputeSharp.D2D1.Package.msbuildproj = src\ComputeSharp.D2D1.Package\ComputeSharp.D2D1.Package.msbuildproj
src\ComputeSharp.Dynamic.Package\ComputeSharp.Dynamic.Package.msbuildproj = src\ComputeSharp.Dynamic.Package\ComputeSharp.Dynamic.Package.msbuildproj
src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj = src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj
- src\ComputeSharp.Package\icon.png = src\ComputeSharp.Package\icon.png
+ src\ComputeSharp.Core.Package\icon.png = src\ComputeSharp.Core.Package\icon.png
+ src\ComputeSharp.Core.Package\icon_highres.png = src\ComputeSharp.Core.Package\icon_highres.png
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Sample", "samples\ComputeSharp.Sample\ComputeSharp.Sample.csproj", "{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}"
@@ -75,6 +78,26 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Dynamic", "src
EndProject
Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "TerraFX.Interop.Windows.Dynamic", "src\TerraFX.Interop.Windows.Dynamic\TerraFX.Interop.Windows.Dynamic.shproj", "{158F984D-CD96-4062-BD02-2268946031A0}"
EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1", "src\ComputeSharp.D2D1\ComputeSharp.D2D1.csproj", "{4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}"
+EndProject
+Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "TerraFX.Interop.Windows.D2D1", "src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.shproj", "{9DA1DA9F-F8B2-4B25-BE80-C21F773029E3}"
+EndProject
+Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.D2D1.NetStandard", "src\ComputeSharp.D2D1.NetStandard\ComputeSharp.D2D1.NetStandard.shproj", "{2608EB41-F98B-4BE5-9F4D-68FED6115088}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Core", "src\ComputeSharp.Core\ComputeSharp.Core.csproj", "{764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}"
+EndProject
+Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.Core.NetStandard", "src\ComputeSharp.Core.NetStandard\ComputeSharp.Core.NetStandard.shproj", "{3ACACF03-6B20-40BA-B8EC-11AC1624D2C9}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Core.SourceGenerators", "src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj", "{BFB003D1-788B-48DE-8065-39479C162CB0}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1.SourceGenerators", "src\ComputeSharp.D2D1.SourceGenerators\ComputeSharp.D2D1.SourceGenerators.csproj", "{E44053BD-A761-47FB-AA78-087A599672EA}"
+EndProject
+Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.SourceGeneration", "src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.shproj", "{51D5A422-D3A5-4C4D-8A6D-A048940BF279}"
+EndProject
+Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.SourceGeneration.Hlsl", "src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.shproj", "{9AC496A3-BBF0-4C8F-A50D-A20BF01C5E05}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1.Tests", "tests\ComputeSharp.D2D1.Tests\ComputeSharp.D2D1.Tests.csproj", "{209C95A3-FA53-431B-B688-3299CA6C29D2}"
+EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
samples\ComputeSharp.SwapChain.Core.Shared\ComputeSharp.SwapChain.Core.Shared.projitems*{0071701e-b9c5-4098-be5f-ef556c4553c6}*SharedItemsImports = 5
@@ -82,18 +105,36 @@ Global
samples\ComputeSharp.SwapChain.Shaders.Shared\ComputeSharp.SwapChain.Shaders.Shared.projitems*{0800bd51-499d-44c2-9417-fd1f7fdfe9c4}*SharedItemsImports = 13
src\ComputeSharp.UI\ComputeSharp.UI.projitems*{0c82ede1-5b8a-4df3-87da-700b29d5e265}*SharedItemsImports = 13
src\TerraFX.Interop.Windows.Dynamic\TerraFX.Interop.Windows.Dynamic.projitems*{158f984d-cd96-4062-bd02-2268946031a0}*SharedItemsImports = 13
+ src\ComputeSharp.D2D1.NetStandard\ComputeSharp.D2D1.NetStandard.projitems*{2608eb41-f98b-4be5-9f4d-68fed6115088}*SharedItemsImports = 13
src\ComputeSharp.NetStandard\ComputeSharp.NetStandard.projitems*{314eb353-e7e3-4146-8111-685cc83ec1de}*SharedItemsImports = 5
src\TerraFX.Interop.Windows\TerraFX.Interop.Windows.projitems*{314eb353-e7e3-4146-8111-685cc83ec1de}*SharedItemsImports = 5
+ src\ComputeSharp.Core.NetStandard\ComputeSharp.Core.NetStandard.projitems*{3acacf03-6b20-40ba-b8ec-11ac1624d2c9}*SharedItemsImports = 13
+ src\ComputeSharp.D2D1.NetStandard\ComputeSharp.D2D1.NetStandard.projitems*{4d7d9ba8-a821-4b1c-9ee2-cbcf5849906e}*SharedItemsImports = 5
+ src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems*{4d7d9ba8-a821-4b1c-9ee2-cbcf5849906e}*SharedItemsImports = 5
src\TerraFX.Interop.Windows\TerraFX.Interop.Windows.projitems*{514ff00e-bbf0-4d55-a47c-eeeb6208adce}*SharedItemsImports = 13
+ src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{51d5a422-d3a5-4c4d-8a6d-a048940bf279}*SharedItemsImports = 13
samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{7048deea-0a6f-46a0-b951-b682a8f1cb75}*SharedItemsImports = 5
samples\ComputeSharp.SwapChain.Core.Shared\ComputeSharp.SwapChain.Core.Shared.projitems*{751bb05b-563d-4b3a-94c6-15e2d79d35ea}*SharedItemsImports = 13
+ src\ComputeSharp.Core.NetStandard\ComputeSharp.Core.NetStandard.projitems*{764bc0f5-0c5e-49ad-abaa-e3874c0f3286}*SharedItemsImports = 5
src\TerraFX.Interop.Windows.Dynamic\TerraFX.Interop.Windows.Dynamic.projitems*{76c66257-fdaa-47ab-85e7-ef757eab10c0}*SharedItemsImports = 5
samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{8cefc324-ca6c-4845-9ad9-70b92bd87057}*SharedItemsImports = 13
+ src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{9ac496a3-bbf0-4c8f-a50d-a20bf01c5e05}*SharedItemsImports = 13
+ src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems*{9da1da9f-f8b2-4b25-be80-c21f773029e3}*SharedItemsImports = 13
src\ComputeSharp.NetStandard\ComputeSharp.NetStandard.projitems*{a5997814-d8d2-4541-87ac-c3e53caa67c0}*SharedItemsImports = 13
src\ComputeSharp.UI\ComputeSharp.UI.projitems*{afaafdc9-be42-45d4-8c79-0ee8c8edbf52}*SharedItemsImports = 5
+ src\ComputeSharp.Core.NetStandard\ComputeSharp.Core.NetStandard.projitems*{bfb003d1-788b-48de-8065-39479c162cb0}*SharedItemsImports = 5
+ src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{bfb003d1-788b-48de-8065-39479c162cb0}*SharedItemsImports = 5
+ src\ComputeSharp.Core.NetStandard\ComputeSharp.Core.NetStandard.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5
+ src\ComputeSharp.D2D1.NetStandard\ComputeSharp.D2D1.NetStandard.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5
+ src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5
+ src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5
+ src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5
samples\ComputeSharp.SwapChain.Shaders.Shared\ComputeSharp.SwapChain.Shaders.Shared.projitems*{e7c9247d-016b-4819-af9f-0e9b3591e04b}*SharedItemsImports = 5
samples\ComputeSharp.SwapChain.Shaders.Shared\ComputeSharp.SwapChain.Shaders.Shared.projitems*{e91f4d24-922a-4921-a8d7-9c45a143c45d}*SharedItemsImports = 5
+ src\ComputeSharp.Core.NetStandard\ComputeSharp.Core.NetStandard.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5
src\ComputeSharp.NetStandard\ComputeSharp.NetStandard.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5
+ src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5
+ src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5
src\TerraFX.Interop.Windows.Dynamic\TerraFX.Interop.Windows.Dynamic.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5
src\TerraFX.Interop.Windows\TerraFX.Interop.Windows.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5
src\ComputeSharp.UI\ComputeSharp.UI.projitems*{fa18ba9f-76bf-4de0-8d24-02fc7657e6cb}*SharedItemsImports = 5
@@ -337,6 +378,66 @@ Global
{76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Release|ARM64.Build.0 = Release|ARM64
{76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Release|x64.ActiveCfg = Release|x64
{76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Release|x64.Build.0 = Release|x64
+ {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|ARM64.ActiveCfg = Debug|Any CPU
+ {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|ARM64.Build.0 = Debug|Any CPU
+ {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|x64.Build.0 = Debug|Any CPU
+ {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|Any CPU.Build.0 = Release|Any CPU
+ {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|ARM64.ActiveCfg = Release|Any CPU
+ {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|ARM64.Build.0 = Release|Any CPU
+ {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|x64.ActiveCfg = Release|Any CPU
+ {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|x64.Build.0 = Release|Any CPU
+ {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|ARM64.ActiveCfg = Debug|Any CPU
+ {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|ARM64.Build.0 = Debug|Any CPU
+ {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|x64.Build.0 = Debug|Any CPU
+ {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|Any CPU.Build.0 = Release|Any CPU
+ {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|ARM64.ActiveCfg = Release|Any CPU
+ {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|ARM64.Build.0 = Release|Any CPU
+ {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|x64.ActiveCfg = Release|Any CPU
+ {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|x64.Build.0 = Release|Any CPU
+ {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|ARM64.ActiveCfg = Debug|Any CPU
+ {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|ARM64.Build.0 = Debug|Any CPU
+ {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|x64.Build.0 = Debug|Any CPU
+ {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|Any CPU.Build.0 = Release|Any CPU
+ {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|ARM64.ActiveCfg = Release|Any CPU
+ {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|ARM64.Build.0 = Release|Any CPU
+ {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|x64.ActiveCfg = Release|Any CPU
+ {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|x64.Build.0 = Release|Any CPU
+ {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|ARM64.ActiveCfg = Debug|Any CPU
+ {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|ARM64.Build.0 = Debug|Any CPU
+ {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|x64.Build.0 = Debug|Any CPU
+ {E44053BD-A761-47FB-AA78-087A599672EA}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {E44053BD-A761-47FB-AA78-087A599672EA}.Release|Any CPU.Build.0 = Release|Any CPU
+ {E44053BD-A761-47FB-AA78-087A599672EA}.Release|ARM64.ActiveCfg = Release|Any CPU
+ {E44053BD-A761-47FB-AA78-087A599672EA}.Release|ARM64.Build.0 = Release|Any CPU
+ {E44053BD-A761-47FB-AA78-087A599672EA}.Release|x64.ActiveCfg = Release|Any CPU
+ {E44053BD-A761-47FB-AA78-087A599672EA}.Release|x64.Build.0 = Release|Any CPU
+ {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|ARM64.ActiveCfg = Debug|Any CPU
+ {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|ARM64.Build.0 = Debug|Any CPU
+ {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|x64.Build.0 = Debug|Any CPU
+ {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|Any CPU.Build.0 = Release|Any CPU
+ {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|ARM64.ActiveCfg = Release|Any CPU
+ {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|ARM64.Build.0 = Release|Any CPU
+ {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|x64.ActiveCfg = Release|Any CPU
+ {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -361,6 +462,10 @@ Global
{751BB05B-563D-4B3A-94C6-15E2D79D35EA} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
{4A8FCE22-851C-442A-8BC9-3EC3FD00B637} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
{158F984D-CD96-4062-BD02-2268946031A0} = {8DCE343F-BA78-4FE1-B562-B57C603A8BAA}
+ {9DA1DA9F-F8B2-4B25-BE80-C21F773029E3} = {8DCE343F-BA78-4FE1-B562-B57C603A8BAA}
+ {2608EB41-F98B-4BE5-9F4D-68FED6115088} = {8DCE343F-BA78-4FE1-B562-B57C603A8BAA}
+ {3ACACF03-6B20-40BA-B8EC-11AC1624D2C9} = {8DCE343F-BA78-4FE1-B562-B57C603A8BAA}
+ {209C95A3-FA53-431B-B688-3299CA6C29D2} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC}
diff --git a/Directory.Build.props b/Directory.Build.props
index c507f133..86d987a3 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -7,9 +7,26 @@
$(NoWarn);MSB3270
+
- 2.0.0.0
- 2.0.0
+ $(MSBuildThisFileDirectory)artifacts/
+
+
+
+
+ 2.0.0
+
+
+
+ $(ComputeSharpPackageVersion).0
+ $(ComputeSharpPackageVersion)
+ alpha
+ pr
+ true
https://github.com/Sergio0694/ComputeSharp/
git
true
diff --git a/Directory.Build.targets b/Directory.Build.targets
new file mode 100644
index 00000000..34a9cdfe
--- /dev/null
+++ b/Directory.Build.targets
@@ -0,0 +1,32 @@
+
+
+
+
+
+
+ $(VersionPrefix)-$(VersionSuffix)
+ $(VersionPrefix)
+
+
+
+
+ $(Version).$(GITHUB_RUN_ID)
+
+
+
+
+ $(Version)
+
+
\ No newline at end of file
diff --git a/README.md b/README.md
index 7458013b..68dd1af3 100644
--- a/README.md
+++ b/README.md
@@ -33,6 +33,7 @@ The sample app is available in the Microsoft Store, showcasing several pixel sha
- [Inspecting shaders](#inspecting-shaders)
- [DirectX interop](#directx-interop)
- [Precompiled shaders](#precompiled-shaders)
+ - [D2D1 support](#d2d1-support)
- [Requirements](#requirements)
- [F# support](#f-support)
- [Sponsors](#sponsors)
@@ -46,6 +47,7 @@ The sample app is available in the Microsoft Store, showcasing several pixel sha
| **ComputeSharp.Dynamic** | An extension for **ComputeSharp**, enabling dynamic shader compilation at runtime and shader metaprogramming | [](https://www.nuget.org/packages/ComputeSharp.Dynamic/) |
| **ComputeSharp.Uwp** | A UWP library (targeting .NET Standard 2.0) with controls to render DX12 shaders powered by **ComputeSharp** | [](https://www.nuget.org/packages/ComputeSharp.Uwp/) |
| **ComputeSharp.WinUI** | A WinUI 3 library (targeting .NET 6) with controls to render DX12 shaders powered by **ComputeSharp** | [](https://www.nuget.org/packages/ComputeSharp.WinUI/) |
+| **ComputeSharp.D2D1** | A library to write D2D1 pixel shaders entirely with C# code, and to easily register and create ID2D1Effect-s from them | [](https://www.nuget.org/packages/ComputeSharp.D2D1/) |
# Installing from NuGet
@@ -378,6 +380,41 @@ public readonly partial struct MultiplyByTwo : IPixelShader
The values in the `[EmbeddedBytecode]` attribute map to the [`[numthreads]` HLSL attribute](https://docs.microsoft.com/windows/win32/direct3dhlsl/sm5-attributes-numthreads) for the shader entry point. Make sure to use the same values when dispatching the shader at runtime (either using the `GraphicsDevice.For` overload with explicit parameters for the tread numbers, or by relying on `GraphicsDevice.ForEach` to always use `(8, 8, 1)` for thread numbers, as it will be dispatching shaders on a 2D texture).
+## D2D1 support
+
+**ComputeSharp** also offers [D2D1 support](https://docs.microsoft.com/en-us/windows/win32/direct2d/d2d1-namespace), through the dedicated package. This shares the same base APIs (primitives, intrinsics, etc.) from **ComputeSharp.Core**, but then adds D2D1 specific support, instead of using DX12 like the main package. This means it offers the ability to implement D2D1 pixel shaders, and to then either load them manually, or to register a D2D1 effect using them, optionally with a custom draw transform as well.
+
+For instance, here's a simple D2D1 pixel shader:
+
+```csharp
+[D2DInputCount(1)]
+[D2DInputSimple(0)]
+[D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)]
+[AutoConstructor]
+public partial struct DifferenceEffect : ID2D1PixelShader
+{
+ public float amount;
+
+ ///
+ public float4 Execute()
+ {
+ float4 color = D2D.GetInput(0);
+ float3 rgb = Hlsl.Saturate(this.amount - color.RGB);
+
+ return new(rgb, 1);
+ }
+}
+```
+
+This can then be used directly to get the shader bytecode and the buffer, like so:
+
+```csharp
+ReadOnlyMemory bytecode = D2D1InteropServices.LoadShaderBytecode();
+ReadOnlyMemory buffer = D2D1InteropServices.GetPixelShaderConstantBuffer(new DifferenceEffect(1));
+```
+
+There are also several other APIs to easily register a pixel shader effect from a shader written using **ComputeSharp.D2D1**, and to then create an `ID2D1Effect` instance from it (from the `D2D1PixelShaderEffect` type), as well as for reflecting into a shader and extract information about it, such as its HLSL source code (from the `D2D1ReflectionServices` type).
+
# Requirements
Building and running **ComputeSharp** from the .NET solution filter has the following prerequisites:
diff --git a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj
index 1ea30a7a..002e1078 100644
--- a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj
+++ b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj
@@ -23,12 +23,11 @@
+
+
-
+
\ No newline at end of file
diff --git a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj
index 779450a0..59564f49 100644
--- a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj
+++ b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj
@@ -15,12 +15,11 @@
+
+
-
+
diff --git a/samples/ComputeSharp.Sample.FSharp.Shaders/ComputeSharp.Sample.FSharp.Shaders.csproj b/samples/ComputeSharp.Sample.FSharp.Shaders/ComputeSharp.Sample.FSharp.Shaders.csproj
index 33165757..6ccc804e 100644
--- a/samples/ComputeSharp.Sample.FSharp.Shaders/ComputeSharp.Sample.FSharp.Shaders.csproj
+++ b/samples/ComputeSharp.Sample.FSharp.Shaders/ComputeSharp.Sample.FSharp.Shaders.csproj
@@ -5,12 +5,11 @@
+
+
-
+
diff --git a/samples/ComputeSharp.Sample.FSharp/ComputeSharp.Sample.FSharp.fsproj b/samples/ComputeSharp.Sample.FSharp/ComputeSharp.Sample.FSharp.fsproj
index 0c746598..f559a565 100644
--- a/samples/ComputeSharp.Sample.FSharp/ComputeSharp.Sample.FSharp.fsproj
+++ b/samples/ComputeSharp.Sample.FSharp/ComputeSharp.Sample.FSharp.fsproj
@@ -15,12 +15,11 @@
+
+
-
+
diff --git a/samples/ComputeSharp.Sample.NuGet/ComputeSharp.Sample.NuGet.csproj b/samples/ComputeSharp.Sample.NuGet/ComputeSharp.Sample.NuGet.csproj
index dd2769fd..f75aab80 100644
--- a/samples/ComputeSharp.Sample.NuGet/ComputeSharp.Sample.NuGet.csproj
+++ b/samples/ComputeSharp.Sample.NuGet/ComputeSharp.Sample.NuGet.csproj
@@ -7,8 +7,9 @@
-
-
+
+
+
diff --git a/samples/ComputeSharp.Sample.NuGet/nuget.config b/samples/ComputeSharp.Sample.NuGet/nuget.config
index c3f2b513..995d3a62 100644
--- a/samples/ComputeSharp.Sample.NuGet/nuget.config
+++ b/samples/ComputeSharp.Sample.NuGet/nuget.config
@@ -1,7 +1,8 @@
-
-
+
+
+
diff --git a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj b/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj
index 138428ab..b1c021b0 100644
--- a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj
+++ b/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj
@@ -7,12 +7,11 @@
+
+
-
+
diff --git a/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj b/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj
index 7470e9ad..a5be5595 100644
--- a/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj
+++ b/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj
@@ -230,6 +230,8 @@
+
+
diff --git a/samples/ComputeSharp.SwapChain.WinUI/ComputeSharp.SwapChain.WinUI.csproj b/samples/ComputeSharp.SwapChain.WinUI/ComputeSharp.SwapChain.WinUI.csproj
index f4dc10e2..f62c81b7 100644
--- a/samples/ComputeSharp.SwapChain.WinUI/ComputeSharp.SwapChain.WinUI.csproj
+++ b/samples/ComputeSharp.SwapChain.WinUI/ComputeSharp.SwapChain.WinUI.csproj
@@ -40,11 +40,9 @@
+
-
+
diff --git a/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj b/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj
index 7220b8f9..d6fcfddc 100644
--- a/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj
+++ b/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj
@@ -8,11 +8,10 @@
+
+
-
+
diff --git a/src/ComputeSharp.Core.NetStandard/ComputeSharp.Core.NetStandard.projitems b/src/ComputeSharp.Core.NetStandard/ComputeSharp.Core.NetStandard.projitems
new file mode 100644
index 00000000..22578e69
--- /dev/null
+++ b/src/ComputeSharp.Core.NetStandard/ComputeSharp.Core.NetStandard.projitems
@@ -0,0 +1,18 @@
+
+
+
+ $(MSBuildAllProjects);$(MSBuildThisFileFullPath)
+ true
+ 3acacf03-6b20-40ba-b8ec-11ac1624d2c9
+
+
+ ComputeSharp.Core.NetStandard
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/ComputeSharp.Core.NetStandard/ComputeSharp.Core.NetStandard.shproj b/src/ComputeSharp.Core.NetStandard/ComputeSharp.Core.NetStandard.shproj
new file mode 100644
index 00000000..9964b218
--- /dev/null
+++ b/src/ComputeSharp.Core.NetStandard/ComputeSharp.Core.NetStandard.shproj
@@ -0,0 +1,13 @@
+
+
+
+ 3acacf03-6b20-40ba-b8ec-11ac1624d2c9
+ 14.0
+
+
+
+
+
+
+
+
diff --git a/src/ComputeSharp.Core.NetStandard/System/InteropServices/MemoryMarshal.cs b/src/ComputeSharp.Core.NetStandard/System/InteropServices/MemoryMarshal.cs
new file mode 100644
index 00000000..86710490
--- /dev/null
+++ b/src/ComputeSharp.Core.NetStandard/System/InteropServices/MemoryMarshal.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Runtime.CompilerServices;
+
+namespace ComputeSharp.Core.NetStandard.System.Runtime.InteropServices;
+
+///
+/// A polyfill type that mirrors some methods from on .NET 6.
+///
+internal static class MemoryMarshal
+{
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ref T GetReference(Span span)
+ {
+ return ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(span);
+ }
+
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ref T GetReference(ReadOnlySpan span)
+ {
+ return ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(span);
+ }
+
+ ///
+ /// Creates a new from a given reference.
+ ///
+ /// The type of reference to wrap.
+ /// The target reference.
+ /// The length of the to create.
+ /// A new wrapping .
+ public static unsafe Span CreateSpan(ref T value, int length)
+ {
+ return new(Unsafe.AsPointer(ref value), length);
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/InterpolatedStringHandlerArgumentAttribute.cs b/src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/InterpolatedStringHandlerArgumentAttribute.cs
similarity index 100%
rename from src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/InterpolatedStringHandlerArgumentAttribute.cs
rename to src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/InterpolatedStringHandlerArgumentAttribute.cs
diff --git a/src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/InterpolatedStringHandlerAttribute.cs b/src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/InterpolatedStringHandlerAttribute.cs
similarity index 100%
rename from src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/InterpolatedStringHandlerAttribute.cs
rename to src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/InterpolatedStringHandlerAttribute.cs
diff --git a/src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/RuntimeHelpers.cs b/src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/RuntimeHelpers.cs
new file mode 100644
index 00000000..9d2046fc
--- /dev/null
+++ b/src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/RuntimeHelpers.cs
@@ -0,0 +1,18 @@
+using System;
+using System.Runtime.InteropServices;
+
+namespace ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices;
+
+///
+/// A polyfill type that mirrors some methods from on .NET 5.
+///
+internal static class RuntimeHelpers
+{
+ ///
+ /// Allocates some memory tied to the lifetime of a specific type.
+ ///
+ /// The type to associate the memory to.
+ /// The size in byte of the memory to allocate.
+ /// A pointer to the allocated memory.
+ public static IntPtr AllocateTypeAssociatedMemory(Type type, int size) => Marshal.AllocHGlobal(size);
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/SkipLocalsInitAttribute.cs b/src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/SkipLocalsInitAttribute.cs
similarity index 100%
rename from src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/SkipLocalsInitAttribute.cs
rename to src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/SkipLocalsInitAttribute.cs
diff --git a/src/ComputeSharp.Core.Package/ComputeSharp.Core.Package.msbuildproj b/src/ComputeSharp.Core.Package/ComputeSharp.Core.Package.msbuildproj
new file mode 100644
index 00000000..aa6080cc
--- /dev/null
+++ b/src/ComputeSharp.Core.Package/ComputeSharp.Core.Package.msbuildproj
@@ -0,0 +1,22 @@
+
+
+
+ net6.0
+
+
+
+ ComputeSharp.Core
+ ComputeSharp.Core
+ A library containing basic primitives to support ComputeSharp (this package is not supposed to be referenced directly by developers)
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/ComputeSharp.Package/icon.png b/src/ComputeSharp.Core.Package/icon.png
similarity index 100%
rename from src/ComputeSharp.Package/icon.png
rename to src/ComputeSharp.Core.Package/icon.png
diff --git a/src/ComputeSharp.Package/icon_highres.png b/src/ComputeSharp.Core.Package/icon_highres.png
similarity index 100%
rename from src/ComputeSharp.Package/icon_highres.png
rename to src/ComputeSharp.Core.Package/icon_highres.png
diff --git a/src/ComputeSharp.Core.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.Core.SourceGenerators/AnalyzerReleases.Shipped.md
new file mode 100644
index 00000000..cc5f50e7
--- /dev/null
+++ b/src/ComputeSharp.Core.SourceGenerators/AnalyzerReleases.Shipped.md
@@ -0,0 +1,9 @@
+; Shipped analyzer releases
+; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
+
+## Release 1.0
+
+### New Rules
+
+Rule ID | Category | Severity | Notes
+--------|----------|----------|-------
diff --git a/src/ComputeSharp.Core.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.Core.SourceGenerators/AnalyzerReleases.Unshipped.md
new file mode 100644
index 00000000..6a6dd08d
--- /dev/null
+++ b/src/ComputeSharp.Core.SourceGenerators/AnalyzerReleases.Unshipped.md
@@ -0,0 +1,2 @@
+; Unshipped analyzer release
+; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs
similarity index 66%
rename from src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs
rename to src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs
index b6afffe2..8a5771e5 100644
--- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs
+++ b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs
@@ -1,14 +1,15 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
-using ComputeSharp.SourceGenerators.Extensions;
-using ComputeSharp.SourceGenerators.Models;
+using ComputeSharp.Core.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
-namespace ComputeSharp.SourceGenerators;
+namespace ComputeSharp.Core.SourceGenerators;
///
/// A source generator creating constructors for types annotated with .
@@ -82,7 +83,7 @@ public sealed partial class AutoConstructorGenerator : IIncrementalGenerator
// ...
// }
ConstructorDeclarationSyntax constructorDeclaration =
- ConstructorDeclaration(hierarchyInfo.Names[0])
+ ConstructorDeclaration(hierarchyInfo.Hierarchy[0].QualifiedName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters.Select(field => Parameter(Identifier(field.Name)).WithType(IdentifierName(field.Type))).ToArray())
.AddBodyStatements(parameters.Select(field => ParseStatement($"this.{field.Name} = {field.Name};")).ToArray());
@@ -104,64 +105,7 @@ public sealed partial class AutoConstructorGenerator : IIncrementalGenerator
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))
};
- // Create the partial shader type declaration with the given method implementation.
- // This code produces a struct declaration as follows:
- //
- // partial struct
- // {
- //
- // }
- StructDeclarationSyntax structDeclarationSyntax =
- StructDeclaration(hierarchyInfo.Names[0])
- .AddModifiers(Token(SyntaxKind.PartialKeyword))
- .AddMembers(constructorDeclaration.AddAttributeLists(attributes));
-
- TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
-
- // Add all parent types in ascending order, if any
- foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1))
- {
- typeDeclarationSyntax =
- ClassDeclaration(parentType)
- .AddModifiers(Token(SyntaxKind.PartialKeyword))
- .AddMembers(typeDeclarationSyntax);
- }
-
- if (hierarchyInfo.Namespace is "")
- {
- // If there is no namespace, attach the pragma directly to the declared type,
- // and skip the namespace declaration. This will produce code as follows:
- //
- // #pragma warning disable
- //
- //
- return
- CompilationUnit().AddMembers(
- typeDeclarationSyntax
- .WithModifiers(TokenList(Token(
- TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
- SyntaxKind.PartialKeyword,
- TriviaList()))))
- .NormalizeWhitespace(eol: "\n");
- }
-
- // Create the compilation unit with disabled warnings, target namespace and generated type.
- // This will produce code as follows:
- //
- // #pragma warning disable
- //
- // namespace ;
- //
- //
- return
- CompilationUnit().AddMembers(
- FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace))
- .AddMembers(typeDeclarationSyntax)
- .WithNamespaceKeyword(Token(TriviaList(
- Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
- SyntaxKind.NamespaceKeyword,
- TriviaList())))
- .NormalizeWhitespace(eol: "\n");
+ return hierarchyInfo.GetSyntax(constructorDeclaration.AddAttributeLists(attributes));
}
}
}
diff --git a/src/ComputeSharp.Core.SourceGenerators/ComputeSharp.Core.SourceGenerators.csproj b/src/ComputeSharp.Core.SourceGenerators/ComputeSharp.Core.SourceGenerators.csproj
new file mode 100644
index 00000000..4a9583fa
--- /dev/null
+++ b/src/ComputeSharp.Core.SourceGenerators/ComputeSharp.Core.SourceGenerators.csproj
@@ -0,0 +1,83 @@
+
+
+
+ netstandard2.0
+ false
+ ComputeSharp.Core.SourceGenerators
+ $(NoWarn);CS1591;CS0649;CS1574
+
+
+
+ $(DefineConstants);SOURCE_GENERATOR
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/ComputeSharp.SourceGenerators/EmbeddedResources/GlobalUsingDirectives.cs b/src/ComputeSharp.Core.SourceGenerators/EmbeddedResources/GlobalUsingDirectives.cs
similarity index 100%
rename from src/ComputeSharp.SourceGenerators/EmbeddedResources/GlobalUsingDirectives.cs
rename to src/ComputeSharp.Core.SourceGenerators/EmbeddedResources/GlobalUsingDirectives.cs
diff --git a/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs b/src/ComputeSharp.Core.SourceGenerators/GlobalUsingDirectivesGenerator.cs
similarity index 83%
rename from src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs
rename to src/ComputeSharp.Core.SourceGenerators/GlobalUsingDirectivesGenerator.cs
index 30d8933d..8fb5b86b 100644
--- a/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs
+++ b/src/ComputeSharp.Core.SourceGenerators/GlobalUsingDirectivesGenerator.cs
@@ -2,7 +2,7 @@
using System.Reflection;
using Microsoft.CodeAnalysis;
-namespace ComputeSharp.SourceGenerators;
+namespace ComputeSharp.Core.SourceGenerators;
///
/// A source generator to create global using directives for the HLSL primitive types.
@@ -15,7 +15,7 @@ public sealed class GlobalUsingDirectivesGenerator : IIncrementalGenerator
{
context.RegisterPostInitializationOutput(static context =>
{
- const string filename = "ComputeSharp.SourceGenerators.EmbeddedResources.GlobalUsingDirectives.cs";
+ const string filename = "ComputeSharp.Core.SourceGenerators.EmbeddedResources.GlobalUsingDirectives.cs";
using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(filename);
using StreamReader reader = new(stream);
diff --git a/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs b/src/ComputeSharp.Core.SourceGenerators/Models/ParameterInfo.cs
similarity index 82%
rename from src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs
rename to src/ComputeSharp.Core.SourceGenerators/Models/ParameterInfo.cs
index 137df444..ff276e79 100644
--- a/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs
+++ b/src/ComputeSharp.Core.SourceGenerators/Models/ParameterInfo.cs
@@ -1,4 +1,4 @@
-namespace ComputeSharp.SourceGenerators.Models;
+namespace ComputeSharp.Core.SourceGenerators.Models;
///
/// A model describing info on a constructor parameter.
diff --git a/src/ComputeSharp.Core.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs b/src/ComputeSharp.Core.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs
new file mode 100644
index 00000000..a914bf06
--- /dev/null
+++ b/src/ComputeSharp.Core.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs
@@ -0,0 +1,12 @@
+using System.ComponentModel;
+
+namespace System.Runtime.CompilerServices;
+
+///
+/// Reserved to be used by the compiler for tracking metadata.
+/// This class should not be used by developers in source code.
+///
+[EditorBrowsable(EditorBrowsableState.Never)]
+internal static class IsExternalInit
+{
+}
diff --git a/src/ComputeSharp/Core/Attributes/AutoConstructorAttribute.cs b/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs
similarity index 100%
rename from src/ComputeSharp/Core/Attributes/AutoConstructorAttribute.cs
rename to src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs
diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj
new file mode 100644
index 00000000..8aa6a689
--- /dev/null
+++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj
@@ -0,0 +1,238 @@
+
+
+
+ netstandard2.0;net6.0
+ bin\Release
+ ComputeSharp.Core.xml
+
+
+
+
+ true
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Hlsl.Void.tt
+ True
+ True
+
+
+ True
+ True
+ Hlsl.tt
+
+
+ True
+ True
+ Bool2.tt
+
+
+ True
+ True
+ Bool3.tt
+
+
+ True
+ True
+ Bool4.tt
+
+
+ True
+ True
+ BoolMxN.tt
+
+
+ True
+ True
+ Double2.tt
+
+
+ True
+ True
+ Double3.tt
+
+
+ True
+ True
+ Double4.tt
+
+
+ True
+ True
+ DoubleMxN.tt
+
+
+ True
+ True
+ Float2.tt
+
+
+ True
+ True
+ Float3.tt
+
+
+ True
+ True
+ Float4.tt
+
+
+ True
+ True
+ FloatMxN.tt
+
+
+ True
+ True
+ Int2.tt
+
+
+ True
+ True
+ Int3.tt
+
+
+ True
+ True
+ Int4.tt
+
+
+ True
+ True
+ IntMxN.tt
+
+
+ True
+ True
+ UInt2.tt
+
+
+ True
+ True
+ UInt3.tt
+
+
+ True
+ True
+ UInt4.tt
+
+
+ True
+ True
+ UIntMxN.tt
+
+
+
+
+
+ Hlsl.Void.g.cs
+ TextTemplatingFileGenerator
+
+
+ TextTemplatingFileGenerator
+ Hlsl.g.cs
+
+
+ TextTemplatingFileGenerator
+ Bool2.g.cs
+
+
+ TextTemplatingFileGenerator
+ Bool3.g.cs
+
+
+ TextTemplatingFileGenerator
+ Bool4.g.cs
+
+
+ TextTemplatingFileGenerator
+ BoolMxN.g.cs
+
+
+ TextTemplatingFileGenerator
+ Double2.g.cs
+
+
+ TextTemplatingFileGenerator
+ Double3.g.cs
+
+
+ TextTemplatingFileGenerator
+ Double4.g.cs
+
+
+ TextTemplatingFileGenerator
+ DoubleMxN.g.cs
+
+
+ TextTemplatingFileGenerator
+ Float2.g.cs
+
+
+ TextTemplatingFileGenerator
+ Float3.g.cs
+
+
+ TextTemplatingFileGenerator
+ Float4.g.cs
+
+
+ TextTemplatingFileGenerator
+ FloatMxN.g.cs
+
+
+ TextTemplatingFileGenerator
+ Int2.g.cs
+
+
+ TextTemplatingFileGenerator
+ Int3.g.cs
+
+
+ TextTemplatingFileGenerator
+ Int4.g.cs
+
+
+ TextTemplatingFileGenerator
+ IntMxN.g.cs
+
+
+ TextTemplatingFileGenerator
+ UInt2.g.cs
+
+
+ TextTemplatingFileGenerator
+ UInt3.g.cs
+
+
+ TextTemplatingFileGenerator
+ UInt4.g.cs
+
+
+ TextTemplatingFileGenerator
+ UIntMxN.g.cs
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.targets b/src/ComputeSharp.Core/ComputeSharp.Core.targets
new file mode 100644
index 00000000..79dfea91
--- /dev/null
+++ b/src/ComputeSharp.Core/ComputeSharp.Core.targets
@@ -0,0 +1,53 @@
+
+
+
+
+
+ <_ComputeSharpAnalyzer Include="@(Analyzer)" Condition="'%(Analyzer.NuGetPackageId)' == 'ComputeSharp.Core'" />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ @(CurrentCompilerAssemblyIdentity->'%(Version)')
+
+
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/ComputeSharp/Core/Exceptions/InvalidExecutionContextException.cs b/src/ComputeSharp.Core/Exceptions/InvalidExecutionContextException.cs
similarity index 100%
rename from src/ComputeSharp/Core/Exceptions/InvalidExecutionContextException.cs
rename to src/ComputeSharp.Core/Exceptions/InvalidExecutionContextException.cs
diff --git a/src/ComputeSharp/Core/Helpers/System.Runtime.CompilerServices/FormatInterpolatedStringHandler.cs b/src/ComputeSharp.Core/Helpers/FormatInterpolatedStringHandler.cs
similarity index 100%
rename from src/ComputeSharp/Core/Helpers/System.Runtime.CompilerServices/FormatInterpolatedStringHandler.cs
rename to src/ComputeSharp.Core/Helpers/FormatInterpolatedStringHandler.cs
diff --git a/src/ComputeSharp/Core/Helpers/System.Runtime.CompilerServices/TryWriteFormatInterpolatedStringHandler.cs b/src/ComputeSharp.Core/Helpers/TryWriteFormatInterpolatedStringHandler.cs
similarity index 100%
rename from src/ComputeSharp/Core/Helpers/System.Runtime.CompilerServices/TryWriteFormatInterpolatedStringHandler.cs
rename to src/ComputeSharp.Core/Helpers/TryWriteFormatInterpolatedStringHandler.cs
diff --git a/src/ComputeSharp/Core/Intrinsics/Attributes/HlslIntrinsicNameAttribute.cs b/src/ComputeSharp.Core/Intrinsics/Attributes/HlslIntrinsicNameAttribute.cs
similarity index 100%
rename from src/ComputeSharp/Core/Intrinsics/Attributes/HlslIntrinsicNameAttribute.cs
rename to src/ComputeSharp.Core/Intrinsics/Attributes/HlslIntrinsicNameAttribute.cs
diff --git a/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.g.cs b/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.g.cs
new file mode 100644
index 00000000..a58bc20b
--- /dev/null
+++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.g.cs
@@ -0,0 +1,308 @@
+using ComputeSharp.Core.Intrinsics.Attributes;
+using ComputeSharp.Exceptions;
+
+namespace ComputeSharp;
+
+///
+partial class Hlsl
+{
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(float x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(float)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float2 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float2)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float3 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float3)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float4 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float4)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float1x1 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float1x1)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float1x2 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float1x2)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float1x3 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float1x3)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float1x4 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float1x4)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float2x1 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float2x1)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float2x2 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float2x2)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float2x3 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float2x3)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float2x4 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float2x4)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float3x1 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float3x1)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float3x2 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float3x2)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float3x3 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float3x3)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float3x4 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float3x4)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float4x1 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float4x1)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float4x2 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float4x2)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float4x3 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float4x3)})");
+
+ ///
+ /// Discards the current pixel if the specified value is less than zero.
+ ///
+ /// The specified value.
+ ///
+ /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ /// Also, use the clip function to test for alpha behavior, as shown in the following example:
+ ///
+ /// Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ///
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("clip")]
+ public static void Clip(Float4x4 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float4x4)})");
+}
diff --git a/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.tt b/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.tt
new file mode 100644
index 00000000..aedffb22
--- /dev/null
+++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.tt
@@ -0,0 +1,71 @@
+<#@include file="Hlsl.Void.ttinclude" #>
+using ComputeSharp.Core.Intrinsics.Attributes;
+using ComputeSharp.Exceptions;
+
+namespace ComputeSharp;
+
+///
+partial class Hlsl
+{
+<#
+PushIndent(" ");
+
+bool isFirst = true;
+
+foreach (var intrinsic in Intrinsics)
+{
+ foreach (var overload in intrinsic.Overloads)
+ {
+ if (isFirst) isFirst = false;
+ else WriteLine("");
+
+ WriteLine("/// ");
+ WriteLine($"/// {intrinsic.Summary}");
+ WriteLine("/// ");
+
+ foreach (var param in intrinsic.Parameters)
+ {
+ WriteLine($"/// {param.Info}");
+ }
+
+ if (intrinsic.Remarks.Length > 0)
+ {
+ var lines = intrinsic.Remarks.Replace("\r", "").Split('\n');
+
+ WriteLine("/// ");
+
+ foreach (var line in lines)
+ {
+ string trimmedLine = line.Trim();
+
+ if (trimmedLine.Length > 0)
+ {
+ WriteLine($"/// {trimmedLine}");
+ }
+ }
+
+ WriteLine("/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.");
+ WriteLine("/// ");
+ }
+ else
+ {
+ WriteLine("/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.");
+ }
+
+ WriteLine($"[HlslIntrinsicName(\"{intrinsic.HlslName}\")]");
+
+ Write($"public static void {intrinsic.Name}(");
+ Write(string.Join(", ", intrinsic.Parameters.Zip(overload, (a, b) => $"{(a.IsOut ? "out " : "")}{b} {a.Name}")));
+ Write(")");
+
+ Write(" => throw new InvalidExecutionContextException(");
+
+ var parameters = string.Join(", ", overload.Select(t => $"{{typeof({t})}}"));
+
+ WriteLine($"$\"{{typeof(Hlsl)}}.{{nameof({intrinsic.Name})}}({parameters})\");");
+ }
+}
+
+PopIndent();
+#>
+}
diff --git a/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.ttinclude b/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.ttinclude
new file mode 100644
index 00000000..90dc8adf
--- /dev/null
+++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.ttinclude
@@ -0,0 +1,51 @@
+<#@ template debug="false" hostspecific="false" language="C#" #>
+<#@ assembly name="System.Core" #>
+<#@ import namespace="System.Linq" #>
+<#@ import namespace="System.Text" #>
+<#@ import namespace="System.Text.RegularExpressions" #>
+<#@ import namespace="System.Collections.Generic" #>
+<#@ output extension=".g.cs"#>
+<#
+var Intrinsics = new[]
+{
+ new
+ {
+ Name = "Clip",
+ HlslName = "clip",
+ Summary = "Discards the current pixel if the specified value is less than zero.",
+ Remarks = @"
+ Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane.
+ Also, use the clip function to test for alpha behavior, as shown in the following example:
+
+ Hlsl.Clip(color.A < 0.1f ? -1 : 1);
+ ",
+ Parameters = new[]
+ {
+ new { IsOut = false, IsRef = false, Name = "x", Info = "The specified value." }
+ },
+ Overloads = new[]
+ {
+ new[] { "float" },
+ new[] { "Float2" },
+ new[] { "Float3" },
+ new[] { "Float4" },
+ new[] { "Float1x1" },
+ new[] { "Float1x2" },
+ new[] { "Float1x3" },
+ new[] { "Float1x4" },
+ new[] { "Float2x1" },
+ new[] { "Float2x2" },
+ new[] { "Float2x3" },
+ new[] { "Float2x4" },
+ new[] { "Float3x1" },
+ new[] { "Float3x2" },
+ new[] { "Float3x3" },
+ new[] { "Float3x4" },
+ new[] { "Float4x1" },
+ new[] { "Float4x2" },
+ new[] { "Float4x3" },
+ new[] { "Float4x4" }
+ }
+ }
+};
+#>
\ No newline at end of file
diff --git a/src/ComputeSharp/Core/Intrinsics/Hlsl.cs b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs
similarity index 93%
rename from src/ComputeSharp/Core/Intrinsics/Hlsl.cs
rename to src/ComputeSharp.Core/Intrinsics/Hlsl.cs
index 535b8b38..a09a054b 100644
--- a/src/ComputeSharp/Core/Intrinsics/Hlsl.cs
+++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs
@@ -1,4 +1,5 @@
-using ComputeSharp.Exceptions;
+using ComputeSharp.Core.Intrinsics.Attributes;
+using ComputeSharp.Exceptions;
namespace ComputeSharp;
@@ -7,6 +8,13 @@ namespace ComputeSharp;
///
public static partial class Hlsl
{
+ ///
+ /// Submits an error message to the information queue and terminates the current draw or dispatch call being executed.
+ ///
+ /// This operation does nothing on rasterizers that do not support it.
+ [HlslIntrinsicName("abort")]
+ public static void Abort() => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Abort)}()");
+
///
/// Blocks execution of all threads in a group until all memory accesses have been completed.
///
@@ -316,4 +324,24 @@ public static partial class Hlsl
/// The original value.
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
public static void InterlockedXor(ref uint destination, uint value, out uint original) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(InterlockedXor)}({typeof(uint)}, {typeof(uint)}, {typeof(uint)})");
+
+ ///
+ /// Returns a lighting coefficient vector.
+ ///
+ /// The dot product of the normalized surface normal and the light vector.
+ /// The dot product of the half-angle vector and the surface normal.
+ /// A specular exponent.
+ /// The lighting coefficient vector.
+ ///
+ /// This function returns a lighting coefficient vector (ambient, diffuse, specular, 1) where:
+ ///
+ /// - Ambient: 1.
+ /// - Diffuse: n * l < 0 ? 0 : n * l.
+ /// - Specular: n * l < 0 || n * h < 0 ? 0 : (n * h) ^ m.
+ ///
+ /// Where the vector n is the normal vector, l is the direction to light and h is the half vector.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ ///
+ [HlslIntrinsicName("lit")]
+ public static float Lit(float nDotL, float nDotH, float m) => default;
}
diff --git a/src/ComputeSharp/Core/Intrinsics/Hlsl.g.cs b/src/ComputeSharp.Core/Intrinsics/Hlsl.g.cs
similarity index 95%
rename from src/ComputeSharp/Core/Intrinsics/Hlsl.g.cs
rename to src/ComputeSharp.Core/Intrinsics/Hlsl.g.cs
index e74bba24..41a98d1b 100644
--- a/src/ComputeSharp/Core/Intrinsics/Hlsl.g.cs
+++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.g.cs
@@ -4,7 +4,7 @@ using ComputeSharp.Exceptions;
namespace ComputeSharp;
///
-public static partial class Hlsl
+partial class Hlsl
{
///
/// Returns the absolute value of the specified value.
@@ -4492,6 +4492,510 @@ public static partial class Hlsl
[HlslIntrinsicName("cross")]
public static Float3 Cross(Float3 x, Float3 y) => default;
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static float DerivativeOfDx(float x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float2 DerivativeOfDx(Float2 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float3 DerivativeOfDx(Float3 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float4 DerivativeOfDx(Float4 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float1x1 DerivativeOfDx(Float1x1 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float1x2 DerivativeOfDx(Float1x2 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float1x3 DerivativeOfDx(Float1x3 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float1x4 DerivativeOfDx(Float1x4 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float2x1 DerivativeOfDx(Float2x1 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float2x2 DerivativeOfDx(Float2x2 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float2x3 DerivativeOfDx(Float2x3 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float2x4 DerivativeOfDx(Float2x4 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float3x1 DerivativeOfDx(Float3x1 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float3x2 DerivativeOfDx(Float3x2 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float3x3 DerivativeOfDx(Float3x3 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float3x4 DerivativeOfDx(Float3x4 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float4x1 DerivativeOfDx(Float4x1 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float4x2 DerivativeOfDx(Float4x2 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float4x3 DerivativeOfDx(Float4x3 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx")]
+ public static Float4x4 DerivativeOfDx(Float4x4 x) => default;
+
+ ///
+ /// Computes a low precision partial derivative with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The low precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx_coarse")]
+ public static float DerivativeOfDxLowPrecision(float x) => default;
+
+ ///
+ /// Computes a low precision partial derivative with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The low precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx_coarse")]
+ public static Float2 DerivativeOfDxLowPrecision(Float2 x) => default;
+
+ ///
+ /// Computes a low precision partial derivative with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The low precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx_coarse")]
+ public static Float3 DerivativeOfDxLowPrecision(Float3 x) => default;
+
+ ///
+ /// Computes a low precision partial derivative with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The low precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx_coarse")]
+ public static Float4 DerivativeOfDxLowPrecision(Float4 x) => default;
+
+ ///
+ /// Computes a high precision partial derivative with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The high precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx_fine")]
+ public static float DerivativeOfDxHighPrecision(float x) => default;
+
+ ///
+ /// Computes a high precision partial derivative with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The high precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx_fine")]
+ public static Float2 DerivativeOfDxHighPrecision(Float2 x) => default;
+
+ ///
+ /// Computes a high precision partial derivative with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The high precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx_fine")]
+ public static Float3 DerivativeOfDxHighPrecision(Float3 x) => default;
+
+ ///
+ /// Computes a high precision partial derivative with respect to the screen-space x-coordinate.
+ ///
+ /// The specified value.
+ /// The high precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddx_fine")]
+ public static Float4 DerivativeOfDxHighPrecision(Float4 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static float DerivativeOfDy(float x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float2 DerivativeOfDy(Float2 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float3 DerivativeOfDy(Float3 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float4 DerivativeOfDy(Float4 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float1x1 DerivativeOfDy(Float1x1 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float1x2 DerivativeOfDy(Float1x2 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float1x3 DerivativeOfDy(Float1x3 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float1x4 DerivativeOfDy(Float1x4 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float2x1 DerivativeOfDy(Float2x1 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float2x2 DerivativeOfDy(Float2x2 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float2x3 DerivativeOfDy(Float2x3 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float2x4 DerivativeOfDy(Float2x4 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float3x1 DerivativeOfDy(Float3x1 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float3x2 DerivativeOfDy(Float3x2 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float3x3 DerivativeOfDy(Float3x3 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float3x4 DerivativeOfDy(Float3x4 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float4x1 DerivativeOfDy(Float4x1 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float4x2 DerivativeOfDy(Float4x2 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float4x3 DerivativeOfDy(Float4x3 x) => default;
+
+ ///
+ /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy")]
+ public static Float4x4 DerivativeOfDy(Float4x4 x) => default;
+
+ ///
+ /// Computes a low precision partial derivative with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The low precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy_coarse")]
+ public static float DerivativeOfDyLowPrecision(float x) => default;
+
+ ///
+ /// Computes a low precision partial derivative with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The low precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy_coarse")]
+ public static Float2 DerivativeOfDyLowPrecision(Float2 x) => default;
+
+ ///
+ /// Computes a low precision partial derivative with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The low precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy_coarse")]
+ public static Float3 DerivativeOfDyLowPrecision(Float3 x) => default;
+
+ ///
+ /// Computes a low precision partial derivative with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The low precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy_coarse")]
+ public static Float4 DerivativeOfDyLowPrecision(Float4 x) => default;
+
+ ///
+ /// Computes a high precision partial derivative with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The high precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy_fine")]
+ public static float DerivativeOfDyHighPrecision(float x) => default;
+
+ ///
+ /// Computes a high precision partial derivative with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The high precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy_fine")]
+ public static Float2 DerivativeOfDyHighPrecision(Float2 x) => default;
+
+ ///
+ /// Computes a high precision partial derivative with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The high precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy_fine")]
+ public static Float3 DerivativeOfDyHighPrecision(Float3 x) => default;
+
+ ///
+ /// Computes a high precision partial derivative with respect to the screen-space y-coordinate.
+ ///
+ /// The specified value.
+ /// The high precision partial derivative with respect to the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("ddy_fine")]
+ public static Float4 DerivativeOfDyHighPrecision(Float4 x) => default;
+
///
/// Converts the specified value from radians to degrees.
///
@@ -5491,7 +5995,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static double FusedMultiplyAccumulate(double a, double b, double c) => default;
+ public static double FusedMultiplyAdd(double a, double b, double c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5502,7 +6006,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double2 FusedMultiplyAccumulate(Double2 a, Double2 b, Double2 c) => default;
+ public static Double2 FusedMultiplyAdd(Double2 a, Double2 b, Double2 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5513,7 +6017,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double3 FusedMultiplyAccumulate(Double3 a, Double3 b, Double3 c) => default;
+ public static Double3 FusedMultiplyAdd(Double3 a, Double3 b, Double3 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5524,7 +6028,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double4 FusedMultiplyAccumulate(Double4 a, Double4 b, Double4 c) => default;
+ public static Double4 FusedMultiplyAdd(Double4 a, Double4 b, Double4 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5535,7 +6039,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double1x1 FusedMultiplyAccumulate(Double1x1 a, Double1x1 b, Double1x1 c) => default;
+ public static Double1x1 FusedMultiplyAdd(Double1x1 a, Double1x1 b, Double1x1 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5546,7 +6050,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double1x2 FusedMultiplyAccumulate(Double1x2 a, Double1x2 b, Double1x2 c) => default;
+ public static Double1x2 FusedMultiplyAdd(Double1x2 a, Double1x2 b, Double1x2 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5557,7 +6061,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double1x3 FusedMultiplyAccumulate(Double1x3 a, Double1x3 b, Double1x3 c) => default;
+ public static Double1x3 FusedMultiplyAdd(Double1x3 a, Double1x3 b, Double1x3 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5568,7 +6072,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double1x4 FusedMultiplyAccumulate(Double1x4 a, Double1x4 b, Double1x4 c) => default;
+ public static Double1x4 FusedMultiplyAdd(Double1x4 a, Double1x4 b, Double1x4 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5579,7 +6083,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double2x1 FusedMultiplyAccumulate(Double2x1 a, Double2x1 b, Double2x1 c) => default;
+ public static Double2x1 FusedMultiplyAdd(Double2x1 a, Double2x1 b, Double2x1 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5590,7 +6094,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double2x2 FusedMultiplyAccumulate(Double2x2 a, Double2x2 b, Double2x2 c) => default;
+ public static Double2x2 FusedMultiplyAdd(Double2x2 a, Double2x2 b, Double2x2 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5601,7 +6105,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double2x3 FusedMultiplyAccumulate(Double2x3 a, Double2x3 b, Double2x3 c) => default;
+ public static Double2x3 FusedMultiplyAdd(Double2x3 a, Double2x3 b, Double2x3 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5612,7 +6116,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double2x4 FusedMultiplyAccumulate(Double2x4 a, Double2x4 b, Double2x4 c) => default;
+ public static Double2x4 FusedMultiplyAdd(Double2x4 a, Double2x4 b, Double2x4 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5623,7 +6127,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double3x1 FusedMultiplyAccumulate(Double3x1 a, Double3x1 b, Double3x1 c) => default;
+ public static Double3x1 FusedMultiplyAdd(Double3x1 a, Double3x1 b, Double3x1 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5634,7 +6138,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double3x2 FusedMultiplyAccumulate(Double3x2 a, Double3x2 b, Double3x2 c) => default;
+ public static Double3x2 FusedMultiplyAdd(Double3x2 a, Double3x2 b, Double3x2 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5645,7 +6149,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double3x3 FusedMultiplyAccumulate(Double3x3 a, Double3x3 b, Double3x3 c) => default;
+ public static Double3x3 FusedMultiplyAdd(Double3x3 a, Double3x3 b, Double3x3 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5656,7 +6160,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double3x4 FusedMultiplyAccumulate(Double3x4 a, Double3x4 b, Double3x4 c) => default;
+ public static Double3x4 FusedMultiplyAdd(Double3x4 a, Double3x4 b, Double3x4 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5667,7 +6171,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double4x1 FusedMultiplyAccumulate(Double4x1 a, Double4x1 b, Double4x1 c) => default;
+ public static Double4x1 FusedMultiplyAdd(Double4x1 a, Double4x1 b, Double4x1 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5678,7 +6182,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double4x2 FusedMultiplyAccumulate(Double4x2 a, Double4x2 b, Double4x2 c) => default;
+ public static Double4x2 FusedMultiplyAdd(Double4x2 a, Double4x2 b, Double4x2 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5689,7 +6193,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double4x3 FusedMultiplyAccumulate(Double4x3 a, Double4x3 b, Double4x3 c) => default;
+ public static Double4x3 FusedMultiplyAdd(Double4x3 a, Double4x3 b, Double4x3 c) => default;
///
/// Returns the double-precision fused multiply-addition of a * b + c.
@@ -5700,7 +6204,7 @@ public static partial class Hlsl
/// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP).
/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
[HlslIntrinsicName("fma")]
- public static Double4x4 FusedMultiplyAccumulate(Double4x4 a, Double4x4 b, Double4x4 c) => default;
+ public static Double4x4 FusedMultiplyAdd(Double4x4 a, Double4x4 b, Double4x4 c) => default;
///
/// Returns the floating-point remainder of x / y.
@@ -6282,6 +6786,186 @@ public static partial class Hlsl
[HlslIntrinsicName("frexp")]
public static Float4x4 Frexp(Float4x4 x, out Float4x4 exp) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Frexp)}({typeof(Float4x4)}, {typeof(Float4x4)})");
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static float Fwidth(float x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float2 Fwidth(Float2 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float3 Fwidth(Float3 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float4 Fwidth(Float4 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float1x1 Fwidth(Float1x1 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float1x2 Fwidth(Float1x2 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float1x3 Fwidth(Float1x3 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float1x4 Fwidth(Float1x4 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float2x1 Fwidth(Float2x1 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float2x2 Fwidth(Float2x2 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float2x3 Fwidth(Float2x3 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float2x4 Fwidth(Float2x4 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float3x1 Fwidth(Float3x1 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float3x2 Fwidth(Float3x2 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float3x3 Fwidth(Float3x3 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float3x4 Fwidth(Float3x4 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float4x1 Fwidth(Float4x1 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float4x2 Fwidth(Float4x2 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float4x3 Fwidth(Float4x3 x) => default;
+
+ ///
+ /// Returns the absolute value of the partial derivatives of the specified value.
+ ///
+ /// The specified value.
+ /// The absolute value of the partial derivatives of the input parameter.
+ /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior.
+ [HlslIntrinsicName("fwidth")]
+ public static Float4x4 Fwidth(Float4x4 x) => default;
+
///
/// Determines if the specified floating-point value is finite.
///
diff --git a/src/ComputeSharp/Core/Intrinsics/Hlsl.tt b/src/ComputeSharp.Core/Intrinsics/Hlsl.tt
similarity index 98%
rename from src/ComputeSharp/Core/Intrinsics/Hlsl.tt
rename to src/ComputeSharp.Core/Intrinsics/Hlsl.tt
index 676840f0..65c93f07 100644
--- a/src/ComputeSharp/Core/Intrinsics/Hlsl.tt
+++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.tt
@@ -5,7 +5,7 @@ using ComputeSharp.Exceptions;
namespace ComputeSharp;
///
-public static partial class Hlsl
+partial class Hlsl
{
<#
PushIndent(" ");
diff --git a/src/ComputeSharp/Core/Intrinsics/Hlsl.ttinclude b/src/ComputeSharp.Core/Intrinsics/Hlsl.ttinclude
similarity index 94%
rename from src/ComputeSharp/Core/Intrinsics/Hlsl.ttinclude
rename to src/ComputeSharp.Core/Intrinsics/Hlsl.ttinclude
index c6b47260..470fdde4 100644
--- a/src/ComputeSharp/Core/Intrinsics/Hlsl.ttinclude
+++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.ttinclude
@@ -739,6 +739,146 @@ var Intrinsics = new[]
}
},
new
+ {
+ Name = "DerivativeOfDx",
+ HlslName = "ddx",
+ Summary = "Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.",
+ Parameters = new[]
+ {
+ new { IsOut = false, Name = "x", Info = "The specified value." }
+ },
+ Returns = "The partial derivative with respect to the input parameter.",
+ Overloads = new[]
+ {
+ new { Return = "float", Params = new[] { "float" } },
+ new { Return = "Float2", Params = new[] { "Float2" } },
+ new { Return = "Float3", Params = new[] { "Float3" } },
+ new { Return = "Float4", Params = new[] { "Float4" } },
+ new { Return = "Float1x1", Params = new[] { "Float1x1" } },
+ new { Return = "Float1x2", Params = new[] { "Float1x2" } },
+ new { Return = "Float1x3", Params = new[] { "Float1x3" } },
+ new { Return = "Float1x4", Params = new[] { "Float1x4" } },
+ new { Return = "Float2x1", Params = new[] { "Float2x1" } },
+ new { Return = "Float2x2", Params = new[] { "Float2x2" } },
+ new { Return = "Float2x3", Params = new[] { "Float2x3" } },
+ new { Return = "Float2x4", Params = new[] { "Float2x4" } },
+ new { Return = "Float3x1", Params = new[] { "Float3x1" } },
+ new { Return = "Float3x2", Params = new[] { "Float3x2" } },
+ new { Return = "Float3x3", Params = new[] { "Float3x3" } },
+ new { Return = "Float3x4", Params = new[] { "Float3x4" } },
+ new { Return = "Float4x1", Params = new[] { "Float4x1" } },
+ new { Return = "Float4x2", Params = new[] { "Float4x2" } },
+ new { Return = "Float4x3", Params = new[] { "Float4x3" } },
+ new { Return = "Float4x4", Params = new[] { "Float4x4" } }
+ }
+ },
+ new
+ {
+ Name = "DerivativeOfDxLowPrecision",
+ HlslName = "ddx_coarse",
+ Summary = "Computes a low precision partial derivative with respect to the screen-space x-coordinate.",
+ Parameters = new[]
+ {
+ new { IsOut = false, Name = "x", Info = "The specified value." }
+ },
+ Returns = "The low precision partial derivative with respect to the input parameter.",
+ Overloads = new[]
+ {
+ new { Return = "float", Params = new[] { "float" } },
+ new { Return = "Float2", Params = new[] { "Float2" } },
+ new { Return = "Float3", Params = new[] { "Float3" } },
+ new { Return = "Float4", Params = new[] { "Float4" } }
+ }
+ },
+ new
+ {
+ Name = "DerivativeOfDxHighPrecision",
+ HlslName = "ddx_fine",
+ Summary = "Computes a high precision partial derivative with respect to the screen-space x-coordinate.",
+ Parameters = new[]
+ {
+ new { IsOut = false, Name = "x", Info = "The specified value." }
+ },
+ Returns = "The high precision partial derivative with respect to the input parameter.",
+ Overloads = new[]
+ {
+ new { Return = "float", Params = new[] { "float" } },
+ new { Return = "Float2", Params = new[] { "Float2" } },
+ new { Return = "Float3", Params = new[] { "Float3" } },
+ new { Return = "Float4", Params = new[] { "Float4" } }
+ }
+ },
+ new
+ {
+ Name = "DerivativeOfDy",
+ HlslName = "ddy",
+ Summary = "Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.",
+ Parameters = new[]
+ {
+ new { IsOut = false, Name = "x", Info = "The specified value." }
+ },
+ Returns = "The partial derivative with respect to the input parameter.",
+ Overloads = new[]
+ {
+ new { Return = "float", Params = new[] { "float" } },
+ new { Return = "Float2", Params = new[] { "Float2" } },
+ new { Return = "Float3", Params = new[] { "Float3" } },
+ new { Return = "Float4", Params = new[] { "Float4" } },
+ new { Return = "Float1x1", Params = new[] { "Float1x1" } },
+ new { Return = "Float1x2", Params = new[] { "Float1x2" } },
+ new { Return = "Float1x3", Params = new[] { "Float1x3" } },
+ new { Return = "Float1x4", Params = new[] { "Float1x4" } },
+ new { Return = "Float2x1", Params = new[] { "Float2x1" } },
+ new { Return = "Float2x2", Params = new[] { "Float2x2" } },
+ new { Return = "Float2x3", Params = new[] { "Float2x3" } },
+ new { Return = "Float2x4", Params = new[] { "Float2x4" } },
+ new { Return = "Float3x1", Params = new[] { "Float3x1" } },
+ new { Return = "Float3x2", Params = new[] { "Float3x2" } },
+ new { Return = "Float3x3", Params = new[] { "Float3x3" } },
+ new { Return = "Float3x4", Params = new[] { "Float3x4" } },
+ new { Return = "Float4x1", Params = new[] { "Float4x1" } },
+ new { Return = "Float4x2", Params = new[] { "Float4x2" } },
+ new { Return = "Float4x3", Params = new[] { "Float4x3" } },
+ new { Return = "Float4x4", Params = new[] { "Float4x4" } }
+ }
+ },
+ new
+ {
+ Name = "DerivativeOfDyLowPrecision",
+ HlslName = "ddy_coarse",
+ Summary = "Computes a low precision partial derivative with respect to the screen-space y-coordinate.",
+ Parameters = new[]
+ {
+ new { IsOut = false, Name = "x", Info = "The specified value." }
+ },
+ Returns = "The low precision partial derivative with respect to the input parameter.",
+ Overloads = new[]
+ {
+ new { Return = "float", Params = new[] { "float" } },
+ new { Return = "Float2", Params = new[] { "Float2" } },
+ new { Return = "Float3", Params = new[] { "Float3" } },
+ new { Return = "Float4", Params = new[] { "Float4" } }
+ }
+ },
+ new
+ {
+ Name = "DerivativeOfDyHighPrecision",
+ HlslName = "ddy_fine",
+ Summary = "Computes a high precision partial derivative with respect to the screen-space y-coordinate.",
+ Parameters = new[]
+ {
+ new { IsOut = false, Name = "x", Info = "The specified value." }
+ },
+ Returns = "The high precision partial derivative with respect to the input parameter.",
+ Overloads = new[]
+ {
+ new { Return = "float", Params = new[] { "float" } },
+ new { Return = "Float2", Params = new[] { "Float2" } },
+ new { Return = "Float3", Params = new[] { "Float3" } },
+ new { Return = "Float4", Params = new[] { "Float4" } }
+ }
+ },
+ new
{
Name = "Degrees",
HlslName = "degrees",
@@ -977,7 +1117,7 @@ var Intrinsics = new[]
},
new
{
- Name = "FusedMultiplyAccumulate",
+ Name = "FusedMultiplyAdd",
HlslName = "fma",
Summary = "Returns the double-precision fused multiply-addition of a * b + c.",
Parameters = new[]
@@ -1116,6 +1256,40 @@ var Intrinsics = new[]
}
},
new
+ {
+ Name = "Fwidth",
+ HlslName = "fwidth",
+ Summary = "Returns the absolute value of the partial derivatives of the specified value.",
+ Parameters = new[]
+ {
+ new { IsOut = false, Name = "x", Info = "The specified value." }
+ },
+ Returns = "The absolute value of the partial derivatives of the input parameter.",
+ Overloads = new[]
+ {
+ new { Return = "float", Params = new[] { "float" } },
+ new { Return = "Float2", Params = new[] { "Float2" } },
+ new { Return = "Float3", Params = new[] { "Float3" } },
+ new { Return = "Float4", Params = new[] { "Float4" } },
+ new { Return = "Float1x1", Params = new[] { "Float1x1" } },
+ new { Return = "Float1x2", Params = new[] { "Float1x2" } },
+ new { Return = "Float1x3", Params = new[] { "Float1x3" } },
+ new { Return = "Float1x4", Params = new[] { "Float1x4" } },
+ new { Return = "Float2x1", Params = new[] { "Float2x1" } },
+ new { Return = "Float2x2", Params = new[] { "Float2x2" } },
+ new { Return = "Float2x3", Params = new[] { "Float2x3" } },
+ new { Return = "Float2x4", Params = new[] { "Float2x4" } },
+ new { Return = "Float3x1", Params = new[] { "Float3x1" } },
+ new { Return = "Float3x2", Params = new[] { "Float3x2" } },
+ new { Return = "Float3x3", Params = new[] { "Float3x3" } },
+ new { Return = "Float3x4", Params = new[] { "Float3x4" } },
+ new { Return = "Float4x1", Params = new[] { "Float4x1" } },
+ new { Return = "Float4x2", Params = new[] { "Float4x2" } },
+ new { Return = "Float4x3", Params = new[] { "Float4x3" } },
+ new { Return = "Float4x4", Params = new[] { "Float4x4" } }
+ }
+ },
+ new
{
Name = "IsFinite",
HlslName = "isfinite",
diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Bool/Bool.cs
rename to src/ComputeSharp.Core/Primitives/Bool/Bool.cs
diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool2.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool2.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Bool/Bool2.cs
rename to src/ComputeSharp.Core/Primitives/Bool/Bool2.cs
diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool2.g.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool2.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Bool/Bool2.g.cs
rename to src/ComputeSharp.Core/Primitives/Bool/Bool2.g.cs
index f1beeb1c..86158121 100644
--- a/src/ComputeSharp/Core/Primitives/Bool/Bool2.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Bool/Bool2.g.cs
@@ -1,8 +1,8 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool2.tt b/src/ComputeSharp.Core/Primitives/Bool/Bool2.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Bool/Bool2.tt
rename to src/ComputeSharp.Core/Primitives/Bool/Bool2.tt
diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool3.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool3.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Bool/Bool3.cs
rename to src/ComputeSharp.Core/Primitives/Bool/Bool3.cs
diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool3.g.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool3.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Bool/Bool3.g.cs
rename to src/ComputeSharp.Core/Primitives/Bool/Bool3.g.cs
index a70a8163..018577c6 100644
--- a/src/ComputeSharp/Core/Primitives/Bool/Bool3.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Bool/Bool3.g.cs
@@ -1,8 +1,8 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool3.tt b/src/ComputeSharp.Core/Primitives/Bool/Bool3.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Bool/Bool3.tt
rename to src/ComputeSharp.Core/Primitives/Bool/Bool3.tt
diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool4.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool4.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Bool/Bool4.cs
rename to src/ComputeSharp.Core/Primitives/Bool/Bool4.cs
diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool4.g.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool4.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Bool/Bool4.g.cs
rename to src/ComputeSharp.Core/Primitives/Bool/Bool4.g.cs
index 699eb862..175339be 100644
--- a/src/ComputeSharp/Core/Primitives/Bool/Bool4.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Bool/Bool4.g.cs
@@ -1,8 +1,8 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool4.tt b/src/ComputeSharp.Core/Primitives/Bool/Bool4.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Bool/Bool4.tt
rename to src/ComputeSharp.Core/Primitives/Bool/Bool4.tt
diff --git a/src/ComputeSharp/Core/Primitives/Bool/BoolMxN.g.cs b/src/ComputeSharp.Core/Primitives/Bool/BoolMxN.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Bool/BoolMxN.g.cs
rename to src/ComputeSharp.Core/Primitives/Bool/BoolMxN.g.cs
index e34bc6bf..3925f701 100644
--- a/src/ComputeSharp/Core/Primitives/Bool/BoolMxN.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Bool/BoolMxN.g.cs
@@ -1,8 +1,8 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
namespace ComputeSharp;
diff --git a/src/ComputeSharp/Core/Primitives/Bool/BoolMxN.tt b/src/ComputeSharp.Core/Primitives/Bool/BoolMxN.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Bool/BoolMxN.tt
rename to src/ComputeSharp.Core/Primitives/Bool/BoolMxN.tt
diff --git a/src/ComputeSharp/Core/Primitives/Double/Double2.cs b/src/ComputeSharp.Core/Primitives/Double/Double2.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Double/Double2.cs
rename to src/ComputeSharp.Core/Primitives/Double/Double2.cs
diff --git a/src/ComputeSharp/Core/Primitives/Double/Double2.g.cs b/src/ComputeSharp.Core/Primitives/Double/Double2.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Double/Double2.g.cs
rename to src/ComputeSharp.Core/Primitives/Double/Double2.g.cs
index fdc974de..86c06ce4 100644
--- a/src/ComputeSharp/Core/Primitives/Double/Double2.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Double/Double2.g.cs
@@ -3,8 +3,8 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/Double/Double2.tt b/src/ComputeSharp.Core/Primitives/Double/Double2.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Double/Double2.tt
rename to src/ComputeSharp.Core/Primitives/Double/Double2.tt
diff --git a/src/ComputeSharp/Core/Primitives/Double/Double3.cs b/src/ComputeSharp.Core/Primitives/Double/Double3.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Double/Double3.cs
rename to src/ComputeSharp.Core/Primitives/Double/Double3.cs
diff --git a/src/ComputeSharp/Core/Primitives/Double/Double3.g.cs b/src/ComputeSharp.Core/Primitives/Double/Double3.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Double/Double3.g.cs
rename to src/ComputeSharp.Core/Primitives/Double/Double3.g.cs
index b9eecdc9..6bad3710 100644
--- a/src/ComputeSharp/Core/Primitives/Double/Double3.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Double/Double3.g.cs
@@ -3,8 +3,8 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/Double/Double3.tt b/src/ComputeSharp.Core/Primitives/Double/Double3.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Double/Double3.tt
rename to src/ComputeSharp.Core/Primitives/Double/Double3.tt
diff --git a/src/ComputeSharp/Core/Primitives/Double/Double4.cs b/src/ComputeSharp.Core/Primitives/Double/Double4.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Double/Double4.cs
rename to src/ComputeSharp.Core/Primitives/Double/Double4.cs
diff --git a/src/ComputeSharp/Core/Primitives/Double/Double4.g.cs b/src/ComputeSharp.Core/Primitives/Double/Double4.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Double/Double4.g.cs
rename to src/ComputeSharp.Core/Primitives/Double/Double4.g.cs
index 6b1a6b8e..47a8035a 100644
--- a/src/ComputeSharp/Core/Primitives/Double/Double4.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Double/Double4.g.cs
@@ -3,8 +3,8 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/Double/Double4.tt b/src/ComputeSharp.Core/Primitives/Double/Double4.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Double/Double4.tt
rename to src/ComputeSharp.Core/Primitives/Double/Double4.tt
diff --git a/src/ComputeSharp/Core/Primitives/Double/DoubleMxN.g.cs b/src/ComputeSharp.Core/Primitives/Double/DoubleMxN.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Double/DoubleMxN.g.cs
rename to src/ComputeSharp.Core/Primitives/Double/DoubleMxN.g.cs
index dfbca48e..0090b66a 100644
--- a/src/ComputeSharp/Core/Primitives/Double/DoubleMxN.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Double/DoubleMxN.g.cs
@@ -1,8 +1,8 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
namespace ComputeSharp;
diff --git a/src/ComputeSharp/Core/Primitives/Double/DoubleMxN.tt b/src/ComputeSharp.Core/Primitives/Double/DoubleMxN.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Double/DoubleMxN.tt
rename to src/ComputeSharp.Core/Primitives/Double/DoubleMxN.tt
diff --git a/src/ComputeSharp/Core/Primitives/Float/Float2.cs b/src/ComputeSharp.Core/Primitives/Float/Float2.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Float/Float2.cs
rename to src/ComputeSharp.Core/Primitives/Float/Float2.cs
diff --git a/src/ComputeSharp/Core/Primitives/Float/Float2.g.cs b/src/ComputeSharp.Core/Primitives/Float/Float2.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Float/Float2.g.cs
rename to src/ComputeSharp.Core/Primitives/Float/Float2.g.cs
index 0f398339..e1962a1a 100644
--- a/src/ComputeSharp/Core/Primitives/Float/Float2.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Float/Float2.g.cs
@@ -3,8 +3,8 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/Float/Float2.tt b/src/ComputeSharp.Core/Primitives/Float/Float2.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Float/Float2.tt
rename to src/ComputeSharp.Core/Primitives/Float/Float2.tt
diff --git a/src/ComputeSharp/Core/Primitives/Float/Float3.cs b/src/ComputeSharp.Core/Primitives/Float/Float3.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Float/Float3.cs
rename to src/ComputeSharp.Core/Primitives/Float/Float3.cs
diff --git a/src/ComputeSharp/Core/Primitives/Float/Float3.g.cs b/src/ComputeSharp.Core/Primitives/Float/Float3.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Float/Float3.g.cs
rename to src/ComputeSharp.Core/Primitives/Float/Float3.g.cs
index 59c29513..22887d9d 100644
--- a/src/ComputeSharp/Core/Primitives/Float/Float3.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Float/Float3.g.cs
@@ -3,8 +3,8 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/Float/Float3.tt b/src/ComputeSharp.Core/Primitives/Float/Float3.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Float/Float3.tt
rename to src/ComputeSharp.Core/Primitives/Float/Float3.tt
diff --git a/src/ComputeSharp/Core/Primitives/Float/Float4.cs b/src/ComputeSharp.Core/Primitives/Float/Float4.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Float/Float4.cs
rename to src/ComputeSharp.Core/Primitives/Float/Float4.cs
diff --git a/src/ComputeSharp/Core/Primitives/Float/Float4.g.cs b/src/ComputeSharp.Core/Primitives/Float/Float4.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Float/Float4.g.cs
rename to src/ComputeSharp.Core/Primitives/Float/Float4.g.cs
index 6f3f7a5a..c22bb7fe 100644
--- a/src/ComputeSharp/Core/Primitives/Float/Float4.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Float/Float4.g.cs
@@ -3,8 +3,8 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/Float/Float4.tt b/src/ComputeSharp.Core/Primitives/Float/Float4.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Float/Float4.tt
rename to src/ComputeSharp.Core/Primitives/Float/Float4.tt
diff --git a/src/ComputeSharp/Core/Primitives/Float/FloatMxN.g.cs b/src/ComputeSharp.Core/Primitives/Float/FloatMxN.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Float/FloatMxN.g.cs
rename to src/ComputeSharp.Core/Primitives/Float/FloatMxN.g.cs
index 6a838b30..54194c88 100644
--- a/src/ComputeSharp/Core/Primitives/Float/FloatMxN.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Float/FloatMxN.g.cs
@@ -1,8 +1,8 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
namespace ComputeSharp;
diff --git a/src/ComputeSharp/Core/Primitives/Float/FloatMxN.tt b/src/ComputeSharp.Core/Primitives/Float/FloatMxN.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Float/FloatMxN.tt
rename to src/ComputeSharp.Core/Primitives/Float/FloatMxN.tt
diff --git a/src/ComputeSharp/Core/Primitives/Int/Int2.cs b/src/ComputeSharp.Core/Primitives/Int/Int2.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Int/Int2.cs
rename to src/ComputeSharp.Core/Primitives/Int/Int2.cs
diff --git a/src/ComputeSharp/Core/Primitives/Int/Int2.g.cs b/src/ComputeSharp.Core/Primitives/Int/Int2.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Int/Int2.g.cs
rename to src/ComputeSharp.Core/Primitives/Int/Int2.g.cs
index 4ecee7dd..af6218ba 100644
--- a/src/ComputeSharp/Core/Primitives/Int/Int2.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Int/Int2.g.cs
@@ -3,8 +3,8 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/Int/Int2.tt b/src/ComputeSharp.Core/Primitives/Int/Int2.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Int/Int2.tt
rename to src/ComputeSharp.Core/Primitives/Int/Int2.tt
diff --git a/src/ComputeSharp/Core/Primitives/Int/Int3.cs b/src/ComputeSharp.Core/Primitives/Int/Int3.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Int/Int3.cs
rename to src/ComputeSharp.Core/Primitives/Int/Int3.cs
diff --git a/src/ComputeSharp/Core/Primitives/Int/Int3.g.cs b/src/ComputeSharp.Core/Primitives/Int/Int3.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Int/Int3.g.cs
rename to src/ComputeSharp.Core/Primitives/Int/Int3.g.cs
index 40afd255..6b64d48c 100644
--- a/src/ComputeSharp/Core/Primitives/Int/Int3.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Int/Int3.g.cs
@@ -3,8 +3,8 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/Int/Int3.tt b/src/ComputeSharp.Core/Primitives/Int/Int3.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Int/Int3.tt
rename to src/ComputeSharp.Core/Primitives/Int/Int3.tt
diff --git a/src/ComputeSharp/Core/Primitives/Int/Int4.cs b/src/ComputeSharp.Core/Primitives/Int/Int4.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Int/Int4.cs
rename to src/ComputeSharp.Core/Primitives/Int/Int4.cs
diff --git a/src/ComputeSharp/Core/Primitives/Int/Int4.g.cs b/src/ComputeSharp.Core/Primitives/Int/Int4.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Int/Int4.g.cs
rename to src/ComputeSharp.Core/Primitives/Int/Int4.g.cs
index a38f14a3..0189a123 100644
--- a/src/ComputeSharp/Core/Primitives/Int/Int4.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Int/Int4.g.cs
@@ -3,8 +3,8 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/Int/Int4.tt b/src/ComputeSharp.Core/Primitives/Int/Int4.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Int/Int4.tt
rename to src/ComputeSharp.Core/Primitives/Int/Int4.tt
diff --git a/src/ComputeSharp/Core/Primitives/Int/IntMxN.g.cs b/src/ComputeSharp.Core/Primitives/Int/IntMxN.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/Int/IntMxN.g.cs
rename to src/ComputeSharp.Core/Primitives/Int/IntMxN.g.cs
index 5b48b091..7f37623c 100644
--- a/src/ComputeSharp/Core/Primitives/Int/IntMxN.g.cs
+++ b/src/ComputeSharp.Core/Primitives/Int/IntMxN.g.cs
@@ -1,8 +1,8 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
namespace ComputeSharp;
diff --git a/src/ComputeSharp/Core/Primitives/Int/IntMxN.tt b/src/ComputeSharp.Core/Primitives/Int/IntMxN.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/Int/IntMxN.tt
rename to src/ComputeSharp.Core/Primitives/Int/IntMxN.tt
diff --git a/src/ComputeSharp/Core/Primitives/MatrixIndex.cs b/src/ComputeSharp.Core/Primitives/MatrixIndex.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/MatrixIndex.cs
rename to src/ComputeSharp.Core/Primitives/MatrixIndex.cs
diff --git a/src/ComputeSharp/Core/Primitives/MatrixType.ttinclude b/src/ComputeSharp.Core/Primitives/MatrixType.ttinclude
similarity index 98%
rename from src/ComputeSharp/Core/Primitives/MatrixType.ttinclude
rename to src/ComputeSharp.Core/Primitives/MatrixType.ttinclude
index 01e662d5..e39de84a 100644
--- a/src/ComputeSharp/Core/Primitives/MatrixType.ttinclude
+++ b/src/ComputeSharp.Core/Primitives/MatrixType.ttinclude
@@ -13,8 +13,8 @@ void GenerateAllMatrixProperties(string typeName, int elementSize)
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
namespace ComputeSharp;
diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt2.cs b/src/ComputeSharp.Core/Primitives/UInt/UInt2.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/UInt/UInt2.cs
rename to src/ComputeSharp.Core/Primitives/UInt/UInt2.cs
diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt2.g.cs b/src/ComputeSharp.Core/Primitives/UInt/UInt2.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/UInt/UInt2.g.cs
rename to src/ComputeSharp.Core/Primitives/UInt/UInt2.g.cs
index b45dd25e..3de44ea2 100644
--- a/src/ComputeSharp/Core/Primitives/UInt/UInt2.g.cs
+++ b/src/ComputeSharp.Core/Primitives/UInt/UInt2.g.cs
@@ -3,8 +3,8 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt2.tt b/src/ComputeSharp.Core/Primitives/UInt/UInt2.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/UInt/UInt2.tt
rename to src/ComputeSharp.Core/Primitives/UInt/UInt2.tt
diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt3.cs b/src/ComputeSharp.Core/Primitives/UInt/UInt3.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/UInt/UInt3.cs
rename to src/ComputeSharp.Core/Primitives/UInt/UInt3.cs
diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt3.g.cs b/src/ComputeSharp.Core/Primitives/UInt/UInt3.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/UInt/UInt3.g.cs
rename to src/ComputeSharp.Core/Primitives/UInt/UInt3.g.cs
index 38114335..1a754e1a 100644
--- a/src/ComputeSharp/Core/Primitives/UInt/UInt3.g.cs
+++ b/src/ComputeSharp.Core/Primitives/UInt/UInt3.g.cs
@@ -3,8 +3,8 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt3.tt b/src/ComputeSharp.Core/Primitives/UInt/UInt3.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/UInt/UInt3.tt
rename to src/ComputeSharp.Core/Primitives/UInt/UInt3.tt
diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt4.cs b/src/ComputeSharp.Core/Primitives/UInt/UInt4.cs
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/UInt/UInt4.cs
rename to src/ComputeSharp.Core/Primitives/UInt/UInt4.cs
diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt4.g.cs b/src/ComputeSharp.Core/Primitives/UInt/UInt4.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/UInt/UInt4.g.cs
rename to src/ComputeSharp.Core/Primitives/UInt/UInt4.g.cs
index 694718aa..e78eb14e 100644
--- a/src/ComputeSharp/Core/Primitives/UInt/UInt4.g.cs
+++ b/src/ComputeSharp.Core/Primitives/UInt/UInt4.g.cs
@@ -3,8 +3,8 @@ using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt4.tt b/src/ComputeSharp.Core/Primitives/UInt/UInt4.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/UInt/UInt4.tt
rename to src/ComputeSharp.Core/Primitives/UInt/UInt4.tt
diff --git a/src/ComputeSharp/Core/Primitives/UInt/UIntMxN.g.cs b/src/ComputeSharp.Core/Primitives/UInt/UIntMxN.g.cs
similarity index 99%
rename from src/ComputeSharp/Core/Primitives/UInt/UIntMxN.g.cs
rename to src/ComputeSharp.Core/Primitives/UInt/UIntMxN.g.cs
index b0359271..b2049e19 100644
--- a/src/ComputeSharp/Core/Primitives/UInt/UIntMxN.g.cs
+++ b/src/ComputeSharp.Core/Primitives/UInt/UIntMxN.g.cs
@@ -1,8 +1,8 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
namespace ComputeSharp;
diff --git a/src/ComputeSharp/Core/Primitives/UInt/UIntMxN.tt b/src/ComputeSharp.Core/Primitives/UInt/UIntMxN.tt
similarity index 100%
rename from src/ComputeSharp/Core/Primitives/UInt/UIntMxN.tt
rename to src/ComputeSharp.Core/Primitives/UInt/UIntMxN.tt
diff --git a/src/ComputeSharp/Core/Primitives/VectorType.ttinclude b/src/ComputeSharp.Core/Primitives/VectorType.ttinclude
similarity index 98%
rename from src/ComputeSharp/Core/Primitives/VectorType.ttinclude
rename to src/ComputeSharp.Core/Primitives/VectorType.ttinclude
index acf95d3b..de653781 100644
--- a/src/ComputeSharp/Core/Primitives/VectorType.ttinclude
+++ b/src/ComputeSharp.Core/Primitives/VectorType.ttinclude
@@ -61,8 +61,8 @@ void GenerateVectorProperties(string typeName, int elementSize)
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
-using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
+using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
+using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal;
#endif
#nullable enable
diff --git a/src/ComputeSharp.Core/Properties/AssemblyInfo.cs b/src/ComputeSharp.Core/Properties/AssemblyInfo.cs
new file mode 100644
index 00000000..0a698d43
--- /dev/null
+++ b/src/ComputeSharp.Core/Properties/AssemblyInfo.cs
@@ -0,0 +1,9 @@
+using System.Runtime.CompilerServices;
+
+[module: SkipLocalsInit]
+
+[assembly: InternalsVisibleTo("ComputeSharp")]
+[assembly: InternalsVisibleTo("ComputeSharp.Dynamic")]
+[assembly: InternalsVisibleTo("ComputeSharp.Uwp")]
+[assembly: InternalsVisibleTo("ComputeSharp.WinUI")]
+[assembly: InternalsVisibleTo("ComputeSharp.D2D1")]
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems
new file mode 100644
index 00000000..5e0080d3
--- /dev/null
+++ b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems
@@ -0,0 +1,21 @@
+
+
+
+ $(MSBuildAllProjects);$(MSBuildThisFileFullPath)
+ true
+ 2608eb41-f98b-4be5-9f4d-68fed6115088
+
+
+ ComputeSharp.D2D1.NetStandard
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.shproj b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.shproj
new file mode 100644
index 00000000..78c7c427
--- /dev/null
+++ b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.shproj
@@ -0,0 +1,13 @@
+
+
+
+ 2608eb41-f98b-4be5-9f4d-68fed6115088
+ 14.0
+
+
+
+
+
+
+
+
diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Buffers/BitOperations.cs b/src/ComputeSharp.D2D1.NetStandard/System/Buffers/BitOperations.cs
new file mode 100644
index 00000000..a8f36d90
--- /dev/null
+++ b/src/ComputeSharp.D2D1.NetStandard/System/Buffers/BitOperations.cs
@@ -0,0 +1,32 @@
+using System.Runtime.CompilerServices;
+
+namespace ComputeSharp.D2D1.NetStandard.System.Buffers;
+
+///
+/// A polyfill type that mirrors some methods from on .NET 6.
+///
+internal static class BitOperations
+{
+ ///
+ /// Rounds the given integral value up to a power of 2.
+ ///
+ /// The value.
+ ///
+ /// The smallest power of 2 which is greater than or equal to .
+ /// If is 0 or the result overflows, returns 0.
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static uint RoundUpToPowerOf2(uint value)
+ {
+ // Based on https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
+ --value;
+
+ value |= value >> 1;
+ value |= value >> 2;
+ value |= value >> 4;
+ value |= value >> 8;
+ value |= value >> 16;
+
+ return value + 1;
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs b/src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs
new file mode 100644
index 00000000..1c6a222e
--- /dev/null
+++ b/src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.Diagnostics.CodeAnalysis;
+
+///
+/// Applied to a method that will never return under any circumstance.
+///
+/// Internal copy from the BCL attribute.
+[AttributeUsage(AttributeTargets.Method, Inherited = false)]
+internal sealed class DoesNotReturnAttribute : Attribute
+{
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Math.cs b/src/ComputeSharp.D2D1.NetStandard/System/Math.cs
new file mode 100644
index 00000000..7885d997
--- /dev/null
+++ b/src/ComputeSharp.D2D1.NetStandard/System/Math.cs
@@ -0,0 +1,46 @@
+using System.Runtime.CompilerServices;
+
+namespace ComputeSharp.D2D1.NetStandard.System;
+
+///
+/// A polyfill type that mirrors some methods from on .NET 6.
+///
+internal static class Math
+{
+ ///
+ /// Returns clamped to the inclusive range of and .
+ ///
+ /// The value to be clamped.
+ /// The lower bound of the result.
+ /// The upper bound of the result.
+ /// The input value clamped to the inclusive range of and .
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static int Clamp(int value, int min, int max)
+ {
+ if (value < min)
+ {
+ return min;
+ }
+
+ if (value > max)
+ {
+ return max;
+ }
+
+ return value;
+ }
+
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static int Min(int val1, int val2)
+ {
+ return global::System.Math.Min(val1, val2);
+ }
+
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static int Max(int val1, int val2)
+ {
+ return global::System.Math.Max(val1, val2);
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/ComputeSharp.D2D1.NetStandard/System/Runtime/CompilerServices/RuntimeHelpers.cs
new file mode 100644
index 00000000..b7a2c4ee
--- /dev/null
+++ b/src/ComputeSharp.D2D1.NetStandard/System/Runtime/CompilerServices/RuntimeHelpers.cs
@@ -0,0 +1,18 @@
+using System;
+using System.Runtime.InteropServices;
+
+namespace ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices;
+
+///
+/// A polyfill type that mirrors some methods from on .NET 5.
+///
+internal static class RuntimeHelpers
+{
+ ///
+ /// Allocates some memory tied to the lifetime of a specific type.
+ ///
+ /// The type to associate the memory to.
+ /// The size in byte of the memory to allocate.
+ /// A pointer to the allocated memory.
+ public static IntPtr AllocateTypeAssociatedMemory(Type type, int size) => Marshal.AllocHGlobal(size);
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Text/EncodingExtensions.cs b/src/ComputeSharp.D2D1.NetStandard/System/Text/EncodingExtensions.cs
new file mode 100644
index 00000000..4f9f5f47
--- /dev/null
+++ b/src/ComputeSharp.D2D1.NetStandard/System/Text/EncodingExtensions.cs
@@ -0,0 +1,41 @@
+using System;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace ComputeSharp.D2D1.NetStandard.System.Text;
+
+///
+/// A polyfill type that mirrors some methods from on .NET 5.
+///
+internal static class EncodingExtensions
+{
+ ///
+ /// Encodes into a span of bytes a set of characters from the specified read-only span.
+ ///
+ /// The input instance to use.
+ /// The span containing the set of characters to encode.
+ /// The byte span to hold the encoded bytes.
+ /// The number of encoded bytes.
+ public static unsafe int GetBytes(this Encoding encoding, ReadOnlySpan chars, Span bytes)
+ {
+ fixed (char* charsPtr = &MemoryMarshal.GetReference(chars))
+ fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes))
+ {
+ return encoding.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length);
+ }
+ }
+
+ ///
+ /// Decodes a text from a sequence of bytes.
+ ///
+ /// The input instance to use.
+ /// The byte span that holds the encoded bytes.
+ /// The resulting text.
+ public static unsafe string GetString(this Encoding encoding, ReadOnlySpan bytes)
+ {
+ fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes))
+ {
+ return encoding.GetString(bytesPtr, bytes.Length);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.Package/ComputeSharp.D2D1.Package.msbuildproj b/src/ComputeSharp.D2D1.Package/ComputeSharp.D2D1.Package.msbuildproj
new file mode 100644
index 00000000..2e056410
--- /dev/null
+++ b/src/ComputeSharp.D2D1.Package/ComputeSharp.D2D1.Package.msbuildproj
@@ -0,0 +1,28 @@
+
+
+
+ net6.0
+
+
+
+ ComputeSharp.D2D1
+ ComputeSharp.D2D1
+ A library to write D2D1 pixel shaders entirely with C# code, and to easily register and create ID2D1Effect-s from them
+
+
+
+
+
+
+
+
+
+
+ PackageVersion=$(PackageVersion)
+
+
+ PackageVersion=$(PackageVersion)
+
+
+
+
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md
new file mode 100644
index 00000000..6cbb9ede
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md
@@ -0,0 +1,50 @@
+; Shipped analyzer releases
+; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
+
+## Release 1.0
+
+### New Rules
+
+Rule ID | Category | Severity | Notes
+--------|----------|----------|-------
+CMPSD2D0001 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0002 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0003 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0004 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0005 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0006 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0007 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0008 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0009 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0010 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0011 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0012 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0013 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0014 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0015 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0016 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0017 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0018 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0019 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0020 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0021 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0022 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0023 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0024 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0025 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0026 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0027 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0028 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0029 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0030 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0031 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0032 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0033 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0034 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0035 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0036 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0037 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0038 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0039 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0040 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPSD2D0041 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Unshipped.md
new file mode 100644
index 00000000..6a6dd08d
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Unshipped.md
@@ -0,0 +1,2 @@
+; Unshipped analyzer release
+; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj
new file mode 100644
index 00000000..095fcb7d
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj
@@ -0,0 +1,104 @@
+
+
+
+ netstandard2.0
+ false
+ ComputeSharp.D2D1.SourceGenerators
+ $(NoWarn);CS1591;CS0649;CS1574
+
+
+
+ $(DefineConstants);SOURCE_GENERATOR
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
new file mode 100644
index 00000000..9d65598d
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
@@ -0,0 +1,586 @@
+using Microsoft.CodeAnalysis;
+
+namespace ComputeSharp.D2D1.SourceGenerators.Diagnostics;
+
+#pragma warning disable IDE0090 // Use 'new(...)'
+
+///
+/// A container for all instances for errors reported by analyzers in this project.
+///
+internal static class DiagnosticDescriptors
+{
+ ///
+ /// Gets a for an invalid shader field.
+ ///
+ /// Format: "The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor InvalidShaderField = new DiagnosticDescriptor(
+ id: "CMPSD2D0001",
+ title: "Invalid shader field",
+ messageFormat: "The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A type representing a compute shader contains a field of a type that is not supported in HLSL.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid object creation expression.
+ ///
+ /// Format: "The type {0} cannot be created in a compute shader".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor InvalidObjectCreationExpression = new DiagnosticDescriptor(
+ id: "CMPSD2D0002",
+ title: "Invalid object creation expression",
+ messageFormat: "The type {0} cannot be created in a compute shader (only unmanaged types are supported)",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "Only unmanaged value type objects can be created in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an anonymous object creation expression.
+ ///
+ public static readonly DiagnosticDescriptor AnonymousObjectCreationExpression = new DiagnosticDescriptor(
+ id: "CMPSD2D0003",
+ title: "Anonymous object creation expression",
+ messageFormat: "An anonymous object cannot be created in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "An anonymous object cannot be created in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an async modifier on a method or function.
+ ///
+ public static readonly DiagnosticDescriptor AsyncModifierOnMethodOrFunction = new DiagnosticDescriptor(
+ id: "CMPSD2D0004",
+ title: "Async modifier on method or function",
+ messageFormat: "The async modifier cannot be used in methods or functions used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The async modifier cannot be used in methods or functions used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an await expression.
+ ///
+ public static readonly DiagnosticDescriptor AwaitExpression = new DiagnosticDescriptor(
+ id: "CMPSD2D0005",
+ title: "Await expression",
+ messageFormat: "The await expression cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The await expression cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a checked expression.
+ ///
+ public static readonly DiagnosticDescriptor CheckedExpression = new DiagnosticDescriptor(
+ id: "CMPSD2D0006",
+ title: "Checked expression",
+ messageFormat: "A checked expression cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A checked expression cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a checked statement.
+ ///
+ public static readonly DiagnosticDescriptor CheckedStatement = new DiagnosticDescriptor(
+ id: "CMPSD2D0007",
+ title: "Checked statement",
+ messageFormat: "A checked statement cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A checked statement cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a fixed statement.
+ ///
+ public static readonly DiagnosticDescriptor FixedStatement = new DiagnosticDescriptor(
+ id: "CMPSD2D0008",
+ title: "Fixed statement",
+ messageFormat: "A fixed statement cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A fixed statement cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a foreach statement.
+ ///
+ public static readonly DiagnosticDescriptor ForEachStatement = new DiagnosticDescriptor(
+ id: "CMPSD2D0009",
+ title: "Foreach statement",
+ messageFormat: "A foreach statement cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A foreach statement cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a lock statement.
+ ///
+ public static readonly DiagnosticDescriptor LockStatement = new DiagnosticDescriptor(
+ id: "CMPSD2D0010",
+ title: "Foreach statement",
+ messageFormat: "A lock statement cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A lock statement cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a query statement.
+ ///
+ public static readonly DiagnosticDescriptor QueryExpression = new DiagnosticDescriptor(
+ id: "CMPSD2D0011",
+ title: "Foreach statement",
+ messageFormat: "A LINQ query expression cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A LINQ query expression cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a range expression.
+ ///
+ public static readonly DiagnosticDescriptor RangeExpression = new DiagnosticDescriptor(
+ id: "CMPSD2D0012",
+ title: "Range expression",
+ messageFormat: "A range expression cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A range expression cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a recursive pattern.
+ ///
+ public static readonly DiagnosticDescriptor RecursivePattern = new DiagnosticDescriptor(
+ id: "CMPSD2D0013",
+ title: "Recursive pattern",
+ messageFormat: "A recursive pattern cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A recursive pattern cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a ref type.
+ ///
+ public static readonly DiagnosticDescriptor RefType = new DiagnosticDescriptor(
+ id: "CMPSD2D0014",
+ title: "Ref type",
+ messageFormat: "A compute shader cannot have a ref type declaration",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A compute shader cannot have a ref type declaration.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a relational pattern.
+ ///
+ public static readonly DiagnosticDescriptor RelationalPattern = new DiagnosticDescriptor(
+ id: "CMPSD2D0015",
+ title: "Relational pattern",
+ messageFormat: "A relational pattern cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A relational pattern cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a sizeof expression.
+ ///
+ public static readonly DiagnosticDescriptor SizeOfExpression = new DiagnosticDescriptor(
+ id: "CMPSD2D0016",
+ title: "Sizeof expression",
+ messageFormat: "A sizeof expression cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A sizeof expression cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a stackalloc expression.
+ ///
+ public static readonly DiagnosticDescriptor StackAllocArrayCreationExpression = new DiagnosticDescriptor(
+ id: "CMPSD2D0017",
+ title: "Stackalloc expression",
+ messageFormat: "A stackalloc expression cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A stackalloc expression cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a throw expression or statement.
+ ///
+ public static readonly DiagnosticDescriptor ThrowExpressionOrStatement = new DiagnosticDescriptor(
+ id: "CMPSD2D0018",
+ title: "Throw expression or statement",
+ messageFormat: "Throw expressions and statements cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "Throw expressions and statements cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a try statement.
+ ///
+ public static readonly DiagnosticDescriptor TryStatement = new DiagnosticDescriptor(
+ id: "CMPSD2D0019",
+ title: "Try statement",
+ messageFormat: "A try statement cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A try statement cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a tuple type.
+ ///
+ public static readonly DiagnosticDescriptor TupleType = new DiagnosticDescriptor(
+ id: "CMPSD2D0020",
+ title: "Tuple type",
+ messageFormat: "A compute shader cannot have a tuple type declaration",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A compute shader cannot have a tuple type declaration.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a using statement or declaration.
+ ///
+ public static readonly DiagnosticDescriptor UsingStatementOrDeclaration = new DiagnosticDescriptor(
+ id: "CMPSD2D0021",
+ title: "Using statement or declaration",
+ messageFormat: "Using statements and declarations cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "Using statements and declarations cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a yield statement.
+ ///
+ public static readonly DiagnosticDescriptor YieldStatement = new DiagnosticDescriptor(
+ id: "CMPSD2D0022",
+ title: "Yield statement",
+ messageFormat: "A yield statement cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A yield statement cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid object declaration.
+ ///
+ /// Format: "A variable of type {0} cannot be declared in a compute shader".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor InvalidObjectDeclaration = new DiagnosticDescriptor(
+ id: "CMPSD2D0023",
+ title: "Invalid object declaration",
+ messageFormat: "A variable of type {0} cannot be declared in a compute shader (only unmanaged types are supported)",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "Only unmanaged value type objects can be declared in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a pointer type.
+ ///
+ public static readonly DiagnosticDescriptor PointerType = new DiagnosticDescriptor(
+ id: "CMPSD2D0024",
+ title: "Pointer type",
+ messageFormat: "A compute shader cannot have a pointer type declaration",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A compute shader cannot have a pointer type declaration.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a function pointer type.
+ ///
+ public static readonly DiagnosticDescriptor FunctionPointer = new DiagnosticDescriptor(
+ id: "CMPSD2D0025",
+ title: "Function pointer type",
+ messageFormat: "A compute shader cannot have a function pointer type declaration",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A compute shader cannot have a function pointer type declaration.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an unsafe statement.
+ ///
+ public static readonly DiagnosticDescriptor UnsafeStatement = new DiagnosticDescriptor(
+ id: "CMPSD2D0026",
+ title: "Unsafe statement",
+ messageFormat: "A compute shader cannot have an unsafe statement",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A compute shader cannot have an unsafe statement.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an unsafe modifier on a method or function.
+ ///
+ public static readonly DiagnosticDescriptor UnsafeModifierOnMethodOrFunction = new DiagnosticDescriptor(
+ id: "CMPSD2D0027",
+ title: "Unsafe modifier on method or function",
+ messageFormat: "The unsafe modifier cannot be used in methods or functions used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The unsafe modifier cannot be used in methods or functions used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a string literal.
+ ///
+ public static readonly DiagnosticDescriptor StringLiteralExpression = new DiagnosticDescriptor(
+ id: "CMPSD2D0028",
+ title: "String literal expression",
+ messageFormat: "String literal expressions cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "String literal expressions cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an incorrect matrix swizzling property argument.
+ ///
+ public static readonly DiagnosticDescriptor NonConstantMatrixSwizzledIndex = new DiagnosticDescriptor(
+ id: "CMPSD2D0029",
+ title: "Non constant matrix swizzled property argument",
+ messageFormat: "The arguments in a swizzled indexer for a matrix type must be compile-time constants",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The arguments in a swizzled indexer for a matrix type must be compile-time constants.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid shader static readonly field type.
+ ///
+ /// Format: "The compute shader of type {0} contains a static readonly field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor InvalidShaderStaticFieldType = new DiagnosticDescriptor(
+ id: "CMPSD2D0030",
+ title: "Invalid shader static readonly field type",
+ messageFormat: "The compute shader of type {0} contains a static readonly field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A type representing a compute shader contains a static readonly field of a type that is not supported.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a property declaration.
+ ///
+ public static readonly DiagnosticDescriptor PropertyDeclaration = new DiagnosticDescriptor(
+ id: "CMPSD2D0031",
+ title: "Property declaration",
+ messageFormat: "Property declarations cannot be used in a compute shader",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "Property declarations cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a shader with a root signature that is too large.
+ ///
+ /// Format: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor ShaderDispatchDataSizeExceeded = new DiagnosticDescriptor(
+ id: "CMPSD2D0032",
+ title: "Shader dispatch data size exceeded",
+ messageFormat: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an embedded bytecode shader failed due to a Win32 exception.
+ ///
+ /// Format: "The shader of type {0} failed to compile due to a Win32 exception (HRESULT: {1:X8}, Message: "{2}")".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithWin32Exception = new DiagnosticDescriptor(
+ id: "CMPSD2D0033",
+ title: "Embedded bytecode compilation failed due to Win32 exception",
+ messageFormat: "The shader of type {0} failed to compile due to a Win32 exception (HRESULT: {1:X8}, Message: \"{2}\")",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The embedded bytecode for a shader failed to be compiled due to a Win32 exception.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an embedded bytecode shader failed due to an HLSL compilation exception.
+ ///
+ /// Format: "The shader of type {0} failed to compile due to an HLSL compiler error (Message: "{1}")".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithDxcCompilationException = new DiagnosticDescriptor(
+ id: "CMPSD2D0034",
+ title: "Embedded bytecode compilation failed due to an HLSL compiler error",
+ messageFormat: "The shader of type {0} failed to compile due to an HLSL compiler error (Message: \"{1}\")",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The embedded bytecode for a shader failed to be compiled due to an HLSL compiler error.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a invalid D2D input count value.
+ ///
+ /// Format: "The D2D1 shader of type {0} is using an incorrect value for [D2DInputCount] (the number of inputs must be in the [0, 8] range)".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor InvalidD2DInputCount = new DiagnosticDescriptor(
+ id: "CMPSD2D0035",
+ title: "Invalid D2D1 shader input count",
+ messageFormat: "The D2D1 shader of type {0} is using an incorrect value for [D2DInputCount] (the number of inputs must be in the [0, 8] range)",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A D2D1 shader must have a number of inputs in the [1, 8] range.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for repeated indices for D2D simple indices.
+ ///
+ /// Format: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputSimple] attributes".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor RepeatedD2DInputSimpleIndices = new DiagnosticDescriptor(
+ id: "CMPSD2D0036",
+ title: "Repeated D2D1 shader simple input indices",
+ messageFormat: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputSimple] attributes",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A D2D1 shader must only have unique indices for all of its [D2DInputSimple] attributes.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for repeated indices for D2D complex indices.
+ ///
+ /// Format: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputComplex] attributes".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor RepeatedD2DInputComplexIndices = new DiagnosticDescriptor(
+ id: "CMPSD2D0037",
+ title: "Repeated D2D1 shader complex input indices",
+ messageFormat: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputComplex] attributes",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A D2D1 shader must only have unique indices for all of its [D2DInputComplex] attributes.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for invalid combination of simple and complex indices.
+ ///
+ /// Format: "The D2D1 shader of type {0} is using some indices in common for simple and complex input indices".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor InvalidSimpleAndComplexIndicesCombination = new DiagnosticDescriptor(
+ id: "CMPSD2D0038",
+ title: "Invalid D2D1 shader simple and complex indices combination",
+ messageFormat: "The D2D1 shader of type {0} is using some indices in common for simple and complex input indices",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A D2D1 shader cannot use the same indices to indicate both simple and complex inputs.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a shader with an out of range input index (or more).
+ ///
+ /// Format: "The D2D1 shader of type {0} is using some out of range input indices".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor OutOfRangeInputIndex = new DiagnosticDescriptor(
+ id: "CMPSD2D0039",
+ title: "Our of range D2D1 shader input indices",
+ messageFormat: "The D2D1 shader of type {0} is using some out of range input indices",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A D2D1 shader must have all the indices of its simple and complex inputs in the valid range (between 0 and the number of declared inputs).",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a method invocation that is not valid from a shader.
+ ///
+ /// Format: "The method {0} cannot be used in a D2D1 shader (methods need to either be HLSL intrinsics or with source available for analysis)".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor InvalidMethodCall = new DiagnosticDescriptor(
+ id: "CMPSD2D0040",
+ title: "Invalid method invocation from a D2D1 shader",
+ messageFormat: "The method {0} cannot be used in a D2D1 shader (methods need to either be HLSL intrinsics or with source available for analysis)",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A D2D1 shader can only invoke methods that are either HLSL intrinsics or with source available for analysis.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid discovered type.
+ ///
+ /// Format: "The D2D1 shader of type {0} uses the invalid type {1}".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor InvalidDiscoveredType = new DiagnosticDescriptor(
+ id: "CMPSD2D0041",
+ title: "Invalid discovered type",
+ messageFormat: "The D2D1 shader of type {0} uses the invalid type {1} (only some .NET primitives and vector types, HLSL primitive, vector and matrix types, and custom types containing these types can be used)",
+ category: "ComputeSharp.D2D1.Shaders",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "D2D1 shaders can only use supported types (some .NET primitives and vector types, HLSL primitive, vector and matrix types, and custom types containing these types can be used).",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs
new file mode 100644
index 00000000..9676c21f
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs
@@ -0,0 +1,42 @@
+using ComputeSharp.D2D1.__Internals;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.D2D1.SourceGenerators;
+
+///
+partial class ID2D1ShaderGenerator
+{
+ ///
+ partial class BuildHlslSource
+ {
+ ///
+ /// Creates a instance for the BuildHlslSource method.
+ ///
+ /// The input HLSL source.
+ /// The resulting instance for the BuildHlslSource method.
+ public static MethodDeclarationSyntax GetSyntax(string hlslSource)
+ {
+ // This code produces a method declaration as follows:
+ //
+ // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.BuildHlslSource(out string hlslSource)
+ // {
+ // hlslSource = ;
+ // }
+ return
+ MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("BuildHlslSource"))
+ .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
+ .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
+ .AddParameterListParameters(
+ Parameter(Identifier("hlslSource")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(PredefinedType(Token(SyntaxKind.StringKeyword))))
+ .WithBody(Block(ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ IdentifierName("hlslSource"),
+ LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(hlslSource))))));
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs
new file mode 100644
index 00000000..f68e444d
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs
@@ -0,0 +1,608 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Linq;
+using System.Text;
+using ComputeSharp.D2D1.SourceGenerators.Diagnostics;
+using ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
+using ComputeSharp.SourceGeneration.Mappings;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+#pragma warning disable CS0618, RS1024
+
+namespace ComputeSharp.D2D1.SourceGenerators;
+
+///
+partial class ID2D1ShaderGenerator
+{
+ ///
+ /// A helper with all logic to generate the BuildHlslSource method.
+ ///
+ internal static partial class BuildHlslSource
+ {
+ ///
+ /// Gathers all necessary information on a transpiled HLSL source for a given shader type.
+ ///
+ /// The input object currently in use.
+ /// The node to process.
+ /// The for .
+ /// The number of inputs for the shader.
+ /// The resulting diagnostics from the processing operation.
+ /// The HLSL source for the shader.
+ public static string GetHlslSource(
+ Compilation compilation,
+ StructDeclarationSyntax structDeclaration,
+ INamedTypeSymbol structDeclarationSymbol,
+ out int inputCount,
+ out ImmutableArray diagnostics)
+ {
+ ImmutableArray.Builder builder = ImmutableArray.CreateBuilder();
+
+ // Properties are not supported
+ DetectAndReportPropertyDeclarations(builder, structDeclarationSymbol);
+
+ // We need to sets to track all discovered custom types and static methods
+ HashSet discoveredTypes = new(SymbolEqualityComparer.Default);
+ Dictionary staticMethods = new(SymbolEqualityComparer.Default);
+ Dictionary constantDefinitions = new(SymbolEqualityComparer.Default);
+
+ // Explore the syntax tree and extract the processed info
+ var semanticModelProvider = new SemanticModelProvider(compilation);
+ var valueFields = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes);
+ var (entryPoint, processedMethods) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions);
+ var declaredTypes = GetDeclaredTypes(builder, structDeclarationSymbol, discoveredTypes);
+ var definedConstants = GetDefinedConstants(constantDefinitions);
+ var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
+
+ // Gather the shader metadata
+ GatherD2D1AttributeInfo(
+ builder,
+ structDeclarationSymbol,
+ out inputCount,
+ out ImmutableArray inputSimpleIndices,
+ out ImmutableArray inputComplexIndices,
+ out bool requiresScenePosition);
+
+ diagnostics = builder.ToImmutable();
+
+ // Get the HLSL source
+ return GetHlslSource(
+ definedConstants,
+ declaredTypes,
+ valueFields,
+ staticFields,
+ processedMethods,
+ entryPoint,
+ inputCount,
+ inputSimpleIndices,
+ inputComplexIndices,
+ requiresScenePosition);
+ }
+
+ ///
+ /// Gets a sequence of captured fields and their mapped names.
+ ///
+ /// The collection of produced instances.
+ /// The input instance to process.
+ /// The collection of currently discovered types.
+ /// A sequence of captured fields in .
+ private static ImmutableArray<(string Name, string HlslType)> GetInstanceFields(
+ ImmutableArray.Builder diagnostics,
+ INamedTypeSymbol structDeclarationSymbol,
+ ICollection types)
+ {
+ ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>();
+
+ foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
+ {
+ if (fieldSymbol.IsStatic)
+ {
+ continue;
+ }
+
+ // Captured fields must be named type symbols
+ if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol)
+ {
+ diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
+
+ continue;
+ }
+
+ string metadataName = typeSymbol.GetFullMetadataName();
+ string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
+
+ _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
+
+ // Allowed fields must be unmanaged values
+ if (typeSymbol.IsUnmanagedType)
+ {
+ // Track the type if it's a custom struct
+ if (!HlslKnownTypes.IsKnownHlslType(metadataName))
+ {
+ types.Add(typeSymbol);
+ }
+
+ values.Add((mapping ?? fieldSymbol.Name, typeName));
+ }
+ else
+ {
+ diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol);
+ }
+ }
+
+ return values.ToImmutable();
+ }
+
+ ///
+ /// Gets a sequence of shader static fields and their mapped names.
+ ///
+ /// The collection of produced instances.
+ /// The instance for the type to process.
+ /// The instance for the current type.
+ /// The type symbol for the shader type.
+ /// The collection of currently discovered types.
+ /// The collection of discovered constant definitions.
+ /// A sequence of static constant fields in .
+ private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
+ ImmutableArray.Builder diagnostics,
+ SemanticModelProvider semanticModel,
+ StructDeclarationSyntax structDeclaration,
+ INamedTypeSymbol structDeclarationSymbol,
+ ICollection discoveredTypes,
+ IDictionary constantDefinitions)
+ {
+ ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>();
+
+ foreach (var fieldDeclaration in structDeclaration.Members.OfType())
+ {
+ foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables)
+ {
+ IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!;
+
+ if (!fieldSymbol.IsStatic || fieldSymbol.IsConst)
+ {
+ continue;
+ }
+
+ // Constant properties must be of a primitive, vector or matrix type
+ if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol ||
+ !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName()))
+ {
+ diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
+
+ continue;
+ }
+
+ _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
+
+ string typeDeclaration = fieldSymbol.IsReadOnly switch
+ {
+ true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}",
+ false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}"
+ };
+
+ StaticFieldRewriter staticFieldRewriter = new(
+ semanticModel,
+ discoveredTypes,
+ constantDefinitions,
+ diagnostics);
+
+ string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString();
+
+ builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment));
+ }
+ }
+
+ return builder.ToImmutable();
+ }
+
+ ///
+ /// Gets a sequence of processed methods declared within a given type.
+ ///
+ /// The collection of produced instances.
+ /// The type symbol for the shader type.
+ /// The instance for the current type.
+ /// The instance for the type to process.
+ /// The collection of currently discovered types.
+ /// The set of discovered and processed static methods.
+ /// The collection of discovered constant definitions.
+ /// A sequence of processed methods in , and the entry point.
+ private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods) GetProcessedMethods(
+ ImmutableArray.Builder diagnostics,
+ StructDeclarationSyntax structDeclaration,
+ INamedTypeSymbol structDeclarationSymbol,
+ SemanticModelProvider semanticModel,
+ ICollection discoveredTypes,
+ IDictionary staticMethods,
+ IDictionary constantDefinitions)
+ {
+ // Find all declared methods in the type
+ ImmutableArray methodDeclarations = (
+ from syntaxNode in structDeclaration.DescendantNodes()
+ where syntaxNode.IsKind(SyntaxKind.MethodDeclaration)
+ select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray();
+
+ string? entryPoint = null;
+ ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>();
+
+ foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations)
+ {
+ IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!;
+ bool isShaderEntryPoint =
+ methodDeclarationSymbol.Name == nameof(ID2D1PixelShader.Execute) &&
+ methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type
+ methodDeclarationSymbol.TypeParameters.Length == 0 &&
+ methodDeclarationSymbol.Parameters.Length == 0;
+
+ // Create the source rewriter for the current method
+ ShaderSourceRewriter shaderSourceRewriter = new(
+ structDeclarationSymbol,
+ semanticModel,
+ discoveredTypes,
+ staticMethods,
+ constantDefinitions,
+ diagnostics);
+
+ // Rewrite the method syntax tree
+ MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
+
+ // Emit the extracted local functions first
+ foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
+ {
+ methods.Add((
+ localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
+ localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
+ }
+
+ // If the method is the shader entry point, do additional processing
+ if (isShaderEntryPoint)
+ {
+ string entryPointDeclaration = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString();
+ string adjustedEntryPointDeclaration = entryPointDeclaration.Replace("float4 Execute()", "D2D_PS_ENTRY(Execute)");
+
+ entryPoint = adjustedEntryPointDeclaration;
+ }
+ else
+ {
+ methods.Add((
+ processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
+ processedMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
+ }
+ }
+
+ // Process static methods as well
+ foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
+ {
+ methods.Add((
+ staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
+ staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
+ }
+
+ return (entryPoint!, methods.ToImmutable());
+ }
+
+ ///
+ /// Gets a sequence of discovered constants.
+ ///
+ /// The collection of discovered constant definitions.
+ /// A sequence of discovered constants to declare in the shader.
+ private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions)
+ {
+ ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count);
+
+ foreach (var constant in constantDefinitions)
+ {
+ var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
+ var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
+
+ builder.Add((constantName, constant.Value));
+ }
+
+ return builder.MoveToImmutable();
+ }
+
+ ///
+ /// Gets the sequence of processed discovered custom types.
+ ///
+ /// The collection of produced instances.
+ /// The type symbol for the shader type.
+ /// The sequence of discovered custom types.
+ /// A sequence of custom type definitions to add to the shader source.
+ private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
+ ImmutableArray.Builder diagnostics,
+ INamedTypeSymbol structDeclarationSymbol,
+ IEnumerable types)
+ {
+ ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>();
+ IReadOnlyCollection invalidTypes;
+
+ // Process the discovered types
+ foreach (var type in HlslKnownTypes.GetCustomTypes(types, out invalidTypes))
+ {
+ var structType = type.GetFullMetadataName().ToHlslIdentifierName();
+ var structDeclaration = StructDeclaration(structType);
+
+ // Declare the fields of the current type
+ foreach (var field in type.GetMembers().OfType())
+ {
+ if (field.IsStatic) continue;
+
+ INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
+
+ // Convert the name to the fully qualified HLSL version
+ if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped))
+ {
+ mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName();
+ }
+
+ structDeclaration = structDeclaration.AddMembers(
+ FieldDeclaration(VariableDeclaration(
+ IdentifierName(mapped!)).AddVariables(
+ VariableDeclarator(Identifier(field.Name)))));
+ }
+
+ // Insert the trailing ; right after the closing bracket (after normalization)
+ builder.Add((
+ structType,
+ structDeclaration
+ .NormalizeWhitespace(eol: "\n")
+ .WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
+ .ToFullString()));
+ }
+
+ // Process the invalid types
+ foreach (INamedTypeSymbol invalidType in invalidTypes)
+ {
+ diagnostics.Add(InvalidDiscoveredType, structDeclarationSymbol, structDeclarationSymbol, invalidType);
+ }
+
+ return builder.ToImmutable();
+ }
+
+ ///
+ /// Finds and reports all declared properties in a shader.
+ ///
+ /// The collection of produced instances.
+ /// The input instance to process.
+ private static void DetectAndReportPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
+ {
+ foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType())
+ {
+ diagnostics.Add(DiagnosticDescriptors.PropertyDeclaration, propertySymbol);
+ }
+ }
+
+ ///
+ /// Extracts the metadata definition for the current shader.
+ ///
+ /// The collection of produced instances.
+ /// The input instance to process.
+ /// The number of shader inputs to declare.
+ /// The indicess of the simple shader inputs.
+ /// The indicess of the complex shader inputs.
+ /// Whether the shader requires the scene position.
+ private static void GatherD2D1AttributeInfo(
+ ImmutableArray.Builder diagnostics,
+ INamedTypeSymbol structDeclarationSymbol,
+ out int inputCount,
+ out ImmutableArray inputSimpleIndices,
+ out ImmutableArray inputComplexIndices,
+ out bool requiresScenePosition)
+ {
+ // We need a separate local here so we can keep the original value to apply
+ // diagnostics to, but without returning invalid values to the caller which
+ // might cause generator errors (eg. -1 would cause other code to just throw).
+ int rawInputCount = 0;
+
+ inputCount = 0;
+ requiresScenePosition = false;
+
+ ImmutableArray.Builder inputSimpleIndicesBuilder = ImmutableArray.CreateBuilder();
+ ImmutableArray.Builder inputComplexIndicesBuilder = ImmutableArray.CreateBuilder();
+
+ foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes())
+ {
+ switch (attributeData.AttributeClass?.GetFullMetadataName())
+ {
+ case "ComputeSharp.D2D1.D2DInputCountAttribute":
+ rawInputCount = (int)attributeData.ConstructorArguments[0].Value!;
+ inputCount = Math.Max(rawInputCount, 0);
+ break;
+ case "ComputeSharp.D2D1.D2DInputSimpleAttribute":
+ inputSimpleIndicesBuilder.Add((int)attributeData.ConstructorArguments[0].Value!);
+ break;
+ case "ComputeSharp.D2D1.D2DInputComplexAttribute":
+ inputComplexIndicesBuilder.Add((int)attributeData.ConstructorArguments[0].Value!);
+ break;
+ case "ComputeSharp.D2D1.D2DRequiresScenePositionAttribute":
+ requiresScenePosition = true;
+ break;
+ default:
+ break;
+ }
+ }
+
+ inputSimpleIndices = inputSimpleIndicesBuilder.ToImmutable();
+ inputComplexIndices = inputComplexIndicesBuilder.ToImmutable();
+
+ // Validate the input count
+ if (rawInputCount is not (>= 0 and <= 8))
+ {
+ diagnostics.Add(InvalidD2DInputCount, structDeclarationSymbol, structDeclarationSymbol);
+
+ return;
+ }
+
+ // All simple indices must be in range
+ if (inputSimpleIndicesBuilder.Concat(inputComplexIndicesBuilder).Any(i => (uint)i >= rawInputCount))
+ {
+ diagnostics.Add(OutOfRangeInputIndex, structDeclarationSymbol, structDeclarationSymbol);
+
+ return;
+ }
+
+ HashSet inputSimpleIndicesAsSet = new(inputSimpleIndicesBuilder);
+ HashSet inputComplexIndicesAsSet = new(inputComplexIndicesBuilder);
+
+ // All simple indices must be unique
+ if (inputSimpleIndicesAsSet.Count != inputSimpleIndicesBuilder.Count)
+ {
+ diagnostics.Add(RepeatedD2DInputSimpleIndices, structDeclarationSymbol, structDeclarationSymbol);
+
+ return;
+ }
+
+ // All complex indices must be unique
+ if (inputComplexIndicesAsSet.Count != inputComplexIndicesBuilder.Count)
+ {
+ diagnostics.Add(RepeatedD2DInputComplexIndices, structDeclarationSymbol, structDeclarationSymbol);
+
+ return;
+ }
+
+ // Simple and complex indices can't have indices in common
+ if (inputSimpleIndicesAsSet.Intersect(inputComplexIndicesAsSet).Any())
+ {
+ diagnostics.Add(InvalidSimpleAndComplexIndicesCombination, structDeclarationSymbol, structDeclarationSymbol);
+
+ return;
+ }
+ }
+
+ ///
+ /// Produces the series of statements to build the current HLSL source.
+ ///
+ /// The sequence of defined constants for the shader.
+ /// The sequence of declared types used by the shader.
+ /// The sequence of value instance fields for the current shader.
+ /// The sequence of static fields referenced by the shader.
+ /// The sequence of processed methods used by the shader.
+ /// The body of the entry point of the shader.
+ /// The number of shader inputs to declare.
+ /// The indicess of the simple shader inputs.
+ /// The indicess of the complex shader inputs.
+ /// Whether the shader requires the scene position.
+ /// The series of statements to build the HLSL source to compile to execute the current shader.
+ private static string GetHlslSource(
+ ImmutableArray<(string Name, string Value)> definedConstants,
+ ImmutableArray<(string Name, string Definition)> declaredTypes,
+ ImmutableArray<(string Name, string HlslType)> valueFields,
+ ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
+ ImmutableArray<(string Signature, string Definition)> processedMethods,
+ string executeMethod,
+ int inputCount,
+ ImmutableArray inputSimpleIndices,
+ ImmutableArray inputComplexIndices,
+ bool requiresScenePosition)
+ {
+ StringBuilder hlslBuilder = new();
+
+ void AppendLF()
+ {
+ hlslBuilder.Append('\n');
+ }
+
+ void AppendLineAndLF(string text)
+ {
+ hlslBuilder.Append(text);
+ hlslBuilder.Append('\n');
+ }
+
+ // Header
+ AppendLineAndLF("// ================================================");
+ AppendLineAndLF("// AUTO GENERATED");
+ AppendLineAndLF("// ================================================");
+ AppendLineAndLF("// This shader was created by ComputeSharp.");
+ AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp.");
+ AppendLF();
+
+ // Shader metadata
+ AppendLineAndLF($"#define D2D_INPUT_COUNT {inputCount}");
+
+ foreach (int simpleInput in inputSimpleIndices)
+ {
+ AppendLineAndLF($"#define D2D_INPUT{simpleInput}_SIMPLE");
+ }
+
+ foreach (int complexInput in inputComplexIndices)
+ {
+ AppendLineAndLF($"#define D2D_INPUT{complexInput}_COMPLEX");
+ }
+
+ if (requiresScenePosition)
+ {
+ AppendLineAndLF("#define D2D_REQUIRES_SCENE_POSITION");
+ }
+
+ // Add the "d2d1effecthelpers.hlsli" header
+ AppendLF();
+ AppendLineAndLF("#include \"d2d1effecthelpers.hlsli\"");
+
+ // Define declarations
+ foreach (var (name, value) in definedConstants)
+ {
+ AppendLineAndLF($"#define {name} {value}");
+ }
+
+ // Static fields
+ if (staticFields.Any())
+ {
+ AppendLF();
+
+ foreach (var field in staticFields)
+ {
+ if (field.Assignment is string assignment)
+ {
+ AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};");
+ }
+ else
+ {
+ AppendLineAndLF($"{field.TypeDeclaration} {field.Name};");
+ }
+ }
+ }
+
+ // Declared types
+ foreach (var (_, typeDefinition) in declaredTypes)
+ {
+ AppendLF();
+ AppendLineAndLF(typeDefinition);
+ }
+
+ // Captured variables
+ AppendLF();
+
+ // User-defined values
+ foreach (var (fieldName, fieldType) in valueFields)
+ {
+ AppendLineAndLF($"{fieldType} {fieldName};");
+ }
+
+ // Forward declarations
+ foreach (var (forwardDeclaration, _) in processedMethods)
+ {
+ AppendLF();
+ AppendLineAndLF(forwardDeclaration);
+ }
+
+ // Captured methods
+ foreach (var (_, method) in processedMethods)
+ {
+ AppendLF();
+ AppendLineAndLF(method);
+ }
+
+ // Entry point
+ AppendLF();
+ AppendLineAndLF(executeMethod);
+
+ return hlslBuilder.ToString();
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs
new file mode 100644
index 00000000..fcdb1248
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs
@@ -0,0 +1,127 @@
+using System.Collections.Immutable;
+using ComputeSharp.D2D1.__Internals;
+using ComputeSharp.D2D1.SourceGenerators.Models;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.D2D1.SourceGenerators;
+
+///
+partial class ID2D1ShaderGenerator
+{
+ ///
+ partial class InitializeFromDispatchData
+ {
+ ///
+ /// Creates a instance for the InitializeFromDispatchData method.
+ ///
+ /// The dispatch info gathered for the current shader.
+ /// The resulting instance for the InitializeFromDispatchData method.
+ public static MethodDeclarationSyntax GetSyntax(DispatchDataInfo dispatchInfo)
+ {
+ // This code produces a method declaration as follows:
+ //
+ // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan data)
+ // {
+ //
+ // }
+ return
+ MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("InitializeFromDispatchData"))
+ .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
+ .AddParameterListParameters(Parameter(Identifier("data")).WithType(
+ GenericName(Identifier("global::System.ReadOnlySpan"))
+ .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))))
+ .WithBody(Block(GetDispatchDataUnloadingStatements(dispatchInfo.FieldInfos)));
+ }
+
+ ///
+ /// Gets a sequence of statements to initialize a shader from a serialized dispatch data buffer.
+ ///
+ /// The array of values for all captured fields.
+ /// The sequence of instances to initialize a shader from the serialized dispatch data buffer.
+ private static ImmutableArray GetDispatchDataUnloadingStatements(ImmutableArray fieldInfos)
+ {
+ ImmutableArray.Builder statements = ImmutableArray.CreateBuilder();
+
+ // Insert the fallback for empty shaders. This will generate the following code:
+ //
+ // if (data.IsEmpty)
+ // {
+ // return;
+ // }
+ statements.Add(
+ IfStatement(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("data"),
+ IdentifierName("IsEmpty")),
+ Block(ReturnStatement())));
+
+ // ref byte r0 = ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data);
+ statements.Add(
+ LocalDeclarationStatement(
+ VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
+ .AddVariables(
+ VariableDeclarator(Identifier("r0"))
+ .WithInitializer(EqualsValueClause(
+ RefExpression(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"),
+ IdentifierName("GetReference")))
+ .AddArgumentListArguments(Argument(IdentifierName("data")))))))));
+
+ // Generate loading statements for each captured field
+ foreach (FieldInfo fieldInfo in fieldInfos)
+ {
+ switch (fieldInfo)
+ {
+ case FieldInfo.Primitive primitive:
+
+ // Read a primitive value from the target buffer. This will generate:
+ //
+ // Unsafe.AsRef(in ) = global::System.Runtime.CompilerServices.Unsafe.As>(
+ // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)))
+ statements.Add(ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", primitive.FieldPath)})"),
+ ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"))));
+ break;
+
+ case FieldInfo.NonLinearMatrix matrix:
+ string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
+ string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0";
+
+ // Declare a local to index into individual rows. This will generate:
+ //
+ // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >(
+ // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in ));
+ statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));"));
+
+ // Generate the loading code for each individual row, with proper alignment.
+ // This will result in the following (assuming Float2x3 m):
+ //
+ // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
+ // global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0) = global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset));
+ // global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1) = global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16)));
+ for (int j = 0; j < matrix.Rows; j++)
+ {
+ statements.Add(ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"),
+ ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"))));
+ }
+ break;
+ }
+ }
+
+ return statements.ToImmutable();
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs
new file mode 100644
index 00000000..27be5445
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs
@@ -0,0 +1,187 @@
+using System;
+using ComputeSharp.__Internals;
+using ComputeSharp.D2D1.__Internals;
+using ComputeSharp.D2D1.SourceGenerators.Models;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.D2D1.SourceGenerators;
+
+///
+partial class ID2D1ShaderGenerator
+{
+ ///
+ partial class LoadBytecode
+ {
+ ///
+ /// Creates a instance for the TryGetBytecode method.
+ ///
+ /// The input bytecode info.
+ /// An opaque instance to transform the final tree into text.
+ /// The resulting instance for the BuildHlslSource method.
+ public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup)
+ {
+ BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals);
+
+ if (bytecodeLiterals is not null)
+ {
+ fixup = tree => tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals);
+ }
+ else
+ {
+ fixup = static tree => tree.ToFullString();
+ }
+
+ // This code produces a method declaration as follows:
+ //
+ // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadBytecode(ref TLoader loader, global::ComputeSharp.D2D1.D2D1ShaderProfile? shaderProfile)
+ // {
+ //
+ // }
+ return
+ MethodDeclaration(
+ PredefinedType(Token(SyntaxKind.VoidKeyword)),
+ Identifier("LoadBytecode"))
+ .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
+ .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
+ .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
+ .AddParameterListParameters(
+ Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader")),
+ Parameter(Identifier("shaderProfile")).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"))))
+ .WithBody(block);
+ }
+
+ ///
+ /// Gets a instance with the logic to try to get a compiled shader bytecode.
+ ///
+ /// The input bytecode info.
+ /// The resulting bytecode literals to insert into the final source code.
+ /// The instance trying to retrieve the precompiled shader.
+ private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals)
+ {
+ // This code produces a method declaration as follows:
+ //
+ // ComputeSharp.D2D1.__Internals.D2D1ShaderCompiler.LoadDynamicBytecode(ref loader, in this, shaderProfile, );
+ ExpressionStatementSyntax dynamicLoadingStatement =
+ ExpressionStatement(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("ComputeSharp.D2D1.__Internals.D2D1ShaderCompiler"),
+ IdentifierName("LoadDynamicBytecode")))
+ .AddArgumentListArguments(
+ Argument(IdentifierName("loader")).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)),
+ Argument(ThisExpression()).WithRefKindKeyword(Token(SyntaxKind.InKeyword)),
+ Argument(IdentifierName("shaderProfile")),
+ Argument(LiteralExpression(bytecodeInfo.IsLinkingSupported ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression))));
+
+ // If there is no precompiled bytecode, just return the dynamic path
+ if (bytecodeInfo.Bytecode.IsDefaultOrEmpty)
+ {
+ bytecodeLiterals = null;
+
+ return Block(dynamicLoadingStatement);
+ }
+
+ bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan());
+
+ // This code produces a branch as follows:
+ //
+ // if (shaderProfile is null or )
+ // {
+ // global::System.ReadOnlySpan bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE };
+ // loader.LoadEmbeddedBytecode(bytecode);
+ // }
+ //
+ // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string
+ // is created by the generator. This greatly speeds up the code generation, as it avoids
+ // having to create/parse tens of thousands of literal expression nodes for every shader.
+ IfStatementSyntax embeddedBranch =
+ IfStatement(
+ IsPatternExpression(
+ IdentifierName("shaderProfile"),
+ BinaryPattern(
+ SyntaxKind.OrPattern,
+ ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression)),
+ ConstantPattern(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"),
+ IdentifierName(bytecodeInfo.ShaderProfile.GetValueOrDefault().ToString()))))),
+ Block(
+ LocalDeclarationStatement(
+ VariableDeclaration(
+ GenericName(Identifier("global::System.ReadOnlySpan"))
+ .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
+ .AddVariables(
+ VariableDeclarator(Identifier("bytecode"))
+ .WithInitializer(
+ EqualsValueClause(
+ ArrayCreationExpression(
+ ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
+ .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression()))))
+ .WithInitializer(
+ InitializerExpression(
+ SyntaxKind.ArrayInitializerExpression,
+ SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))))),
+ ExpressionStatement(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("loader"),
+ IdentifierName("LoadEmbeddedBytecode")))
+ .AddArgumentListArguments(Argument(IdentifierName("bytecode"))))));
+
+ // Return the combined block
+ return Block(embeddedBranch.WithElse(ElseClause(Block(dynamicLoadingStatement))));
+ }
+
+ ///
+ /// A mapping of precomputed literals for all values.
+ ///
+ private static readonly string[] formattedBytes =
+ {
+ "0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F",
+ "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F",
+ "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F",
+ "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F",
+ "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F",
+ "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F",
+ "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F",
+ "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F",
+ "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F",
+ "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F",
+ "0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF",
+ "0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF",
+ "0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF",
+ "0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF",
+ "0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF",
+ "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF"
+ };
+
+ ///
+ /// Creates a formatted expression to initialize a with a given shader data.
+ ///
+ /// The input shader bytecode to serialize.
+ /// A formatted with the serialized data.
+ private static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode)
+ {
+ //The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values
+ using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6);
+
+ builder.Append(formattedBytes[bytecode[0]]);
+
+ foreach (byte b in bytecode.Slice(1))
+ {
+ builder.Append(", ");
+ builder.Append(formattedBytes[b]);
+ }
+
+ return builder.WrittenSpan.ToString();
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs
new file mode 100644
index 00000000..f616dd12
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs
@@ -0,0 +1,134 @@
+using System;
+using System.Collections.Immutable;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Text.RegularExpressions;
+using System.Threading;
+using ComputeSharp.D2D1.Exceptions;
+using ComputeSharp.D2D1.Shaders.Translation;
+using ComputeSharp.D2D1.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Models;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using TerraFX.Interop.DirectX;
+using TerraFX.Interop.Windows;
+using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors;
+
+namespace ComputeSharp.D2D1.SourceGenerators;
+
+///
+partial class ID2D1ShaderGenerator
+{
+ ///
+ internal static partial class LoadBytecode
+ {
+ ///
+ /// Extracts the shader profile for the current shader.
+ ///
+ /// The input instance to process.
+ /// The shader profile to use to compile the shader, if present.
+ public static D2D1ShaderProfile? GetShaderProfile(INamedTypeSymbol structDeclarationSymbol)
+ {
+ if (structDeclarationSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DEmbeddedBytecodeAttribute", out AttributeData? attributeData))
+ {
+ return (D2D1ShaderProfile)attributeData!.ConstructorArguments[0].Value!;
+ }
+
+ return null;
+ }
+
+ ///
+ /// Extracts the metadata definition for the current shader.
+ ///
+ /// The input instance to process.
+ /// The number of inputs for the shader.
+ /// Whether the shader only has simple inputs.
+ public static bool IsSimpleInputShader(INamedTypeSymbol structDeclarationSymbol, int inputCount)
+ {
+ // Build a map of all simple inputs (unmarked inputs default to being complex)
+ bool[] simpleInputsMap = new bool[inputCount];
+
+ foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes())
+ {
+ switch (attributeData.AttributeClass?.GetFullMetadataName())
+ {
+ case "ComputeSharp.D2D1.D2DInputSimpleAttribute":
+ simpleInputsMap[(int)attributeData.ConstructorArguments[0].Value!] = true;
+ break;
+ }
+ }
+
+ return simpleInputsMap.All(static x => x);
+ }
+
+ ///
+ /// Gets a instance with the logic to try to get a compiled shader bytecode.
+ ///
+ /// The source info for the shader to compile.
+ /// The used to cancel the operation, if needed.
+ /// The resulting diagnostic from the processing operation, if any.
+ /// The instance with the compiled shader bytecode.
+ public static unsafe ImmutableArray GetBytecode(HlslShaderSourceInfo sourceInfo, CancellationToken token, out DiagnosticInfo? diagnostic)
+ {
+ ImmutableArray bytecode = ImmutableArray.Empty;
+
+ // No embedded shader was requested, or there were some errors earlier in the pipeline.
+ // In this case, skip the compilation, as diagnostic will be emitted for those anyway.
+ // Compiling would just add overhead and result in more errors, as the HLSL would be invalid.
+ if (sourceInfo.HasErrors ||
+ sourceInfo.ShaderProfile is null)
+ {
+ diagnostic = null;
+
+ goto End;
+ }
+
+ try
+ {
+ token.ThrowIfCancellationRequested();
+
+ // Compile the shader bytecode
+ using ComPtr dxcBlobBytecode = D2D1ShaderCompiler.Compile(
+ sourceInfo.HlslSource.AsSpan(),
+ sourceInfo.ShaderProfile.Value,
+ sourceInfo.IsLinkingSupported);
+
+ token.ThrowIfCancellationRequested();
+
+ byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer();
+ int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize());
+
+ byte[] array = new ReadOnlySpan(buffer, length).ToArray();
+
+ bytecode = Unsafe.As>(ref array);
+ diagnostic = null;
+ }
+ catch (Win32Exception e)
+ {
+ diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, FixupExceptionMessage(e.Message));
+ }
+ catch (FxcCompilationException e)
+ {
+ diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithDxcCompilationException, FixupExceptionMessage(e.Message));
+ }
+
+ End:
+ return bytecode;
+ }
+
+ ///
+ /// Fixes up an exception message to improve the way it's displayed in VS.
+ ///
+ /// The input exception message.
+ /// The updated exception message.
+ private static string FixupExceptionMessage(string message)
+ {
+ // Add square brackets around error headers
+ message = Regex.Replace(message, @"((?:error|warning) \w+):", static m => $"[{m.Groups[1].Value}]:");
+
+ return message.NormalizeToSingleLine();
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
new file mode 100644
index 00000000..848298d9
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
@@ -0,0 +1,138 @@
+using System.Collections.Immutable;
+using ComputeSharp.D2D1.__Internals;
+using ComputeSharp.D2D1.SourceGenerators.Models;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.D2D1.SourceGenerators;
+
+///
+partial class ID2D1ShaderGenerator
+{
+ ///
+ partial class LoadDispatchData
+ {
+ ///
+ /// Creates a instance for the LoadDispatchDataMethod method.
+ ///
+ /// The dispatch info gathered for the current shader.
+ /// The resulting instance for the LoadDispatchDataMethod method.
+ public static MethodDeclarationSyntax GetSyntax(DispatchDataInfo dispatchInfo)
+ {
+ // This code produces a method declaration as follows:
+ //
+ // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadDispatchData(ref TLoader loader)
+ // {
+ //
+ // }
+ return
+ MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("LoadDispatchData"))
+ .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
+ .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
+ .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
+ .AddParameterListParameters(Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader")))
+ .WithBody(Block(GetDispatchDataLoadingStatements(dispatchInfo.FieldInfos, dispatchInfo.Root32BitConstantCount)));
+ }
+
+ ///
+ /// Gets a sequence of statements to load the dispatch data for a given shader.
+ ///
+ /// The array of values for all captured fields.
+ /// The total number of needed 32 bit constants in the shader root signature.
+ /// The sequence of instances to load shader dispatch data.
+ private static ImmutableArray GetDispatchDataLoadingStatements(ImmutableArray fieldInfos, int root32BitConstantsCount)
+ {
+ ImmutableArray.Builder statements = ImmutableArray.CreateBuilder();
+
+ // Generate loading statements for each captured field
+ foreach (FieldInfo fieldInfo in fieldInfos)
+ {
+ switch (fieldInfo)
+ {
+ case FieldInfo.Primitive primitive:
+
+ // Read a primitive value and serialize it into the target buffer. This will generate:
+ //
+ // global::System.Runtime.CompilerServices.Unsafe.As>(
+ // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) =
+ statements.Add(ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"),
+ ParseExpression($"{string.Join(".", primitive.FieldPath)}"))));
+ break;
+
+ case FieldInfo.NonLinearMatrix matrix:
+ string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
+ string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0";
+
+ // Declare a local to index into individual rows. This will generate:
+ //
+ // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >(
+ // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in ));
+ statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));"));
+
+ // Generate the loading code for each individual row, with proper alignment.
+ // This will result in the following (assuming Float2x3 m):
+ //
+ // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
+ // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0);
+ // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1);
+ for (int j = 0; j < matrix.Rows; j++)
+ {
+ statements.Add(ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"),
+ ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"))));
+ }
+ break;
+ }
+ }
+
+ // global::System.Span data = stackalloc uint[];
+ statements.Insert(0,
+ LocalDeclarationStatement(
+ VariableDeclaration(
+ GenericName(Identifier("global::System.Span"))
+ .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
+ .AddVariables(
+ VariableDeclarator(Identifier("data"))
+ .WithInitializer(EqualsValueClause(
+ StackAllocArrayCreationExpression(
+ ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
+ .AddRankSpecifiers(
+ ArrayRankSpecifier(SingletonSeparatedList(
+ LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
+
+ // ref uint r0 = ref data[0];
+ statements.Insert(1,
+ LocalDeclarationStatement(
+ VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
+ .AddVariables(
+ VariableDeclarator(Identifier("r0"))
+ .WithInitializer(EqualsValueClause(
+ RefExpression(
+ ElementAccessExpression(IdentifierName("data"))
+ .AddArgumentListArguments(Argument(
+ LiteralExpression(
+ SyntaxKind.NumericLiteralExpression,
+ Literal(0))))))))));
+
+ // loader.LoadConstantBuffer(data);
+ statements.Add(
+ ExpressionStatement(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("loader"),
+ IdentifierName("LoadConstantBuffer")))
+ .AddArgumentListArguments(Argument(IdentifierName("data")))));
+
+ return statements.ToImmutable();
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs
new file mode 100644
index 00000000..14f23044
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs
@@ -0,0 +1,176 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using ComputeSharp.Core.Helpers;
+using ComputeSharp.D2D1.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Mappings;
+using Microsoft.CodeAnalysis;
+using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors;
+
+namespace ComputeSharp.D2D1.SourceGenerators;
+
+///
+partial class ID2D1ShaderGenerator
+{
+ ///
+ /// A helper with all logic to generate the LoadDispatchData method.
+ ///
+ private static partial class LoadDispatchData
+ {
+ ///
+ /// Explores a given type hierarchy and generates statements to load fields.
+ ///
+ /// The current shader type being explored.
+ /// The total number of needed 32 bit constants in the shader root signature.
+ /// The resulting diagnostics from the processing operation.
+ /// The sequence of instances for all captured resources and values.
+ public static ImmutableArray GetInfo(
+ ITypeSymbol structDeclarationSymbol,
+ out int root32BitConstantCount,
+ out ImmutableArray diagnostics)
+ {
+ // Helper method that uses boxes instead of ref-s (illegal in enumerators)
+ static IEnumerable GetCapturedFieldInfos(
+ ITypeSymbol currentTypeSymbol,
+ ImmutableArray fieldPath,
+ StrongBox rawDataOffset)
+ {
+ bool isFirstField = true;
+
+ foreach (
+ IFieldSymbol fieldSymbol in
+ from fieldSymbol in currentTypeSymbol.GetMembers().OfType()
+ where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
+ !fieldSymbol.IsConst && !fieldSymbol.IsStatic &&
+ !fieldSymbol.IsFixedSizeBuffer
+ select fieldSymbol)
+ {
+ string fieldName = fieldSymbol.Name;
+ string typeName = fieldSymbol.Type.GetFullMetadataName();
+
+ // Disambiguates the name of target fields against the current input parameters
+ if (fieldName is "loader")
+ {
+ fieldName = $"this.{fieldName}";
+ }
+
+ // The first item in each nested struct needs to be aligned to 16 bytes
+ if (isFirstField && fieldPath.Length > 0)
+ {
+ rawDataOffset.Value = AlignmentHelper.Pad(rawDataOffset.Value, 16);
+
+ isFirstField = false;
+ }
+
+ if (HlslKnownTypes.IsKnownHlslType(typeName))
+ {
+ yield return GetHlslKnownTypeFieldInfo(fieldPath.Add(fieldName), typeName, ref rawDataOffset.Value);
+ }
+ else if (fieldSymbol.Type.IsUnmanagedType)
+ {
+ // Custom struct type defined by the user
+ foreach (var fieldInfo in GetCapturedFieldInfos(fieldSymbol.Type, fieldPath.Add(fieldName), rawDataOffset))
+ {
+ yield return fieldInfo;
+ }
+ }
+ }
+ }
+
+ ImmutableArray.Builder builder = ImmutableArray.CreateBuilder();
+
+ // Setup the resource and byte offsets for tracking
+ StrongBox rawDataOffsetAsBox = new();
+
+ // Traverse all shader fields and gather info, and update the tracking offsets
+ ImmutableArray fieldInfos = GetCapturedFieldInfos(
+ structDeclarationSymbol,
+ ImmutableArray.Empty,
+ rawDataOffsetAsBox).ToImmutableArray();
+
+ // After all the captured fields have been processed, ansure the reported byte size for
+ // the local variables is padded to a multiple of a 32 bit value. This is necessary to
+ // enable loading all the dispatch data after reinterpreting it to a sequence of values
+ // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
+ root32BitConstantCount = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int);
+
+ // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
+ // Loaded values in the root signature have the following costs:
+ // - Root constants cost 1 DWORD each, since they are 32-bit values.
+ // - Descriptor tables cost 1 DWORD each.
+ // - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
+ // So here we check whether the current signature respects that constraint,
+ // and emit a build error otherwise. For more info on this, see the docs here:
+ // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
+ int rootSignatureDwordSize = root32BitConstantCount;
+
+ if (rootSignatureDwordSize > 64)
+ {
+ builder.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
+ }
+
+ diagnostics = builder.ToImmutable();
+
+ return fieldInfos;
+ }
+
+ ///
+ /// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix).
+ ///
+ /// The current path of the field with respect to the shader instance.
+ /// The type name currently being read.
+ /// The current offset within the loaded data buffer.
+ private static FieldInfo GetHlslKnownTypeFieldInfo(
+ ImmutableArray fieldPath,
+ string typeName,
+ ref int rawDataOffset)
+ {
+ // For scalar, vector and linear matrix types, serialize the value normally.
+ // Only the initial alignment needs to be considered, while data is packed.
+ var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
+
+ // Check if the current type is a matrix type with more than one row. In this
+ // case, each row is aligned as if it was a separate array, so the start of
+ // each row needs to be at a multiple of 16 bytes (a float4 register).
+ if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
+ {
+ ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(rows);
+
+ for (int j = 0; j < rows; j++)
+ {
+ int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
+
+ builder.Add(startingRawDataOffset);
+
+ rawDataOffset = startingRawDataOffset + fieldPack * columns;
+ }
+
+ return new FieldInfo.NonLinearMatrix(
+ fieldPath,
+ typeName,
+ elementName!,
+ rows,
+ columns,
+ builder.MoveToImmutable());
+ }
+ else
+ {
+ // Calculate the right offset with 16-bytes padding (HLSL constant buffer).
+ // Since we're in a constant buffer, we need to both pad the starting offset
+ // to be aligned to the packing size of the type, and also to align the initial
+ // offset to ensure that values do not cross 16 bytes boundaries either.
+ int startingRawDataOffset = AlignmentHelper.AlignToBoundary(
+ AlignmentHelper.Pad(rawDataOffset, fieldPack),
+ fieldSize,
+ 16);
+
+ rawDataOffset = startingRawDataOffset + fieldSize;
+
+ return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset);
+ }
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs
new file mode 100644
index 00000000..9232e403
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs
@@ -0,0 +1,72 @@
+using System.Collections.Generic;
+using ComputeSharp.SourceGeneration.Models;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+namespace ComputeSharp.D2D1.SourceGenerators;
+
+///
+partial class ID2D1ShaderGenerator
+{
+ ///
+ /// Gets the shader type for a given shader, if any.
+ ///
+ /// The input instance to check.
+ /// The instance for .
+ /// Whether or not implements .
+ private static bool IsD2D1PixelShaderType(INamedTypeSymbol typeSymbol, INamedTypeSymbol d2D1PixelShaderSymbol)
+ {
+ foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.Interfaces)
+ {
+ if (interfaceSymbol.Name == nameof(ID2D1PixelShader) &&
+ SymbolEqualityComparer.Default.Equals(interfaceSymbol, d2D1PixelShaderSymbol))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ ///
+ /// Creates a instance wrapping the given method.
+ ///
+ /// The instance for the current type.
+ /// The item to insert.
+ /// Whether [SkipLocalsInit] can be used.
+ /// A object wrapping .
+ private static CompilationUnitSyntax GetCompilationUnitFromMethod(
+ HierarchyInfo hierarchyInfo,
+ MethodDeclarationSyntax methodDeclaration,
+ bool canUseSkipLocalsInit)
+ {
+ // Method attributes
+ List attributes = new()
+ {
+ AttributeList(SingletonSeparatedList(
+ Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
+ AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))),
+ AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))),
+ AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
+ AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))),
+ AttributeList(SingletonSeparatedList(
+ Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments(
+ AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))),
+ AttributeList(SingletonSeparatedList(
+ Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments(
+ AttributeArgument(LiteralExpression(
+ SyntaxKind.StringLiteralExpression,
+ Literal("This method is not intended to be used directly by user code"))))))
+ };
+
+ // Add [SkipLocalsInit] if the target project allows it
+ if (canUseSkipLocalsInit)
+ {
+ attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
+ }
+
+ return hierarchyInfo.GetSyntax(methodDeclaration.AddAttributeLists(attributes.ToArray()));
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
new file mode 100644
index 00000000..62b802d5
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
@@ -0,0 +1,202 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Linq;
+using ComputeSharp.D2D1.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Models;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+
+namespace ComputeSharp.D2D1.SourceGenerators;
+
+///
+/// A source generator creating data loaders for the type.
+///
+[Generator(LanguageNames.CSharp)]
+public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
+{
+ ///
+ public void Initialize(IncrementalGeneratorInitializationContext context)
+ {
+ // Check whether [SkipLocalsInit] can be used
+ IncrementalValueProvider canUseSkipLocalsInit =
+ context.CompilationProvider
+ .Select(static (compilation, token) =>
+ compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } &&
+ compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute") is not null);
+
+ // Get all declared struct types and their type symbols
+ IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol)> structDeclarations =
+ context.SyntaxProvider
+ .CreateSyntaxProvider(
+ static (node, token) => node is StructDeclarationSyntax structDeclaration,
+ static (context, token) => (
+ (StructDeclarationSyntax)context.Node,
+ Symbol: (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token)))
+ .Where(static pair => pair.Symbol is { Interfaces.IsEmpty: false })!;
+
+ // Get the symbol for the ID2D1PixelShader interface
+ IncrementalValueProvider pixelShaderInterface =
+ context.CompilationProvider
+ .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(ID2D1PixelShader).FullName)!);
+
+ // Filter struct declarations that implement the shader interface, and also gather the hierarchy info
+ IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, HierarchyInfo Hierarchy)> shaderDeclarations =
+ structDeclarations
+ .Combine(pixelShaderInterface)
+ .Where(static item => IsD2D1PixelShaderType(item.Left.Symbol, item.Right))
+ .Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol)));
+
+ // Get the dispatch data, HLSL source and embedded bytecode info. This info is computed on the
+ // same step as parts are shared in following sub-branches in the incremental generator pipeline.
+ IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result Dispatch, Result Source)> shaderInfoWithErrors =
+ shaderDeclarations
+ .Combine(context.CompilationProvider)
+ .Select(static (item, token) =>
+ {
+ // LoadDispatchData() info
+ ImmutableArray fieldInfos = LoadDispatchData.GetInfo(
+ item.Left.Symbol,
+ out int root32BitConstantCount,
+ out ImmutableArray dispatchDataDiagnostics);
+
+ token.ThrowIfCancellationRequested();
+
+ DispatchDataInfo dispatchDataInfo = new(fieldInfos, root32BitConstantCount);
+
+ // Get HLSL source for BuildHlslSource()
+ string hlslSource = BuildHlslSource.GetHlslSource(
+ item.Right,
+ item.Left.Syntax,
+ item.Left.Symbol,
+ out int inputCount,
+ out ImmutableArray hlslSourceDiagnostics);
+
+ token.ThrowIfCancellationRequested();
+
+ // Get the shader profile and linking info for LoadBytecode()
+ D2D1ShaderProfile? shaderProfile = LoadBytecode.GetShaderProfile(item.Left.Symbol);
+ bool hasErrors = !dispatchDataDiagnostics.IsDefaultOrEmpty || !hlslSourceDiagnostics.IsDefaultOrEmpty;
+ bool isLinkingSupported = !hasErrors && LoadBytecode.IsSimpleInputShader(item.Left.Symbol, inputCount);
+
+ HlslShaderSourceInfo sourceInfo = new(
+ hlslSource,
+ shaderProfile,
+ isLinkingSupported,
+ hasErrors);
+
+ token.ThrowIfCancellationRequested();
+
+ return (
+ item.Left.Hierarchy,
+ new Result(dispatchDataInfo, dispatchDataDiagnostics),
+ new Result(sourceInfo, hlslSourceDiagnostics));
+ });
+
+ // Output the diagnostics
+ context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Dispatch.Errors));
+ context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Source.Errors));
+
+ // Filter all items to enable caching at a coarse level, and remove diagnostics
+ IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, HlslShaderSourceInfo Source)> shaderInfo =
+ shaderInfoWithErrors
+ .Select(static (item, token) => (item.Hierarchy, item.Dispatch.Value, item.Source.Value))
+ .WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default, EqualityComparer.Default);
+
+ // Get a filtered sequence to enable caching
+ IncrementalValuesProvider< (HierarchyInfo Hierarchy, DispatchDataInfo Dispatch)> dispatchDataInfo =
+ shaderInfo
+ .Select(static (item, token) => (item.Hierarchy, item.Dispatch))
+ .WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default);
+
+ // Generate the LoadDispatchData() methods
+ context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
+ {
+ MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Left.Dispatch);
+ CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadDispatchDataMethod, item.Right);
+
+ context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}", compilationUnit.ToFullString());
+ });
+
+ // Generate the InitializeFromDispatchData() methods
+ context.RegisterSourceOutput(dispatchDataInfo, static (context, item) =>
+ {
+ MethodDeclarationSyntax loadDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Dispatch);
+ CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadDispatchDataMethod, false);
+
+ context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(InitializeFromDispatchData)}", compilationUnit.ToFullString());
+ });
+
+ // Get the filtered sequence to enable caching
+ IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource)> hlslSourceInfo =
+ shaderInfo
+ .Select(static (item, token) => (item.Hierarchy, item.Source.HlslSource))
+ .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default);
+
+ // Generate the BuildHlslSource() methods
+ context.RegisterSourceOutput(hlslSourceInfo, static (context, item) =>
+ {
+ MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.HlslSource);
+ CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: false);
+
+ context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}", compilationUnit.ToFullString());
+ });
+
+ // Get a filtered sequence to enable caching
+ IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo Source)> shaderBytecodeInfo =
+ shaderInfo
+ .Select(static (item, token) => (item.Hierarchy, item.Source))
+ .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default);
+
+ // Compile the requested shader bytecodes
+ IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors =
+ shaderBytecodeInfo
+ .Select(static (item, token) =>
+ {
+ ImmutableArray bytecode = LoadBytecode.GetBytecode(item.Source, token, out DiagnosticInfo? diagnostic);
+
+ token.ThrowIfCancellationRequested();
+
+ EmbeddedBytecodeInfo bytecodeInfo = new(item.Source.HlslSource, item.Source.ShaderProfile, item.Source.IsLinkingSupported, bytecode);
+
+ return (item.Hierarchy, bytecodeInfo, diagnostic);
+ });
+
+ // Gather the diagnostics
+ IncrementalValuesProvider embeddedBytecodeDiagnostics =
+ embeddedBytecodeWithErrors
+ .Select(static (item, token) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic))
+ .Where(static item => item.Diagnostic is not null)
+ .Combine(context.CompilationProvider)
+ .Select(static (item, token) =>
+ {
+ INamedTypeSymbol typeSymbol = item.Right.GetTypeByMetadataName(item.Left.FullyQualifiedMetadataName)!;
+
+ return Diagnostic.Create(
+ item.Left.Diagnostic!.Descriptor,
+ typeSymbol.Locations.FirstOrDefault(),
+ new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Args).ToArray());
+ });
+
+ // Output the diagnostics
+ context.ReportDiagnostics(embeddedBytecodeDiagnostics);
+
+ // Get the filtered sequence to enable caching
+ IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode =
+ embeddedBytecodeWithErrors
+ .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo))
+ .WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeInfo.Comparer.Default);
+
+ // Generate the LoadBytecode() methods
+ context.RegisterSourceOutput(embeddedBytecode, static (context, item) =>
+ {
+ MethodDeclarationSyntax loadBytecodeMethod = LoadBytecode.GetSyntax(item.BytecodeInfo, out Func fixup);
+ CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadBytecodeMethod, false);
+ string text = fixup(compilationUnit);
+
+ context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(LoadBytecode)}", text);
+ });
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownKeywords.cs b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownKeywords.cs
new file mode 100644
index 00000000..78098a82
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownKeywords.cs
@@ -0,0 +1,22 @@
+using System.Collections.Generic;
+using System.Reflection;
+using ComputeSharp.Core.Intrinsics.Attributes;
+using ComputeSharp.D2D1;
+
+namespace ComputeSharp.SourceGeneration.Mappings;
+
+///
+partial class HlslKnownKeywords
+{
+ ///
+ static partial void AddKnownKeywords(ICollection knownKeywords)
+ {
+ // D2D1 intrinsics method names
+ foreach (var method in typeof(D2D).GetMethods(BindingFlags.Public | BindingFlags.Static))
+ {
+ string name = method.GetCustomAttribute()?.Name ?? method.Name;
+
+ knownKeywords.Add(name);
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownMethods.cs b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownMethods.cs
new file mode 100644
index 00000000..99964394
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownMethods.cs
@@ -0,0 +1,29 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using ComputeSharp.Core.Intrinsics.Attributes;
+using ComputeSharp.D2D1;
+
+namespace ComputeSharp.SourceGeneration.Mappings;
+
+///
+partial class HlslKnownMethods
+{
+ ///
+
+ static partial void AddKnownMethods(IDictionary knownMethods)
+ {
+ // Programmatically load mappings from the D2D1 class as well
+ foreach (var method in
+ from method in typeof(D2D).GetMethods(BindingFlags.Public | BindingFlags.Static)
+ group method by method.Name
+ into groups
+ select groups.First())
+ {
+ string hlslName = method.GetCustomAttribute()?.Name ?? method.Name;
+
+ knownMethods.Add($"{typeof(D2D).FullName}{Type.Delimiter}{method.Name}", hlslName);
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownTypes.cs
new file mode 100644
index 00000000..33dc9cbe
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownTypes.cs
@@ -0,0 +1,23 @@
+using ComputeSharp.SourceGeneration.Extensions;
+using Microsoft.CodeAnalysis;
+
+namespace ComputeSharp.SourceGeneration.Mappings;
+
+///
+partial class HlslKnownTypes
+{
+ ///
+ public static partial string GetMappedName(INamedTypeSymbol typeSymbol)
+ {
+ string typeName = typeSymbol.GetFullMetadataName();
+
+ // The captured field is of an HLSL primitive type
+ if (KnownHlslTypes.TryGetValue(typeName, out string? mappedType))
+ {
+ return mappedType;
+ }
+
+ // The captured field is of a custom struct type
+ return typeName.ToHlslIdentifierName();
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs
new file mode 100644
index 00000000..a34e3bad
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
+
+namespace ComputeSharp.D2D1.SourceGenerators.Models;
+
+///
+/// A model representing gathered info on a shader dispatch data.
+///
+/// The description on shader instance fields.
+/// The size of the shader root signature, in 32 bit constants.
+internal sealed record DispatchDataInfo(ImmutableArray FieldInfos, int Root32BitConstantCount)
+{
+ ///
+ /// An implementation for .
+ ///
+ public sealed class Comparer : Comparer
+ {
+ ///
+ protected override void AddToHashCode(ref HashCode hashCode, DispatchDataInfo obj)
+ {
+ hashCode.AddRange(obj.FieldInfos, FieldInfo.Comparer.Default);
+ hashCode.Add(obj.Root32BitConstantCount);
+ }
+
+ ///
+ protected override bool AreEqual(DispatchDataInfo x, DispatchDataInfo y)
+ {
+ return
+ x.FieldInfos.SequenceEqual(y.FieldInfos, FieldInfo.Comparer.Default) &&
+ x.Root32BitConstantCount == y.Root32BitConstantCount;
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs
new file mode 100644
index 00000000..385b0144
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs
@@ -0,0 +1,42 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
+
+namespace ComputeSharp.D2D1.SourceGenerators.Models;
+
+///
+/// A model representing a shared and its compiled bytecode, if available.
+///
+/// The HLSL source for the shader.
+/// The shader profile to use to compile the shader, if requested.
+/// Whether linking is supported for the current shader.
+/// The compiled shader bytecode, if available.
+internal sealed record EmbeddedBytecodeInfo(string HlslSource, D2D1ShaderProfile? ShaderProfile, bool IsLinkingSupported, ImmutableArray Bytecode)
+{
+ ///
+ /// An implementation for .
+ ///
+ public sealed class Comparer : Comparer
+ {
+ ///
+ protected override void AddToHashCode(ref HashCode hashCode, EmbeddedBytecodeInfo obj)
+ {
+ hashCode.Add(obj.HlslSource);
+ hashCode.Add(obj.ShaderProfile);
+ hashCode.Add(obj.IsLinkingSupported);
+ hashCode.AddBytes(obj.Bytecode.AsSpan());
+ }
+
+ ///
+ protected override bool AreEqual(EmbeddedBytecodeInfo x, EmbeddedBytecodeInfo y)
+ {
+ return
+ x.HlslSource == y.HlslSource &&
+ x.ShaderProfile == y.ShaderProfile &&
+ x.IsLinkingSupported == y.IsLinkingSupported &&
+ x.Bytecode.SequenceEqual(y.Bytecode);
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/FieldInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/FieldInfo.cs
new file mode 100644
index 00000000..073900bd
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/FieldInfo.cs
@@ -0,0 +1,91 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
+
+namespace ComputeSharp.D2D1.SourceGenerators.Models;
+
+///
+/// A base type for a model describing a given captured field in a shader.
+///
+internal abstract record FieldInfo
+{
+ ///
+ /// A captured primitive value (either a scalar, a vector, or a linear matrix).
+ ///
+ /// The path of the field with respect to the shader instance.
+ /// The full metadata name for the primitive type.
+ /// The byte offset of the value within the root signature.
+ public sealed record Primitive(ImmutableArray FieldPath, string TypeName, int Offset) : FieldInfo;
+
+ ///
+ /// A captured non linear matrix value.
+ ///
+ /// The path of the field with respect to the shader instance.
+ /// The full metadata name for the matrix type.
+ /// The name of each element in the matrix type.
+ /// The number of rows in the matrix.
+ /// The number of columns in the matrix.
+ /// The sequence of byte offsets for each row within the root signature.
+ public sealed record NonLinearMatrix(
+ ImmutableArray FieldPath,
+ string TypeName,
+ string ElementName,
+ int Rows,
+ int Columns,
+ ImmutableArray Offsets) : FieldInfo;
+
+ ///
+ /// An implementation for .
+ ///
+ public sealed class Comparer : Comparer
+ {
+ ///
+ protected override void AddToHashCode(ref HashCode hashCode, FieldInfo obj)
+ {
+ switch (obj)
+ {
+ case Primitive primitive:
+ hashCode.AddRange(primitive.FieldPath);
+ hashCode.Add(primitive.TypeName);
+ hashCode.Add(primitive.Offset);
+ break;
+ case NonLinearMatrix matrix:
+ hashCode.AddRange(matrix.FieldPath);
+ hashCode.Add(matrix.TypeName);
+ hashCode.Add(matrix.ElementName);
+ hashCode.Add(matrix.Rows);
+ hashCode.Add(matrix.Columns);
+ hashCode.AddRange(matrix.Offsets);
+ break;
+ default:
+ break;
+ }
+ }
+
+ ///
+ protected override bool AreEqual(FieldInfo x, FieldInfo y)
+ {
+ if (x is Primitive primitiveX && y is Primitive primitiveY)
+ {
+ return
+ primitiveX.FieldPath.SequenceEqual(primitiveY.FieldPath) &&
+ primitiveX.TypeName == primitiveY.TypeName &&
+ primitiveX.Offset == primitiveY.Offset;
+ }
+ else if (x is NonLinearMatrix matrixX && y is NonLinearMatrix matrixY)
+ {
+ return
+ matrixX.FieldPath.SequenceEqual(matrixY.FieldPath) &&
+ matrixX.TypeName == matrixY.TypeName &&
+ matrixX.ElementName == matrixY.ElementName &&
+ matrixX.Rows == matrixY.Rows &&
+ matrixY.Columns == matrixY.Columns &&
+ matrixX.Offsets.SequenceEqual(matrixY.Offsets);
+ }
+
+ return false;
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderSourceInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderSourceInfo.cs
new file mode 100644
index 00000000..76f7c60d
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderSourceInfo.cs
@@ -0,0 +1,10 @@
+namespace ComputeSharp.D2D1.SourceGenerators.Models;
+
+///
+/// A model for extracted info on a processed HLSL shader.
+///
+/// The HLSL source.
+/// The shader profile to use to compile the shader, if requested.
+/// Whether the shader supports linking.
+/// Whether any errors have been detected, and therefore the shader compilation should be skipped.
+internal sealed record HlslShaderSourceInfo(string HlslSource, D2D1ShaderProfile? ShaderProfile, bool IsLinkingSupported, bool HasErrors);
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs
new file mode 100644
index 00000000..d722dd00
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs
@@ -0,0 +1,205 @@
+using ComputeSharp.SourceGeneration.Extensions;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors;
+
+namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters;
+
+///
+internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
+{
+ ///
+ public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
+ {
+ var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!;
+
+ Diagnostics.Add(AnonymousObjectCreationExpression, node);
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node)
+ {
+ Diagnostics.Add(AwaitExpression, node);
+
+ return base.VisitAwaitExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node)
+ {
+ Diagnostics.Add(CheckedExpression, node);
+
+ return base.VisitCheckedExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node)
+ {
+ Diagnostics.Add(CheckedStatement, node);
+
+ return base.VisitCheckedStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node)
+ {
+ Diagnostics.Add(FixedStatement, node);
+
+ return base.VisitFixedStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node)
+ {
+ Diagnostics.Add(ForEachStatement, node);
+
+ return base.VisitForEachStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
+ {
+ Diagnostics.Add(ForEachStatement, node);
+
+ return base.VisitForEachVariableStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitLockStatement(LockStatementSyntax node)
+ {
+ Diagnostics.Add(LockStatement, node);
+
+ return base.VisitLockStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node)
+ {
+ Diagnostics.Add(QueryExpression, node);
+
+ return base.VisitQueryExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node)
+ {
+ Diagnostics.Add(RangeExpression, node);
+
+ return base.VisitRangeExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node)
+ {
+ Diagnostics.Add(RecursivePattern, node);
+
+ return base.VisitRecursivePattern(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitRefType(RefTypeSyntax node)
+ {
+ Diagnostics.Add(RefType, node);
+
+ return base.VisitRefType(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node)
+ {
+ Diagnostics.Add(RelationalPattern, node);
+
+ return base.VisitRelationalPattern(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node)
+ {
+ Diagnostics.Add(SizeOfExpression, node);
+
+ return base.VisitSizeOfExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node)
+ {
+ Diagnostics.Add(StackAllocArrayCreationExpression, node);
+
+ return base.VisitStackAllocArrayCreationExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node)
+ {
+ Diagnostics.Add(ThrowExpressionOrStatement, node);
+
+ return base.VisitThrowExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node)
+ {
+ Diagnostics.Add(ThrowExpressionOrStatement, node);
+
+ return base.VisitThrowStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitTryStatement(TryStatementSyntax node)
+ {
+ Diagnostics.Add(TryStatement, node);
+
+ return base.VisitTryStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitTupleType(TupleTypeSyntax node)
+ {
+ Diagnostics.Add(TupleType, node);
+
+ return base.VisitTupleType(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node)
+ {
+ Diagnostics.Add(UsingStatementOrDeclaration, node);
+
+ return base.VisitUsingStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node)
+ {
+ Diagnostics.Add(YieldStatement, node);
+
+ return base.VisitYieldStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node)
+ {
+ Diagnostics.Add(FunctionPointer, node);
+
+ return base.VisitFunctionPointerType(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitPointerType(PointerTypeSyntax node)
+ {
+ Diagnostics.Add(PointerType, node);
+
+ return base.VisitPointerType(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node)
+ {
+ Diagnostics.Add(UnsafeStatement, node);
+
+ return base.VisitUnsafeStatement(node);
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs
new file mode 100644
index 00000000..83e1cecd
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs
@@ -0,0 +1,301 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Globalization;
+using System.Linq;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
+using ComputeSharp.SourceGeneration.Mappings;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Operations;
+using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters;
+
+///
+/// A base type that processes C# source to convert to HLSL compliant code.
+/// This class contains only the shared logic for all derived HLSL source rewriters.
+///
+internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
+{
+ ///
+ /// The instance with semantic info on the target syntax tree.
+ ///
+ protected readonly SemanticModelProvider SemanticModel;
+
+ ///
+ /// The collection of discovered custom types.
+ ///
+ protected readonly ICollection DiscoveredTypes;
+
+ ///
+ /// The collection of discovered constant definitions.
+ ///
+ protected readonly IDictionary ConstantDefinitions;
+
+ ///
+ /// The collection of produced instances.
+ ///
+ protected readonly ImmutableArray.Builder Diagnostics;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The instance for the target syntax tree.
+ /// The set of discovered custom types.
+ /// The collection of discovered constant definitions.
+ /// The collection of produced instances.
+ protected HlslSourceRewriter(
+ SemanticModelProvider semanticModel,
+ ICollection discoveredTypes,
+ IDictionary constantDefinitions,
+ ImmutableArray.Builder diagnostics)
+ {
+ SemanticModel = semanticModel;
+ DiscoveredTypes = discoveredTypes;
+ ConstantDefinitions = constantDefinitions;
+ Diagnostics = diagnostics;
+ }
+
+ ///
+ public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
+ {
+ var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!;
+
+ return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
+ }
+
+ ///
+ public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node)
+ {
+ var updatedNode = (VariableDeclarationSyntax)base.VisitVariableDeclaration(node)!;
+
+ if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type)
+ {
+ Diagnostics.Add(InvalidObjectDeclaration, node, type);
+ }
+
+ // If var is used, replace it with the explicit type
+ if (updatedNode.Type is IdentifierNameSyntax { IsVar: true })
+ {
+ updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
+ {
+ var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!;
+
+ if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
+ {
+ Diagnostics.Add(InvalidObjectCreationExpression, node, type);
+ }
+
+ updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel.For(node), DiscoveredTypes);
+
+ // New objects use the default HLSL cast syntax, eg. (float4)0
+ if (updatedNode.ArgumentList!.Arguments.Count == 0)
+ {
+ return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
+ }
+
+ // Add explicit casts for matrix constructors to help the overload resolution
+ if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType &&
+ HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
+ {
+ for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++)
+ {
+ IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!;
+ INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type;
+
+ updatedNode = updatedNode.ReplaceNode(
+ updatedNode.ArgumentList!.Arguments[i].Expression,
+ CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression));
+ }
+ }
+
+ return InvocationExpression(updatedNode.Type, updatedNode.ArgumentList!);
+ }
+
+ ///
+ public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node)
+ {
+ var updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!;
+
+ if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
+ {
+ Diagnostics.Add(InvalidObjectCreationExpression, node, type);
+ }
+
+ TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel.For(node), DiscoveredTypes);
+
+ // Mutate the syntax like with explicit object creation expressions
+ if (updatedNode.ArgumentList!.Arguments.Count == 0)
+ {
+ return CastExpression(explicitType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
+ }
+
+ // Add explicit casts like with the explicit object creation expressions above
+ if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType &&
+ HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
+ {
+ for (int i = 0; i < node.ArgumentList.Arguments.Count; i++)
+ {
+ IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!;
+ INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type;
+
+ updatedNode = updatedNode.ReplaceNode(
+ updatedNode.ArgumentList.Arguments[i].Expression,
+ CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression));
+ }
+ }
+
+ return InvocationExpression(explicitType, updatedNode.ArgumentList);
+ }
+
+ ///
+ public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node)
+ {
+ var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!;
+
+ updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
+
+ // A default expression becomes (T)0 in HLSL
+ return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
+ }
+
+ ///
+ public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node)
+ {
+ var updatedNode = (LiteralExpressionSyntax)base.VisitLiteralExpression(node)!;
+
+ if (updatedNode.IsKind(SyntaxKind.DefaultLiteralExpression))
+ {
+ TypeSyntax type = node.TrackType(SemanticModel.For(node), DiscoveredTypes);
+
+ // Same HLSL-style expression in the form (T)0
+ return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
+ }
+ else if (updatedNode.IsKind(SyntaxKind.NumericLiteralExpression) &&
+ SemanticModel.For(node).GetOperation(node) is ILiteralOperation operation &&
+ operation.Type is INamedTypeSymbol type)
+ {
+ // If the expression is a literal floating point value, we need to ensure the proper suffixes are
+ // used in the HLSL representation. Floating point values accept either f or F, but they don't work
+ // when the literal doesn't contain a decimal point. Since 32 bit floating point values are the default
+ // in HLSL, we can remove the suffix entirely. As for 64 bit values, we simply use the 'L' suffix.
+ if (type.GetFullMetadataName().Equals(typeof(float).FullName))
+ {
+ string literal = updatedNode.Token.ValueText;
+
+ // If the numeric literal is neither a decimal nor an exponential, add the ".0" suffix
+ if (literal.IndexOfAny(new[] { '.', 'E' }) == -1)
+ {
+ literal += ".0";
+ }
+
+ return updatedNode.WithToken(Literal(literal, 0f));
+ }
+ else if (type.GetFullMetadataName().Equals(typeof(double).FullName))
+ {
+ return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d));
+ }
+ }
+ else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression))
+ {
+ Diagnostics.Add(StringLiteralExpression, node);
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node)
+ {
+ var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!;
+
+ if (SemanticModel.For(node).GetOperation(node) is IPropertyReferenceOperation operation)
+ {
+ string propertyName = operation.Property.GetFullMetadataName();
+
+ // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite
+ // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01.
+ if (HlslKnownProperties.IsKnownMatrixIndexer(propertyName))
+ {
+ bool isValid = true;
+
+ // Validate the arguments
+ foreach (ArgumentSyntax argument in node.ArgumentList.Arguments)
+ {
+ if (SemanticModel.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference ||
+ !HlslKnownProperties.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName()))
+ {
+ Diagnostics.Add(NonConstantMatrixSwizzledIndex, argument);
+
+ isValid = false;
+ }
+ }
+
+ if (isValid)
+ {
+ // Rewrite the indexer as a property access
+ string hlslPropertyName = string.Join("",
+ from argument in node.ArgumentList.Arguments
+ let fieldReference = (IFieldReferenceOperation)SemanticModel.For(node).GetOperation(argument.Expression)!
+ let fieldName = fieldReference.Field.Name
+ let row = (char)(fieldName[1] - 1)
+ let column = (char)(fieldName[2] - 1)
+ select $"_m{row}{column}");
+
+ return MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ updatedNode.Expression,
+ IdentifierName(hlslPropertyName));
+ }
+ }
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node)
+ {
+ var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!;
+
+ if (SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation &&
+ operation.Field.IsConst &&
+ operation.Type!.TypeKind != TypeKind.Enum)
+ {
+ ConstantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
+
+ var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
+ var constantName = $"__{ownerTypeName}__{operation.Field.Name}";
+
+ return IdentifierName(constantName);
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxToken VisitToken(SyntaxToken token)
+ {
+ SyntaxToken updatedToken = base.VisitToken(token);
+
+ // Replace all identifier tokens when needed, to avoid colliding with HLSL keywords
+ if (updatedToken.IsKind(SyntaxKind.IdentifierToken) &&
+ HlslKnownKeywords.TryGetMappedName(updatedToken.Text, out string? mapped))
+ {
+ return ParseToken(mapped!);
+ }
+
+ return updatedToken.WithoutTrivia();
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
new file mode 100644
index 00000000..b519066b
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
@@ -0,0 +1,350 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Globalization;
+using System.Linq;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
+using ComputeSharp.SourceGeneration.Mappings;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Operations;
+using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters;
+
+///
+/// A custom type that processes C# methods to convert to HLSL compliant code.
+///
+internal sealed class ShaderSourceRewriter : HlslSourceRewriter
+{
+ ///
+ /// The type symbol for the shader type.
+ ///
+ private readonly INamedTypeSymbol? shaderType;
+
+ ///
+ /// The collection of discovered static methods.
+ ///
+ private readonly IDictionary staticMethods;
+
+ ///
+ /// The collection of processed local functions in the current tree.
+ ///
+ private readonly Dictionary localFunctions;
+
+ ///
+ /// The list of implicit variables to declare at the start of the body.
+ ///
+ private readonly List implicitVariables;
+
+ ///
+ /// The current tree being visited.
+ ///
+ private MethodDeclarationSyntax? currentMethod;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The type symbol for the shader type.
+ /// The instance for the target syntax tree.
+ /// The set of discovered custom types.
+ /// The set of discovered and processed static methods.
+ /// The collection of discovered constant definitions.
+ /// The collection of produced instances.
+ public ShaderSourceRewriter(
+ INamedTypeSymbol shaderType,
+ SemanticModelProvider semanticModel,
+ ICollection discoveredTypes,
+ IDictionary staticMethods,
+ IDictionary constantDefinitions,
+ ImmutableArray.Builder diagnostics)
+ : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
+ {
+ this.shaderType = shaderType;
+ this.staticMethods = staticMethods;
+ this.localFunctions = new();
+ this.implicitVariables = new();
+ }
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The instance for the target syntax tree.
+ /// The set of discovered custom types.
+ /// The set of discovered and processed static methods.
+ /// The collection of discovered constant definitions.
+ /// The collection of produced instances.
+ public ShaderSourceRewriter(
+ SemanticModelProvider semanticModel,
+ ICollection discoveredTypes,
+ IDictionary staticMethods,
+ IDictionary constantDefinitions,
+ ImmutableArray.Builder diagnostics)
+ : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
+ {
+ this.staticMethods = staticMethods;
+ this.implicitVariables = new();
+ this.localFunctions = new();
+ }
+
+ ///
+ /// Gets the collection of processed local functions in the current tree.
+ ///
+ public IReadOnlyDictionary LocalFunctions => this.localFunctions;
+
+ ///
+ public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node)
+ {
+ this.currentMethod = node;
+
+ var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!;
+
+ updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes);
+
+ if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
+ {
+ Diagnostics.Add(AsyncModifierOnMethodOrFunction, node);
+ }
+
+ if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
+ {
+ Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
+ }
+
+ if (updatedNode is not null)
+ {
+ var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray());
+
+ // Add the tracked implicit declarations (at the start of the body)
+ updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements(updatedNode.Body!.Statements.ToArray());
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode VisitParameter(ParameterSyntax node)
+ {
+ var updatedNode = (ParameterSyntax)base.VisitParameter(node)!;
+
+ // Convert the C# parameter modifiers to the HLSL equivalent
+ SyntaxToken modifier =
+ node.Modifiers
+ .Where(static m => m.Kind() is SyntaxKind.OutKeyword or SyntaxKind.RefKeyword or SyntaxKind.InKeyword)
+ .Select(static m => m.Kind() switch
+ {
+ SyntaxKind.OutKeyword => m,
+ SyntaxKind.InKeyword => m,
+ SyntaxKind.RefKeyword => ParseToken("inout"),
+ _ => Token(SyntaxKind.None)
+ }).FirstOrDefault();
+
+ return updatedNode
+ .WithAttributeLists(default)
+ .ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel.For(node), DiscoveredTypes)
+ .WithModifiers(TokenList(modifier));
+ }
+
+ ///
+ public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
+ {
+ var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!);
+
+ if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration })
+ {
+ Diagnostics.Add(UsingStatementOrDeclaration, node);
+ }
+
+ return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes);
+ }
+
+ ///
+ public override SyntaxNode? VisitDeclarationExpression(DeclarationExpressionSyntax node)
+ {
+ var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!;
+
+ updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
+
+ // Add the variable to the list of implicit declarations
+ this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString())));
+
+ return IdentifierName(updatedNode.Designation.ToString());
+ }
+
+ ///
+ public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node)
+ {
+ return
+ ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!)
+ .WithBlockBody()
+ .WithoutAccessibilityModifiers()
+ .WithAttributeLists(List());
+ }
+
+ ///
+ public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node)
+ {
+ var updatedNode =
+ ((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!)
+ .WithBlockBody()
+ .WithAttributeLists(List())
+ .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}"));
+
+ updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes);
+
+ if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
+ {
+ Diagnostics.Add(AsyncModifierOnMethodOrFunction, node);
+ }
+
+ if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
+ {
+ Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
+ }
+
+ // HLSL doesn't support local functions, so we first process them as usual and then remove
+ // them from the current syntax tree completely. These will be added to the shader source
+ // as external static method with a special name to avoid conflicts with other methods.
+ // The name will simply be in the format: "____".
+ this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode);
+
+ return null;
+ }
+
+ ///
+ public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
+ {
+ var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!;
+
+ if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
+ SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation)
+ {
+ if (operation is IFieldReferenceOperation fieldOperation)
+ {
+ // If the member access is a constant, track it and replace the tree with the processed constant name
+ if (fieldOperation.Field.IsConst &&
+ fieldOperation.Type!.TypeKind != TypeKind.Enum)
+ {
+ if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral))
+ {
+ return ParseExpression(constantLiteral!);
+ }
+
+ ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
+
+ var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
+ var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}";
+
+ return IdentifierName(constantName);
+ }
+
+ // If the member access is a this. access, rewrite it to strip "this."
+ if (node.Expression.IsKind(SyntaxKind.ThisExpression))
+ {
+ return node.Name;
+ }
+ }
+
+ // If the current member access is a field or property access, check the lookup table
+ // to see if the member should be rewritten for HLSL compliance, and rewrite if needed.
+ if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping))
+ {
+ // Static and instance members are handled differently, with static members being
+ // converted into a literal expression, and instance getting an updated identifier.
+ // For instance, consider these three cases:
+ // - Vector3.One (static) => float3(1.0f, 1.0f, 1.0f)
+ // - ThreadIds.X (custom) => ThreadIds.x
+ // - uint3.X (instance) => [arg].x
+ return operation.Member.IsStatic switch
+ {
+ true => ParseExpression(mapping!),
+ false => updatedNode.WithName(IdentifierName(mapping!))
+ };
+ }
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
+ {
+ var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!;
+
+ if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation &&
+ operation.TargetMethod is IMethodSymbol method &&
+ method.IsStatic)
+ {
+ // If the invocation consists of invoking a static method that has a direct
+ // mapping to HLSL, rewrite the expression in the current invocation node.
+ // For instance: Math.Abs(expr) => abs(expr).
+ if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping))
+ {
+ return updatedNode.WithExpression(ParseExpression(mapping!));
+ }
+
+ // Update the name if the target is a local function. The exact schema for the
+ // updated name is detailed in the override handling the local function statement.
+ if (method.MethodKind == MethodKind.LocalFunction)
+ {
+ var functionIdentifier = $"__{this.currentMethod!.Identifier.Text}__{method.Name}";
+
+ return updatedNode.WithExpression(ParseExpression(functionIdentifier));
+ }
+
+ // If the method is an external static method, import and rewrite it as well.
+ // This assumes that the target method is actually part of the same compilation.
+ // We need to check the declaring type to avoid rewriting static methods in the shader
+ // type as well, as they will be processed by the generator in a different path.
+ if (!SymbolEqualityComparer.Default.Equals(this.shaderType, method.ContainingType))
+ {
+ var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName();
+
+ if (!this.staticMethods.ContainsKey(method))
+ {
+ if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode)
+ {
+ Diagnostics.Add(InvalidMethodCall, node, method);
+
+ return updatedNode;
+ }
+
+ ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics);
+ MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia();
+
+ this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier)));
+ }
+
+ return updatedNode.WithExpression(ParseExpression(methodIdentifier));
+ }
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode? VisitArgument(ArgumentSyntax node)
+ {
+ var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!;
+
+ // Strip the ref keywords from arguments
+ updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None));
+
+ // Track and rewrite the discarded declaration
+ if (SemanticModel.For(node).GetOperation(node.Expression) is IDiscardOperation operation)
+ {
+ TypeSyntax typeSyntax = ParseTypeName(HlslKnownTypes.TrackType(operation.Type!, DiscoveredTypes));
+ string identifier = $"__implicit{this.implicitVariables.Count}";
+
+ // Add the variable to the list of implicit declarations
+ this.implicitVariables.Add(VariableDeclaration(typeSyntax).AddVariables(VariableDeclarator(identifier)));
+
+ return updatedNode.WithExpression(IdentifierName(identifier));
+ }
+
+ return updatedNode;
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs
new file mode 100644
index 00000000..56623724
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs
@@ -0,0 +1,116 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Globalization;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
+using ComputeSharp.SourceGeneration.Mappings;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Operations;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters;
+
+///
+/// A custom type that processes C# static field to convert to HLSL static fields (possibly constant).
+///
+internal sealed class StaticFieldRewriter : HlslSourceRewriter
+{
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The instance for the target syntax tree.
+ /// The set of discovered custom types.
+ /// The collection of discovered constant definitions.
+ /// The collection of produced instances.
+ public StaticFieldRewriter(
+ SemanticModelProvider semanticModel,
+ ICollection discoveredTypes,
+ IDictionary constantDefinitions,
+ ImmutableArray.Builder diagnostics)
+ : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
+ {
+ }
+
+ ///
+ public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node)
+ {
+ if (node?.Initializer is EqualsValueClauseSyntax fieldInitializer)
+ {
+ return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value;
+ }
+
+ return null;
+ }
+
+ ///
+ public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
+ {
+ var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!;
+
+ if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
+ SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation)
+ {
+ // Track and replace constants
+ if (operation is IFieldReferenceOperation fieldOperation &&
+ fieldOperation.Field.IsConst &&
+ fieldOperation.Type!.TypeKind != TypeKind.Enum)
+ {
+ if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral))
+ {
+ return ParseExpression(constantLiteral!);
+ }
+
+ ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
+
+ var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
+ var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}";
+
+ return IdentifierName(constantName);
+ }
+
+ if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping))
+ {
+ // Rewrite static and instance mapped members
+ return operation.Member.IsStatic switch
+ {
+ true => ParseExpression(mapping!),
+ false => updatedNode.WithName(IdentifierName(mapping!))
+ };
+ }
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
+ {
+ var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!;
+
+ if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation &&
+ operation.TargetMethod is IMethodSymbol method &&
+ method.IsStatic)
+ {
+ // Rewrite HLSL intrinsic methods
+ if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping))
+ {
+ return updatedNode.WithExpression(ParseExpression(mapping!));
+ }
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode? VisitArgument(ArgumentSyntax node)
+ {
+ var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!;
+
+ updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None));
+
+ return updatedNode;
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Attributes/D2DEmbeddedBytecodeAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DEmbeddedBytecodeAttribute.cs
new file mode 100644
index 00000000..ab9ab4c7
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Attributes/D2DEmbeddedBytecodeAttribute.cs
@@ -0,0 +1,52 @@
+using System;
+#if !SOURCE_GENERATOR
+using ComputeSharp.D2D1.Helpers;
+#endif
+
+namespace ComputeSharp.D2D1;
+
+///
+/// An attribute that indicates that a given D2D1 shader should be precompiled at build time and embedded
+/// directly into the containing assembly as static bytecode, to avoid compiling it at runtime.
+///
+/// This attribute can be used to annotate shader types as follows:
+///
+/// // A compute shader that is dispatched on a target buffer
+/// [D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)]
+/// struct MyShader : ID2D1PixelShader
+/// {
+/// }
+///
+///
+///
+///
+/// The runtime compilation will automatically be skipped if the shader bytecode is then retrieved using a matching profile,
+/// otherwise the usual runtime compilation will be used as fallback (or an exception will be thrown, depending on the API).
+///
+[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
+public sealed class D2DEmbeddedBytecodeAttribute : Attribute
+{
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The target shader profile to use to compile the shader.
+ public D2DEmbeddedBytecodeAttribute(D2D1ShaderProfile shaderProfile)
+ {
+#if !SOURCE_GENERATOR
+ ShaderProfile = shaderProfile switch
+ {
+ D2D1ShaderProfile.PixelShader40 or
+ D2D1ShaderProfile.PixelShader40Level91 or
+ D2D1ShaderProfile.PixelShader40Level93 or
+ D2D1ShaderProfile.PixelShader41 or
+ D2D1ShaderProfile.PixelShader50 => shaderProfile,
+ _ => ThrowHelper.ThrowArgumentException(nameof(shaderProfile), "Invalid shader profile value.")
+ };
+#endif
+ }
+
+ ///
+ /// Gets the number of threads in each thread group for the X axis
+ ///
+ public D2D1ShaderProfile ShaderProfile { get; }
+}
diff --git a/src/ComputeSharp.D2D1/Attributes/D2DInputComplexAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DInputComplexAttribute.cs
new file mode 100644
index 00000000..59f8188b
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Attributes/D2DInputComplexAttribute.cs
@@ -0,0 +1,28 @@
+using System;
+
+namespace ComputeSharp.D2D1;
+
+///
+/// An attribute for a D2D1 shader indicating that an input resource at a specified index uses complex sampling.
+/// This attribute is optional, and not using it will cause inputs to default to complex sampling as well.
+///
+///
+/// This attribute directly maps to #define D2D_INPUT<N>_COMPLEX.
+/// For more info, see .
+[AttributeUsage(AttributeTargets.Struct, AllowMultiple = true)]
+public sealed class D2DInputComplexAttribute : Attribute
+{
+ ///
+ /// Creates a new instance of the type with the specified arguments.
+ ///
+ /// The index of the resource to declare as using complex sampling.
+ public D2DInputComplexAttribute(int index)
+ {
+ Index = index;
+ }
+
+ ///
+ /// Gets the index of the resource declared as using complex sampling.
+ ///
+ public int Index { get; }
+}
diff --git a/src/ComputeSharp.D2D1/Attributes/D2DInputCountAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DInputCountAttribute.cs
new file mode 100644
index 00000000..e578bf23
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Attributes/D2DInputCountAttribute.cs
@@ -0,0 +1,28 @@
+using System;
+
+namespace ComputeSharp.D2D1;
+
+///
+/// An attribute for a D2D1 shader indicating the number of texture inputs for the shader.
+/// Using this attribute is mandatory when defining a D2D1 shader.
+///
+///
+/// This attribute directly maps to #define D2D_INPUT_COUNT <N>.
+/// For more info, see .
+[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
+public sealed class D2DInputCountAttribute : Attribute
+{
+ ///
+ /// Creates a new instance of the type with the specified arguments.
+ ///
+ /// The number of texture inputs for the shader.
+ public D2DInputCountAttribute(int count)
+ {
+ Count = count;
+ }
+
+ ///
+ /// Gets the number of texture inputs for the shader.
+ ///
+ public int Count { get; }
+}
diff --git a/src/ComputeSharp.D2D1/Attributes/D2DInputSimpleAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DInputSimpleAttribute.cs
new file mode 100644
index 00000000..7a23e2ac
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Attributes/D2DInputSimpleAttribute.cs
@@ -0,0 +1,28 @@
+using System;
+
+namespace ComputeSharp.D2D1;
+
+///
+/// An attribute for a D2D1 shader indicating that an input resource at a specified index uses simple
+/// sampling. This attribute is optional, and not using it will cause inputs to default to complex sampling.
+///
+///
+/// This attribute directly maps to #define D2D_INPUT<N>_SIMPLE.
+/// For more info, see .
+[AttributeUsage(AttributeTargets.Struct, AllowMultiple = true)]
+public sealed class D2DInputSimpleAttribute : Attribute
+{
+ ///
+ /// Creates a new instance of the type with the specified arguments.
+ ///
+ /// The index of the resource to declare as using simple sampling.
+ public D2DInputSimpleAttribute(int index)
+ {
+ Index = index;
+ }
+
+ ///
+ /// Gets the index of the resource declared as using simple sampling.
+ ///
+ public int Index { get; }
+}
diff --git a/src/ComputeSharp.D2D1/Attributes/D2DRequiresScenePositionAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DRequiresScenePositionAttribute.cs
new file mode 100644
index 00000000..f61dbc35
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Attributes/D2DRequiresScenePositionAttribute.cs
@@ -0,0 +1,16 @@
+using System;
+
+namespace ComputeSharp.D2D1;
+
+///
+/// An attribute for a D2D1 shader indicating that the shader function calls helper methods that use the scene position
+/// value (that is, ). This parameter should only be included when necessary, since
+/// only one function per linked shader can utilize this parameter. Defining this value is optional.
+///
+///
+/// This attribute directly maps to #define D2D_REQUIRES_SCENE_POSITION.
+/// For more info, see .
+[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
+public sealed class D2DRequiresScenePositionAttribute : Attribute
+{
+}
diff --git a/src/ComputeSharp.D2D1/Attributes/Profiles/D2D1ShaderProfile.cs b/src/ComputeSharp.D2D1/Attributes/Profiles/D2D1ShaderProfile.cs
new file mode 100644
index 00000000..2580c5d2
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Attributes/Profiles/D2D1ShaderProfile.cs
@@ -0,0 +1,69 @@
+namespace ComputeSharp.D2D1;
+
+///
+/// A to be used with to indicate the shader profile to use to precompile a shader.
+///
+public enum D2D1ShaderProfile
+{
+ ///
+ /// Indicates a D2D1 pixel shader compiled for Direct3D 9.1 feature level.
+ ///
+ /// This has the following features:
+ ///
+ /// - 64 arithmetic and 32 texture instructions.
+ /// - 12 temporary registers.
+ /// - 4 levels of dependent reads.
+ ///
+ ///
+ ///
+ ///
+ /// For more info, see .
+ ///
+ PixelShader40Level91,
+
+ ///
+ /// Indicates a D2D1 pixel shader compiled for Direct3D 9.3 feature level.
+ ///
+ /// This has the following features:
+ ///
+ /// - 512 instructions.
+ /// - 32 temporary registers.
+ /// - Static flow control (max depth of 4).
+ /// - Dynamic flow control (max depth of 24).
+ /// - D3DPS20CAPS_ARBITRARYSWIZZLE.
+ /// - D3DPS20CAPS_GRADIENTINSTRUCTIONS.
+ /// - D3DPS20CAPS_PREDICATION.
+ /// - D3DPS20CAPS_NODEPENDENTREADLIMIT.
+ /// - D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT.
+ ///
+ ///
+ ///
+ ///
+ /// For more info, see .
+ ///
+ PixelShader40Level93,
+
+ ///
+ /// Indicates a D2D1 pixel shader compiled for Direct3D 10.0 feature level.
+ ///
+ ///
+ /// For more info, see .
+ ///
+ PixelShader40,
+
+ ///
+ /// Indicates a D2D1 pixel shader compiled for Direct3D 10.1 feature level.
+ ///
+ ///
+ /// For more info, see .
+ ///
+ PixelShader41,
+
+ ///
+ /// Indicates a D2D1 pixel shader compiled for Direct3D 11.0 and 11.1 feature levels.
+ ///
+ ///
+ /// For more info, see .
+ ///
+ PixelShader50
+}
diff --git a/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj b/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj
new file mode 100644
index 00000000..653a3a30
--- /dev/null
+++ b/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj
@@ -0,0 +1,35 @@
+
+
+ netstandard2.0;net6.0
+ bin\Release
+ ComputeSharp.D2D1.xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ true
+ true
+
+
+
+
+
+
+
+
diff --git a/src/ComputeSharp.D2D1/ComputeSharp.D2D1.targets b/src/ComputeSharp.D2D1/ComputeSharp.D2D1.targets
new file mode 100644
index 00000000..7db216b0
--- /dev/null
+++ b/src/ComputeSharp.D2D1/ComputeSharp.D2D1.targets
@@ -0,0 +1,56 @@
+
+
+
+
+
+ <_ComputeSharpAnalyzer Include="@(Analyzer)" Condition="'%(Analyzer.NuGetPackageId)' == 'ComputeSharp.D2D1'" />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ @(CurrentCompilerAssemblyIdentity->'%(Version)')
+
+
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/ComputeSharp.D2D1/Extensions/ComPtrExtensions.cs b/src/ComputeSharp.D2D1/Extensions/ComPtrExtensions.cs
new file mode 100644
index 00000000..ef82e319
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Extensions/ComPtrExtensions.cs
@@ -0,0 +1,42 @@
+using System.Runtime.CompilerServices;
+using TerraFX.Interop.Windows;
+
+namespace ComputeSharp.D2D1.Extensions;
+
+///
+/// Helper methods for working with the type.
+///
+/// Trimmed down version of the same file in ComputeSharp.
+internal static class ComPtrExtensions
+{
+ ///
+ /// Gets the address of the current instance as a raw double pointer.
+ ///
+ /// The type to wrap in the current instance.
+ /// The input instance to get the address for.
+ /// The raw pointer to the input instance.
+ /// This method is only valid when the current instance is on the stack or pinned.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe void** GetVoidAddressOf(this in ComPtr ptr)
+ where T : unmanaged
+ {
+ return (void**)Unsafe.AsPointer(ref Unsafe.AsRef(in ptr));
+ }
+
+ ///
+ /// Moves the current instance and resets it without releasing the reference.
+ ///
+ /// The type to wrap in the current instance.
+ /// The input instance to move.
+ /// The moved instance.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ComPtr Move(this in ComPtr ptr)
+ where T : unmanaged
+ {
+ ComPtr copy = default;
+
+ Unsafe.AsRef(in ptr).Swap(ref copy);
+
+ return copy;
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Extensions/HResultExtensions.cs b/src/ComputeSharp.D2D1/Extensions/HResultExtensions.cs
new file mode 100644
index 00000000..1d5ef42c
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Extensions/HResultExtensions.cs
@@ -0,0 +1,53 @@
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Runtime.CompilerServices;
+using TerraFX.Interop.Windows;
+
+namespace ComputeSharp.D2D1.Extensions;
+
+///
+/// Helper methods to efficiently throw exceptions.
+///
+/// Trimmed down version of the same file in ComputeSharp.
+[DebuggerStepThrough]
+internal static class HResultExtensions
+{
+ ///
+ /// Throws a if represents an error.
+ ///
+ /// The input to check.
+ /// Thrown if represents an error.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void Assert(this HRESULT result)
+ {
+ if ((int)result < 0)
+ {
+ ThrowWin32Exception(result);
+ }
+ }
+
+ ///
+ /// Throws a if represents an error.
+ ///
+ /// The input to check.
+ /// Thrown if represents an error.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void Assert(this int result)
+ {
+ if (result < 0)
+ {
+ ThrowWin32Exception(result);
+ }
+ }
+
+ ///
+ /// Throws a .
+ ///
+ /// The input return code.
+ [DoesNotReturn]
+ private static void ThrowWin32Exception(int result)
+ {
+ throw new Win32Exception(result);
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Extensions/RECTExtensions.cs b/src/ComputeSharp.D2D1/Extensions/RECTExtensions.cs
new file mode 100644
index 00000000..792b7374
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Extensions/RECTExtensions.cs
@@ -0,0 +1,78 @@
+using System.Drawing;
+using System.Runtime.CompilerServices;
+using TerraFX.Interop.Windows;
+#if NET6_0_OR_GREATER
+using Math = System.Math;
+#else
+using Math = ComputeSharp.D2D1.NetStandard.System.Math;
+#endif
+
+namespace ComputeSharp.D2D1.Extensions;
+
+///
+/// Helper methods for and .
+///
+internal static class RECTExtensions
+{
+ ///
+ /// Modifies a target instance to be a D2D1 infinite rectangle.
+ ///
+ /// The target instance to modify.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void MakeD2D1Infinite(this ref RECT rect)
+ {
+ rect.left = int.MinValue;
+ rect.top = int.MinValue;
+ rect.right = int.MaxValue;
+ rect.bottom = int.MaxValue;
+ }
+
+ ///
+ /// Creates a from a value.
+ ///
+ /// The input value.
+ /// The resulting value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Rectangle ToRectangle(this in RECT rect)
+ {
+ int left = Math.Clamp(rect.left, int.MinValue / 2, int.MaxValue / 2);
+ int top = Math.Clamp(rect.top, int.MinValue / 2, int.MaxValue / 2);
+ int right = Math.Clamp(rect.right, int.MinValue / 2, int.MaxValue / 2);
+ int bottom = Math.Clamp(rect.bottom, int.MinValue / 2, int.MaxValue / 2);
+
+ int minX = Math.Min(left, right);
+ int minY = Math.Min(top, bottom);
+ int maxX = Math.Max(left, right);
+ int maxY = Math.Max(top, bottom);
+
+ return new(minX, minY, maxX - minX, maxY - minY);
+ }
+
+ ///
+ /// Creates a from a value.
+ ///
+ /// The input value.
+ /// The resulting value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static RECT ToRECT(this in Rectangle rectangle)
+ {
+ if (rectangle.IsD2D1Infinite())
+ {
+ return new()
+ {
+ left = int.MinValue,
+ top = int.MinValue,
+ right = int.MaxValue,
+ bottom = int.MaxValue
+ };
+ }
+
+ return new()
+ {
+ left = rectangle.Left,
+ top = rectangle.Top,
+ right = rectangle.Right,
+ bottom = rectangle.Bottom
+ };
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Extensions/RectangleExtensions.cs b/src/ComputeSharp.D2D1/Extensions/RectangleExtensions.cs
new file mode 100644
index 00000000..8826f625
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Extensions/RectangleExtensions.cs
@@ -0,0 +1,39 @@
+using System.Drawing;
+using System.Runtime.CompilerServices;
+
+namespace ComputeSharp.D2D1;
+
+///
+/// Helper methods for .
+///
+public static class RectangleExtensions
+{
+ ///
+ /// Modifies a target instance to be a D2D1 infinite rectangle.
+ ///
+ /// The target instance to modify.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void ToD2D1Infinite(this ref Rectangle rectangle)
+ {
+ rectangle = new Rectangle(
+ int.MinValue / 2,
+ int.MinValue / 2,
+ int.MaxValue,
+ int.MaxValue);
+ }
+
+ ///
+ /// Checks whether a given instance represents a D2D1 infinite rectangle.
+ ///
+ /// The input instance to check.
+ /// Whether or not represents a D2D1 infinite rectangle.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static bool IsD2D1Infinite(this in Rectangle rectangle)
+ {
+ return rectangle == new Rectangle(
+ int.MinValue / 2,
+ int.MinValue / 2,
+ int.MaxValue,
+ int.MaxValue);
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Helpers/ThrowHelper.cs b/src/ComputeSharp.D2D1/Helpers/ThrowHelper.cs
new file mode 100644
index 00000000..012eca14
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Helpers/ThrowHelper.cs
@@ -0,0 +1,69 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+
+namespace ComputeSharp.D2D1.Helpers;
+
+///
+/// Helper methods to efficiently throw exceptions.
+///
+internal static partial class ThrowHelper
+{
+ ///
+ /// Throws a new .
+ ///
+ /// The argument name.
+ /// The message to include in the exception.
+ /// Thrown with the specified parameters.
+ [DoesNotReturn]
+ public static void ThrowArgumentException(string? name, string? message)
+ {
+ throw new ArgumentException(message, name);
+ }
+
+ ///
+ /// Throws a new .
+ ///
+ /// The type of expected result.
+ /// The argument name.
+ /// The message to include in the exception.
+ /// Thrown with the specified parameters.
+ /// This method always throws, so it actually never returns a value.
+ [DoesNotReturn]
+ public static T ThrowArgumentException(string? name, string? message)
+ {
+ throw new ArgumentException(message, name);
+ }
+
+ ///
+ /// Throws a new .
+ ///
+ /// The argument name.
+ /// Thrown with the specified parameter.
+ [DoesNotReturn]
+ public static void ThrowArgumentOutOfRangeException(string? name)
+ {
+ throw new ArgumentOutOfRangeException(name);
+ }
+
+ ///
+ /// Throws a new .
+ ///
+ /// The message to include in the exception.
+ /// Thrown with the specified parameter.
+ [DoesNotReturn]
+ public static void ThrowInvalidOperationException(string? message)
+ {
+ throw new InvalidOperationException(message);
+ }
+
+ ///
+ /// Throws a new .
+ ///
+ /// The message to include in the exception.
+ /// Thrown with the specified parameter.
+ [DoesNotReturn]
+ public static void ThrowNotSupportedException(string? message)
+ {
+ throw new NotSupportedException(message);
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1/Interfaces/ID2D1PixelShader.cs b/src/ComputeSharp.D2D1/Interfaces/ID2D1PixelShader.cs
new file mode 100644
index 00000000..c748211a
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Interfaces/ID2D1PixelShader.cs
@@ -0,0 +1,17 @@
+using ComputeSharp.D2D1.__Internals;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.D2D1;
+
+///
+/// An representing a D2D1 pixel shader.
+///
+public interface ID2D1PixelShader : ID2D1Shader
+{
+ ///
+ /// Executes the current pixel shader.
+ ///
+ /// The pixel value for the current invocation.
+ Float4 Execute();
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapper{T}.cs b/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapper{T}.cs
new file mode 100644
index 00000000..ef12cbe1
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapper{T}.cs
@@ -0,0 +1,80 @@
+using System;
+using System.Drawing;
+
+namespace ComputeSharp.D2D1;
+
+///
+/// An providing support for custom, stateful draw transform mappings for shaders.
+///
+public interface ID2D1TransformMapper
+ where T : unmanaged, ID2D1PixelShader
+{
+ ///
+ ///
+ /// Allows a transform to state how it would map a a set of sample rectangles on its input to an output rectangle.
+ ///
+ ///
+ /// This is effectively the inverse mapping of .
+ ///
+ ///
+ /// The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties).
+ /// The input rectangles to be mapped to the output rectangle. This parameter is always equal to the input bounds.
+ /// The input rectangles to be mapped to the opaque output rectangle.
+ /// The output rectangle that maps to the corresponding input rectangle.
+ /// The output rectangle that maps to the corresponding opaque input rectangle.
+ ///
+ ///
+ /// Unlike and , this method is explicitly called by the renderer at
+ /// a determined place in its rendering algorithm. The transform implementation may change its state based on the input rectangles
+ /// and use this information to control its rendering information. This method is always called before the
+ /// and methods.
+ ///
+ ///
+ /// For more info, see .
+ ///
+ ///
+ void MapInputsToOutput(
+ in T shader,
+ ReadOnlySpan inputs,
+ ReadOnlySpan opaqueInputs,
+ out Rectangle output,
+ out Rectangle opaqueOutput);
+
+ ///
+ /// Allows a transform to state how it would map a rectangle requested on its output to a set of sample rectangles on its input.
+ ///
+ /// The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties).
+ /// The output rectangle from which the inputs must be mapped.
+ /// The corresponding set of inputs. The inputs will directly correspond to the transform inputs.
+ ///
+ ///
+ /// The transform implementation must regard this method as purely functional. It can base the mapped input and output rectangles on its
+ /// current state as specified by the encapsulating effect properties. However, it must not change its own state in response to this method
+ /// being invoked. The Direct2D renderer implementation reserves the right to call this method at any time and in any sequence.
+ ///
+ ///
+ /// For more info, see .
+ ///
+ ///
+ void MapOutputToInputs(in T shader, in Rectangle output, Span inputs);
+
+ ///
+ /// Sets the input rectangles for this rendering pass into the transform.
+ ///
+ /// The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties).
+ /// The index of the input rectangle.
+ /// The invalid input rectangle.
+ /// The output rectangle to which the input rectangle must be mapped.
+ ///
+ ///
+ /// The transform implementation must regard this method as purely functional. The transform implementation can base the mapped input rectangle on
+ /// the transform implementation's current state as specified by the encapsulating effect properties. But the transform implementation can't change
+ /// its own state in response to a call to . Direct2D can call this method at any time
+ /// and in any sequence following a call to .
+ ///
+ ///
+ /// For more info, see .
+ ///
+ ///
+ void MapInvalidOutput(in T shader, int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput);
+}
diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1BytecodeLoader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1BytecodeLoader.cs
new file mode 100644
index 00000000..1a20a785
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1BytecodeLoader.cs
@@ -0,0 +1,26 @@
+using System;
+using System.ComponentModel;
+
+namespace ComputeSharp.D2D1.__Internals;
+
+///
+/// A base representing a bytecode loader for a D2D1 shader.
+///
+[EditorBrowsable(EditorBrowsableState.Never)]
+[Obsolete("This interface is not intended to be used directly by user code")]
+public interface ID2D1BytecodeLoader
+{
+ ///
+ /// Loads a dynamic shader bytecode.
+ ///
+ /// An opaque handle to the shader bytecode.
+ /// Thrown if the shader has already been initialized or a precompiled bytecode was requested when not available.
+ void LoadDynamicBytecode(IntPtr handle);
+
+ ///
+ /// Loads the embedded shader bytecode for the shader.
+ ///
+ /// The shader bytecode.
+ /// Thrown if the shader has already been initialized.
+ void LoadEmbeddedBytecode(ReadOnlySpan bytecode);
+}
diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1DispatchDataLoader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1DispatchDataLoader.cs
new file mode 100644
index 00000000..447e3cc9
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1DispatchDataLoader.cs
@@ -0,0 +1,18 @@
+using System;
+using System.ComponentModel;
+
+namespace ComputeSharp.D2D1.__Internals;
+
+///
+/// A base representing a data loader for a D2D1 shader being dispatched.
+///
+[EditorBrowsable(EditorBrowsableState.Never)]
+[Obsolete("This interface is not intended to be used directly by user code")]
+public interface ID2D1DispatchDataLoader
+{
+ ///
+ /// Loads the captured values used by the D2D1 shader to be dispatched.
+ ///
+ /// The sequence of serialized captured values.
+ void LoadConstantBuffer(ReadOnlySpan data);
+}
diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs
new file mode 100644
index 00000000..ef8f36db
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs
@@ -0,0 +1,79 @@
+using System;
+using System.ComponentModel;
+
+namespace ComputeSharp.D2D1.__Internals;
+
+///
+/// A base representing a given shader that can be dispatched.
+///
+[EditorBrowsable(EditorBrowsableState.Never)]
+[Obsolete("This interface is not intended to be used directly by user code")]
+public interface ID2D1Shader
+{
+ ///
+ /// Initializes the current shader from a buffer with the serialized dispatch data.
+ ///
+ /// The input buffer with the serialized dispatch data.
+ /// The input buffer must be retrieved from .
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [Obsolete("This method is not intended to be called directly by user code")]
+ void InitializeFromDispatchData(ReadOnlySpan data)
+#if NET6_0_OR_GREATER
+ {
+ throw new NotImplementedException();
+ }
+#else
+ ;
+#endif
+
+ ///
+ /// Loads the dispatch data for the shader.
+ ///
+ /// The type of data loader being used.
+ /// The instance to use to load the data.
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [Obsolete("This method is not intended to be called directly by user code")]
+ void LoadDispatchData(ref TLoader loader)
+ where TLoader : struct, ID2D1DispatchDataLoader
+#if NET6_0_OR_GREATER
+ {
+ throw new NotImplementedException();
+ }
+#else
+ ;
+#endif
+
+ ///
+ /// Builds the HLSL source code for the current shader instance.
+ ///
+ /// The resulting HLSL source.
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [Obsolete("This method is not intended to be called directly by user code")]
+ void BuildHlslSource(out string hlslSource)
+#if NET6_0_OR_GREATER
+ {
+ throw new NotImplementedException();
+ }
+#else
+ ;
+#endif
+
+ ///
+ /// Loads the bytecode for the current shader.
+ ///
+ /// The type of bytecode loader being used.
+ /// The instance to use to load the bytecode.
+ /// The shader profile to use to get the shader bytecode (if , the precompiled shader will be used).
+ /// Thrown if a precompiled bytecode was requested ( is ), but it wasn't availablle.
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [Obsolete("This method is not intended to be used directly by user code")]
+ void LoadBytecode(ref TLoader loader, D2D1ShaderProfile? shaderProfile)
+ where TLoader : struct, ID2D1BytecodeLoader
+#if NET6_0_OR_GREATER
+ {
+ throw new NotImplementedException();
+ }
+#else
+ ;
+#endif
+}
diff --git a/src/ComputeSharp.D2D1/Intrinsics/D2D.cs b/src/ComputeSharp.D2D1/Intrinsics/D2D.cs
new file mode 100644
index 00000000..328e7dbd
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Intrinsics/D2D.cs
@@ -0,0 +1,67 @@
+using ComputeSharp.Core.Intrinsics.Attributes;
+using ComputeSharp.Exceptions;
+
+namespace ComputeSharp.D2D1;
+
+///
+/// A that maps the supported HLSL intrinsic functions specifically for D2D1 shaders.
+///
+/// For more info, see .
+public static class D2D
+{
+ ///
+ /// Returns the color of the input texture at a specific index, for the curreent coordinate.
+ ///
+ /// The index of the input texture to get the input from.
+ /// The color from the target input at the current coordinate, in INPUTN format.
+ /// This method is only available for simple inputs.
+ [HlslIntrinsicName("D2DGetInput")]
+ public static Float4 GetInput(int index) => throw new InvalidExecutionContextException($"{typeof(D2D)}.{nameof(GetInput)}({typeof(int)})");
+
+ ///
+ /// Returns the coordinate of the input texture at a specific index.
+ ///
+ /// The index of the input texture to get the coordinate for.
+ /// The input coordinate, in TEXCOORDN format.
+ /// This method is only available for complex inputs.
+ [HlslIntrinsicName("D2DGetInputCoordinate")]
+ public static Float4 GetInputCoordinate(int index) => throw new InvalidExecutionContextException($"{typeof(D2D)}.{nameof(GetInputCoordinate)}({typeof(int)})");
+
+ ///
+ /// Returns the value of the current scene position.
+ ///
+ /// The current scene position, in SCENE_POSITION format.
+ /// This method is only available when is used on the shader type.
+ [HlslIntrinsicName("D2DGetScenePosition")]
+ public static Float4 GetScenePosition() => throw new InvalidExecutionContextException($"{typeof(D2D)}.{nameof(GetScenePosition)}()");
+
+ ///
+ /// Samples the input texture at a specified index and at a given position.
+ ///
+ /// The index of the input texture to sample.
+ /// The normalized coordinate to use to sample the texture.
+ /// The sampled value from the texture, in TEXCOORDN format.
+ /// This method is only available for complex inputs.
+ [HlslIntrinsicName("D2DSampleInput")]
+ public static Float4 SampleInput(int index, Float2 uv) => throw new InvalidExecutionContextException($"{typeof(D2D)}.{nameof(SampleInput)}({typeof(int)}, {typeof(Float2)})");
+
+ ///
+ /// Samples the input texturee at a specified index and at a given offset from the input coordinate.
+ ///
+ /// The index of the input texture to sample.
+ /// The normalized offset to use to sample the texture.
+ /// The sampled value from the texture, in TEXCOORDN format.
+ /// This method is only available for simple inputs.
+ [HlslIntrinsicName("D2DSampleInputAtOffset")]
+ public static Float4 SampleInputAtOffset(int index, Float2 offset) => throw new InvalidExecutionContextException($"{typeof(D2D)}.{nameof(SampleInputAtOffset)}({typeof(int)}, {typeof(Float2)})");
+
+ ///
+ /// Samples the input texture at a specified index and at an absolute scene position (not an input-relative position).
+ ///
+ /// The index of the input texture to sample.
+ /// The normalized coordinate to use to sample the texture.
+ /// The sampled value from the texture, in TEXCOORDN format.
+ /// This method is only available for complex inputs.
+ [HlslIntrinsicName("D2DSampleInputAtPosition")]
+ public static Float4 SampleInputAtPosition(int index, Float2 uv) => throw new InvalidExecutionContextException($"{typeof(D2D)}.{nameof(SampleInputAtPosition)}({typeof(int)}, {typeof(Float2)})");
+}
diff --git a/src/ComputeSharp.D2D1/Properties/AssemblyInfo.cs b/src/ComputeSharp.D2D1/Properties/AssemblyInfo.cs
new file mode 100644
index 00000000..196f23c5
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Properties/AssemblyInfo.cs
@@ -0,0 +1,3 @@
+using System.Runtime.CompilerServices;
+
+[module: SkipLocalsInit]
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs
new file mode 100644
index 00000000..2b00632a
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using ComputeSharp.D2D1.__Internals;
+using TerraFX.Interop.DirectX;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.D2D1.Shaders.Dispatching;
+
+///
+/// A data loader for D2D1 pixel shaders dispatched via .
+///
+internal struct D2D1ByteArrayDispatchDataLoader : ID2D1DispatchDataLoader
+{
+ ///
+ /// The object in use.
+ ///
+ private byte[]? data;
+
+ ///
+ /// Gets the resulting pixel shader constant buffer.
+ ///
+ /// A array with the constant buffer for the current shader.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public byte[] GetResultingDispatchData()
+ {
+ return this.data!;
+ }
+
+ ///
+ public void LoadConstantBuffer(ReadOnlySpan data)
+ {
+ this.data = MemoryMarshal.AsBytes(data).ToArray();
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs
new file mode 100644
index 00000000..be47d04c
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs
@@ -0,0 +1,38 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using ComputeSharp.D2D1.__Internals;
+using TerraFX.Interop.DirectX;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.D2D1.Shaders.Dispatching;
+
+///
+/// A data loader for D2D1 pixel shaders dispatched via .
+///
+internal readonly unsafe struct D2D1DrawInfoDispatchDataLoader : ID2D1DispatchDataLoader
+{
+ ///
+ /// The object in use.
+ ///
+ private readonly ID2D1DrawInfo* d2D1DrawInfo;
+
+ ///
+ /// Creates a new instance.
+ ///
+ /// The object to use.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal D2D1DrawInfoDispatchDataLoader(ID2D1DrawInfo* d2D1DrawInfo)
+ {
+ this.d2D1DrawInfo = d2D1DrawInfo;
+ }
+
+ ///
+ public void LoadConstantBuffer(ReadOnlySpan data)
+ {
+ this.d2D1DrawInfo->SetPixelShaderConstantBuffer(
+ buffer: (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data)),
+ bufferCount: (uint)data.Length * sizeof(uint));
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1EffectDispatchDataLoader.cs b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1EffectDispatchDataLoader.cs
new file mode 100644
index 00000000..e5697042
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1EffectDispatchDataLoader.cs
@@ -0,0 +1,41 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using ComputeSharp.D2D1.__Internals;
+using ComputeSharp.D2D1.Extensions;
+using TerraFX.Interop.DirectX;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.D2D1.Shaders.Dispatching;
+
+///
+/// A data loader for D2D1 pixel shaders dispatched via .
+///
+internal readonly unsafe struct D2D1EffectDispatchDataLoader : ID2D1DispatchDataLoader
+{
+ ///
+ /// The object in use.
+ ///
+ private readonly ID2D1Effect* d2D1Effect;
+
+ ///
+ /// Creates a new instance.
+ ///
+ /// The object to use.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal D2D1EffectDispatchDataLoader(ID2D1Effect* d2D1Effect)
+ {
+ this.d2D1Effect = d2D1Effect;
+ }
+
+ ///
+ public void LoadConstantBuffer(ReadOnlySpan data)
+ {
+ this.d2D1Effect->SetValue(
+ index: 0,
+ type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BLOB,
+ data: (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data)),
+ dataSize: (uint)data.Length * sizeof(uint)).Assert();
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs
new file mode 100644
index 00000000..0d0da779
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs
@@ -0,0 +1,78 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using ComputeSharp.D2D1.__Internals;
+using ComputeSharp.D2D1.Extensions;
+using ComputeSharp.D2D1.Helpers;
+using TerraFX.Interop.DirectX;
+using TerraFX.Interop.Windows;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.D2D1.Shaders.Dispatching;
+
+///
+/// A bytecode loader for D2D1 shaders.
+///
+internal unsafe struct D2D1ShaderBytecodeLoader : ID2D1BytecodeLoader
+{
+ ///
+ /// A pointer to the precompiled shader, if available.
+ ///
+ private byte* embeddedBytecodePtr;
+
+ ///
+ /// The length of the precompiled shader buffer, if available.
+ ///
+ private int embeddedBytecodeSize;
+
+ ///
+ /// The dynamically compiled shader bytecode blob, if available.
+ ///
+ private ComPtr d3DBlob;
+
+ ///
+ /// Gets the resulting shader bytecode that was available.
+ ///
+ /// The precompiled bytecode, if available.
+ /// An with the shader bytecode, if dynamically compiled.
+ /// Either is empty, or the returned pointer is .
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ComPtr GetResultingShaderBytecode(out ReadOnlySpan precompiledBytecode)
+ {
+ precompiledBytecode = new ReadOnlySpan(this.embeddedBytecodePtr, this.embeddedBytecodeSize);
+
+ return this.d3DBlob.Move();
+ }
+
+ ///
+ public unsafe void LoadDynamicBytecode(IntPtr handle)
+ {
+ if (this.embeddedBytecodePtr is not null ||
+ this.d3DBlob.Get() is not null)
+ {
+ ThrowHelper.ThrowInvalidOperationException("The shader has already been initialized.");
+ }
+
+ if (handle == IntPtr.Zero)
+ {
+ ThrowHelper.ThrowNotSupportedException("Runtime shader compilation is not supported by the current configuration.");
+ }
+
+ this.d3DBlob = new ComPtr((ID3DBlob*)handle);
+ }
+
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void LoadEmbeddedBytecode(ReadOnlySpan bytecode)
+ {
+ if (this.embeddedBytecodePtr is not null ||
+ this.d3DBlob.Get() is not null)
+ {
+ ThrowHelper.ThrowInvalidOperationException("The shader has already been initialized.");
+ }
+
+ this.embeddedBytecodePtr = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(bytecode));
+ this.embeddedBytecodeSize = bytecode.Length;
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Shaders/Exceptions/FxcCompilationException.cs b/src/ComputeSharp.D2D1/Shaders/Exceptions/FxcCompilationException.cs
new file mode 100644
index 00000000..cdb5e2a3
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Shaders/Exceptions/FxcCompilationException.cs
@@ -0,0 +1,38 @@
+using System;
+using System.Text;
+
+namespace ComputeSharp.D2D1.Exceptions;
+
+///
+/// A custom type that indicates when a shader compilation with the FXC compiler has failed.
+///
+public sealed class FxcCompilationException : Exception
+{
+ ///
+ /// Creates a new instance.
+ ///
+ /// The error message produced by the DXC compiler.
+ internal FxcCompilationException(string error)
+ : base(GetExceptionMessage(error))
+ {
+ }
+
+ ///
+ /// Gets a formatted exception message for a given compilation error.
+ ///
+ /// The input compilatin error message from the FXC compiler.
+ /// A formatted error message for a new instance.
+ private static string GetExceptionMessage(string error)
+ {
+ StringBuilder builder = new(512);
+
+ builder.AppendLine("The FXC compiler encountered one or more errors while trying to compile the shader:");
+ builder.AppendLine();
+ builder.AppendLine(error.Trim());
+ builder.AppendLine();
+ builder.AppendLine("Make sure to only be using supported features by checking the README file in the ComputeSharp repository: https://github.com/Sergio0694/ComputeSharp.");
+ builder.Append("If you're sure that your C# shader code is valid, please open an issue an include a working repro and this error message.");
+
+ return builder.ToString();
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs
new file mode 100644
index 00000000..ebef74a0
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs
@@ -0,0 +1,235 @@
+using System;
+using System.Buffers;
+using System.Numerics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Text;
+#if !NET6_0_OR_GREATER
+using ComputeSharp.D2D1.NetStandard.System.Text;
+using BitOperations = ComputeSharp.D2D1.NetStandard.System.Buffers.BitOperations;
+#endif
+
+namespace ComputeSharp.D2D1.Shaders.Interop.Buffers;
+
+///
+/// Represents a heap-based, array-backed output sink into which binary data can be written.
+///
+internal ref struct ArrayPoolBinaryWriter
+{
+ ///
+ /// The default buffer size to use to expand empty arrays.
+ ///
+ public const int DefaultInitialBufferSize = 256;
+
+ ///
+ /// The underlying array.
+ ///
+ private byte[]? array;
+
+ ///
+ /// The starting offset within .
+ ///
+ private int index;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public ArrayPoolBinaryWriter(int capacity)
+ {
+ this.array = ArrayPool.Shared.Rent(capacity);
+ this.index = 0;
+ }
+
+ ///
+ /// Gets the data written to the underlying buffer so far, as a .
+ ///
+ public ReadOnlySpan WrittenSpan
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get
+ {
+ byte[]? array = this.array;
+
+ if (array is null)
+ {
+ ThrowObjectDisposedException();
+ }
+
+ return array!.AsSpan(0, this.index);
+ }
+ }
+
+ ///
+ /// Writes a value of type into the buffer.
+ ///
+ /// The type of value to write.
+ /// The value to write.
+ public unsafe void Write(in T value)
+ where T : unmanaged
+ {
+ Span span = GetSpan(sizeof(T));
+
+ MemoryMarshal.Write(span, ref Unsafe.AsRef(in value));
+
+ Advance(sizeof(T));
+ }
+
+ ///
+ /// Writes text as UTF8 bytes into the buffer.
+ ///
+ /// The text to write.
+ public unsafe void WriteAsUtf8(string text)
+ {
+ int maximumByteSize = Encoding.UTF8.GetMaxByteCount(text.Length);
+
+ Span span = GetSpan(maximumByteSize);
+
+ int writtenBytes = Encoding.UTF8.GetBytes(text.AsSpan(), span);
+
+ Advance(writtenBytes);
+ }
+
+ ///
+ /// Advances the current writer.
+ ///
+ /// The amount to advance.
+ /// Must be called after .
+ private void Advance(int count)
+ {
+ byte[]? array = this.array;
+
+ if (array is null)
+ {
+ ThrowObjectDisposedException();
+ }
+
+ if (count < 0)
+ {
+ ThrowArgumentOutOfRangeExceptionForNegativeCount();
+ }
+
+ if (this.index > array!.Length - count)
+ {
+ ThrowArgumentExceptionForAdvancedTooFar();
+ }
+
+ this.index += count;
+ }
+
+ ///
+ /// Gets a to write data to, with an optional minimum capacity.
+ ///
+ /// The capacity to request.
+ /// A to write data to.
+ private Span GetSpan(int sizeHint = 0)
+ {
+ CheckBufferAndEnsureCapacity(sizeHint);
+
+ return this.array.AsSpan(this.index);
+ }
+
+ ///
+ /// Ensures that has enough free space to contain a given number of new items.
+ ///
+ /// The minimum number of items to ensure space for in .
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private void CheckBufferAndEnsureCapacity(int sizeHint)
+ {
+ byte[]? array = this.array;
+
+ if (array is null)
+ {
+ ThrowObjectDisposedException();
+ }
+
+ if (sizeHint < 0)
+ {
+ ThrowArgumentOutOfRangeExceptionForNegativeSizeHint();
+ }
+
+ if (sizeHint == 0)
+ {
+ sizeHint = 1;
+ }
+
+ if (sizeHint > array!.Length - this.index)
+ {
+ ResizeBuffer(sizeHint);
+ }
+ }
+
+ ///
+ /// Resizes to ensure it can fit the specified number of new items.
+ ///
+ /// The minimum number of items to ensure space for in .
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private void ResizeBuffer(int sizeHint)
+ {
+ uint minimumSize = (uint)this.index + (uint)sizeHint;
+
+ // The ArrayPool class has a maximum threshold of 1024 * 1024 for the maximum length of
+ // pooled arrays, and once this is exceeded it will just allocate a new array every time
+ // of exactly the requested size. In that case, we manually round up the requested size to
+ // the nearest power of two, to ensure that repeated consecutive writes when the array in
+ // use is bigger than that threshold don't end up causing a resize every single time.
+ if (minimumSize > 1024 * 1024)
+ {
+ minimumSize = BitOperations.RoundUpToPowerOf2(minimumSize);
+ }
+
+ byte[] newArray = ArrayPool.Shared.Rent((int)minimumSize);
+
+ Buffer.BlockCopy(this.array!, 0, newArray, 0, this.index);
+
+ ArrayPool.Shared.Return(this.array!);
+
+ this.array = newArray;
+ }
+
+ ///
+ public void Dispose()
+ {
+ byte[]? array = this.array;
+
+ if (array is null)
+ {
+ return;
+ }
+
+ this.array = null;
+
+ ArrayPool.Shared.Return(array);
+ }
+
+ ///
+ /// Throws an when the requested count is negative.
+ ///
+ private static void ThrowArgumentOutOfRangeExceptionForNegativeCount()
+ {
+ throw new ArgumentOutOfRangeException("count", "The count can't be a negative value.");
+ }
+
+ ///
+ /// Throws an when the size hint is negative.
+ ///
+ private static void ThrowArgumentOutOfRangeExceptionForNegativeSizeHint()
+ {
+ throw new ArgumentOutOfRangeException("sizeHint", "The size hint can't be a negative value.");
+ }
+
+ ///
+ /// Throws an when the requested count is negative.
+ ///
+ private static void ThrowArgumentExceptionForAdvancedTooFar()
+ {
+ throw new ArgumentException("The buffer writer has advanced too far.");
+ }
+
+ ///
+ /// Throws an when is .
+ ///
+ private static void ThrowObjectDisposedException()
+ {
+ throw new ObjectDisposedException("The current buffer has already been disposed.");
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/PinnedBufferMemoryManager.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/PinnedBufferMemoryManager.cs
new file mode 100644
index 00000000..4fb3d71d
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/PinnedBufferMemoryManager.cs
@@ -0,0 +1,60 @@
+using System;
+using System.Buffers;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using ComputeSharp.D2D1.Helpers;
+
+namespace ComputeSharp.D2D1.Shaders.Interop.Buffers;
+
+///
+/// A custom that wraps a pinned memory buffer.
+///
+internal sealed unsafe class PinnedBufferMemoryManager : MemoryManager
+{
+ ///
+ /// A pointer to the buffer.
+ ///
+ private readonly byte* buffer;
+
+ ///
+ /// The length of the buffer.
+ ///
+ private readonly int length;
+
+ ///
+ /// Initializes a new instance of the class with the specified parameters.
+ ///
+ /// A wrapping the input pinned buffer.
+ public PinnedBufferMemoryManager(ReadOnlySpan span)
+ {
+ this.buffer = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span));
+ this.length = span.Length;
+ }
+
+ ///
+ public override Span GetSpan()
+ {
+ return new(this.buffer, this.length);
+ }
+
+ ///
+ public override unsafe MemoryHandle Pin(int elementIndex = 0)
+ {
+ if ((uint)elementIndex >= this.length)
+ {
+ ThrowHelper.ThrowArgumentOutOfRangeException(nameof(elementIndex));
+ }
+
+ return new(this.buffer + elementIndex);
+ }
+
+ ///
+ public override void Unpin()
+ {
+ }
+
+ ///
+ protected override void Dispose(bool disposing)
+ {
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1EffectRegistrationData.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1EffectRegistrationData.cs
new file mode 100644
index 00000000..cba3bc9b
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1EffectRegistrationData.cs
@@ -0,0 +1,301 @@
+using System;
+using System.Runtime.InteropServices;
+using System.Text;
+using ComputeSharp.D2D1.Helpers;
+#if !NET6_0_OR_GREATER
+using ComputeSharp.D2D1.NetStandard.System.Text;
+#endif
+
+namespace ComputeSharp.D2D1.Interop;
+
+///
+/// A helper type used to read and validate effect registration blobs produced
+/// by .
+///
+///
+///
+/// The values in a instance contain all necessary
+/// information to register a new D2D1 effect by calling ID2D1Factory1::RegisterEffectFromString.
+///
+///
+/// For more info, see .
+///
+///
+public static class D2D1EffectRegistrationData
+{
+ ///
+ /// The containing type for deserialized version 1 registration blobs.
+ ///
+ public unsafe readonly struct V1
+ {
+ ///
+ /// The blob id for V1 registration data.
+ ///
+ internal static readonly Guid BlobId = new(0xA1B4A55E, 0x4C78, 0x413F, 0xA2, 0xE6, 0x0A, 0x02, 0xE6, 0x0A, 0x76, 0x18);
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The effect class id.
+ /// The number of inputs for the effect.
+ /// The XML text that can be used to register the effect.
+ /// The values for the effect.
+ /// A pointer to the effect factory callback.
+ private V1(
+ Guid classId,
+ int numberOfInputs,
+ string propertyXml,
+ D2D1PropertyBinding[] propertyBindings,
+ nint effectFactory)
+ {
+ ClassId = classId;
+ NumberOfInputs = numberOfInputs;
+ PropertyXml = propertyXml;
+ PropertyBindings = propertyBindings;
+ EffectFactory = (void*)effectFactory;
+ }
+
+ ///
+ /// Gets the id to use to register the effect.
+ ///
+ public Guid ClassId { get; }
+
+ ///
+ /// Gets the number of inputs for the effect.
+ ///
+ public int NumberOfInputs { get; }
+
+ ///
+ /// Gets the XML text with the effect description, that can be used to register it.
+ ///
+ public string PropertyXml { get; }
+
+ ///
+ /// Gets the sequence of values for the effect.
+ ///
+ public ReadOnlyMemory PropertyBindings { get; }
+
+ ///
+ /// Gets a callback to an effect factory (a ).
+ ///
+ public void* EffectFactory { get; }
+
+ ///
+ /// Loads a instance from the input binary blob.
+ ///
+ /// The input binary blob to deserialize.
+ /// The resulting instance.
+ /// Thrown if the loading failed.
+ ///
+ /// The input blob should have been created by a call to any of the overloads
+ /// of .
+ ///
+ public static V1 Load(ReadOnlyMemory blob)
+ {
+ switch (TryLoadAndGetResult(blob, out V1 data))
+ {
+ case LoadingResult.Success:
+ return data;
+ case LoadingResult.EmptyBuffer:
+ ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob is empty.");
+ break;
+ case LoadingResult.BufferTooShort:
+ ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob is too short.");
+ break;
+ case LoadingResult.BufferTooLong:
+ ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob is too long.");
+ break;
+ case LoadingResult.MismatchedBlobVersionId:
+ ThrowHelper.ThrowArgumentException(nameof(blob), "The blob version id from the input blob does not match.");
+ break;
+ case LoadingResult.InvalidNumberOfInputs:
+ ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob has an invalid number of inputs.");
+ break;
+ case LoadingResult.InvalidPropertyXml:
+ ThrowHelper.ThrowArgumentException(nameof(blob), "The property XML value in the input blob is invalid.");
+ break;
+ case LoadingResult.InvalidNumberOfBindings:
+ ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob declares an invalid number of bindings.");
+ break;
+ case LoadingResult.InvalidBindingPropertyName:
+ ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob has an invalid property name for one of its property bindings.");
+ break;
+ default:
+ ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob failed to be loaded for an unknown reason.");
+ break;
+ }
+
+ return data;
+ }
+
+ ///
+ /// Tries to load a instance from the input binary blob.
+ ///
+ /// The input binary blob to deserialize.
+ /// The resulting instance, if successful.
+ /// Whether or not the input blob has been correctly deserialized (if it was not malformed).
+ ///
+ /// The input blob should have been created by a call to any of the overloads
+ /// of .
+ ///
+ public static bool TryLoad(ReadOnlyMemory blob, out V1 data)
+ {
+ return TryLoadAndGetResult(blob, out data) is LoadingResult.Success;
+ }
+
+ ///
+ /// Tries to load a instance from the input binary blob and returns a result.
+ ///
+ /// The input binary blob to deserialize.
+ /// The resulting instance, if successful.
+ /// The result of the loading operation.
+ private static LoadingResult TryLoadAndGetResult(ReadOnlyMemory blob, out V1 data)
+ {
+ data = default;
+
+ if (blob.IsEmpty)
+ {
+ return LoadingResult.EmptyBuffer;
+ }
+
+ ReadOnlySpan span = blob.Span;
+
+ // Blob id
+ if (!MemoryMarshal.TryRead(span, out Guid blobId))
+ {
+ return LoadingResult.BufferTooShort;
+ }
+
+ // Validate the blob id
+ if (blobId != BlobId)
+ {
+ return LoadingResult.MismatchedBlobVersionId;
+ }
+
+ span = span.Slice(sizeof(Guid));
+
+ // Effect class id
+ if (!MemoryMarshal.TryRead(span, out Guid effectId))
+ {
+ return LoadingResult.BufferTooShort;
+ }
+
+ span = span.Slice(sizeof(Guid));
+
+ // Number of inputs
+ if (!MemoryMarshal.TryRead(span, out int numberOfInputs))
+ {
+ return LoadingResult.BufferTooShort;
+ }
+
+ // Validate the number of inputs
+ if (numberOfInputs < 0)
+ {
+ return LoadingResult.InvalidNumberOfInputs;
+ }
+
+ span = span.Slice(sizeof(int));
+
+ // Effect property XML
+ int lengthOfXml = span.IndexOf((byte)'\0');
+
+ if (lengthOfXml == -1)
+ {
+ return LoadingResult.InvalidPropertyXml;
+ }
+
+ string xml = Encoding.UTF8.GetString(span.Slice(0, lengthOfXml));
+
+ span = span.Slice(lengthOfXml + 1);
+
+ // Number of bindings
+ if (!MemoryMarshal.TryRead(span, out int numberOfBindings))
+ {
+ return LoadingResult.BufferTooShort;
+ }
+
+ // Validate the number of bindings
+ if (numberOfBindings < 0)
+ {
+ return LoadingResult.InvalidNumberOfBindings;
+ }
+
+ span = span.Slice(sizeof(int));
+
+ D2D1PropertyBinding[] propertyBindings = new D2D1PropertyBinding[numberOfBindings];
+
+ // Property bindings
+ for (int i = 0; i < numberOfBindings; i++)
+ {
+ // Property name
+ int lengthOfName = span.IndexOf((byte)'\0');
+
+ if (lengthOfName == -1)
+ {
+ return LoadingResult.InvalidBindingPropertyName;
+ }
+
+ string name = Encoding.UTF8.GetString(span.Slice(0, lengthOfName));
+
+ span = span.Slice(lengthOfName + 1);
+
+ // Property get function
+ if (!MemoryMarshal.TryRead(span, out nint getFunction))
+ {
+ return LoadingResult.BufferTooShort;
+ }
+
+ span = span.Slice(sizeof(nint));
+
+ // Property set function
+ if (!MemoryMarshal.TryRead(span, out nint setFunction))
+ {
+ return LoadingResult.BufferTooShort;
+ }
+
+ span = span.Slice(sizeof(nint));
+
+ propertyBindings[i] = new D2D1PropertyBinding(name, (void*)getFunction, (void*)setFunction);
+ }
+
+ // Effect factory
+ if (!MemoryMarshal.TryRead(span, out nint effectFactory))
+ {
+ return LoadingResult.BufferTooShort;
+ }
+
+ span = span.Slice(sizeof(nint));
+
+ // If the buffer is bigger than expected, also consider it malformed
+ if (span.Length > 0)
+ {
+ return LoadingResult.BufferTooLong;
+ }
+
+ data = new V1(
+ effectId,
+ numberOfInputs,
+ xml,
+ propertyBindings,
+ effectFactory);
+
+ return LoadingResult.Success;
+ }
+
+ ///
+ /// Indicates the result of a blob loading operation.
+ ///
+ private enum LoadingResult
+ {
+ Success,
+ EmptyBuffer,
+ BufferTooShort,
+ BufferTooLong,
+ MismatchedBlobVersionId,
+ InvalidNumberOfInputs,
+ InvalidPropertyXml,
+ InvalidNumberOfBindings,
+ InvalidBindingPropertyName
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.cs
new file mode 100644
index 00000000..ab88fa9c
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.cs
@@ -0,0 +1,113 @@
+using System;
+using System.Runtime.CompilerServices;
+using ComputeSharp.D2D1.Shaders.Dispatching;
+using ComputeSharp.D2D1.Shaders.Interop.Buffers;
+using TerraFX.Interop.DirectX;
+using TerraFX.Interop.Windows;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.D2D1.Interop;
+
+///
+/// Provides methods to interop with D2D1 APIs and compile shaders or extract their constant buffer data.
+///
+public static unsafe class D2D1InteropServices
+{
+ ///
+ /// Loads the bytecode from an input D2D1 pixel shader.
+ ///
+ /// The type of D2D1 pixel shader to load the bytecode for.
+ /// A instance with the resulting shader bytecode.
+ ///
+ /// This method will only compile the shader using if no precompiled shader is available.
+ ///
+ /// If the input shader was precompiled, the returned instance will wrap a pinned memory buffer (from the PE section).
+ /// If the shader was compiled at runtime, the returned instance will wrap a array with the bytecode.
+ ///
+ ///
+ public static ReadOnlyMemory LoadShaderBytecode()
+ where T : unmanaged, ID2D1PixelShader
+ {
+ return LoadOrCompileShaderBytecode(null);
+ }
+
+ ///
+ /// Loads the bytecode from an input D2D1 pixel shader.
+ ///
+ /// The type of D2D1 pixel shader to load the bytecode for.
+ /// The shader profile to use to get the shader bytecode.
+ /// A instance with the resulting shader bytecode.
+ ///
+ /// If the input shader was precompiled, the returned instance will wrap a pinned memory buffer (from the PE section).
+ /// If the shader was compiled at runtime, the returned instance will wrap a array with the bytecode.
+ ///
+ public static ReadOnlyMemory LoadShaderBytecode(D2D1ShaderProfile shaderProfile)
+ where T : unmanaged, ID2D1PixelShader
+ {
+ return LoadOrCompileShaderBytecode(shaderProfile);
+ }
+
+ ///
+ /// Loads or compiles the bytecode from an input D2D1 pixel shader.
+ ///
+ /// The type of D2D1 pixel shader to load the bytecode for.
+ /// The shader profile to use to get the shader bytecode.
+ /// A instance with the resulting shader bytecode.
+ /// Thrown if the input shader has not been precompiled.
+ private static ReadOnlyMemory LoadOrCompileShaderBytecode(D2D1ShaderProfile? shaderProfile)
+ where T : unmanaged, ID2D1PixelShader
+ {
+ D2D1ShaderBytecodeLoader bytecodeLoader = default;
+
+ Unsafe.NullRef().LoadBytecode(ref bytecodeLoader, shaderProfile);
+
+ using ComPtr dynamicBytecode = bytecodeLoader.GetResultingShaderBytecode(out ReadOnlySpan