using System; using System.Collections.Immutable; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading; using ComputeSharp.D2D1.Shaders.Translation; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Windows.Win32; using Windows.Win32.Graphics.Direct3D; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.D2D1.SourceGenerators; /// partial class D2DPixelShaderDescriptorGenerator { /// /// A helper with all logic to generate the HLSL bytecode properties. /// internal static partial class HlslBytecode { /// /// The shared cache of values. /// private static readonly DynamicCache HlslBytecodeCache = new(); /// /// Extracts the requested shader profile for the current shader. /// /// The input instance to process. /// The requested shader profile to use to compile the shader, if present. public static D2D1ShaderProfile? GetRequestedShaderProfile(INamedTypeSymbol structDeclarationSymbol) { if (structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out AttributeData? attributeData)) { return (D2D1ShaderProfile)attributeData.ConstructorArguments[0].Value!; } if (structDeclarationSymbol.ContainingAssembly.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out attributeData)) { return (D2D1ShaderProfile)attributeData.ConstructorArguments[0].Value!; } return null; } /// /// Extracts the requested compile options for the current shader. /// /// The collection of produced instances. /// The input instance to process. /// The requested compile options to use to compile the shader, if present. public static D2D1CompileOptions? GetRequestedCompileOptions(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) { if (structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData)) { D2D1CompileOptions options = (D2D1CompileOptions)attributeData.ConstructorArguments[0].Value!; if ((options & D2D1CompileOptions.PackMatrixColumnMajor) != 0) { diagnostics.Add( InvalidPackMatrixColumnMajorOption, structDeclarationSymbol, structDeclarationSymbol); } // PackMatrixRowMajor is always automatically enabled return options | D2D1CompileOptions.PackMatrixRowMajor; } if (structDeclarationSymbol.ContainingAssembly.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out attributeData)) { // No need to validate against PackMatrixColumnMajor as that's checked separately return (D2D1CompileOptions)attributeData.ConstructorArguments[0].Value! | D2D1CompileOptions.PackMatrixRowMajor; } return null; } /// /// Gets the effective shader profile to use. /// /// The requested shader profile. /// Whether compilation should be performed with the input profile. /// The effective shader profile. public static D2D1ShaderProfile GetEffectiveShaderProfile(D2D1ShaderProfile? shaderProfile, out bool isCompilationEnabled) { // Compilation is only enabled if the user explicitly selected a shader profile isCompilationEnabled = shaderProfile is not null; // The effective shader profile is either be the requested one, or the default value (which maps to PS5.0) return shaderProfile ?? D2D1ShaderProfile.PixelShader50; } /// /// Gets the effective compile options to use. /// /// The requested compile options. /// Whether the input shader supports linking. /// The effective compile options. public static D2D1CompileOptions GetEffectiveCompileOptions(D2D1CompileOptions? compileOptions, bool isLinkingSupported) { // If an explicit set of compile options is provided, use that directly. Otherwise, use the default // options plus the option to enable linking only if the shader can potentially support it. return compileOptions ?? (D2D1CompileOptions.Default | (isLinkingSupported ? D2D1CompileOptions.EnableLinking : 0)); } /// /// Extracts the metadata definition for the current shader. /// /// The input object currently in use. /// The input instance to process. /// The number of inputs for the shader. /// Whether the shader only has simple inputs. public static bool IsSimpleInputShader( Compilation compilation, INamedTypeSymbol structDeclarationSymbol, int inputCount) { return IsSimpleInputShader( structDeclarationSymbol, compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputSimpleAttribute")!, inputCount); } /// /// Extracts the metadata definition for the current shader. /// /// The input instance to process. /// The symbol for the [D2DInputSimple] attribute. /// The number of inputs for the shader. /// Whether the shader only has simple inputs. public static bool IsSimpleInputShader( INamedTypeSymbol structDeclarationSymbol, INamedTypeSymbol d2DInputSimpleSymbolAttributeSymbol, int inputCount) { // We cannot trust the input count to be valid at this point (it may be invalid and // with diagnostic already emitted for it). So first, just clamp it in the right range. inputCount = Math.Max(0, Math.Min(8, inputCount)); // If there are no inputs, the shader is as if only had simple inputs if (inputCount == 0) { return true; } // Build a map of all simple inputs (unmarked inputs default to being complex). // We can never have more than 8 inputs, and if there are it means the shader is // not valid. Just ignore them, and the generator will emit a separate diagnostic. Span simpleInputsMap = stackalloc bool[8]; // We first start with all inputs marked as complex (ie. not simple) simpleInputsMap.Clear(); foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes()) { // Only retrieve indices of simple inputs that are in range. If an input is out of // range, the diagnostic for it will already be emitted by a previous generator step. if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DInputSimpleSymbolAttributeSymbol) && attributeData.ConstructorArguments is [{ Value: >= 0 and < 8 and int index }]) { simpleInputsMap[index] = true; } } bool isSimpleInputShader = true; // Validate all inputs in our range (filtered by the allowed one) foreach (bool isSimpleInput in simpleInputsMap[..inputCount]) { isSimpleInputShader &= isSimpleInput; } return isSimpleInputShader; } /// /// Gets the instance for the input shader info. /// /// The instance for the shader to compile. /// The used to cancel the operation, if needed. /// The instance for the current shader. public static HlslBytecodeInfo GetInfo(ref HlslBytecodeInfoKey key, CancellationToken token) { static unsafe HlslBytecodeInfo GetInfo(HlslBytecodeInfoKey key, CancellationToken token) { // Check if the compilation is not enabled (eg. if there's been errors earlier in the pipeline). // In this case, skip the compilation, as diagnostic will be emitted for those anyway. // Compiling would just add overhead and result in more errors, as the HLSL would be invalid. if (!key.IsCompilationEnabled) { return HlslBytecodeInfo.Missing.Instance; } try { token.ThrowIfCancellationRequested(); // Compile the shader bytecode using the effective parameters using ComPtr d3DBlob = D3DCompiler.Compile( key.HlslSource.AsSpan(), key.ShaderProfile, key.CompileOptions); token.ThrowIfCancellationRequested(); // Check whether double precision operations are required bool requiresDoublePrecisionSupport = D3DCompiler.IsDoublePrecisionSupportRequired(d3DBlob.Get()); token.ThrowIfCancellationRequested(); byte* buffer = (byte*)d3DBlob.Get()->GetBufferPointer(); int length = checked((int)d3DBlob.Get()->GetBufferSize()); byte[] array = new ReadOnlySpan(buffer, length).ToArray(); ImmutableArray bytecode = Unsafe.As>(ref array); return new HlslBytecodeInfo.Success(bytecode, requiresDoublePrecisionSupport); } catch (Win32Exception e) { return new HlslBytecodeInfo.Win32Error(e.NativeErrorCode, D3DCompiler.PrettifyFxcErrorMessage(e.Message)); } catch (FxcCompilationException e) { return new HlslBytecodeInfo.CompilerError(D3DCompiler.PrettifyFxcErrorMessage(e.Message)); } } // Get or create the HLSL bytecode compilation result for the input key. The dynamic cache // will take care of retrieving an existing cached value if the same shader has been compiled // already with the same parameters. After this call, callers must use the updated key value. return HlslBytecodeCache.GetOrCreate(ref key, GetInfo, token); } /// /// Gets any diagnostics from a processed instance. /// /// The input instance to process. /// The source instance. /// The collection of produced instances. public static void GetInfoDiagnostics( INamedTypeSymbol structDeclarationSymbol, HlslBytecodeInfo info, ImmutableArrayBuilder diagnostics) { DiagnosticInfo? diagnostic = null; if (info is HlslBytecodeInfo.Win32Error win32Error) { diagnostic = DiagnosticInfo.Create( HlslBytecodeFailedWithWin32Exception, structDeclarationSymbol, [structDeclarationSymbol, win32Error.HResult, win32Error.Message]); } else if (info is HlslBytecodeInfo.CompilerError fxcError) { diagnostic = DiagnosticInfo.Create( HlslBytecodeFailedWithFxcCompilationException, structDeclarationSymbol, [structDeclarationSymbol, fxcError.Message]); } if (diagnostic is not null) { diagnostics.Add(diagnostic); } } /// /// Gets the diagnostics for when double precision support is configured incorrectly. /// /// The input instance to process. /// The source instance. /// The collection of produced instances. public static void GetDoublePrecisionSupportDiagnostics( INamedTypeSymbol structDeclarationSymbol, HlslBytecodeInfo info, ImmutableArrayBuilder diagnostics) { // If we have no compiled HLSL bytecode, there is nothing more to do if (info is not HlslBytecodeInfo.Success success) { return; } bool hasD2DRequiresDoublePrecisionSupportAttribute = structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName( "ComputeSharp.D2D1.D2DRequiresDoublePrecisionSupportAttribute", out AttributeData? attributeData); // Check the two cases where diagnostics are necessary: // - The shader does not have [D2DRequiresDoublePrecisionSupport], but it needs it // - The shader has [D2DRequiresDoublePrecisionSupport], but it does not need it if (!hasD2DRequiresDoublePrecisionSupportAttribute && success.RequiresDoublePrecisionSupport) { diagnostics.Add(DiagnosticInfo.Create( MissingD2DRequiresDoublePrecisionSupportAttribute, structDeclarationSymbol, structDeclarationSymbol)); } else if (hasD2DRequiresDoublePrecisionSupportAttribute && !success.RequiresDoublePrecisionSupport) { diagnostics.Add(DiagnosticInfo.Create( UnnecessaryD2DRequiresDoublePrecisionSupportAttribute, attributeData!.GetLocation(), structDeclarationSymbol)); } } } }