diff --git a/src/ComputeSharp.D2D1/Extensions/RECTExtensions.cs b/src/ComputeSharp.D2D1/Extensions/RECTExtensions.cs
new file mode 100644
index 00000000..05afc06b
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Extensions/RECTExtensions.cs
@@ -0,0 +1,22 @@
+using System.Drawing;
+using System.Runtime.CompilerServices;
+using TerraFX.Interop.Windows;
+
+namespace ComputeSharp.D2D1.Extensions;
+
+///
+/// Helper methods for .
+///
+internal static class RECTExtensions
+{
+ ///
+ /// Creates a from a value.
+ ///
+ /// The input value.
+ /// The resulting value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Rectangle ToRectangle(this in RECT rect)
+ {
+ return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom);
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Extensions/RectangleExtensions.cs b/src/ComputeSharp.D2D1/Extensions/RectangleExtensions.cs
new file mode 100644
index 00000000..260afe57
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Extensions/RectangleExtensions.cs
@@ -0,0 +1,29 @@
+using System.Drawing;
+using System.Runtime.CompilerServices;
+using TerraFX.Interop.Windows;
+
+namespace ComputeSharp.D2D1.Extensions;
+
+///
+/// Helper methods for .
+///
+internal static class RectangleExtensions
+{
+ ///
+ /// Creates a from a value.
+ ///
+ /// The input value.
+ /// The resulting value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static RECT ToRECT(this in Rectangle rectangle)
+ {
+ RECT result;
+
+ result.left = rectangle.Left;
+ result.top = rectangle.Top;
+ result.right = rectangle.Right;
+ result.bottom = rectangle.Bottom;
+
+ return result;
+ }
+}
diff --git a/src/ComputeSharp.D2D1/Interfaces/ID2D1DrawTransformMapper.cs b/src/ComputeSharp.D2D1/Interfaces/ID2D1DrawTransformMapper.cs
new file mode 100644
index 00000000..f026098a
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Interfaces/ID2D1DrawTransformMapper.cs
@@ -0,0 +1,66 @@
+using System;
+using System.Drawing;
+
+namespace ComputeSharp.D2D1;
+
+///
+/// An providing support for custom, stateful draw transform mappings for shaders.
+///
+public interface ID2D1DrawTransformMapper
+{
+ ///
+ /// Allows a transform to state how it would map a rectangle requested on its output to a set of sample rectangles on its input.
+ ///
+ /// The output rectangle from which the inputs must be mapped.
+ /// The corresponding set of inputs. The inputs will directly correspond to the transform inputs.
+ ///
+ ///
+ /// The transform implementation must regard this method as purely functional. It can base the mapped input and output rectangles on its
+ /// current state as specified by the encapsulating effect properties. However, it must not change its own state in response to this method
+ /// being invoked. The Direct2D renderer implementation reserves the right to call this method at any time and in any sequence.
+ ///
+ ///
+ /// For more info, see .
+ ///
+ ///
+ void MapOutputToInputs(in Rectangle output, Span inputs);
+
+ ///
+ /// Performs the inverse mapping of .
+ ///
+ /// The input rectangles to be mapped to the output rectangle. This parameter is always equal to the input bounds.
+ /// The input rectangles to be mapped to the opaque output rectangle.
+ /// The output rectangle that maps to the corresponding input rectangle.
+ /// The output rectangle that maps to the corresponding opaque input rectangle.
+ ///
+ ///
+ /// Unlike and , this
+ /// method is explicitly called by the renderer at a determined place in its rendering algorithm. The transform implementation may change its state
+ /// based on the input rectangles and use this information to control its rendering information. This method is always called before the
+ /// and methods.
+ ///
+ ///
+ /// For more info, see .
+ ///
+ ///
+ void MapInputsToOutput(ReadOnlySpan inputs, ReadOnlySpan opaqueInputs, out Rectangle output, out Rectangle opaqueOutput);
+
+ ///
+ /// Sets the input rectangles for this rendering pass into the transform.
+ ///
+ /// The index of the input rectangle.
+ /// The invalid input rectangle.
+ /// The output rectangle to which the input rectangle must be mapped.
+ ///
+ ///
+ /// The transform implementation must regard this method as purely functional. The transform implementation can base the mapped input rectangle on
+ /// the transform implementation's current state as specified by the encapsulating effect properties. But the transform implementation can't change
+ /// its own state in response to a call to . Direct2D can call this method at any time
+ /// and in any sequence following a call to .
+ ///
+ ///
+ /// For more info, see .
+ ///
+ ///
+ void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput);
+}
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.Effects.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.Effects.cs
index df1ebcf2..4907311c 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.Effects.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.Effects.cs
@@ -26,9 +26,40 @@ unsafe partial class D2D1InteropServices
/// For more info, see .
public static unsafe void RegisterPixelShaderEffectForD2D1Factory1(void* d2D1Factory1, out Guid effectId)
where T : unmanaged, ID2D1PixelShader
+ {
+ RegisterPixelShaderEffectForD2D1Factory1(d2D1Factory1, null, out effectId);
+ }
+
+ ///
+ /// Registers an effect from an input D2D1 pixel shader, by calling ID2D1Factory1::RegisterEffectFromString.
+ ///
+ /// The type of D2D1 pixel shader to register.
+ /// The type of implementation to register.
+ /// A pointer to the ID2D1Factory1 instance to use.
+ /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect.
+ /// For more info, see .
+ public static unsafe void RegisterPixelShaderEffectForD2D1Factory1(void* d2D1Factory1, out Guid effectId)
+ where T : unmanaged, ID2D1PixelShader
+ where TMapper : class, ID2D1DrawTransformMapper, new()
+ {
+ RegisterPixelShaderEffectForD2D1Factory1(d2D1Factory1, static () => new TMapper(), out effectId);
+ }
+
+ ///
+ /// Registers an effect from an input D2D1 pixel shader, by calling ID2D1Factory1::RegisterEffectFromString.
+ ///
+ /// The type of D2D1 pixel shader to register.
+ /// A pointer to the ID2D1Factory1 instance to use.
+ /// An optional factory of instances to use for the transform.
+ /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect.
+ /// For more info, see .
+ public static unsafe void RegisterPixelShaderEffectForD2D1Factory1(void* d2D1Factory1, Func? mapperFactory, out Guid effectId)
+ where T : unmanaged, ID2D1PixelShader
{
effectId = default;
+ PixelShaderEffect.For.Initialize(mapperFactory);
+
// Setup the input string
StringBuilder effectInputsBuilder = new();
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs
index 176b7422..7ea4cce1 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs
@@ -1,5 +1,7 @@
using System;
+using System.Drawing;
using System.Runtime.InteropServices;
+using ComputeSharp.D2D1.Extensions;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#if !NET6_0_OR_GREATER
@@ -125,9 +127,38 @@ partial struct PixelShaderEffect
return E.E_INVALIDARG;
}
- for (int i = 0; i < @this->numberOfInputs; i++)
+ if (@this->d2D1DrawTransformMapperFactoryHandle.Target is ID2D1DrawTransformMapper d2D1DrawTransformMapper)
{
- inputRects[i] = *outputRect;
+ Rectangle output = outputRect->ToRectangle();
+ Span inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectsCount);
+
+ for (int i = 0; i < (int)inputRectsCount; i++)
+ {
+ inputs[i] = inputRects[i].ToRectangle();
+ }
+
+ // Invoke MapOutputToInputs and handle exceptions so they don't cross the ABI boundary
+ try
+ {
+ d2D1DrawTransformMapper.MapOutputToInputs(in output, inputs);
+ }
+ catch (Exception e)
+ {
+ return e.HResult;
+ }
+
+ for (int i = 0; i < (int)inputRectsCount; i++)
+ {
+ inputRects[i] = inputs[i].ToRECT();
+ }
+ }
+ else
+ {
+ // Default mapping
+ for (int i = 0; i < (int)inputRectsCount; i++)
+ {
+ inputRects[i] = *outputRect;
+ }
}
return S.S_OK;
@@ -144,11 +175,51 @@ partial struct PixelShaderEffect
return E.E_INVALIDARG;
}
- *outputRect = inputRects[0];
+ if (@this->d2D1DrawTransformMapperFactoryHandle.Target is ID2D1DrawTransformMapper d2D1DrawTransformMapper)
+ {
+ Span inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount);
+ Span opaqueInputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount);
- @this->inputRect = inputRects[0];
+ for (int i = 0; i < (int)inputRectCount; i++)
+ {
+ inputs[i] = inputRects[i].ToRectangle();
+ opaqueInputs[i] = inputOpaqueSubRects[i].ToRectangle();
+ }
- *outputOpaqueSubRect = default;
+ Rectangle output;
+ Rectangle opaqueOutput;
+
+ // Handle exceptions, as mentioned above
+ try
+ {
+ d2D1DrawTransformMapper.MapInputsToOutput(inputs, opaqueInputs, out output, out opaqueOutput);
+ }
+ catch (Exception e)
+ {
+ return e.HResult;
+ }
+
+ *outputRect = output.ToRECT();
+ *outputOpaqueSubRect = opaqueOutput.ToRECT();
+ }
+ else if (inputRectCount == 0)
+ {
+ // If there are no inputs, just ignore (users will need a custom mapping)
+ *outputRect = default;
+
+ @this->inputRect = default;
+
+ *outputOpaqueSubRect = default;
+ }
+ else
+ {
+ // Default mapping
+ *outputRect = inputRects[0];
+
+ @this->inputRect = inputRects[0];
+
+ *outputOpaqueSubRect = default;
+ }
return S.S_OK;
}
@@ -159,7 +230,28 @@ partial struct PixelShaderEffect
{
@this = (PixelShaderEffect*)&((void**)@this)[-1];
- *invalidOutputRect = @this->inputRect;
+ if (@this->d2D1DrawTransformMapperFactoryHandle.Target is ID2D1DrawTransformMapper d2D1DrawTransformMapper)
+ {
+ Rectangle invalidInput = invalidInputRect.ToRectangle();
+ Rectangle invalidOutput;
+
+ // Handle exceptions once again
+ try
+ {
+ d2D1DrawTransformMapper.MapInvalidOutput((int)inputIndex, invalidInput, out invalidOutput);
+ }
+ catch (Exception e)
+ {
+ return e.HResult;
+ }
+
+ *invalidOutputRect = invalidOutput.ToRECT();
+ }
+ else
+ {
+ // Default mapping
+ *invalidOutputRect = @this->inputRect;
+ }
return S.S_OK;
}
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs
index 7d78ad65..01307788 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs
@@ -2,6 +2,7 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
+using ComputeSharp.D2D1.Helpers;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#if NET6_0_OR_GREATER
@@ -65,47 +66,83 @@ internal unsafe partial struct PixelShaderEffect
public static class For
where T : unmanaged, ID2D1PixelShader
{
- ///
- /// The for the shader.
- ///
- private static readonly Guid shaderId;
-
- ///
- /// The shader bytecode.
- ///
- private static readonly byte* bytecode;
-
- ///
- /// The size of .
- ///
- private static readonly int bytecodeSize;
-
- ///
- /// The number of inputs for the shader.
- ///
- private static readonly int numberOfInputs;
-
///
/// The wrapper for the shader factory.
///
private static readonly FactoryDelegate EffectFactory = CreateEffect;
///
- /// The static constructor for .
+ /// Indicates whether or not initialization has completed.
///
- static For()
+ private static bool isInitialized;
+
+ ///
+ /// The for the shader.
+ ///
+ private static Guid shaderId;
+
+ ///
+ /// The number of inputs for the shader.
+ ///
+ private static int numberOfInputs;
+
+ ///
+ /// The shader bytecode.
+ ///
+ private static byte* bytecode;
+
+ ///
+ /// The size of .
+ ///
+ private static int bytecodeSize;
+
+ ///
+ /// The factory of instances to use for each created effect.
+ ///
+ private static Func? d2D1DrawTransformMapperFactory;
+
+ ///
+ /// Initializes the shared state.
+ ///
+ /// The factory of instances to use for each created effect.
+ /// Thrown if initialization is attempted with a mismatched transform factory.
+ public static void Initialize(Func? factory)
{
- shaderId = typeof(T).GUID;
+ // This conceptually acts as a static constructor, and this type is
+ // internal, so in this very specific case locking on the type is fine.
+ lock (typeof(For))
+ {
+ if (isInitialized)
+ {
+ // If the factory is already initialized, ensure the draw transform mapper is the same
+ if (d2D1DrawTransformMapperFactory != factory)
+ {
+ ThrowHelper.ThrowInvalidOperationException(
+ "Cannot initialize an ID2D1Effect factory for the same shader type with two different transform mappings. " +
+ "Make sure to only ever register a pixel shader effect with either no transform, or the same transform type.");
+ }
+ }
+ else
+ {
+ // Load all shader properties
+ Guid guid = Guid.NewGuid();
+ int inputCount = ((D2DInputCountAttribute[])typeof(T).GetCustomAttributes(typeof(D2DInputCountAttribute), false))[0].Count;
+ ReadOnlyMemory buffer = D2D1InteropServices.LoadShaderBytecode();
+ byte* typeAssociatedMemory = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), buffer.Length);
- ReadOnlyMemory buffer = D2D1InteropServices.LoadShaderBytecode();
+ // Copy the bytecode to the target buffer
+ buffer.Span.CopyTo(new Span(typeAssociatedMemory, buffer.Length));
- bytecode = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), buffer.Length);
+ // Set the shared state and mark the type as initialized
+ shaderId = guid;
+ numberOfInputs = inputCount;
+ bytecode = typeAssociatedMemory;
+ bytecodeSize = buffer.Length;
+ d2D1DrawTransformMapperFactory = factory;
- buffer.Span.CopyTo(new Span(bytecode, buffer.Length));
-
- bytecodeSize = buffer.Length;
-
- numberOfInputs = ((D2DInputCountAttribute[])typeof(T).GetCustomAttributes(typeof(D2DInputCountAttribute), false))[0].Count;
+ isInitialized = true;
+ }
+ }
}
///
@@ -124,7 +161,9 @@ internal unsafe partial struct PixelShaderEffect
///
private static int CreateEffect(IUnknown** effectImpl)
{
- return PixelShaderEffect.Factory(shaderId, bytecode, bytecodeSize, numberOfInputs, effectImpl);
+ ID2D1DrawTransformMapper? d2D1DrawTransformMapper = d2D1DrawTransformMapperFactory?.Invoke();
+
+ return PixelShaderEffect.Factory(shaderId, numberOfInputs, bytecode, bytecodeSize, d2D1DrawTransformMapper, effectImpl);
}
}
@@ -217,6 +256,11 @@ internal unsafe partial struct PixelShaderEffect
///
private Guid shaderId;
+ ///
+ /// The number of inputs for the shader.
+ ///
+ private int numberOfInputs;
+
///
/// The shader bytecode.
///
@@ -228,9 +272,9 @@ internal unsafe partial struct PixelShaderEffect
private int bytecodeSize;
///
- /// The number of inputs for the shader.
+ /// The handle for the instance in use, if any.
///
- private int numberOfInputs;
+ private GCHandle d2D1DrawTransformMapperFactoryHandle;
///
/// The current input rectangle.
@@ -246,12 +290,19 @@ internal unsafe partial struct PixelShaderEffect
/// The factory method for .
///
/// The for the shader.
- /// The shader bytecode.
- /// The resulting effect instance.
- /// The size of .
/// The number of inputs for the shader.
+ /// The shader bytecode.
+ /// The size of .
+ /// The instance to use for the effect.
+ /// The resulting effect instance.
/// This always returns 0.
- private static int Factory(Guid shaderId, byte* bytecode, int bytecodeSize, int numberOfInputs, IUnknown** effectImpl)
+ private static int Factory(
+ Guid shaderId,
+ int numberOfInputs,
+ byte* bytecode,
+ int bytecodeSize,
+ ID2D1DrawTransformMapper? d2D1DrawTransformMapper,
+ IUnknown** effectImpl)
{
PixelShaderEffect* @this = (PixelShaderEffect*)NativeMemory.Alloc((nuint)sizeof(PixelShaderEffect));
@@ -261,9 +312,10 @@ internal unsafe partial struct PixelShaderEffect
@this->lpVtblForID2D1DrawTransform = VtblForID2D1DrawTransform;
@this->referenceCount = 1;
@this->shaderId = shaderId;
+ @this->numberOfInputs = numberOfInputs;
@this->bytecode = bytecode;
@this->bytecodeSize = bytecodeSize;
- @this->numberOfInputs = numberOfInputs;
+ @this->d2D1DrawTransformMapperFactoryHandle = GCHandle.Alloc(d2D1DrawTransformMapper);
*effectImpl = (IUnknown*)@this;
@@ -367,6 +419,8 @@ internal unsafe partial struct PixelShaderEffect
NativeMemory.Free(this.constantBuffer);
}
+ this.d2D1DrawTransformMapperFactoryHandle.Free();
+
NativeMemory.Free(Unsafe.AsPointer(ref this));
}