diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml
index d348c6f2..d8f2a7d9 100644
--- a/.github/workflows/dotnet.yml
+++ b/.github/workflows/dotnet.yml
@@ -42,8 +42,8 @@ jobs:
run: dotnet pack src\ComputeSharp.Core\ComputeSharp.Core.csproj -c Release
- name: Build ComputeSharp package
run: dotnet pack src\ComputeSharp\ComputeSharp.csproj -c Release
- - name: Build ComputeSharp.Dynamic package
- run: dotnet pack src\ComputeSharp.Dynamic\ComputeSharp.Dynamic.csproj -c Release
+ - name: Build ComputeSharp.Dxc package
+ run: dotnet pack src\ComputeSharp.Dxc\ComputeSharp.Dxc.csproj -c Release
- name: Build ComputeSharp.D3D12MemoryAllocator package
run: dotnet pack src\ComputeSharp.D3D12MemoryAllocator\ComputeSharp.D3D12MemoryAllocator.csproj -c Release
- name: Build ComputeSharp.D2D1 package
@@ -68,7 +68,7 @@ jobs:
needs: [build-solution]
runs-on: windows-2022
- # Set the environment variable which is then looked up in ComputeSharp.Dynamic.
+ # Set the environment variable which is then looked up in ComputeSharp.Dxc.
# This is a workaround for https://github.com/actions/runner-images/issues/6531.
env:
CI_RUNNER_DOTNET_TEST_PLATFORM: x64
@@ -289,8 +289,8 @@ jobs:
path: artifacts
- name: Build and run ComputeSharp.NuGet
run: dotnet run --project tests\ComputeSharp.NuGet\ComputeSharp.NuGet.csproj -c Release -r win-x64 --no-self-contained -v n
- - name: Build and run ComputeSharp.Dynamic.NuGet
- run: dotnet run --project tests\ComputeSharp.Dynamic.NuGet\ComputeSharp.Dynamic.NuGet.csproj -c Release -r win-x64 --no-self-contained -v n
+ - name: Build and run ComputeSharp.Dxc.NuGet
+ run: dotnet run --project tests\ComputeSharp.Dxc.NuGet\ComputeSharp.Dxc.NuGet.csproj -c Release -r win-x64 --no-self-contained -v n
- name: Build and run ComputeSharp.Pix.NuGet
run: dotnet run --project tests\ComputeSharp.Pix.NuGet\ComputeSharp.Pix.NuGet.csproj -c Release -r win-x64 --no-self-contained -v n
@@ -306,11 +306,11 @@ jobs:
$env:COMPUTESHARP_NUGET_TESTS_PUBLISH_AOT='true';
dotnet publish tests\ComputeSharp.NuGet\ComputeSharp.NuGet.csproj -c Release -r win-x64 -v n;
tests\ComputeSharp.NuGet\bin\Release\net7.0\win-x64\publish\ComputeSharp.NuGet.exe
- - name: Publish and run ComputeSharp.Dynamic.NuGet with NativeAOT
+ - name: Publish and run ComputeSharp.Dxc.NuGet with NativeAOT
run: >
$env:COMPUTESHARP_NUGET_TESTS_PUBLISH_AOT='true';
- dotnet publish tests\ComputeSharp.Dynamic.NuGet\ComputeSharp.Dynamic.NuGet.csproj -c Release -r win-x64 -v n;
- tests\ComputeSharp.Dynamic.NuGet\bin\Release\net7.0\win-x64\publish\ComputeSharp.Dynamic.NuGet.exe
+ dotnet publish tests\ComputeSharp.Dxc.NuGet\ComputeSharp.Dxc.NuGet.csproj -c Release -r win-x64 -v n;
+ tests\ComputeSharp.Dxc.NuGet\bin\Release\net7.0\win-x64\publish\ComputeSharp.Dxc.NuGet.exe
- name: Publish and run ComputeSharp.Pix.NuGet with NativeAOT
run: >
$env:COMPUTESHARP_NUGET_TESTS_PUBLISH_AOT='true';
diff --git a/ComputeSharp.sln b/ComputeSharp.sln
index d4ae56c6..e3be080b 100644
--- a/ComputeSharp.sln
+++ b/ComputeSharp.sln
@@ -60,7 +60,7 @@ Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.SwapChain.Shad
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.DisableDynamicCompilation", "tests\ComputeSharp.Tests.DisableDynamicCompilation\ComputeSharp.Tests.DisableDynamicCompilation.csproj", "{4A8FCE22-851C-442A-8BC9-3EC3FD00B637}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Dynamic", "src\ComputeSharp.Dynamic\ComputeSharp.Dynamic.csproj", "{76C66257-FDAA-47AB-85E7-EF757EAB10C0}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Dxc", "src\ComputeSharp.Dxc\ComputeSharp.Dxc.csproj", "{76C66257-FDAA-47AB-85E7-EF757EAB10C0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1", "src\ComputeSharp.D2D1\ComputeSharp.D2D1.csproj", "{4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}"
EndProject
@@ -82,10 +82,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1.Tests.Ass
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Pix", "src\ComputeSharp.Pix\ComputeSharp.Pix.csproj", "{14EF12A3-90E6-4683-BD71-9896AF87026B}"
EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ComputeSharp.Dynamic.NuGet", "ComputeSharp.Dynamic.NuGet", "{CBA545B4-31EF-4E9F-A1A8-2A1290B54046}"
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ComputeSharp.Dxc.NuGet", "ComputeSharp.Dxc.NuGet", "{CBA545B4-31EF-4E9F-A1A8-2A1290B54046}"
ProjectSection(SolutionItems) = preProject
- tests\ComputeSharp.Dynamic.NuGet\ComputeSharp.Dynamic.NuGet.csproj = tests\ComputeSharp.Dynamic.NuGet\ComputeSharp.Dynamic.NuGet.csproj
- tests\ComputeSharp.Dynamic.NuGet\Program.cs = tests\ComputeSharp.Dynamic.NuGet\Program.cs
+ tests\ComputeSharp.Dxc.NuGet\ComputeSharp.Dxc.NuGet.csproj = tests\ComputeSharp.Dxc.NuGet\ComputeSharp.Dxc.NuGet.csproj
+ tests\ComputeSharp.Dxc.NuGet\Program.cs = tests\ComputeSharp.Dxc.NuGet\Program.cs
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ComputeSharp.Pix.NuGet", "ComputeSharp.Pix.NuGet", "{C0B903AA-F32C-4760-B4B6-199AC4FE1C5A}"
@@ -148,7 +148,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Win32", "Win32", "{D991153C
EndProject
Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.CodeFixing", "src\ComputeSharp.CodeFixing\ComputeSharp.CodeFixing.shproj", "{29F6E256-BA0E-4F3B-854E-50839D67C6DD}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.CodeFixers", "src\ComputeSharp.CodeFixers\ComputeSharp.CodeFixers.csproj", "{9B4448B1-200F-4966-8A13-A508691B3003}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.CodeFixers", "src\ComputeSharp.CodeFixers\ComputeSharp.CodeFixers.csproj", "{9B4448B1-200F-4966-8A13-A508691B3003}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
diff --git a/README.md b/README.md
index c3bb9bfa..c9ce216d 100644
--- a/README.md
+++ b/README.md
@@ -34,8 +34,8 @@ The sample app is available in the Microsoft Store, showcasing several pixel sha
| Name | Description |
| ------ | ------ |
| **ComputeSharp** | The main library, with compiled shaders support |
-| **ComputeSharp.Dynamic** | An extension for **ComputeSharp**, enabling dynamic shader compilation at runtime and shader metaprogramming |
-| **ComputeSharp.D3D12MemoryAllocator** | An extension for **ComputeSharp**, adding D3D12MA as the memory allocator for graphics resources. |
+| **ComputeSharp.D3D12MemoryAllocator** | An extension library for **ComputeSharp**, adding D3D12MA as the memory allocator for graphics resources. |
+| **ComputeSharp.Dxc** | An extension library for **ComputeSharp**, bundling the DXC compiler and enabling shader reflection |
| **ComputeSharp.Pix** | An extension library for **ComputeSharp**, enabling PIX support to produce debugging information |
| **ComputeSharp.WinUI** | A WinUI 3 library with controls to render DX12 shaders powered by **ComputeSharp** |
| **ComputeSharp.D2D1** | A library to write D2D1 pixel shaders entirely with C# code, and to easily register and create ID2D1Effect-s from them |
diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj
index 74743472..64e1c888 100644
--- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj
+++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj
@@ -6,7 +6,7 @@
-
+
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs
index 7d478063..212b146f 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs
@@ -2,7 +2,6 @@ using System;
using System.Runtime.CompilerServices;
using ComputeSharp.D2D1.Descriptors;
using ComputeSharp.D2D1.Extensions;
-using ComputeSharp.D2D1.Shaders.Translation;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
@@ -31,33 +30,15 @@ public static class D2D1ReflectionServices
{
Unsafe.SkipInit(out T shader);
- string hlslSource = shader.HlslSource;
+ ReadOnlyMemory hlslBytecode = D2D1PixelShader.LoadBytecode();
using ComPtr d3D11ShaderReflection = default;
- // If the shader already has embedded bytecode, use that directly
- if (shader.HlslBytecode is ReadOnlyMemory { Length: > 0 } hlslBytecode)
+ fixed (byte* hlslBytecodePtr = hlslBytecode.Span)
{
- fixed (byte* hlslBytecodePtr = hlslBytecode.Span)
- {
- DirectX.D3DReflect(
- pSrcData: hlslBytecodePtr,
- SrcDataSize: (nuint)hlslBytecode.Length,
- pInterface: Windows.__uuidof(),
- ppReflector: (void**)d3D11ShaderReflection.GetAddressOf()).Assert();
- }
- }
- else
- {
- // Otherwise, compile it with default shader profile and compile options and use that.
- // Note that we're intentionally retrieving an ID3DBlob instance here to avoid having
- // to allocate a ReadOnlyMemory object to throw away immediately, as we don't
- // actually need to keep the bytecode for later.
- using ComPtr dynamicBytecode = D3DCompiler.Compile(hlslSource.AsSpan(), shader.ShaderProfile, shader.CompileOptions);
-
DirectX.D3DReflect(
- pSrcData: (byte*)dynamicBytecode.Get()->GetBufferPointer(),
- SrcDataSize: dynamicBytecode.Get()->GetBufferSize(),
+ pSrcData: hlslBytecodePtr,
+ SrcDataSize: (nuint)hlslBytecode.Length,
pInterface: Windows.__uuidof(),
ppReflector: (void**)d3D11ShaderReflection.GetAddressOf()).Assert();
}
@@ -72,7 +53,8 @@ public static class D2D1ReflectionServices
return new(
CompilerVersion: new string(d3D11ShaderDescription.Creator),
- HlslSource: hlslSource,
+ HlslSource: shader.HlslSource,
+ HlslBytecode: hlslBytecode,
ConstantBufferCount: d3D11ShaderDescription.ConstantBuffers,
BoundResourceCount: d3D11ShaderDescription.BoundResources,
InstructionCount: d3D11ShaderDescription.InstructionCount,
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderInfo.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderInfo.cs
index b909aa39..1106b56f 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderInfo.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderInfo.cs
@@ -1,3 +1,5 @@
+using System;
+
namespace ComputeSharp.D2D1.Interop;
///
@@ -5,6 +7,7 @@ namespace ComputeSharp.D2D1.Interop;
///
/// The compiler version used to build the shader.
/// The HLSL source code the shader was built from.
+/// The HLSL bytecode for the shader.
/// The number of shader constant buffers.
/// The number of resource (textures and buffers) bound to a shader.
/// The number of intermediate-language instructions in the compiled shader.
@@ -32,6 +35,7 @@ namespace ComputeSharp.D2D1.Interop;
public sealed record D2D1ShaderInfo(
string CompilerVersion,
string HlslSource,
+ ReadOnlyMemory HlslBytecode,
uint ConstantBufferCount,
uint BoundResourceCount,
uint InstructionCount,
diff --git a/src/ComputeSharp.Dynamic/ComputeSharp.Dynamic.csproj b/src/ComputeSharp.Dxc/ComputeSharp.Dxc.csproj
similarity index 100%
rename from src/ComputeSharp.Dynamic/ComputeSharp.Dynamic.csproj
rename to src/ComputeSharp.Dxc/ComputeSharp.Dxc.csproj
diff --git a/src/ComputeSharp.Dxc/Interop/ReflectionServices.LibraryLoading.cs b/src/ComputeSharp.Dxc/Interop/ReflectionServices.LibraryLoading.cs
new file mode 100644
index 00000000..679ebe0d
--- /dev/null
+++ b/src/ComputeSharp.Dxc/Interop/ReflectionServices.LibraryLoading.cs
@@ -0,0 +1,77 @@
+using System;
+using System.IO;
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+namespace ComputeSharp.Interop;
+
+///
+partial class ReflectionServices
+{
+ ///
+ /// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries.
+ ///
+ static ReflectionServices()
+ {
+ // Register a custom library resolver for the two DXC libraries. We need to either manually load the two
+ // libraries from the NuGet directory, if an RID is not in use, or we need to ensure that dxil.dll is
+ // loaded correctly in case the program was executed with the host being in another directory.
+ // This happens when doing eg. "dotnet bin\Debug\net8.0\MyApp.dll", which would crash at runtime.
+ NativeLibrary.SetDllImportResolver(typeof(ReflectionServices).Assembly, OnDllImport);
+ }
+
+ ///
+ /// The custom for this assembly.
+ ///
+ ///
+ private static IntPtr OnDllImport(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
+ {
+ if (libraryName is not "dxcompiler")
+ {
+ return IntPtr.Zero;
+ }
+
+ string rid = RuntimeInformation.ProcessArchitecture switch
+ {
+ Architecture.X64 => "win-x64",
+ Architecture.Arm64 => "win-arm64",
+ _ => default(NotSupportedException).Throw()
+ };
+
+ // Test whether the native libraries are present in the same folder of the executable
+ // (which is the case when the program was built with a runtime identifier), or whether
+ // they are in the "runtimes\win-x64\native" folder in the executable directory.
+ string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, $@"runtimes\{rid}\native");
+ bool isNuGetRuntimeLibrariesDirectoryPresent = Directory.Exists(nugetNativeLibsPath);
+
+ if (isNuGetRuntimeLibrariesDirectoryPresent)
+ {
+ string dxcompilerPath = Path.Combine(AppContext.BaseDirectory, $@"runtimes\{rid}\native\dxcompiler.dll");
+ string dxilPath = Path.Combine(AppContext.BaseDirectory, $@"runtimes\{rid}\native\dxil.dll");
+
+ // Load DXIL first so that DXC doesn't fail to load it, and then DXIL, both from the NuGet path
+ if (NativeLibrary.TryLoad(dxilPath, out _) &&
+ NativeLibrary.TryLoad(dxcompilerPath, out IntPtr handle))
+ {
+ return handle;
+ }
+ }
+ else
+ {
+ // Even when the two libraries are correctly copied next to the executable in use, we load them
+ // manually to ensure the operation is successful. This is to avoid failures in cases such as when
+ // doing "dotnet bin\MyApp.dll", ie. when the host is in another path than the executable in use.
+ // This is probably because DXIL is a native dependency for DXC, but the way Windows loads these
+ // libraries doesn't take into account the .NET concepts of "app directory": neither the current "bin"
+ // directory nor the "process directory", which is "C:\Program Files\dotnet", actually contain the
+ // native library we need, hence the runtime crash. Manually loading the library this way solves this.
+ if (NativeLibrary.TryLoad("dxil", assembly, searchPath, out _) &&
+ NativeLibrary.TryLoad("dxcompiler", assembly, searchPath, out IntPtr handle))
+ {
+ return handle;
+ }
+ }
+
+ return IntPtr.Zero;
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs b/src/ComputeSharp.Dxc/Interop/ReflectionServices.cs
similarity index 52%
rename from src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs
rename to src/ComputeSharp.Dxc/Interop/ReflectionServices.cs
index adfff47f..44d51921 100644
--- a/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs
+++ b/src/ComputeSharp.Dxc/Interop/ReflectionServices.cs
@@ -13,101 +13,47 @@ namespace ComputeSharp.Interop;
///
/// Provides methods to extract reflection info on compute shaders generated using this library.
///
-public static class ReflectionServices
+public static partial class ReflectionServices
{
///
/// Gets the shader info associated with a given compute shader.
- ///
- /// This overload can be used for simplicity when the compute shader being inspected does not rely on captured
- /// objects to be processed correctly. This is the case when it does not contain any -s.
- ///
///
/// The type of compute shader to retrieve info for.
/// The resulting instance.
- ///
- /// The thread group sizes will always be set to (1, 1, 1) in the returned shader. This is done to
- /// avoid having to compiler multiple shaders just to get reflection info for them. When using any of
- /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead.
- ///
public static ShaderInfo GetShaderInfo()
where T : struct, IComputeShader, IComputeShaderDescriptor
{
- return GetNonGenericShaderInfo(default(T));
- }
-
- ///
- /// Gets the shader info associated with a given compute shader.
- ///
- /// The type of compute shader to retrieve info for.
- /// The input compute shader to retrieve info for.
- /// The resulting instance.
- ///
- /// The thread group sizes will always be set to (1, 1, 1) in the returned shader. This is done to
- /// avoid having to compiler multiple shaders just to get reflection info for them. When using any of
- /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead.
- ///
- public static unsafe ShaderInfo GetShaderInfo(in T shader)
- where T : struct, IComputeShader, IComputeShaderDescriptor
- {
- return GetNonGenericShaderInfo(in shader);
+ return GetNonGenericShaderInfo();
}
///
/// Gets the shader info associated with a given pixel shader.
- ///
- /// This overload can be used for simplicity when the pixel shader being inspected does not rely on captured
- /// objects to be processed correctly. This is the case when it does not contain any -s.
- ///
///
/// The type of pixel shader to retrieve info for.
/// The type of pixels being processed by the shader.
/// The resulting instance.
- ///
- /// The thread group sizes will always be set to (1, 1, 1) in the returned shader. This is done to
- /// avoid having to compiler multiple shaders just to get reflection info for them. When using any of
- /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead.
- ///
public static ShaderInfo GetShaderInfo()
where T : struct, IComputeShader, IComputeShaderDescriptor
where TPixel : unmanaged
{
- return GetNonGenericShaderInfo(default(T));
- }
-
- ///
- /// Gets the shader info associated with a given pixel shader.
- ///
- /// The type of pixel shader to retrieve info for.
- /// The type of pixels being processed by the shader.
- /// The input pixel shader to retrieve info for.
- /// The resulting instance.
- ///
- /// The thread group sizes will always be set to (1, 1, 1) in the returned shader. This is done to
- /// avoid having to compiler multiple shaders just to get reflection info for them. When using any of
- /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead.
- ///
- public static unsafe ShaderInfo GetShaderInfo(in T shader)
- where T : struct, IComputeShader, IComputeShaderDescriptor
- where TPixel : unmanaged
- {
- return GetNonGenericShaderInfo(in shader);
+ return GetNonGenericShaderInfo();
}
///
/// Gets the shader info associated with a given shader of any type.
///
/// The type of shader to retrieve info for.
- /// The input shader to retrieve info for.
/// The resulting instance.
- private static unsafe ShaderInfo GetNonGenericShaderInfo(in T shader)
+ private static unsafe ShaderInfo GetNonGenericShaderInfo()
where T : struct, IComputeShaderDescriptor
{
- string hlslSource = Unsafe.AsRef(in shader).HlslSource;
+ Unsafe.SkipInit(out T shader);
- using ComPtr dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(hlslSource);
+ ReadOnlyMemory hlslBytecode = shader.HlslBytecode;
using ComPtr dxcUtils = default;
+ // Load the DXC compiler (the package will bundle the necessary .dll-s)
DirectX.DxcCreateInstance(
(Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcLibrary)),
Windows.__uuidof(),
@@ -115,14 +61,19 @@ public static class ReflectionServices
using ComPtr d3D12ShaderReflection = default;
- DxcBuffer dxcBuffer = default;
- dxcBuffer.Ptr = dxcBlobBytecode.Get()->GetBufferPointer();
- dxcBuffer.Size = dxcBlobBytecode.Get()->GetBufferSize();
+ // Reflect over the shader (this will fail if reflection metadata has been stripped).
+ // Since that's just opt-in from users, that is the expected behavior, so not an issue.
+ fixed (byte* hlslBytecodePtr = hlslBytecode.Span)
+ {
+ DxcBuffer dxcBuffer = default;
+ dxcBuffer.Ptr = hlslBytecodePtr;
+ dxcBuffer.Size = (uint)hlslBytecode.Length;
- dxcUtils.Get()->CreateReflection(
- &dxcBuffer,
- Windows.__uuidof(),
- (void**)d3D12ShaderReflection.GetAddressOf()).Assert();
+ dxcUtils.Get()->CreateReflection(
+ &dxcBuffer,
+ Windows.__uuidof(),
+ (void**)d3D12ShaderReflection.GetAddressOf()).Assert();
+ }
D3D12_SHADER_DESC d3D12ShaderDescription;
@@ -130,7 +81,8 @@ public static class ReflectionServices
return new(
CompilerVersion: new string(d3D12ShaderDescription.Creator),
- HlslSource: hlslSource,
+ HlslSource: shader.HlslSource,
+ HlslBytecode: hlslBytecode,
ConstantBufferCount: d3D12ShaderDescription.ConstantBuffers,
BoundResourceCount: d3D12ShaderDescription.BoundResources,
InstructionCount: d3D12ShaderDescription.InstructionCount,
diff --git a/src/ComputeSharp.Dynamic/Shaders/Interop/ShaderInfo.cs b/src/ComputeSharp.Dxc/Interop/ShaderInfo.cs
similarity index 96%
rename from src/ComputeSharp.Dynamic/Shaders/Interop/ShaderInfo.cs
rename to src/ComputeSharp.Dxc/Interop/ShaderInfo.cs
index 2b2064b7..4dba4231 100644
--- a/src/ComputeSharp.Dynamic/Shaders/Interop/ShaderInfo.cs
+++ b/src/ComputeSharp.Dxc/Interop/ShaderInfo.cs
@@ -1,3 +1,5 @@
+using System;
+
namespace ComputeSharp.Interop;
///
@@ -5,6 +7,7 @@ namespace ComputeSharp.Interop;
///
/// The compiler version used to build the shader.
/// The HLSL source code the shader was built from.
+/// The HLSL bytecode for the shader.
/// The number of shader constant buffers.
/// The number of resource (textures and buffers) bound to a shader.
/// The number of intermediate-language instructions in the compiled shader.
@@ -31,6 +34,7 @@ namespace ComputeSharp.Interop;
public sealed record ShaderInfo(
string CompilerVersion,
string HlslSource,
+ ReadOnlyMemory HlslBytecode,
uint ConstantBufferCount,
uint BoundResourceCount,
uint InstructionCount,
diff --git a/src/ComputeSharp.Dynamic/Libraries/arm64/dxcompiler.dll b/src/ComputeSharp.Dxc/Libraries/arm64/dxcompiler.dll
similarity index 100%
rename from src/ComputeSharp.Dynamic/Libraries/arm64/dxcompiler.dll
rename to src/ComputeSharp.Dxc/Libraries/arm64/dxcompiler.dll
diff --git a/src/ComputeSharp.Dynamic/Libraries/arm64/dxil.dll b/src/ComputeSharp.Dxc/Libraries/arm64/dxil.dll
similarity index 100%
rename from src/ComputeSharp.Dynamic/Libraries/arm64/dxil.dll
rename to src/ComputeSharp.Dxc/Libraries/arm64/dxil.dll
diff --git a/src/ComputeSharp.Dynamic/Libraries/x64/dxcompiler.dll b/src/ComputeSharp.Dxc/Libraries/x64/dxcompiler.dll
similarity index 100%
rename from src/ComputeSharp.Dynamic/Libraries/x64/dxcompiler.dll
rename to src/ComputeSharp.Dxc/Libraries/x64/dxcompiler.dll
diff --git a/src/ComputeSharp.Dynamic/Libraries/x64/dxil.dll b/src/ComputeSharp.Dxc/Libraries/x64/dxil.dll
similarity index 100%
rename from src/ComputeSharp.Dynamic/Libraries/x64/dxil.dll
rename to src/ComputeSharp.Dxc/Libraries/x64/dxil.dll
diff --git a/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.LibraryLoading.cs b/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.LibraryLoading.cs
deleted file mode 100644
index f92c8808..00000000
--- a/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.LibraryLoading.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-#if NET6_0_OR_GREATER
-
-using System;
-using System.IO;
-using System.Runtime.InteropServices;
-using TerraFX.Interop.Windows;
-
-namespace ComputeSharp.Shaders.Translation;
-
-///
-unsafe partial class ShaderCompiler
-{
- ///
- /// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries.
- ///
- static ShaderCompiler()
- {
- // Register a custom library resolver for the two DXC libraries. We need to either manually load the two
- // libraries from the NuGet directory, if an RID is not in use, or we need to ensure that dxil.dll is
- // loaded correctly in case the program was executed with the host being in another directory.
- // This happens when doing eg. "dotnet bin\Debug\net5.0\MyApp.dll", which would crash at runtime.
- Windows.ResolveLibrary += static (libraryName, assembly, searchPath) =>
- {
- if (libraryName is not "dxcompiler")
- {
- return IntPtr.Zero;
- }
-
- string rid = RuntimeInformation.ProcessArchitecture switch
- {
- Architecture.X64 => "win-x64",
- Architecture.Arm64 => "win-arm64",
- _ => default(NotSupportedException).Throw()
- };
-
- // Test whether the native libraries are present in the same folder of the executable
- // (which is the case when the program was built with a runtime identifier), or whether
- // they are in the "runtimes\win-x64\native" folder in the executable directory.
- string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, $@"runtimes\{rid}\native");
- bool isNuGetRuntimeLibrariesDirectoryPresent = Directory.Exists(nugetNativeLibsPath);
-
- if (isNuGetRuntimeLibrariesDirectoryPresent)
- {
- string dxcompilerPath = Path.Combine(AppContext.BaseDirectory, $@"runtimes\{rid}\native\dxcompiler.dll");
- string dxilPath = Path.Combine(AppContext.BaseDirectory, $@"runtimes\{rid}\native\dxil.dll");
-
- // Load DXIL first so that DXC doesn't fail to load it, and then DXIL, both from the NuGet path
- if (NativeLibrary.TryLoad(dxilPath, out _) &&
- NativeLibrary.TryLoad(dxcompilerPath, out IntPtr handle))
- {
- return handle;
- }
- }
- else
- {
- // Even when the two libraries are correctly copied next to the executable in use, we load them
- // manually to ensure the operation is successful. This is to avoid failures in cases such as when
- // doing "dotnet bin\MyApp.dll", ie. when the host is in another path than the executable in use.
- // This is probably because DXIL is a native dependency for DXC, but the way Windows loads these
- // libraries doesn't take into account the .NET concepts of "app directory": neither the current "bin"
- // directory nor the "process directory", which is "C:\Program Files\dotnet", actually contain the
- // native library we need, hence the runtime crash. Manually loading the library this way solves this.
- if (NativeLibrary.TryLoad("dxil", assembly, searchPath, out _) &&
- NativeLibrary.TryLoad("dxcompiler", assembly, searchPath, out IntPtr handle))
- {
- return handle;
- }
- }
-
- return IntPtr.Zero;
- };
- }
-}
-
-#endif
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs
index adcd069d..6883c166 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs
+++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs
@@ -1,24 +1,17 @@
using System;
using System.Collections.Immutable;
using System.ComponentModel;
-using System.IO;
-using System.Reflection;
using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
-using ComputeSharp.Shaders.Translation;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
+using ComputeSharp.SourceGenerators.Dxc;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
-using TerraFX.Interop.DirectX;
-using TerraFX.Interop.Windows;
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
-#pragma warning disable RS1035
-
namespace ComputeSharp.SourceGenerators;
///
@@ -34,11 +27,6 @@ partial class ComputeShaderDescriptorGenerator
///
private static readonly DynamicCache HlslBytecodeCache = new();
- ///
- /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded.
- ///
- private static volatile bool areDxcLibrariesLoaded;
-
///
/// Gets the instance for the input shader info.
///
@@ -57,24 +45,19 @@ partial class ComputeShaderDescriptorGenerator
try
{
+ token.ThrowIfCancellationRequested();
+
// Try to load dxcompiler.dll and dxil.dll
- LoadNativeDxcLibraries();
+ DxcLibraryLoader.LoadNativeDxcLibraries();
token.ThrowIfCancellationRequested();
// Compile the shader bytecode
- using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.Compile(key.HlslSource.AsSpan());
+ byte[] bytecode = DxcShaderCompiler.Instance.Compile(key.HlslSource.AsSpan(), token);
token.ThrowIfCancellationRequested();
- byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer();
- int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize());
-
- byte[] array = new ReadOnlySpan(buffer, length).ToArray();
-
- ImmutableArray bytecode = Unsafe.As>(ref array);
-
- return new HlslBytecodeInfo.Success(bytecode);
+ return new HlslBytecodeInfo.Success(Unsafe.As>(ref bytecode));
}
catch (Win32Exception e)
{
@@ -141,70 +124,5 @@ partial class ComputeShaderDescriptorGenerator
return message.NormalizeToSingleLine();
}
-
- ///
- /// Extracts and loads the dxcompiler.dll and dxil.dll libraries.
- ///
- /// Thrown if the CPU architecture is not supported.
- /// Thrown if a library fails to load.
- private static void LoadNativeDxcLibraries()
- {
- // Extracts a specified native library for a given runtime identifier
- static string ExtractLibrary(string folder, string rid, string name)
- {
- string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll";
- string targetFilename = Path.Combine(folder, rid, $"{name}.dll");
-
- _ = Directory.CreateDirectory(Path.GetDirectoryName(targetFilename));
-
- using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename);
-
- try
- {
- using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write);
-
- sourceStream.CopyTo(destinationStream);
- }
- catch (IOException)
- {
- }
-
- return targetFilename;
- }
-
- // Loads a target native library
- static unsafe void LoadLibrary(string filename)
- {
- [DllImport("kernel32", ExactSpelling = true, SetLastError = true)]
- static extern void* LoadLibraryW(ushort* lpLibFileName);
-
- fixed (char* p = filename)
- {
- if (LoadLibraryW((ushort*)p) is null)
- {
- int hresult = Marshal.GetLastWin32Error();
-
- throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}.");
- }
- }
- }
-
- if (!areDxcLibrariesLoaded)
- {
- string rid = RuntimeInformation.ProcessArchitecture switch
- {
- Architecture.X64 => "x64",
- Architecture.Arm64 => "arm64",
- _ => throw new NotSupportedException("Invalid process architecture")
- };
-
- string folder = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName());
-
- LoadLibrary(ExtractLibrary(folder, rid, "dxil"));
- LoadLibrary(ExtractLibrary(folder, rid, "dxcompiler"));
-
- areDxcLibrariesLoaded = true;
- }
- }
}
}
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.NumThreads.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.NumThreads.cs
index 0efd19fb..2b21811e 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.NumThreads.cs
+++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.NumThreads.cs
@@ -32,7 +32,7 @@ partial class ComputeShaderDescriptorGenerator
out int threadsZ,
out bool isCompilationEnabled)
{
- // Try to get the attribute that controls shader precompilation (has to be present when ComputeSharp.Dynamic is not referenced)
+ // Try to get the attribute that controls shader precompilation (this is always required)
if (!structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName(typeof(EmbeddedBytecodeAttribute).FullName, out AttributeData? attribute))
{
// Emit the diagnostics if dynamic shaders are not supported
diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
index 35b85d5a..66666ac9 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
+++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
@@ -8,7 +8,6 @@
-
@@ -67,9 +66,6 @@
-
-
-
@@ -82,10 +78,10 @@
-
-
-
-
+
+
+
+
diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp/Graphics/Extensions/Interop/HRESULTExtensions.cs b/src/ComputeSharp.SourceGenerators/ComputeSharp/Graphics/Extensions/Interop/HRESULTExtensions.cs
deleted file mode 100644
index da6a898f..00000000
--- a/src/ComputeSharp.SourceGenerators/ComputeSharp/Graphics/Extensions/Interop/HRESULTExtensions.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-using System.ComponentModel;
-using System.Diagnostics;
-using TerraFX.Interop.Windows;
-
-namespace ComputeSharp.Core.Extensions;
-
-///
-/// Helper methods to efficiently throw exceptions.
-///
-[DebuggerStepThrough]
-internal static class HRESULTExtensions
-{
- ///
- /// Throws a if represents an error.
- ///
- /// The input to check.
- /// Thrown if represents an error.
- public static void Assert(this HRESULT result)
- {
- Assert((int)result);
- }
-
- ///
- /// Throws a if represents an error.
- ///
- /// The input to check.
- /// Thrown if represents an error.
- public static void Assert(this int result)
- {
- if (result < 0)
- {
- throw new Win32Exception(result);
- }
- }
-}
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
index 0d5f840a..5002c477 100644
--- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
+++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
@@ -640,7 +640,7 @@ partial class DiagnosticDescriptors
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
///
- /// Gets a for a shader without the embedded bytecode attribute, when dynamic shaders are not supported.
+ /// Gets a for a shader without the embedded bytecode attribute,.
///
/// Format: "The shader of type {0} needs to be annotated as having embedded bytecode (using the [EmbeddedBytecode] attribute), as dynamic shader compilation is not supported".
///
@@ -652,7 +652,7 @@ partial class DiagnosticDescriptors
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
- description: "When dynamic shader compilation is not supported (ie. when ComputeSharp.Dynamic is not referenced), all shaders need to be annotated as having embedded bytecode (using the [EmbeddedBytecode] attribute).",
+ description: "All shaders need to be annotated as having embedded bytecode (using the [EmbeddedBytecode] attribute).",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
///
diff --git a/src/ComputeSharp.Dynamic/Shaders/Exceptions/DxcCompilationException.cs b/src/ComputeSharp.SourceGenerators/Dxc/DxcCompilationException.cs
similarity index 82%
rename from src/ComputeSharp.Dynamic/Shaders/Exceptions/DxcCompilationException.cs
rename to src/ComputeSharp.SourceGenerators/Dxc/DxcCompilationException.cs
index 7aa7ee72..7b690b9e 100644
--- a/src/ComputeSharp.Dynamic/Shaders/Exceptions/DxcCompilationException.cs
+++ b/src/ComputeSharp.SourceGenerators/Dxc/DxcCompilationException.cs
@@ -1,11 +1,11 @@
using System;
-namespace ComputeSharp;
+namespace ComputeSharp.SourceGenerators.Dxc;
///
/// A custom type that indicates when a shader compilation with the DXC compiler has failed.
///
-public sealed class DxcCompilationException : Exception
+internal sealed class DxcCompilationException : Exception
{
///
/// Creates a new instance.
@@ -23,14 +23,8 @@ public sealed class DxcCompilationException : Exception
/// A formatted error message for a new instance.
private static string GetExceptionMessage(string error)
{
-#if NET6_0_OR_GREATER
- ReadOnlySpan message = error.AsSpan().Trim();
-#else
- string message = error.Trim();
-#endif
-
return
- $"""The DXC compiler encountered one or more errors while trying to compile the shader: "{message}". """ +
+ $"""The DXC compiler encountered one or more errors while trying to compile the shader: "{error.Trim()}". """ +
$"""Make sure to only be using supported features by checking the README file in the ComputeSharp repository: https://github.com/Sergio0694/ComputeSharp. """ +
$"""If you're sure that your C# shader code is valid, please open an issue an include a working repro and this error message.""";
}
diff --git a/src/ComputeSharp.SourceGenerators/Dxc/DxcLibraryLoader.cs b/src/ComputeSharp.SourceGenerators/Dxc/DxcLibraryLoader.cs
new file mode 100644
index 00000000..f8aae469
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/Dxc/DxcLibraryLoader.cs
@@ -0,0 +1,100 @@
+using System;
+using System.ComponentModel;
+using System.IO;
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+#pragma warning disable RS1035
+
+namespace ComputeSharp.SourceGenerators.Dxc;
+
+///
+/// A that handles loading the DXC libraries.
+///
+internal sealed unsafe class DxcLibraryLoader
+{
+ ///
+ /// An object to use to synchronize loading the DXC libraries.
+ ///
+ private static readonly object LoadingLock = new();
+
+ ///
+ /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded.
+ ///
+ private static volatile bool areDxcLibrariesLoaded;
+
+ ///
+ /// Extracts and loads the dxcompiler.dll and dxil.dll libraries.
+ ///
+ /// Thrown if the CPU architecture is not supported.
+ /// Thrown if a library fails to load.
+ public static void LoadNativeDxcLibraries()
+ {
+ // Extracts a specified native library for a given runtime identifier
+ static string ExtractLibrary(string folder, string rid, string name)
+ {
+ string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll";
+ string targetFilename = Path.Combine(folder, rid, $"{name}.dll");
+
+ _ = Directory.CreateDirectory(Path.GetDirectoryName(targetFilename));
+
+ using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename);
+
+ try
+ {
+ using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write);
+
+ sourceStream.CopyTo(destinationStream);
+ }
+ catch (IOException)
+ {
+ }
+
+ return targetFilename;
+ }
+
+ // Loads a target native library
+ static unsafe void LoadLibrary(string filename)
+ {
+ [DllImport("kernel32", ExactSpelling = true, SetLastError = true)]
+ static extern void* LoadLibraryW(ushort* lpLibFileName);
+
+ fixed (char* p = filename)
+ {
+ if (LoadLibraryW((ushort*)p) is null)
+ {
+ int hresult = Marshal.GetLastWin32Error();
+
+ throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}.");
+ }
+ }
+ }
+
+ if (areDxcLibrariesLoaded)
+ {
+ return;
+ }
+
+ lock (LoadingLock)
+ {
+ if (areDxcLibrariesLoaded)
+ {
+ return;
+ }
+
+ string rid = RuntimeInformation.ProcessArchitecture switch
+ {
+ Architecture.X64 => "x64",
+ Architecture.Arm64 => "arm64",
+ _ => throw new NotSupportedException("Invalid process architecture")
+ };
+
+ string folder = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName());
+
+ LoadLibrary(ExtractLibrary(folder, rid, "dxil"));
+ LoadLibrary(ExtractLibrary(folder, rid, "dxcompiler"));
+
+ areDxcLibrariesLoaded = true;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs
similarity index 64%
rename from src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.cs
rename to src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs
index ff33ffde..9360ef72 100644
--- a/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.cs
+++ b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs
@@ -1,23 +1,24 @@
using System;
using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
-using ComputeSharp.Core.Extensions;
+using System.Threading;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
-namespace ComputeSharp.Shaders.Translation;
+namespace ComputeSharp.SourceGenerators.Dxc;
///
/// A that uses the DXC APIs to compile compute shaders.
///
-internal sealed unsafe partial class ShaderCompiler
+internal sealed unsafe class DxcShaderCompiler
{
///
- /// The thread local instance.
+ /// The thread local instance.
/// This is necessary because the DXC library is strictly single-threaded.
///
[ThreadStatic]
- private static ShaderCompiler? instance;
+ private static DxcShaderCompiler? instance;
///
/// The instance to use to create the bytecode for HLSL sources.
@@ -35,35 +36,35 @@ internal sealed unsafe partial class ShaderCompiler
private readonly ComPtr dxcIncludeHandler;
///
- /// Creates a new instance.
+ /// Creates a new instance.
///
- private ShaderCompiler()
+ private DxcShaderCompiler()
{
using ComPtr dxcCompiler = default;
using ComPtr dxcLibrary = default;
using ComPtr dxcIncludeHandler = default;
- DirectX.DxcCreateInstance(
+ Marshal.ThrowExceptionForHR(DirectX.DxcCreateInstance(
(Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcCompiler)),
Windows.__uuidof(),
- (void**)dxcCompiler.GetAddressOf()).Assert();
+ (void**)dxcCompiler.GetAddressOf()));
- DirectX.DxcCreateInstance(
+ Marshal.ThrowExceptionForHR(DirectX.DxcCreateInstance(
(Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcLibrary)),
Windows.__uuidof(),
- (void**)dxcLibrary.GetAddressOf()).Assert();
+ (void**)dxcLibrary.GetAddressOf()));
- dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()).Assert();
+ Marshal.ThrowExceptionForHR(dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()));
- this.dxcCompiler = dxcCompiler.Move();
- this.dxcLibrary = dxcLibrary.Move();
- this.dxcIncludeHandler = dxcIncludeHandler.Move();
+ this.dxcCompiler = new ComPtr(dxcCompiler.Get());
+ this.dxcLibrary = new ComPtr(dxcLibrary.Get());
+ this.dxcIncludeHandler = new ComPtr(dxcIncludeHandler.Get());
}
///
- /// Destroys the current instance.
+ /// Destroys the current instance.
///
- ~ShaderCompiler()
+ ~DxcShaderCompiler()
{
this.dxcCompiler.Dispose();
this.dxcLibrary.Dispose();
@@ -71,31 +72,35 @@ internal sealed unsafe partial class ShaderCompiler
}
///
- /// Gets a instance to use.
+ /// Gets a instance to use.
///
- public static ShaderCompiler Instance => instance ??= new();
+ public static DxcShaderCompiler Instance => instance ??= new();
///
/// Compiles a new HLSL shader from the input source code.
///
/// The HLSL source code to compile.
+ /// The used to cancel the operation, if needed.
/// The bytecode for the compiled shader.
- public ComPtr Compile(ReadOnlySpan source)
+ public byte[] Compile(ReadOnlySpan source, CancellationToken token)
{
using ComPtr dxcBlobEncoding = default;
using ComPtr dxcOperationResult = default;
- using ComPtr dxcBlobBytecode = default;
// Get the encoded blob from the source code
fixed (char* p = source)
{
- this.dxcLibrary.Get()->CreateBlobWithEncodingOnHeapCopy(
+ int hresult = this.dxcLibrary.Get()->CreateBlobWithEncodingOnHeapCopy(
p,
(uint)source.Length * 2,
1200,
- dxcBlobEncoding.GetAddressOf()).Assert();
+ dxcBlobEncoding.GetAddressOf());
+
+ Marshal.ThrowExceptionForHR(hresult);
}
+ token.ThrowIfCancellationRequested();
+
// Try to compile the new compute shader
fixed (char* shaderName = "")
fixed (char* entryPoint = nameof(IComputeShader.Execute))
@@ -106,7 +111,7 @@ internal sealed unsafe partial class ShaderCompiler
{
char** arguments = stackalloc char*[3] { optimization, rowMajor, warningsAsErrors };
- this.dxcCompiler.Get()->Compile(
+ int hresult = this.dxcCompiler.Get()->Compile(
(IDxcBlob*)dxcBlobEncoding.Get(),
(ushort*)shaderName,
(ushort*)entryPoint,
@@ -116,19 +121,28 @@ internal sealed unsafe partial class ShaderCompiler
null,
0,
this.dxcIncludeHandler.Get(),
- dxcOperationResult.GetAddressOf()).Assert();
+ dxcOperationResult.GetAddressOf());
+
+ Marshal.ThrowExceptionForHR(hresult);
}
+ token.ThrowIfCancellationRequested();
+
HRESULT status;
- dxcOperationResult.Get()->GetStatus(&status).Assert();
+ Marshal.ThrowExceptionForHR(dxcOperationResult.Get()->GetStatus(&status));
// The compilation was successful, so we can extract the shader bytecode
if (status == 0)
{
- dxcOperationResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf()).Assert();
+ using ComPtr dxcBlobBytecode = default;
- return dxcBlobBytecode.Move();
+ Marshal.ThrowExceptionForHR(dxcOperationResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf()));
+
+ byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer();
+ int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize());
+
+ return new ReadOnlySpan(buffer, length).ToArray();
}
return ThrowHslsCompilationException(dxcOperationResult.Get());
@@ -140,11 +154,11 @@ internal sealed unsafe partial class ShaderCompiler
/// The input (faulting) operation.
/// This method always throws and never actually returs.
[MethodImpl(MethodImplOptions.NoInlining)]
- private static ComPtr ThrowHslsCompilationException(IDxcOperationResult* dxcOperationResult)
+ private static byte[] ThrowHslsCompilationException(IDxcOperationResult* dxcOperationResult)
{
using ComPtr dxcBlobEncodingError = default;
- dxcOperationResult->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()).Assert();
+ Marshal.ThrowExceptionForHR(dxcOperationResult->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()));
string message = new((sbyte*)dxcBlobEncodingError.Get()->GetBufferPointer());
@@ -158,8 +172,7 @@ internal sealed unsafe partial class ShaderCompiler
message = Regex.Replace(message, @"^hlsl\.hlsl:\d+:\d+: (\w+:)", static m => m.Groups[1].Value, RegexOptions.Multiline);
// Add a trailing '.' if not present
- if (message is { Length: > 0 } &&
- message[message.Length - 1] != '.')
+ if (message is [.., not '.'])
{
message += '.';
}
diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj
index a2410fee..efc44dd0 100644
--- a/src/ComputeSharp/ComputeSharp.csproj
+++ b/src/ComputeSharp/ComputeSharp.csproj
@@ -6,7 +6,7 @@
-
+
diff --git a/src/ComputeSharp/Core/Attributes/EmbeddedBytecodeAttribute.cs b/src/ComputeSharp/Core/Attributes/EmbeddedBytecodeAttribute.cs
index fb39c5f0..faf2154e 100644
--- a/src/ComputeSharp/Core/Attributes/EmbeddedBytecodeAttribute.cs
+++ b/src/ComputeSharp/Core/Attributes/EmbeddedBytecodeAttribute.cs
@@ -30,12 +30,12 @@ namespace ComputeSharp;
///
///
/// The runtime compilation will automatically be skipped if the shader is invoked using matching thread count values,
-/// otherwise the usual runtime compilation will be used as fallback if the ComputeSharp.Dynamic library is
+/// otherwise the usual runtime compilation will be used as fallback if the ComputeSharp.Dxc library is
/// referenced. If not, will be thrown when trying to dispatch the shader.
///
///
///
-/// Using this attribute is mandatory when not referencing ComputeSharp.Dynamic.
+/// Using this attribute is mandatory when not referencing ComputeSharp.Dxc.
///
///
/// This attribute can only be used when the shader type being annotated does not require dynamic
diff --git a/src/Directory.Build.props b/src/Directory.Build.props
index 82e682af..435885da 100644
--- a/src/Directory.Build.props
+++ b/src/Directory.Build.props
@@ -20,8 +20,8 @@
-
-
+
+
diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1ReflectionServicesTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1ReflectionServicesTests.cs
index df51cd07..3e3947d2 100644
--- a/tests/ComputeSharp.D2D1.Tests/D2D1ReflectionServicesTests.cs
+++ b/tests/ComputeSharp.D2D1.Tests/D2D1ReflectionServicesTests.cs
@@ -18,6 +18,7 @@ public partial class D2D1ReflectionServicesTests
Assert.IsFalse(shaderInfo.RequiresDoublePrecisionSupport);
Assert.AreEqual(D3DFeatureLevel.FeatureLevel10_1, shaderInfo.MinimumFeatureLevel);
Assert.IsNotNull(shaderInfo.CompilerVersion);
+
Assert.AreEqual("""
// ================================================
// AUTO GENERATED
@@ -52,6 +53,8 @@ public partial class D2D1ReflectionServicesTests
return input0 + input1 + input2 + value3 + value4;
}
""".Replace("\r\n", "\n"), shaderInfo.HlslSource);
+
+ CollectionAssert.AreEqual(D2D1PixelShader.LoadBytecode().ToArray(), shaderInfo.HlslBytecode.ToArray());
}
[D2DInputCount(3)]
@@ -98,6 +101,7 @@ public partial class D2D1ReflectionServicesTests
Assert.IsTrue(shaderInfo.RequiresDoublePrecisionSupport);
Assert.AreEqual(D3DFeatureLevel.FeatureLevel11_0, shaderInfo.MinimumFeatureLevel);
Assert.IsNotNull(shaderInfo.CompilerVersion);
+
Assert.AreEqual("""
// ================================================
// AUTO GENERATED
@@ -116,6 +120,8 @@ public partial class D2D1ReflectionServicesTests
return (float4)(D2DGetInput(0) + (double4)amount);
}
""".Replace("\r\n", "\n"), shaderInfo.HlslSource);
+
+ CollectionAssert.AreEqual(D2D1PixelShader.LoadBytecode().ToArray(), shaderInfo.HlslBytecode.ToArray());
}
[D2DInputCount(1)]
diff --git a/tests/ComputeSharp.Dynamic.NuGet/ComputeSharp.Dynamic.NuGet.csproj b/tests/ComputeSharp.Dxc.NuGet/ComputeSharp.Dxc.NuGet.csproj
similarity index 89%
rename from tests/ComputeSharp.Dynamic.NuGet/ComputeSharp.Dynamic.NuGet.csproj
rename to tests/ComputeSharp.Dxc.NuGet/ComputeSharp.Dxc.NuGet.csproj
index 8ace0fde..79096162 100644
--- a/tests/ComputeSharp.Dynamic.NuGet/ComputeSharp.Dynamic.NuGet.csproj
+++ b/tests/ComputeSharp.Dxc.NuGet/ComputeSharp.Dxc.NuGet.csproj
@@ -15,6 +15,6 @@
-
+
diff --git a/tests/ComputeSharp.Dynamic.NuGet/Program.cs b/tests/ComputeSharp.Dxc.NuGet/Program.cs
similarity index 100%
rename from tests/ComputeSharp.Dynamic.NuGet/Program.cs
rename to tests/ComputeSharp.Dxc.NuGet/Program.cs
diff --git a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj
index 70a95d5d..92eee51b 100644
--- a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj
+++ b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj
@@ -15,7 +15,7 @@
-
+
diff --git a/tests/ComputeSharp.Tests.Internals/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderCompilerTests.cs
deleted file mode 100644
index ff01970d..00000000
--- a/tests/ComputeSharp.Tests.Internals/ShaderCompilerTests.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-using System;
-using ComputeSharp.Shaders.Translation;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using TerraFX.Interop.DirectX;
-using TerraFX.Interop.Windows;
-
-namespace ComputeSharp.Tests.Internals;
-
-[TestClass]
-[TestCategory("ShaderCompiler")]
-public class ShaderCompilerTests
-{
- private const string ShaderSource = """
- cbuffer _ : register(b0)
- {
- uint __x;
- uint __y;
- uint __z;
- }
-
- RWStructuredBuffer buffer : register(u0);
-
- [NumThreads(32, 1, 1)]
- void Execute(uint3 ids : SV_DispatchThreadId)
- {
- if (ids.x < __x && ids.y < __y && ids.z < __z)
- {
- buffer[ids.x] *= 2;
- }
- }
- """;
-
- [TestMethod]
- public void CompileTest_Ok()
- {
- using ComPtr dxcBlob = ShaderCompiler.Instance.Compile(ShaderSource.AsSpan());
- }
-
- [TestMethod]
- [ExpectedException(typeof(DxcCompilationException))]
- public void CompileTest_Fail()
- {
- string faultyShader = ShaderSource.Replace("ids.x", "ids.X");
-
- using ComPtr dxcBlob = ShaderCompiler.Instance.Compile(faultyShader.AsSpan());
- }
-}
\ No newline at end of file
diff --git a/tests/ComputeSharp.Tests.NativeLibrariesResolver/DynamicNativeLibrariesResolverTests.cs b/tests/ComputeSharp.Tests.NativeLibrariesResolver/DxcNativeLibrariesResolverTests.cs
similarity index 73%
rename from tests/ComputeSharp.Tests.NativeLibrariesResolver/DynamicNativeLibrariesResolverTests.cs
rename to tests/ComputeSharp.Tests.NativeLibrariesResolver/DxcNativeLibrariesResolverTests.cs
index 539562d0..848d209c 100644
--- a/tests/ComputeSharp.Tests.NativeLibrariesResolver/DynamicNativeLibrariesResolverTests.cs
+++ b/tests/ComputeSharp.Tests.NativeLibrariesResolver/DxcNativeLibrariesResolverTests.cs
@@ -6,10 +6,10 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests.NativeLibrariesResolver;
[TestClass]
-public class DynamicNativeLibrariesResolverTests : NativeLibrariesResolverTestsBase
+public class DxcNativeLibrariesResolverTests : NativeLibrariesResolverTestsBase
{
///
- protected override string SampleProjectName => "ComputeSharp.Dynamic.NuGet";
+ protected override string SampleProjectName => "ComputeSharp.Dxc.NuGet";
///
/// Performs static initialization for the assembly before any unit tests are run.
@@ -18,7 +18,7 @@ public class DynamicNativeLibrariesResolverTests : NativeLibrariesResolverTestsB
[ClassInitialize]
public static void InitializeDynamicDependencies(TestContext _)
{
- string path = Path.GetDirectoryName(typeof(DynamicNativeLibrariesResolverTests).Assembly.Location)!;
+ string path = Path.GetDirectoryName(typeof(DxcNativeLibrariesResolverTests).Assembly.Location)!;
while (Path.GetFileName(path) is not "ComputeSharp")
{
@@ -27,10 +27,10 @@ public class DynamicNativeLibrariesResolverTests : NativeLibrariesResolverTestsB
string coreProjectPath = Path.Combine(path, "src", "ComputeSharp.Core", "ComputeSharp.Core.csproj");
string projectPath = Path.Combine(path, "src", "ComputeSharp", "ComputeSharp.csproj");
- string dynamicProjectPath = Path.Combine(path, "src", "ComputeSharp.Dynamic", "ComputeSharp.Dynamic.csproj");
+ string dxcProjectPath = Path.Combine(path, "src", "ComputeSharp.Dxc", "ComputeSharp.Dxc.csproj");
Process.Start("dotnet", $"pack {coreProjectPath} -c Release").WaitForExit();
Process.Start("dotnet", $"pack {projectPath} -c Release").WaitForExit();
- Process.Start("dotnet", $"pack {dynamicProjectPath} -c Release").WaitForExit();
+ Process.Start("dotnet", $"pack {dxcProjectPath} -c Release").WaitForExit();
}
}
\ No newline at end of file
diff --git a/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs b/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs
index 5d895df0..5fa54a0c 100644
--- a/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs
+++ b/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs
@@ -18,7 +18,7 @@ public class NativeLibrariesResolverTests : NativeLibrariesResolverTestsBase
[ClassInitialize]
public static void InitializeDynamicDependencies(TestContext _)
{
- string path = Path.GetDirectoryName(typeof(DynamicNativeLibrariesResolverTests).Assembly.Location)!;
+ string path = Path.GetDirectoryName(typeof(DxcNativeLibrariesResolverTests).Assembly.Location)!;
while (Path.GetFileName(path) is not "ComputeSharp")
{
diff --git a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj
index 35c21b0b..772d7f15 100644
--- a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj
+++ b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj
@@ -25,7 +25,7 @@
-
+
diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs
index ca4f35b0..80ef6827 100644
--- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs
+++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs
@@ -1,4 +1,5 @@
using ComputeSharp;
+using ComputeSharp.Descriptors;
using ComputeSharp.Interop;
using ComputeSharp.Tests.Misc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
@@ -11,6 +12,14 @@ namespace ComputeSharp.Tests
[TestCategory("ShaderCompiler")]
public partial class ShaderCompilerTests
{
+ [TestMethod]
+ public void ReflectionBytecode()
+ {
+ ShaderInfo shaderInfo = ReflectionServices.GetShaderInfo();
+
+ CollectionAssert.AreEqual(((IComputeShaderDescriptor)default(ReservedKeywordsShader)).HlslBytecode.ToArray(), shaderInfo.HlslBytecode.ToArray());
+ }
+
[TestMethod]
public void ReservedKeywords()
{