Merge pull request #622 from Sergio0694/dev/reflection-tweaks

Remove shader compilation from reflection services, rename Dynamic library
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-10-17 12:46:01 +02:00
コミット 38c02e48d0
35ファイル変更
+318 -420

検索条件に一致するファイルはありません

+8 -8
ファイルの表示
@@ -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';
+5 -5
ファイルの表示
@@ -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
+2 -2
ファイルの表示
@@ -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 |
+1 -1
ファイルの表示
@@ -6,7 +6,7 @@
<ItemGroup>
<InternalsVisibleTo Include="ComputeSharp, PublicKey=$(AssemblySignPublicKey)" />
<InternalsVisibleTo Include="ComputeSharp.D3D12MemoryAllocator, PublicKey=$(AssemblySignPublicKey)" />
<InternalsVisibleTo Include="ComputeSharp.Dynamic, PublicKey=$(AssemblySignPublicKey)" />
<InternalsVisibleTo Include="ComputeSharp.Dxc, PublicKey=$(AssemblySignPublicKey)" />
<InternalsVisibleTo Include="ComputeSharp.Pix, PublicKey=$(AssemblySignPublicKey)" />
<InternalsVisibleTo Include="ComputeSharp.WinUI, PublicKey=$(AssemblySignPublicKey)" />
<InternalsVisibleTo Include="ComputeSharp.D2D1, PublicKey=$(AssemblySignPublicKey)" />
+6 -24
ファイルの表示
@@ -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<byte> hlslBytecode = D2D1PixelShader.LoadBytecode<T>();
using ComPtr<ID3D11ShaderReflection> d3D11ShaderReflection = default;
// If the shader already has embedded bytecode, use that directly
if (shader.HlslBytecode is ReadOnlyMemory<byte> { Length: > 0 } hlslBytecode)
fixed (byte* hlslBytecodePtr = hlslBytecode.Span)
{
fixed (byte* hlslBytecodePtr = hlslBytecode.Span)
{
DirectX.D3DReflect(
pSrcData: hlslBytecodePtr,
SrcDataSize: (nuint)hlslBytecode.Length,
pInterface: Windows.__uuidof<ID3D11ShaderReflection>(),
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<byte> object to throw away immediately, as we don't
// actually need to keep the bytecode for later.
using ComPtr<ID3DBlob> 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<ID3D11ShaderReflection>(),
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,
+4
ファイルの表示
@@ -1,3 +1,5 @@
using System;
namespace ComputeSharp.D2D1.Interop;
/// <summary>
@@ -5,6 +7,7 @@ namespace ComputeSharp.D2D1.Interop;
/// </summary>
/// <param name="CompilerVersion">The compiler version used to build the shader.</param>
/// <param name="HlslSource">The HLSL source code the shader was built from.</param>
/// <param name="HlslBytecode">The HLSL bytecode for the shader.</param>
/// <param name="ConstantBufferCount">The number of shader constant buffers.</param>
/// <param name="BoundResourceCount">The number of resource (textures and buffers) bound to a shader.</param>
/// <param name="InstructionCount">The number of intermediate-language instructions in the compiled shader.</param>
@@ -32,6 +35,7 @@ namespace ComputeSharp.D2D1.Interop;
public sealed record D2D1ShaderInfo(
string CompilerVersion,
string HlslSource,
ReadOnlyMemory<byte> HlslBytecode,
uint ConstantBufferCount,
uint BoundResourceCount,
uint InstructionCount,
差分なしでファイル名を変更。
+77
ファイルの表示
@@ -0,0 +1,77 @@
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
namespace ComputeSharp.Interop;
/// <inheritdoc/>
partial class ReflectionServices
{
/// <summary>
/// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries.
/// </summary>
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);
}
/// <summary>
/// The custom <see cref="DllImportResolver"/> for this assembly.
/// </summary>
/// <inheritdoc cref="DllImportResolver"/>
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<string>()
};
// 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;
}
}
@@ -13,101 +13,47 @@ namespace ComputeSharp.Interop;
/// <summary>
/// Provides methods to extract reflection info on compute shaders generated using this library.
/// </summary>
public static class ReflectionServices
public static partial class ReflectionServices
{
/// <summary>
/// Gets the shader info associated with a given compute shader.
/// <para>
/// 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 <see cref="Delegate"/>-s.
/// </para>
/// </summary>
/// <typeparam name="T">The type of compute shader to retrieve info for.</typeparam>
/// <returns>The resulting <see cref="ShaderInfo"/> instance.</returns>
/// <remarks>
/// 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.
/// </remarks>
public static ShaderInfo GetShaderInfo<T>()
where T : struct, IComputeShader, IComputeShaderDescriptor<T>
{
return GetNonGenericShaderInfo(default(T));
}
/// <summary>
/// Gets the shader info associated with a given compute shader.
/// </summary>
/// <typeparam name="T">The type of compute shader to retrieve info for.</typeparam>
/// <param name="shader">The input compute shader to retrieve info for.</param>
/// <returns>The resulting <see cref="ShaderInfo"/> instance.</returns>
/// <remarks>
/// 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.
/// </remarks>
public static unsafe ShaderInfo GetShaderInfo<T>(in T shader)
where T : struct, IComputeShader, IComputeShaderDescriptor<T>
{
return GetNonGenericShaderInfo(in shader);
return GetNonGenericShaderInfo<T>();
}
/// <summary>
/// Gets the shader info associated with a given pixel shader.
/// <para>
/// 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 <see cref="Delegate"/>-s.
/// </para>
/// </summary>
/// <typeparam name="T">The type of pixel shader to retrieve info for.</typeparam>
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
/// <returns>The resulting <see cref="ShaderInfo"/> instance.</returns>
/// <remarks>
/// 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.
/// </remarks>
public static ShaderInfo GetShaderInfo<T, TPixel>()
where T : struct, IComputeShader<TPixel>, IComputeShaderDescriptor<T>
where TPixel : unmanaged
{
return GetNonGenericShaderInfo(default(T));
}
/// <summary>
/// Gets the shader info associated with a given pixel shader.
/// </summary>
/// <typeparam name="T">The type of pixel shader to retrieve info for.</typeparam>
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
/// <param name="shader">The input pixel shader to retrieve info for.</param>
/// <returns>The resulting <see cref="ShaderInfo"/> instance.</returns>
/// <remarks>
/// 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.
/// </remarks>
public static unsafe ShaderInfo GetShaderInfo<T, TPixel>(in T shader)
where T : struct, IComputeShader<TPixel>, IComputeShaderDescriptor<T>
where TPixel : unmanaged
{
return GetNonGenericShaderInfo(in shader);
return GetNonGenericShaderInfo<T>();
}
/// <summary>
/// Gets the shader info associated with a given shader of any type.
/// </summary>
/// <typeparam name="T">The type of shader to retrieve info for.</typeparam>
/// <param name="shader">The input shader to retrieve info for.</param>
/// <returns>The resulting <see cref="ShaderInfo"/> instance.</returns>
private static unsafe ShaderInfo GetNonGenericShaderInfo<T>(in T shader)
private static unsafe ShaderInfo GetNonGenericShaderInfo<T>()
where T : struct, IComputeShaderDescriptor<T>
{
string hlslSource = Unsafe.AsRef(in shader).HlslSource;
Unsafe.SkipInit(out T shader);
using ComPtr<IDxcBlob> dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(hlslSource);
ReadOnlyMemory<byte> hlslBytecode = shader.HlslBytecode;
using ComPtr<IDxcUtils> 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<IDxcUtils>(),
@@ -115,14 +61,19 @@ public static class ReflectionServices
using ComPtr<ID3D12ShaderReflection> 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<ID3D12ShaderReflection>(),
(void**)d3D12ShaderReflection.GetAddressOf()).Assert();
dxcUtils.Get()->CreateReflection(
&dxcBuffer,
Windows.__uuidof<ID3D12ShaderReflection>(),
(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,
@@ -1,3 +1,5 @@
using System;
namespace ComputeSharp.Interop;
/// <summary>
@@ -5,6 +7,7 @@ namespace ComputeSharp.Interop;
/// </summary>
/// <param name="CompilerVersion">The compiler version used to build the shader.</param>
/// <param name="HlslSource">The HLSL source code the shader was built from.</param>
/// <param name="HlslBytecode">The HLSL bytecode for the shader.</param>
/// <param name="ConstantBufferCount">The number of shader constant buffers.</param>
/// <param name="BoundResourceCount">The number of resource (textures and buffers) bound to a shader.</param>
/// <param name="InstructionCount">The number of intermediate-language instructions in the compiled shader.</param>
@@ -31,6 +34,7 @@ namespace ComputeSharp.Interop;
public sealed record ShaderInfo(
string CompilerVersion,
string HlslSource,
ReadOnlyMemory<byte> HlslBytecode,
uint ConstantBufferCount,
uint BoundResourceCount,
uint InstructionCount,
差分なしでファイル名を変更。
差分なしでファイル名を変更。
差分なしでファイル名を変更。
差分なしでファイル名を変更。
-75
ファイルの表示
@@ -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;
/// <inheritdoc cref="ShaderCompiler"/>
unsafe partial class ShaderCompiler
{
/// <summary>
/// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries.
/// </summary>
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<string>()
};
// 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
+6 -88
ファイルの表示
@@ -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;
/// <inheritdoc/>
@@ -34,11 +27,6 @@ partial class ComputeShaderDescriptorGenerator
/// </summary>
private static readonly DynamicCache<HlslBytecodeInfoKey, HlslBytecodeInfo> HlslBytecodeCache = new();
/// <summary>
/// Indicates whether the required <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries have been loaded.
/// </summary>
private static volatile bool areDxcLibrariesLoaded;
/// <summary>
/// Gets the <see cref="HlslBytecodeInfo"/> instance for the input shader info.
/// </summary>
@@ -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<IDxcBlob> 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<byte>(buffer, length).ToArray();
ImmutableArray<byte> bytecode = Unsafe.As<byte[], ImmutableArray<byte>>(ref array);
return new HlslBytecodeInfo.Success(bytecode);
return new HlslBytecodeInfo.Success(Unsafe.As<byte[], ImmutableArray<byte>>(ref bytecode));
}
catch (Win32Exception e)
{
@@ -141,70 +124,5 @@ partial class ComputeShaderDescriptorGenerator
return message.NormalizeToSingleLine();
}
/// <summary>
/// Extracts and loads the <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries.
/// </summary>
/// <exception cref="NotSupportedException">Thrown if the CPU architecture is not supported.</exception>
/// <exception cref="Win32Exception">Thrown if a library fails to load.</exception>
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;
}
}
}
}
+1 -1
ファイルの表示
@@ -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
+4 -8
ファイルの表示
@@ -8,7 +8,6 @@
<ItemGroup>
<!-- ComputeSharp.Core APIs -->
<Compile Include="..\ComputeSharp.Core\Attributes\AutoConstructorAttribute.cs" Link="ComputeSharp.Core\Attributes\AutoConstructorAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Exceptions\InvalidExecutionContextException.cs" Link="ComputeSharp.Core\Exceptions\InvalidExecutionContextException.cs" />
<Compile Include="..\ComputeSharp.Core\Intrinsics\Attributes\HlslIntrinsicNameAttribute.cs" Link="ComputeSharp.Core\Intrinsics\Attributes\HlslIntrinsicNameAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Intrinsics\Hlsl.Casts.g.cs" Link="ComputeSharp.Core\Intrinsics\Hlsl.Casts.g.cs" />
@@ -67,9 +66,6 @@
<Compile Include="..\ComputeSharp\Core\Helpers\AlignmentHelper.cs" Link="ComputeSharp\Core\Helpers\AlignmentHelper.cs" />
<Compile Include="..\ComputeSharp\Core\Interfaces\IComputeShader.cs" Link="ComputeSharp\Core\Interfaces\IComputeShader.cs" />
<Compile Include="..\ComputeSharp\Core\Interfaces\IComputeShader{TPixel}.cs" Link="ComputeSharp\Core\Interfaces\IComputeShader{TPixel}.cs" />
<Compile Include="..\ComputeSharp\Graphics\Extensions\Interop\ComPtrExtensions.cs" Link="ComputeSharp\Graphics\Extensions\Interop\ComPtrExtensions.cs" />
<Compile Include="..\ComputeSharp.Dynamic\Shaders\Exceptions\DxcCompilationException.cs" Link="ComputeSharp\Shaders\Exceptions\DxcCompilationException.cs" />
<Compile Include="..\ComputeSharp.Dynamic\Shaders\Translation\ShaderCompiler.cs" Link="ComputeSharp\Shaders\Translation\ShaderCompiler.cs" />
</ItemGroup>
<ItemGroup>
@@ -82,10 +78,10 @@
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="..\ComputeSharp.Dynamic\Libraries\x64\dxcompiler.dll" Link="ComputeSharp\Libraries\x64\dxcompiler.dll" />
<EmbeddedResource Include="..\ComputeSharp.Dynamic\Libraries\x64\dxil.dll" Link="ComputeSharp\Libraries\x64\dxil.dll" />
<EmbeddedResource Include="..\ComputeSharp.Dynamic\Libraries\arm64\dxcompiler.dll" Link="ComputeSharp\Libraries\arm64\dxcompiler.dll" />
<EmbeddedResource Include="..\ComputeSharp.Dynamic\Libraries\arm64\dxil.dll" Link="ComputeSharp\Libraries\arm64\dxil.dll" />
<EmbeddedResource Include="..\ComputeSharp.Dxc\Libraries\x64\dxcompiler.dll" Link="ComputeSharp\Libraries\x64\dxcompiler.dll" />
<EmbeddedResource Include="..\ComputeSharp.Dxc\Libraries\x64\dxil.dll" Link="ComputeSharp\Libraries\x64\dxil.dll" />
<EmbeddedResource Include="..\ComputeSharp.Dxc\Libraries\arm64\dxcompiler.dll" Link="ComputeSharp\Libraries\arm64\dxcompiler.dll" />
<EmbeddedResource Include="..\ComputeSharp.Dxc\Libraries\arm64\dxil.dll" Link="ComputeSharp\Libraries\arm64\dxil.dll" />
</ItemGroup>
<!-- Shared project with common helpers -->
@@ -1,35 +0,0 @@
using System.ComponentModel;
using System.Diagnostics;
using TerraFX.Interop.Windows;
namespace ComputeSharp.Core.Extensions;
/// <summary>
/// Helper methods to efficiently throw exceptions.
/// </summary>
[DebuggerStepThrough]
internal static class HRESULTExtensions
{
/// <summary>
/// Throws a <see cref="Win32Exception"/> if <paramref name="result"/> represents an error.
/// </summary>
/// <param name="result">The input <see cref="HRESULT"/> to check.</param>
/// <exception cref="Win32Exception">Thrown if <paramref name="result"/> represents an error.</exception>
public static void Assert(this HRESULT result)
{
Assert((int)result);
}
/// <summary>
/// Throws a <see cref="Win32Exception"/> if <paramref name="result"/> represents an error.
/// </summary>
/// <param name="result">The input <see cref="int"/> to check.</param>
/// <exception cref="Win32Exception">Thrown if <paramref name="result"/> represents an error.</exception>
public static void Assert(this int result)
{
if (result < 0)
{
throw new Win32Exception(result);
}
}
}
+2 -2
ファイルの表示
@@ -640,7 +640,7 @@ partial class DiagnosticDescriptors
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a shader without the embedded bytecode attribute, when dynamic shaders are not supported.
/// Gets a <see cref="DiagnosticDescriptor"/> for a shader without the embedded bytecode attribute,.
/// <para>
/// Format: <c>"The shader of type {0} needs to be annotated as having embedded bytecode (using the [EmbeddedBytecode] attribute), as dynamic shader compilation is not supported"</c>.
/// </para>
@@ -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");
/// <summary>
@@ -1,11 +1,11 @@
using System;
namespace ComputeSharp;
namespace ComputeSharp.SourceGenerators.Dxc;
/// <summary>
/// A custom <see cref="Exception"/> type that indicates when a shader compilation with the DXC compiler has failed.
/// </summary>
public sealed class DxcCompilationException : Exception
internal sealed class DxcCompilationException : Exception
{
/// <summary>
/// Creates a new <see cref="DxcCompilationException"/> instance.
@@ -23,14 +23,8 @@ public sealed class DxcCompilationException : Exception
/// <returns>A formatted error message for a new <see cref="DxcCompilationException"/> instance.</returns>
private static string GetExceptionMessage(string error)
{
#if NET6_0_OR_GREATER
ReadOnlySpan<char> 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.""";
}
+100
ファイルの表示
@@ -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;
/// <summary>
/// A <see langword="class"/> that handles loading the DXC libraries.
/// </summary>
internal sealed unsafe class DxcLibraryLoader
{
/// <summary>
/// An object to use to synchronize loading the DXC libraries.
/// </summary>
private static readonly object LoadingLock = new();
/// <summary>
/// Indicates whether the required <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries have been loaded.
/// </summary>
private static volatile bool areDxcLibrariesLoaded;
/// <summary>
/// Extracts and loads the <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries.
/// </summary>
/// <exception cref="NotSupportedException">Thrown if the CPU architecture is not supported.</exception>
/// <exception cref="Win32Exception">Thrown if a library fails to load.</exception>
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;
}
}
}
@@ -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;
/// <summary>
/// A <see langword="class"/> that uses the DXC APIs to compile compute shaders.
/// </summary>
internal sealed unsafe partial class ShaderCompiler
internal sealed unsafe class DxcShaderCompiler
{
/// <summary>
/// The thread local <see cref="ShaderCompiler"/> instance.
/// The thread local <see cref="DxcShaderCompiler"/> instance.
/// This is necessary because the DXC library is strictly single-threaded.
/// </summary>
[ThreadStatic]
private static ShaderCompiler? instance;
private static DxcShaderCompiler? instance;
/// <summary>
/// The <see cref="IDxcCompiler"/> instance to use to create the bytecode for HLSL sources.
@@ -35,35 +36,35 @@ internal sealed unsafe partial class ShaderCompiler
private readonly ComPtr<IDxcIncludeHandler> dxcIncludeHandler;
/// <summary>
/// Creates a new <see cref="ShaderCompiler"/> instance.
/// Creates a new <see cref="DxcShaderCompiler"/> instance.
/// </summary>
private ShaderCompiler()
private DxcShaderCompiler()
{
using ComPtr<IDxcCompiler> dxcCompiler = default;
using ComPtr<IDxcLibrary> dxcLibrary = default;
using ComPtr<IDxcIncludeHandler> dxcIncludeHandler = default;
DirectX.DxcCreateInstance(
Marshal.ThrowExceptionForHR(DirectX.DxcCreateInstance(
(Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcCompiler)),
Windows.__uuidof<IDxcCompiler>(),
(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<IDxcLibrary>(),
(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<IDxcCompiler>(dxcCompiler.Get());
this.dxcLibrary = new ComPtr<IDxcLibrary>(dxcLibrary.Get());
this.dxcIncludeHandler = new ComPtr<IDxcIncludeHandler>(dxcIncludeHandler.Get());
}
/// <summary>
/// Destroys the current <see cref="ShaderCompiler"/> instance.
/// Destroys the current <see cref="DxcShaderCompiler"/> instance.
/// </summary>
~ShaderCompiler()
~DxcShaderCompiler()
{
this.dxcCompiler.Dispose();
this.dxcLibrary.Dispose();
@@ -71,31 +72,35 @@ internal sealed unsafe partial class ShaderCompiler
}
/// <summary>
/// Gets a <see cref="ShaderCompiler"/> instance to use.
/// Gets a <see cref="DxcShaderCompiler"/> instance to use.
/// </summary>
public static ShaderCompiler Instance => instance ??= new();
public static DxcShaderCompiler Instance => instance ??= new();
/// <summary>
/// Compiles a new HLSL shader from the input source code.
/// </summary>
/// <param name="source">The HLSL source code to compile.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <returns>The bytecode for the compiled shader.</returns>
public ComPtr<IDxcBlob> Compile(ReadOnlySpan<char> source)
public byte[] Compile(ReadOnlySpan<char> source, CancellationToken token)
{
using ComPtr<IDxcBlobEncoding> dxcBlobEncoding = default;
using ComPtr<IDxcOperationResult> dxcOperationResult = default;
using ComPtr<IDxcBlob> 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<IDxcBlob> 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<byte>(buffer, length).ToArray();
}
return ThrowHslsCompilationException(dxcOperationResult.Get());
@@ -140,11 +154,11 @@ internal sealed unsafe partial class ShaderCompiler
/// <param name="dxcOperationResult">The input (faulting) operation.</param>
/// <returns>This method always throws and never actually returs.</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
private static ComPtr<IDxcBlob> ThrowHslsCompilationException(IDxcOperationResult* dxcOperationResult)
private static byte[] ThrowHslsCompilationException(IDxcOperationResult* dxcOperationResult)
{
using ComPtr<IDxcBlobEncoding> 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 += '.';
}
+1 -1
ファイルの表示
@@ -6,7 +6,7 @@
<ItemGroup>
<InternalsVisibleTo Include="ComputeSharp.D3D12MemoryAllocator, PublicKey=$(AssemblySignPublicKey)" />
<InternalsVisibleTo Include="ComputeSharp.Dynamic, PublicKey=$(AssemblySignPublicKey)" />
<InternalsVisibleTo Include="ComputeSharp.Dxc, PublicKey=$(AssemblySignPublicKey)" />
<InternalsVisibleTo Include="ComputeSharp.Pix, PublicKey=$(AssemblySignPublicKey)" />
<InternalsVisibleTo Include="ComputeSharp.WinUI, PublicKey=$(AssemblySignPublicKey)" />
<InternalsVisibleTo Include="ComputeSharp.Tests.Internals, PublicKey=$(AssemblySignPublicKey)" />
+2 -2
ファイルの表示
@@ -30,12 +30,12 @@ namespace ComputeSharp;
/// <para>
/// </para>
/// 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 <c>ComputeSharp.Dynamic</c> library is
/// otherwise the usual runtime compilation will be used as fallback if the <c>ComputeSharp.Dxc</c> library is
/// referenced. If not, <see cref="NotSupportedException"/> will be thrown when trying to dispatch the shader.
/// </summary>
/// <remarks>
/// <para>
/// Using this attribute is mandatory when not referencing <c>ComputeSharp.Dynamic</c>.
/// Using this attribute is mandatory when not referencing <c>ComputeSharp.Dxc</c>.
/// </para>
/// <para>
/// This attribute can only be used when the shader type being annotated does not require dynamic
+2 -2
ファイルの表示
@@ -20,8 +20,8 @@
<Description Condition="'$(MSBuildProjectName)' == 'ComputeSharp.D3D12MemoryAllocator'">
<![CDATA[An extension library for ComputeSharp to enable using D3D12MA as the memory allocator for graphics resources.]]>
</Description>
<Description Condition="'$(MSBuildProjectName)' == 'ComputeSharp.Dynamic'">
<![CDATA[An extension library for ComputeSharp to enable dynamic compilation of shaders at runtime.]]>
<Description Condition="'$(MSBuildProjectName)' == 'ComputeSharp.Dxc'">
<![CDATA[An extension library for ComputeSharp bundling the DXC compiler and enabling shader reflection.]]>
</Description>
<Description Condition="'$(MSBuildProjectName)' == 'ComputeSharp.Pix'">
<![CDATA[An extension library for ComputeSharp to enable PIX support to produce debugging information.]]>
+6
ファイルの表示
@@ -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<ReflectedShader>().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<ReflectedShaderWithDoubleOperations>().ToArray(), shaderInfo.HlslBytecode.ToArray());
}
[D2DInputCount(1)]
@@ -15,6 +15,6 @@
<ItemGroup>
<PackageReference Include="ComputeSharp.Core" Version="$(PackageVersion)" />
<PackageReference Include="ComputeSharp" Version="$(PackageVersion)" />
<PackageReference Include="ComputeSharp.Dynamic" Version="$(PackageVersion)" />
<PackageReference Include="ComputeSharp.Dxc" Version="$(PackageVersion)" />
</ItemGroup>
</Project>
差分なしでファイル名を変更。
+1 -1
ファイルの表示
@@ -15,7 +15,7 @@
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Dynamic\ComputeSharp.Dynamic.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Dxc\ComputeSharp.Dxc.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
</ItemGroup>
-47
ファイルの表示
@@ -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<float> 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<IDxcBlob> dxcBlob = ShaderCompiler.Instance.Compile(ShaderSource.AsSpan());
}
[TestMethod]
[ExpectedException(typeof(DxcCompilationException))]
public void CompileTest_Fail()
{
string faultyShader = ShaderSource.Replace("ids.x", "ids.X");
using ComPtr<IDxcBlob> dxcBlob = ShaderCompiler.Instance.Compile(faultyShader.AsSpan());
}
}
@@ -6,10 +6,10 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests.NativeLibrariesResolver;
[TestClass]
public class DynamicNativeLibrariesResolverTests : NativeLibrariesResolverTestsBase
public class DxcNativeLibrariesResolverTests : NativeLibrariesResolverTestsBase
{
/// <inheritdoc/>
protected override string SampleProjectName => "ComputeSharp.Dynamic.NuGet";
protected override string SampleProjectName => "ComputeSharp.Dxc.NuGet";
/// <summary>
/// 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();
}
}
+1 -1
ファイルの表示
@@ -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")
{
+1 -1
ファイルの表示
@@ -25,7 +25,7 @@
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp.D3D12MemoryAllocator\ComputeSharp.D3D12MemoryAllocator.csproj" Condition="'$(UseD3D12MemoryAllocator)' == 'true'" />
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Dynamic\ComputeSharp.Dynamic.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Dxc\ComputeSharp.Dxc.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
</ItemGroup>
+9
ファイルの表示
@@ -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<ReservedKeywordsShader>();
CollectionAssert.AreEqual(((IComputeShaderDescriptor<ReservedKeywordsShader>)default(ReservedKeywordsShader)).HlslBytecode.ToArray(), shaderInfo.HlslBytecode.ToArray());
}
[TestMethod]
public void ReservedKeywords()
{