Add initial ID2D1DrawTransformMapper support and APIs

このコミットが含まれているのは:
Sergio Pedri committed 2022-04-24 21:04:31 +02:00
1 親 a67237370a
コミット a36bae8e5a
6ファイル変更
+338 -44

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

+22
ファイルの表示
@@ -0,0 +1,22 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TerraFX.Interop.Windows;
namespace ComputeSharp.D2D1.Extensions;
/// <summary>
/// Helper methods for <see cref="RECT"/>.
/// </summary>
internal static class RECTExtensions
{
/// <summary>
/// Creates a <see cref="Rectangle"/> from a <see cref="RECT"/> value.
/// </summary>
/// <param name="rect">The input <see cref="RECT"/> value.</param>
/// <returns>The resulting <see cref="Rectangle"/> value.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Rectangle ToRectangle(this in RECT rect)
{
return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom);
}
}
+29
ファイルの表示
@@ -0,0 +1,29 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TerraFX.Interop.Windows;
namespace ComputeSharp.D2D1.Extensions;
/// <summary>
/// Helper methods for <see cref="Rectangle"/>.
/// </summary>
internal static class RectangleExtensions
{
/// <summary>
/// Creates a <see cref="RECT"/> from a <see cref="Rectangle"/> value.
/// </summary>
/// <param name="rectangle">The input <see cref="Rectangle"/> value.</param>
/// <returns>The resulting <see cref="RECT"/> value.</returns>
[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;
}
}
+66
ファイルの表示
@@ -0,0 +1,66 @@
using System;
using System.Drawing;
namespace ComputeSharp.D2D1;
/// <summary>
/// An <see langword="interface"/> providing support for custom, stateful draw transform mappings for shaders.
/// </summary>
public interface ID2D1DrawTransformMapper
{
/// <summary>
/// Allows a transform to state how it would map a rectangle requested on its output to a set of sample rectangles on its input.
/// </summary>
/// <param name="output">The output rectangle from which the inputs must be mapped.</param>
/// <param name="inputs">The corresponding set of inputs. The inputs will directly correspond to the transform inputs.</param>
/// <remarks>
/// <para>
/// 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.
/// </para>
/// <para>
/// For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1effectauthor/nf-d2d1effectauthor-id2d1transform-mapoutputrecttoinputrects"/>.
/// </para>
/// </remarks>
void MapOutputToInputs(in Rectangle output, Span<Rectangle> inputs);
/// <summary>
/// Performs the inverse mapping of <see cref="MapOutputToInputs(in Rectangle, Span{Rectangle})"/>.
/// </summary>
/// <param name="inputs">The input rectangles to be mapped to the output rectangle. This parameter is always equal to the input bounds.</param>
/// <param name="opaqueInputs">The input rectangles to be mapped to the opaque output rectangle.</param>
/// <param name="output">The output rectangle that maps to the corresponding input rectangle.</param>
/// <param name="opaqueOutput">The output rectangle that maps to the corresponding opaque input rectangle.</param>
/// <remarks>
/// <para>
/// Unlike <see cref="MapOutputToInputs(in Rectangle, Span{Rectangle})"/> and <see cref="MapInvalidOutput(int, Rectangle, out Rectangle)"/>, 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
/// <see cref="MapInvalidOutput(int, Rectangle, out Rectangle)"/> and <see cref="MapOutputToInputs(in Rectangle, Span{Rectangle})"/> methods.
/// </para>
/// <para>
/// For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1effectauthor/nf-d2d1effectauthor-id2d1transform-mapinputrectstooutputrect"/>.
/// </para>
/// </remarks>
void MapInputsToOutput(ReadOnlySpan<Rectangle> inputs, ReadOnlySpan<Rectangle> opaqueInputs, out Rectangle output, out Rectangle opaqueOutput);
/// <summary>
/// Sets the input rectangles for this rendering pass into the transform.
/// </summary>
/// <param name="inputIndex">The index of the input rectangle.</param>
/// <param name="invalidInput">The invalid input rectangle.</param>
/// <param name="invalidOutput">The output rectangle to which the input rectangle must be mapped.</param>
/// <remarks>
/// <para>
/// 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 <see cref="MapInvalidOutput(int, Rectangle, out Rectangle)"/>. Direct2D can call this method at any time
/// and in any sequence following a call to <see cref="MapInputsToOutput(ReadOnlySpan{Rectangle}, ReadOnlySpan{Rectangle}, out Rectangle, out Rectangle)"/>.
/// </para>
/// <para>
/// For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1effectauthor/nf-d2d1effectauthor-id2d1transform-mapinvalidrect"/>.
/// </para>
/// </remarks>
void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput);
}
+31
ファイルの表示
@@ -26,9 +26,40 @@ unsafe partial class D2D1InteropServices
/// <remarks>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.</remarks>
public static unsafe void RegisterPixelShaderEffectForD2D1Factory1<T>(void* d2D1Factory1, out Guid effectId)
where T : unmanaged, ID2D1PixelShader
{
RegisterPixelShaderEffectForD2D1Factory1<T>(d2D1Factory1, null, out effectId);
}
/// <summary>
/// Registers an effect from an input D2D1 pixel shader, by calling <c>ID2D1Factory1::RegisterEffectFromString</c>.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader to register.</typeparam>
/// <typeparam name="TMapper">The type of <see cref="ID2D1DrawTransformMapper"/> implementation to register.</typeparam>
/// <param name="d2D1Factory1">A pointer to the <c>ID2D1Factory1</c> instance to use.</param>
/// <param name="effectId">The <see cref="Guid"/> of the registered effect, which can be used to call <c>ID2D1DeviceContext::CreateEffect</c>.</param>
/// <remarks>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.</remarks>
public static unsafe void RegisterPixelShaderEffectForD2D1Factory1<T, TMapper>(void* d2D1Factory1, out Guid effectId)
where T : unmanaged, ID2D1PixelShader
where TMapper : class, ID2D1DrawTransformMapper, new()
{
RegisterPixelShaderEffectForD2D1Factory1<T>(d2D1Factory1, static () => new TMapper(), out effectId);
}
/// <summary>
/// Registers an effect from an input D2D1 pixel shader, by calling <c>ID2D1Factory1::RegisterEffectFromString</c>.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader to register.</typeparam>
/// <param name="d2D1Factory1">A pointer to the <c>ID2D1Factory1</c> instance to use.</param>
/// <param name="mapperFactory">An optional factory of <see cref="ID2D1DrawTransformMapper"/> instances to use for the transform.</param>
/// <param name="effectId">The <see cref="Guid"/> of the registered effect, which can be used to call <c>ID2D1DeviceContext::CreateEffect</c>.</param>
/// <remarks>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.</remarks>
public static unsafe void RegisterPixelShaderEffectForD2D1Factory1<T>(void* d2D1Factory1, Func<ID2D1DrawTransformMapper>? mapperFactory, out Guid effectId)
where T : unmanaged, ID2D1PixelShader
{
effectId = default;
PixelShaderEffect.For<T>.Initialize(mapperFactory);
// Setup the input string
StringBuilder effectInputsBuilder = new();
@@ -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<Rectangle> 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<Rectangle> inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount);
Span<Rectangle> 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;
}
+92 -38
ファイルの表示
@@ -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<T>
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// The <see cref="Guid"/> for the shader.
/// </summary>
private static readonly Guid shaderId;
/// <summary>
/// The shader bytecode.
/// </summary>
private static readonly byte* bytecode;
/// <summary>
/// The size of <see cref="bytecode"/>.
/// </summary>
private static readonly int bytecodeSize;
/// <summary>
/// The number of inputs for the shader.
/// </summary>
private static readonly int numberOfInputs;
/// <summary>
/// The <see cref="FactoryDelegate"/> wrapper for the shader factory.
/// </summary>
private static readonly FactoryDelegate EffectFactory = CreateEffect;
/// <summary>
/// The static constructor for <see cref="For{T}"/>.
/// Indicates whether or not initialization has completed.
/// </summary>
static For()
private static bool isInitialized;
/// <summary>
/// The <see cref="Guid"/> for the shader.
/// </summary>
private static Guid shaderId;
/// <summary>
/// The number of inputs for the shader.
/// </summary>
private static int numberOfInputs;
/// <summary>
/// The shader bytecode.
/// </summary>
private static byte* bytecode;
/// <summary>
/// The size of <see cref="bytecode"/>.
/// </summary>
private static int bytecodeSize;
/// <summary>
/// The factory of <see cref="ID2D1DrawTransformMapper"/> instances to use for each created effect.
/// </summary>
private static Func<ID2D1DrawTransformMapper>? d2D1DrawTransformMapperFactory;
/// <summary>
/// Initializes the <see cref="For{T}"/> shared state.
/// </summary>
/// <param name="factory">The factory of <see cref="ID2D1DrawTransformMapper"/> instances to use for each created effect.</param>
/// <exception cref="InvalidOperationException">Thrown if initialization is attempted with a mismatched transform factory.</exception>
public static void Initialize(Func<ID2D1DrawTransformMapper>? 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<T>))
{
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<byte> buffer = D2D1InteropServices.LoadShaderBytecode<T>();
byte* typeAssociatedMemory = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For<T>), buffer.Length);
ReadOnlyMemory<byte> buffer = D2D1InteropServices.LoadShaderBytecode<T>();
// Copy the bytecode to the target buffer
buffer.Span.CopyTo(new Span<byte>(typeAssociatedMemory, buffer.Length));
bytecode = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For<T>), 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<byte>(bytecode, buffer.Length));
bytecodeSize = buffer.Length;
numberOfInputs = ((D2DInputCountAttribute[])typeof(T).GetCustomAttributes(typeof(D2DInputCountAttribute), false))[0].Count;
isInitialized = true;
}
}
}
/// <summary>
@@ -124,7 +161,9 @@ internal unsafe partial struct PixelShaderEffect
/// <inheritdoc cref="FactoryDelegate"/>
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
/// </summary>
private Guid shaderId;
/// <summary>
/// The number of inputs for the shader.
/// </summary>
private int numberOfInputs;
/// <summary>
/// The shader bytecode.
/// </summary>
@@ -228,9 +272,9 @@ internal unsafe partial struct PixelShaderEffect
private int bytecodeSize;
/// <summary>
/// The number of inputs for the shader.
/// The handle for the <see cref="ID2D1DrawTransformMapper"/> instance in use, if any.
/// </summary>
private int numberOfInputs;
private GCHandle d2D1DrawTransformMapperFactoryHandle;
/// <summary>
/// The current input rectangle.
@@ -246,12 +290,19 @@ internal unsafe partial struct PixelShaderEffect
/// The factory method for <see cref="ID2D1Factory1.RegisterEffectFromString"/>.
/// </summary>
/// <param name="shaderId">The <see cref="Guid"/> for the shader.</param>
/// <param name="bytecode">The shader bytecode.</param>
/// <param name="effectImpl">The resulting effect instance.</param>
/// <param name="bytecodeSize">The size of <paramref name="bytecode"/>.</param>
/// <param name="numberOfInputs">The number of inputs for the shader.</param>
/// <param name="bytecode">The shader bytecode.</param>
/// <param name="bytecodeSize">The size of <paramref name="bytecode"/>.</param>
/// <param name="d2D1DrawTransformMapper">The <see cref="ID2D1DrawTransformMapper"/> instance to use for the effect.</param>
/// <param name="effectImpl">The resulting effect instance.</param>
/// <returns>This always returns <c>0</c>.</returns>
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));
}