diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs
index 94057b71..04e1e4bc 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs
@@ -1,8 +1,8 @@
using System;
using System.Text;
using ComputeSharp.D2D1.__Internals;
+using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Helpers;
-using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -22,10 +22,10 @@ partial class ID2D1ShaderGenerator
///
/// Creates a instance for the EffectId property.
///
- /// The input instance.
+ /// The input instance.
/// An opaque instance to transform the final tree into text.
/// The resulting instance for the EffectId property.
- public static PropertyDeclarationSyntax GetSyntax(HierarchyInfo info, out Func fixup)
+ public static PropertyDeclarationSyntax GetSyntax(EffectIdInfo info, out Func fixup)
{
// Create the local declaration:
//
@@ -48,7 +48,7 @@ partial class ID2D1ShaderGenerator
SingletonSeparatedList(IdentifierName("__EMBEDDED_EFFECT_ID_BYTES"))))))));
// Prepare the initialization text
- string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(new byte[] { 1, 2, 3, 4 }.AsSpan());
+ string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(info.Bytes.AsSpan());
// Set the fixup function
fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_EFFECT_ID_BYTES", effectIdLiterals), Encoding.UTF8);
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs
new file mode 100644
index 00000000..831069bc
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs
@@ -0,0 +1,77 @@
+using System;
+using System.Collections.Immutable;
+using System.Runtime.CompilerServices;
+using System.Security.Cryptography;
+using System.Text;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
+using ComputeSharp.SourceGeneration.Models;
+using Microsoft.CodeAnalysis;
+
+namespace ComputeSharp.D2D1.SourceGenerators;
+
+///
+partial class ID2D1ShaderGenerator
+{
+ ///
+ /// A helper with all logic to generate the EffectId property.
+ ///
+ private static partial class EffectId
+ {
+ ///
+ /// The instance currently in use for the running thread, if any.
+ ///
+ [ThreadStatic]
+ private static IncrementalHash? incrementalHash;
+
+ ///
+ /// Extracts the effect id info for the current shader.
+ ///
+ /// The collection of produced instances.
+ /// The for the shader type in use.
+ /// The resulting effect id.
+ public static ImmutableArray GetInfo(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol)
+ {
+ // Initialize an instance using the MD5 algorithm. We use this for several reasons:
+ // - We don't really need security, this is just to uniquely identify types
+ // - The hash size is 128 bits, which is exactly the size of a GUID.
+ IncrementalHash incrementalHash = EffectId.incrementalHash ??= IncrementalHash.CreateHash(HashAlgorithmName.MD5);
+
+ string assemblyName = structDeclarationSymbol.ContainingAssembly?.Name ?? string.Empty;
+
+ using ImmutableArrayBuilder byteBuffer = ImmutableArrayBuilder.Rent();
+ using ImmutableArrayBuilder charBuffer = ImmutableArrayBuilder.Rent();
+
+ // Format the fully qualified name into a pooled builder to avoid the string allocation
+ structDeclarationSymbol.AppendFullyQualifiedMetadataName(in charBuffer);
+
+ int maxTypeNameCharsLength = Encoding.UTF8.GetMaxByteCount(charBuffer.Count);
+ int maxAssemblyNameCharsLength = Encoding.UTF8.GetMaxByteCount(assemblyName.Length);
+ int maxEncodedCharsLength = Math.Max(maxTypeNameCharsLength, maxAssemblyNameCharsLength);
+
+ byteBuffer.EnsureCapacity(maxEncodedCharsLength);
+
+ // UTF8 encode the fully qualified name first
+ int typeNameCharsLength = Encoding.UTF8.GetBytes(charBuffer.WrittenSpan, byteBuffer.DangerousGetArray().AsSpan());
+
+ byteBuffer.Advance(typeNameCharsLength);
+
+ // Append the UTF8 fully qualified name to the MD5 hash
+ incrementalHash.AppendData(byteBuffer.DangerousGetArray(), 0, byteBuffer.Count);
+
+ // UTF8 encode the assembly name as well
+ int assemblyNameCharsLength = Encoding.UTF8.GetBytes(assemblyName.AsSpan(), byteBuffer.DangerousGetArray().AsSpan());
+
+ byteBuffer.Advance(assemblyNameCharsLength);
+
+ // Append the UTF8 assembly name to the MD5 hash
+ incrementalHash.AppendData(byteBuffer.DangerousGetArray(), 0, byteBuffer.Count);
+
+ // Get the resulting MD5 hash (128 bits)
+ byte[] hash = incrementalHash.GetHashAndReset();
+
+ // We own this buffer, so we can just reinterpret to an immutable array
+ return Unsafe.As>(ref hash);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
index 703bda66..61e2fead 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
@@ -52,6 +52,11 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
using ImmutableArrayBuilder diagnostics = ImmutableArrayBuilder.Rent();
+ // EffectId info
+ ImmutableArray effectId = EffectId.GetInfo(diagnostics, typeSymbol);
+
+ token.ThrowIfCancellationRequested();
+
// LoadDispatchData() info
ImmutableArray fieldInfos = LoadDispatchData.GetInfo(
diagnostics,
@@ -115,6 +120,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
return new D2D1ShaderInfo(
Hierarchy: HierarchyInfo.From(typeSymbol),
+ EffectId: new EffectIdInfo(effectId),
DispatchData: new DispatchDataInfo(fieldInfos, constantBufferSizeInBytes),
InputTypes: new InputTypesInfo(inputTypes),
ResourceTextureDescriptions: new ResourceTextureDescriptionsInfo(resourceTextureDescriptions),
@@ -136,10 +142,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
shaderInfoWithErrors
.Select(static (item, _) => item.Diagnostcs));
- // Get the EffectDisplayName and EffectId info (hierarchy)
- IncrementalValuesProvider hierarchyInfo =
- shaderInfoWithErrors
- .Select(static (item, _) => item.Hierarchy);
+ // Get the EffectDisplayName info (hierarchy)
+ IncrementalValuesProvider hierarchyInfo = shaderInfoWithErrors.Select(static (item, _) => item.Hierarchy);
// Generate the EffectDisplayName properties
context.RegisterSourceOutput(hierarchyInfo, static (context, item) =>
@@ -150,14 +154,19 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
context.AddSource($"{item.FullyQualifiedMetadataName}.{nameof(EffectDisplayName)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
+ // Get the EffectId info (hierarchy and effect id info)
+ IncrementalValuesProvider<(HierarchyInfo Hierarchy, EffectIdInfo EffectId)> effectIdInfo =
+ shaderInfoWithErrors
+ .Select(static (item, _) => (item.Hierarchy, item.EffectId));
+
// Generate the EffectId properties
- context.RegisterSourceOutput(hierarchyInfo, static (context, item) =>
+ context.RegisterSourceOutput(effectIdInfo, static (context, item) =>
{
- PropertyDeclarationSyntax effectDisplayNameProperty = EffectId.GetSyntax(item, out Func fixup);
- CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item, effectDisplayNameProperty, canUseSkipLocalsInit: false);
+ PropertyDeclarationSyntax effectDisplayNameProperty = EffectId.GetSyntax(item.EffectId, out Func fixup);
+ CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDisplayNameProperty, canUseSkipLocalsInit: false);
SourceText text = fixup(compilationUnit);
- context.AddSource($"{item.FullyQualifiedMetadataName}.{nameof(EffectId)}.g.cs", text);
+ context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(EffectId)}.g.cs", text);
});
// Get the GetInputCount() info (hierarchy and input count)
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs
index 5674a782..df8c8c7d 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs
@@ -7,6 +7,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// A model representing all necessary info for a full generation pass for a D2D1 shader.
///
/// The hierarchy info for the shader type.
+/// The effect id info for the shader type.
/// The gathered shader dispatch data.
/// The gathered input types for the shader.
/// The gathered resource texture descriptions for the shader.
@@ -17,6 +18,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// The discovered diagnostics, if any.
internal sealed record D2D1ShaderInfo(
HierarchyInfo Hierarchy,
+ EffectIdInfo EffectId,
DispatchDataInfo DispatchData,
InputTypesInfo InputTypes,
ResourceTextureDescriptionsInfo ResourceTextureDescriptions,
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EffectIdInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EffectIdInfo.cs
new file mode 100644
index 00000000..7b0a55de
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/EffectIdInfo.cs
@@ -0,0 +1,9 @@
+using ComputeSharp.SourceGeneration.Helpers;
+
+namespace ComputeSharp.D2D1.SourceGenerators.Models;
+
+///
+/// A model representing info to use to generate an effect id for a shader.
+///
+/// The bytes for the processed effect id.
+internal sealed record EffectIdInfo(EquatableArray Bytes);
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs
index 3aa5b62b..fca0f6f0 100644
--- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs
+++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs
@@ -75,6 +75,33 @@ internal struct ImmutableArrayBuilder : IDisposable
this.writer!.AddRange(items);
}
+ ///
+ /// Advances the current writer by the specified amount.
+ ///
+ /// The amoutn to advance by.
+ public readonly void Advance(int count)
+ {
+ this.writer!.Advance(count);
+ }
+
+ ///
+ /// Gets the array currently in use (rented from the pool).
+ ///
+ /// The array currently in use.
+ public readonly T[] DangerousGetArray()
+ {
+ return this.writer!.DangerousGetArray();
+ }
+
+ ///
+ /// Ensures that the current instance has enough free space to contain a given number of new items.
+ ///
+ /// The minimum number of items to ensure space for.
+ public readonly void EnsureCapacity(int requestedSize)
+ {
+ this.writer!.EnsureCapacity(requestedSize);
+ }
+
///
/// Inserts an item to the builder at the specified index.
///
@@ -177,6 +204,23 @@ internal struct ImmutableArrayBuilder : IDisposable
this.index += items.Length;
}
+ ///
+ public void Advance(int count)
+ {
+ if (count > this.array.Length - this.index)
+ {
+ ImmutableArrayBuilder.ThrowArgumentOutOfRangeExceptionForCount();
+ }
+
+ this.index += count;
+ }
+
+ ///
+ public T[] DangerousGetArray()
+ {
+ return this.array;
+ }
+
///
public void Insert(int index, T item)
{
@@ -209,12 +253,9 @@ internal struct ImmutableArrayBuilder : IDisposable
this.index = 0;
}
- ///
- /// Ensures that has enough free space to contain a given number of new items.
- ///
- /// The minimum number of items to ensure space for in .
+ ///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void EnsureCapacity(int requestedSize)
+ public void EnsureCapacity(int requestedSize)
{
if (requestedSize > this.array.Length - this.index)
{
@@ -253,4 +294,12 @@ file static class ImmutableArrayBuilder
{
throw new ArgumentOutOfRangeException("index");
}
+
+ ///
+ /// Throws an for "count".
+ ///
+ public static void ThrowArgumentOutOfRangeExceptionForCount()
+ {
+ throw new ArgumentOutOfRangeException("count");
+ }
}
\ No newline at end of file