Move dynamic shader types to ComputeSharp.Dynamic

このコミットが含まれているのは:
Sergio Pedri committed 2021-12-19 16:45:12 +01:00
1 親 5f8196716b
コミット 3bbf7754ba
13ファイル変更
+7 -1

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

+73
ファイルの表示
@@ -0,0 +1,73 @@
#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT && NET6_0_OR_GREATER
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Toolkit.Diagnostics;
using TerraFX.Interop.Windows;
namespace ComputeSharp.Shaders.Translation;
/// <inheritdoc cref="ShaderCompiler"/>
internal sealed 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",
_ => ThrowHelper.ThrowNotSupportedException<string>("Invalid process architecture")
};
// 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
+159
ファイルの表示
@@ -0,0 +1,159 @@
#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Core.Extensions;
using ComputeSharp.Exceptions;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
namespace ComputeSharp.Shaders.Translation;
/// <summary>
/// A <see langword="class"/> that uses the DXC APIs to compile compute shaders.
/// </summary>
internal sealed unsafe partial class ShaderCompiler
{
/// <summary>
/// The thread local <see cref="ShaderCompiler"/> instance.
/// This is necessary because the DXC library is strictly single-threaded.
/// </summary>
[ThreadStatic]
private static ShaderCompiler? instance;
/// <summary>
/// The <see cref="IDxcCompiler"/> instance to use to create the bytecode for HLSL sources.
/// </summary>
private readonly ComPtr<IDxcCompiler> DxcCompiler;
/// <summary>
/// The <see cref="IDxcLibrary"/> instance to use to work with <see cref="DxcCompiler"/>.
/// </summary>
private readonly ComPtr<IDxcLibrary> DxcLibrary;
/// <summary>
/// The <see cref="IDxcIncludeHandler"/> instance used to compile shaders with <see cref="DxcCompiler"/>.
/// </summary>
private readonly ComPtr<IDxcIncludeHandler> DxcIncludeHandler;
/// <summary>
/// Creates a new <see cref="ShaderCompiler"/> instance.
/// </summary>
private ShaderCompiler()
{
using ComPtr<IDxcCompiler> dxcCompiler = default;
using ComPtr<IDxcLibrary> dxcLibrary = default;
using ComPtr<IDxcIncludeHandler> dxcIncludeHandler = default;
DirectX.DxcCreateInstance(
(Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcCompiler)),
Windows.__uuidof<IDxcCompiler>(),
dxcCompiler.GetVoidAddressOf()).Assert();
DirectX.DxcCreateInstance(
(Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcLibrary)),
Windows.__uuidof<IDxcLibrary>(),
dxcLibrary.GetVoidAddressOf()).Assert();
dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()).Assert();
DxcCompiler = dxcCompiler.Move();
DxcLibrary = dxcLibrary.Move();
DxcIncludeHandler = dxcIncludeHandler.Move();
}
/// <summary>
/// Destroys the current <see cref="ShaderCompiler"/> instance.
/// </summary>
~ShaderCompiler()
{
DxcCompiler.Dispose();
DxcLibrary.Dispose();
DxcIncludeHandler.Dispose();
}
/// <summary>
/// Gets a <see cref="ShaderCompiler"/> instance to use.
/// </summary>
public static ShaderCompiler 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>
/// <returns>The bytecode for the compiled shader.</returns>
[Pure]
public ComPtr<IDxcBlob> CompileShader(ReadOnlySpan<char> source)
{
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)
{
DxcLibrary.Get()->CreateBlobWithEncodingOnHeapCopy(
p,
(uint)source.Length * 2,
1200,
dxcBlobEncoding.GetAddressOf()).Assert();
}
// Try to compile the new compute shader
fixed (char* shaderName = "")
fixed (char* entryPoint = nameof(IComputeShader.Execute))
fixed (char* shaderProfile = "cs_6_0")
fixed (char* optimization = "-O3")
fixed (char* rowMajor = "-Zpr")
fixed (char* warningsAsErrors = "-Werror")
{
char** arguments = stackalloc char*[3] { optimization, rowMajor, warningsAsErrors };
DxcCompiler.Get()->Compile(
(IDxcBlob*)dxcBlobEncoding.Get(),
(ushort*)shaderName,
(ushort*)entryPoint,
(ushort*)shaderProfile,
(ushort**)arguments,
3,
null,
0,
DxcIncludeHandler.Get(),
dxcOperationResult.GetAddressOf()).Assert();
}
HRESULT status;
dxcOperationResult.Get()->GetStatus(&status).Assert();
// The compilation was successful, so we can extract the shader bytecode
if (status == 0)
{
dxcOperationResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf()).Assert();
return dxcBlobBytecode.Move();
}
return ThrowHslsCompilationException(dxcOperationResult);
}
/// <summary>
/// Throws an exception when a shader compilation fails.
/// </summary>
/// <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)
{
using ComPtr<IDxcBlobEncoding> dxcBlobEncodingError = default;
dxcOperationResult->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()).Assert();
string message = new((sbyte*)dxcBlobEncodingError.Get()->GetBufferPointer());
throw new HlslCompilationException(message);
}
}
#endif
+161
ファイルの表示
@@ -0,0 +1,161 @@
using System;
using System.Buffers;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace ComputeSharp.__Internals;
/// <summary>
/// A helper type that implements a pooled buffer writer for <see cref="char"/> values.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This type is not intended to be used directly by user code")]
[DebuggerTypeProxy(typeof(DebugView))]
public ref struct ArrayPoolStringBuilder
{
/// <summary>
/// The underlying <see cref="char"/> array.
/// </summary>
private char[] array;
/// <summary>
/// The starting offset within <see cref="array"/>.
/// </summary>
private int index;
/// <summary>
/// Creates a new <see cref="ArrayPoolStringBuilder"/> instance ready to use.
/// </summary>
/// <param name="sizeHint">The size hint for the internal buffer to allocate.</param>
/// <returns>A new <see cref="ArrayPoolStringBuilder"/> instance with default values.</returns>
[Pure]
public static ArrayPoolStringBuilder Create(int sizeHint)
{
ArrayPoolStringBuilder builder;
builder.array = ArrayPool<char>.Shared.Rent(sizeHint);
builder.index = 0;
return builder;
}
/// <inheritdoc/>
public ReadOnlySpan<char> WrittenSpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new(this.array, 0, this.index);
}
/// <summary>
/// Appends the input character to the current buffer.
/// </summary>
/// <param name="value">The input character to write.</param>
public void Append(char value)
{
EnsureCapacity(1);
this.array[this.index++] = value;
}
/// <summary>
/// Appends the input sequence of characters to the current buffer.
/// </summary>
/// <param name="value">The input characters to write.</param>
public void Append(string value)
{
EnsureCapacity(value.Length);
#if NET6_0_OR_GREATER
value.CopyTo(this.array.AsSpan(this.index));
#else
value.AsSpan().CopyTo(this.array.AsSpan(this.index));
#endif
this.index += value.Length;
}
/// <summary>
/// Appends the text representation of the input value to the current buffer.
/// </summary>
/// <param name="value">The input value to write.</param>
public void Append(int value)
{
#if NET6_0_OR_GREATER
int charsWritten;
while (!value.TryFormat(this.array.AsSpan(this.index), out charsWritten))
{
EnsureCapacity(10);
}
this.index += charsWritten;
#else
Append(value.ToString());
#endif
}
/// <summary>
/// Ensures that <see cref="array"/> has enough free space to contain a given number of new items.
/// </summary>
/// <param name="requestedSize">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCapacity(int requestedSize)
{
if (requestedSize > this.array.Length - this.index)
{
ResizeBuffer(requestedSize);
}
}
/// <summary>
/// Resizes <see cref="array"/> to ensure it can fit the specified number of new items.
/// </summary>
/// <param name="sizeHint">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void ResizeBuffer(int sizeHint)
{
int minimumSize = this.index + sizeHint;
// Rent a new array with the specified size, and copy as many items from the current array
// as possible to the new array. This mirrors the behavior of the Array.Resize API from
// the BCL: if the new size is greater than the length of the current array, copy all the
// items from the original array into the new one. Otherwise, copy as many items as possible,
// until the new array is completely filled, and ignore the remaining items in the first array.
char[] newArray = ArrayPool<char>.Shared.Rent(minimumSize);
int itemsToCopy = Math.Min(this.array.Length, minimumSize);
Array.Copy(this.array, 0, newArray, 0, itemsToCopy);
ArrayPool<char>.Shared.Return(array);
this.array = newArray;
}
/// <inheritdoc/>
public void Dispose()
{
ArrayPool<char>.Shared.Return(this.array);
}
/// <summary>
/// A debug proxy used for displaying debug info.
/// </summary>
internal sealed class DebugView
{
/// <summary>
/// Initializes a new instance of the <see cref="DebugView"/> class with the specified parameters.
/// </summary>
/// <param name="builder">The input <see cref="ArrayPoolStringBuilder"/> instance to display.</param>
public DebugView(ArrayPoolStringBuilder builder)
{
Text = builder.WrittenSpan.ToString();
}
/// <summary>
/// Gets the text to display for the current instance.
/// </summary>
public string Text { get; }
}
}