using System; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using ComputeSharp.Core.Extensions; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; namespace ComputeSharp.Shaders.Translation; /// /// A that uses the DXC APIs to compile compute shaders. /// internal sealed unsafe partial class ShaderCompiler { /// /// The thread local instance. /// This is necessary because the DXC library is strictly single-threaded. /// [ThreadStatic] private static ShaderCompiler? instance; /// /// The instance to use to create the bytecode for HLSL sources. /// private readonly ComPtr dxcCompiler; /// /// The instance to use to work with . /// private readonly ComPtr dxcLibrary; /// /// The instance used to compile shaders with . /// private readonly ComPtr dxcIncludeHandler; /// /// Creates a new instance. /// private ShaderCompiler() { using ComPtr dxcCompiler = default; using ComPtr dxcLibrary = default; using ComPtr dxcIncludeHandler = default; DirectX.DxcCreateInstance( (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcCompiler)), Windows.__uuidof(), (void**)dxcCompiler.GetAddressOf()).Assert(); DirectX.DxcCreateInstance( (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcLibrary)), Windows.__uuidof(), (void**)dxcLibrary.GetAddressOf()).Assert(); dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()).Assert(); this.dxcCompiler = dxcCompiler.Move(); this.dxcLibrary = dxcLibrary.Move(); this.dxcIncludeHandler = dxcIncludeHandler.Move(); } /// /// Destroys the current instance. /// ~ShaderCompiler() { this.dxcCompiler.Dispose(); this.dxcLibrary.Dispose(); this.dxcIncludeHandler.Dispose(); } /// /// Gets a instance to use. /// public static ShaderCompiler Instance => instance ??= new(); /// /// Compiles a new HLSL shader from the input source code. /// /// The HLSL source code to compile. /// The bytecode for the compiled shader. public ComPtr Compile(ReadOnlySpan source) { 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( 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 }; this.dxcCompiler.Get()->Compile( (IDxcBlob*)dxcBlobEncoding.Get(), (ushort*)shaderName, (ushort*)entryPoint, (ushort*)shaderProfile, (ushort**)arguments, 3, null, 0, this.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.Get()); } /// /// Throws an exception when a shader compilation fails. /// /// The input (faulting) operation. /// This method always throws and never actually returs. [MethodImpl(MethodImplOptions.NoInlining)] private static ComPtr ThrowHslsCompilationException(IDxcOperationResult* dxcOperationResult) { using ComPtr dxcBlobEncodingError = default; dxcOperationResult->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()).Assert(); string message = new((sbyte*)dxcBlobEncodingError.Get()->GetBufferPointer()); // The error message will be in a format like this: // "hlsl.hlsl:11:20: error: redefinition of 'float1' as different kind of symbol // static const float float1 = asfloat(0xFFC00000); // ^ // note: previous definition is here" // These regex-s try to match the unnecessary headers and remove them, if present. // This doesn't need to be bulletproof, and these regex-s should match all cases anyway. 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] != '.') { message += '.'; } throw new DxcCompilationException(message); } }